🧪 Test legacy import
The tests build a legacy SQLite fixture from the old migrations and cover the field mapping, skipped invalid rows, the replace-on-rerun behaviour, the dry run and the guarantee that the legacy file and its directory stay untouched.
This commit is contained in:
@@ -0,0 +1,817 @@
|
||||
package legacyimport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tests"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
_ "github.com/wotra/wotra/internal/migrations"
|
||||
_ "modernc.org/sqlite"
|
||||
_ "time/tzdata"
|
||||
)
|
||||
|
||||
// Tables of the legacy database, copied from internal/store/migrations.
|
||||
// The import ignores sync_log and the start_time/end_time columns of
|
||||
// closed_days, so they are only kept for fidelity.
|
||||
const (
|
||||
legacyEntries = `
|
||||
CREATE TABLE entries (
|
||||
id TEXT PRIMARY KEY,
|
||||
start_time INTEGER NOT NULL,
|
||||
end_time INTEGER,
|
||||
auto_stopped INTEGER NOT NULL DEFAULT 0,
|
||||
note TEXT,
|
||||
day_key TEXT NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
deleted_at INTEGER
|
||||
);
|
||||
CREATE INDEX idx_entries_day ON entries(day_key);
|
||||
`
|
||||
legacyClosedDays = `
|
||||
CREATE TABLE closed_days (
|
||||
day_key TEXT PRIMARY KEY,
|
||||
start_time INTEGER,
|
||||
end_time INTEGER,
|
||||
worked_ms INTEGER NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
closed_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`
|
||||
legacyClosedWeeks = `
|
||||
CREATE TABLE closed_weeks (
|
||||
week_key TEXT PRIMARY KEY,
|
||||
expected_ms INTEGER NOT NULL,
|
||||
worked_ms INTEGER NOT NULL,
|
||||
delta_ms INTEGER NOT NULL,
|
||||
closed_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`
|
||||
legacyBalanceAdjustments = `
|
||||
CREATE TABLE balance_adjustments (
|
||||
id TEXT PRIMARY KEY,
|
||||
delta_ms INTEGER NOT NULL,
|
||||
note TEXT NOT NULL DEFAULT '',
|
||||
effective_at INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_balance_adjustments_effective_at ON balance_adjustments(effective_at);
|
||||
`
|
||||
legacySyncLog001 = `
|
||||
CREATE TABLE sync_log (
|
||||
entity TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
op TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
PRIMARY KEY (entity, entity_id, version)
|
||||
);
|
||||
`
|
||||
legacySyncLog003 = `
|
||||
CREATE TABLE sync_log (
|
||||
entity TEXT NOT NULL,
|
||||
entity_id TEXT NOT NULL,
|
||||
op TEXT NOT NULL,
|
||||
version INTEGER NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
logged_at INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (entity, entity_id, version)
|
||||
);
|
||||
`
|
||||
legacySettings001 = `
|
||||
CREATE TABLE settings_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
effective_from TEXT NOT NULL,
|
||||
hours_per_week REAL NOT NULL,
|
||||
workdays_mask INTEGER NOT NULL DEFAULT 31,
|
||||
timezone TEXT NOT NULL DEFAULT 'UTC',
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
`
|
||||
legacySettings003 = `
|
||||
CREATE TABLE settings_history (
|
||||
id TEXT PRIMARY KEY,
|
||||
effective_from TEXT NOT NULL,
|
||||
hours_per_week REAL NOT NULL,
|
||||
workdays_mask INTEGER NOT NULL DEFAULT 31,
|
||||
timezone TEXT NOT NULL DEFAULT 'UTC',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
`
|
||||
)
|
||||
|
||||
// The schema after migration 003, which every database has that ran the old wotra since.
|
||||
const legacySchema = legacyEntries + legacyClosedDays + legacyClosedWeeks +
|
||||
legacySettings003 + legacySyncLog003 + legacyBalanceAdjustments
|
||||
|
||||
const legacySchemaBefore003 = legacyEntries + legacyClosedDays + legacyClosedWeeks +
|
||||
legacySettings001 + legacySyncLog001 + legacyBalanceAdjustments
|
||||
|
||||
const legacySchemaBefore002 = legacyEntries + legacyClosedDays + legacyClosedWeeks +
|
||||
legacySettings003 + legacySyncLog003
|
||||
|
||||
const legacyRows = `
|
||||
INSERT INTO entries (id, start_time, end_time, auto_stopped, note, day_key, updated_at, deleted_at) VALUES
|
||||
('entry-1', 1700000000000, 1700003600000, 1, 'deleted', '2023-11-14', 1700003600001, 1700003600002),
|
||||
('entry-2', 1700007200000, NULL, 0, NULL, '2023-11-15', 1700007200000, NULL),
|
||||
('entry-3', 1700020000000, 1700020600000, 0, 'invalid', 'bad', 1700020600000, NULL);
|
||||
INSERT INTO closed_days (day_key, start_time, end_time, worked_ms, kind, closed_at, updated_at)
|
||||
VALUES ('2023-11-14', 1700000000000, 1700003600000, 3600000, 'work', 1700003600000, 1700003600002);
|
||||
INSERT INTO closed_weeks (week_key, expected_ms, worked_ms, delta_ms, closed_at, updated_at)
|
||||
VALUES ('2023-W47', 14400000, 3600000, -10800000, 1700050000000, 1700050000001);
|
||||
INSERT INTO settings_history (id, effective_from, hours_per_week, workdays_mask, timezone, created_at, updated_at) VALUES
|
||||
('settings-1', '2000-01-01', 40.0, 31, 'UTC', 1600000000000, 1600000000000),
|
||||
('settings-2', '2026-01-01', 32.5, 127, 'America/New_York', 1700000000000, 1700000000001);
|
||||
INSERT INTO balance_adjustments (id, delta_ms, note, effective_at, created_at, updated_at)
|
||||
VALUES ('adjustment-1', -3600000, 'correction', 1690000000000, 1690000000000, 1690000000001);
|
||||
INSERT INTO sync_log (entity, entity_id, op, version, payload) VALUES ('entries', 'entry-1', 'upsert', 1, '{}');
|
||||
`
|
||||
|
||||
const invalidRows = `
|
||||
INSERT INTO entries (id, start_time, end_time, auto_stopped, note, day_key, updated_at, deleted_at) VALUES
|
||||
('neg-start', -1, 100, 0, '', '2023-11-14', 1, NULL),
|
||||
('neg-end', 100, -1, 0, '', '2023-11-14', 1, NULL),
|
||||
('bad-day', 100, 200, 0, '', '2023-11-1', 1, NULL),
|
||||
('text-time', 'soon', 200, 0, '', '2023-11-14', 1, NULL);
|
||||
INSERT INTO closed_days (day_key, start_time, end_time, worked_ms, kind, closed_at, updated_at) VALUES
|
||||
('2023-11-14', NULL, NULL, -5, 'work', 1, 1),
|
||||
('2023-11-15', NULL, NULL, 5, 'weekend', 1, 1),
|
||||
('2023-11-16', NULL, NULL, 5, 'work', 1, 1);
|
||||
INSERT INTO closed_weeks (week_key, expected_ms, worked_ms, delta_ms, closed_at, updated_at)
|
||||
VALUES ('2023-47', 1, 1, 0, 1, 1);
|
||||
INSERT INTO settings_history (id, effective_from, hours_per_week, workdays_mask, timezone, created_at, updated_at) VALUES
|
||||
('settings-hours', '2000-01-01', -5, 31, 'UTC', 1, 1),
|
||||
('settings-tz', '2000-01-02', 40, 31, '', 1, 1),
|
||||
('settings-from', '2000/01/01', 40, 31, 'UTC', 1, 1);
|
||||
INSERT INTO balance_adjustments (id, delta_ms, note, effective_at, created_at, updated_at)
|
||||
VALUES ('adjustment-text', 5, '', 'soon', 1, 1);
|
||||
`
|
||||
|
||||
var idPattern = regexp.MustCompile(`^[a-z0-9]{15}$`)
|
||||
|
||||
var wantSummary = Summary{Entries: 2, ClosedDays: 1, ClosedWeeks: 1, Settings: 2, Adjustments: 1, Skipped: 1}
|
||||
|
||||
func createLegacy(t *testing.T, journal, schema, rows string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "wotra.db")
|
||||
db, err := sql.Open("sqlite", "file:"+path+"?_pragma=journal_mode("+journal+")")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, stmt := range []string{schema, rows} {
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// createCrashedLegacy returns a fixture whose committed rows live only in the
|
||||
// -wal file (as after a server crash) on read-only media: wotra.db plus
|
||||
// wotra.db-wal, no -shm, in a directory without write permission.
|
||||
func createCrashedLegacy(t *testing.T) string {
|
||||
t.Helper()
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root ignores directory permissions")
|
||||
}
|
||||
live := filepath.Join(t.TempDir(), "wotra.db")
|
||||
db, err := sql.Open("sqlite", "file:"+live+"?_pragma=journal_mode(wal)")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, stmt := range []string{legacySchema, legacyRows} {
|
||||
if _, err := db.Exec(stmt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// an open connection keeps the sidecars alive and prevents a checkpoint
|
||||
conn, err := db.Conn(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
defer db.Close()
|
||||
|
||||
crashed := filepath.Join(t.TempDir(), "wotra.db")
|
||||
for _, suffix := range []string{"", "-wal"} {
|
||||
content, err := os.ReadFile(live + suffix)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(crashed+suffix, content, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Chmod(filepath.Dir(crashed), 0o555); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chmod(filepath.Dir(crashed), 0o755) })
|
||||
probe := crashed + "-probe"
|
||||
if f, err := os.Create(probe); err == nil {
|
||||
f.Close()
|
||||
t.Skip("directory permissions are not enforced here")
|
||||
}
|
||||
if main, _ := os.ReadFile(crashed); bytes.Contains(main, []byte("entry-1")) {
|
||||
t.Fatal("precondition failed: fixture data is not confined to the -wal file")
|
||||
}
|
||||
return crashed
|
||||
}
|
||||
|
||||
func setup(t *testing.T) (*tests.TestApp, *core.Record, *core.Record) {
|
||||
t.Helper()
|
||||
app, err := tests.NewTestApp()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(app.Cleanup)
|
||||
users, err := app.FindCollectionByNameOrId("users")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mk := func(email string) *core.Record {
|
||||
u := core.NewRecord(users)
|
||||
u.SetEmail(email)
|
||||
u.SetPassword("password123456")
|
||||
if err := app.Save(u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
return app, mk("import@example.com"), mk("other@example.com")
|
||||
}
|
||||
|
||||
func seed(t *testing.T, app core.App, collection, owner string, data map[string]any) *core.Record {
|
||||
t.Helper()
|
||||
col, err := app.FindCollectionByNameOrId(collection)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := core.NewRecord(col)
|
||||
r.Set("owner", owner)
|
||||
for field, value := range data {
|
||||
r.Set(field, value)
|
||||
}
|
||||
r.Set("client_updated_at", 1000)
|
||||
r.Set("rev", 1)
|
||||
if err := app.Save(r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func owned(t *testing.T, app core.App, collection, owner string) []*core.Record {
|
||||
t.Helper()
|
||||
records, err := app.FindAllRecords(collection, dbx.HashExp{"owner": owner})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
func byKey(t *testing.T, records []*core.Record, key, value string) *core.Record {
|
||||
t.Helper()
|
||||
for _, r := range records {
|
||||
if r.GetString(key) == value {
|
||||
return r
|
||||
}
|
||||
}
|
||||
t.Fatalf("no record with %s=%q among %d records", key, value, len(records))
|
||||
return nil
|
||||
}
|
||||
|
||||
func importLegacy(t *testing.T, app core.App, path, owner, tz string, dryRun bool) (Summary, string) {
|
||||
t.Helper()
|
||||
legacy, err := openLegacy(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = legacy.Close() })
|
||||
summary, err := Import(app, legacy.db, owner, tz, dryRun)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tmpDir := legacy.tmpDir
|
||||
if err := legacy.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return summary, tmpDir
|
||||
}
|
||||
|
||||
type dirState map[string]string
|
||||
|
||||
func readDir(t *testing.T, dir string) dirState {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := dirState{}
|
||||
for _, entry := range entries {
|
||||
content, err := os.ReadFile(filepath.Join(dir, entry.Name()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state[entry.Name()] = fmt.Sprintf("%x", sha256.Sum256(content))
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func captureWarnings(t *testing.T, fn func()) string {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
original := warnf
|
||||
warnf = func(format string, a ...any) { fmt.Fprintf(&buf, format+"\n", a...) }
|
||||
t.Cleanup(func() { warnf = original })
|
||||
fn()
|
||||
warnf = original
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func TestImport(t *testing.T) {
|
||||
app, user, other := setup(t)
|
||||
path := createLegacy(t, "wal", legacySchema, legacyRows)
|
||||
stale := seed(t, app, "entries", user.Id, map[string]any{
|
||||
"start_time": 1, "end_time": 2, "day_key": "2020-01-01", "note": "stale",
|
||||
})
|
||||
foreign := seed(t, app, "entries", other.Id, map[string]any{
|
||||
"start_time": 1, "end_time": 2, "day_key": "2020-01-01", "note": "foreign",
|
||||
})
|
||||
counts := func() map[string]int {
|
||||
return map[string]int{
|
||||
"entries": len(owned(t, app, "entries", user.Id)),
|
||||
"closed_days": len(owned(t, app, "closed_days", user.Id)),
|
||||
"closed_weeks": len(owned(t, app, "closed_weeks", user.Id)),
|
||||
"settings_history": len(owned(t, app, "settings_history", user.Id)),
|
||||
"balance_adjustments": len(owned(t, app, "balance_adjustments", user.Id)),
|
||||
}
|
||||
}
|
||||
assertCounts := func(want map[string]int) {
|
||||
t.Helper()
|
||||
if got := counts(); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("counts: got %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// dry run: reports the rows but writes nothing and deletes nothing
|
||||
summary, tmpDir := importLegacy(t, app, path, user.Id, "Europe/Berlin", true)
|
||||
if summary != wantSummary {
|
||||
t.Fatalf("dry run summary: got %+v, want %+v", summary, wantSummary)
|
||||
}
|
||||
if tmpDir != "" {
|
||||
t.Fatalf("dry run read a copy in %q instead of the file itself", tmpDir)
|
||||
}
|
||||
assertCounts(map[string]int{"entries": 1, "closed_days": 0, "closed_weeks": 0, "settings_history": 0, "balance_adjustments": 0})
|
||||
|
||||
summary, tmpDir = importLegacy(t, app, path, user.Id, "Europe/Berlin", false)
|
||||
if summary != wantSummary {
|
||||
t.Fatalf("summary: got %+v, want %+v", summary, wantSummary)
|
||||
}
|
||||
if tmpDir != "" {
|
||||
t.Fatalf("import read a copy in %q instead of the file itself", tmpDir)
|
||||
}
|
||||
// the stale record of the owner is replaced, the record of another user is kept
|
||||
assertCounts(map[string]int{
|
||||
"entries": 2, "closed_days": 1, "closed_weeks": 1, "settings_history": 2, "balance_adjustments": 1,
|
||||
})
|
||||
if _, err := app.FindRecordById("entries", stale.Id); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("stale entry %s should have been deleted, got err=%v", stale.Id, err)
|
||||
}
|
||||
if _, err := app.FindRecordById("entries", foreign.Id); err != nil {
|
||||
t.Fatalf("entry of another user was deleted: %v", err)
|
||||
}
|
||||
|
||||
all := map[string][]*core.Record{
|
||||
"entries": owned(t, app, "entries", user.Id),
|
||||
"closed_days": owned(t, app, "closed_days", user.Id),
|
||||
"closed_weeks": owned(t, app, "closed_weeks", user.Id),
|
||||
"settings_history": owned(t, app, "settings_history", user.Id),
|
||||
"balance_adjustments": owned(t, app, "balance_adjustments", user.Id),
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for collection, records := range all {
|
||||
for _, r := range records {
|
||||
if !idPattern.MatchString(r.Id) {
|
||||
t.Errorf("%s: id %q does not match the PocketBase id pattern", collection, r.Id)
|
||||
}
|
||||
if r.GetString("owner") != user.Id {
|
||||
t.Errorf("%s %s: owner is %q", collection, r.Id, r.GetString("owner"))
|
||||
}
|
||||
if got := r.GetInt("rev"); got != 1 {
|
||||
t.Errorf("%s %s: rev is %d", collection, r.Id, got)
|
||||
}
|
||||
if r.GetDateTime("created").IsZero() {
|
||||
t.Errorf("%s %s: created is not set", collection, r.Id)
|
||||
}
|
||||
ids[r.Id] = true
|
||||
}
|
||||
}
|
||||
|
||||
entries := all["entries"]
|
||||
check := func(r *core.Record, want map[string]any) {
|
||||
t.Helper()
|
||||
for field, expected := range want {
|
||||
var got any
|
||||
switch expected.(type) {
|
||||
case string:
|
||||
got = r.GetString(field)
|
||||
case int64:
|
||||
got = r.GetInt64(field)
|
||||
case float64:
|
||||
got = r.GetFloat(field)
|
||||
case bool:
|
||||
got = r.GetBool(field)
|
||||
}
|
||||
if got != expected {
|
||||
t.Errorf("%s %s: %s is %v, want %v", r.Collection().Name, r.Id, field, got, expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
// the running entry: NULL end_time and NULL note become the zero values
|
||||
check(byKey(t, entries, "note", ""), map[string]any{
|
||||
"start_time": int64(1700007200000), "end_time": int64(0), "auto_stopped": false,
|
||||
"day_key": "2023-11-15", "deleted": false, "client_updated_at": int64(1700007200000),
|
||||
})
|
||||
// the soft deleted entry keeps its deleted flag and its auto_stopped marker
|
||||
check(byKey(t, entries, "note", "deleted"), map[string]any{
|
||||
"start_time": int64(1700000000000), "end_time": int64(1700003600000), "auto_stopped": true,
|
||||
"day_key": "2023-11-14", "deleted": true, "client_updated_at": int64(1700003600001),
|
||||
})
|
||||
check(byKey(t, all["closed_days"], "day_key", "2023-11-14"), map[string]any{
|
||||
"worked_ms": int64(3600000), "kind": "work", "closed_at": int64(1700003600000),
|
||||
"client_updated_at": int64(1700003600002), "deleted": false,
|
||||
})
|
||||
check(byKey(t, all["closed_weeks"], "week_key", "2023-W47"), map[string]any{
|
||||
"expected_ms": int64(14400000), "worked_ms": int64(3600000), "delta_ms": int64(-10800000),
|
||||
"closed_at": int64(1700050000000), "client_updated_at": int64(1700050000001),
|
||||
})
|
||||
check(byKey(t, all["settings_history"], "effective_from", "2000-01-01"), map[string]any{
|
||||
"hours_per_week": 40.0, "workdays_mask": int64(31), "timezone": "Europe/Berlin",
|
||||
"client_updated_at": int64(1600000000000),
|
||||
})
|
||||
check(byKey(t, all["settings_history"], "effective_from", "2026-01-01"), map[string]any{
|
||||
"hours_per_week": 32.5, "workdays_mask": int64(127), "timezone": "Europe/Berlin",
|
||||
"client_updated_at": int64(1700000000001),
|
||||
})
|
||||
check(byKey(t, all["balance_adjustments"], "note", "correction"), map[string]any{
|
||||
"delta_ms": int64(-3600000), "effective_at": int64(1690000000000),
|
||||
"client_updated_at": int64(1690000000001), "deleted": false,
|
||||
})
|
||||
|
||||
// entries are inserted in start_time order (rowid follows the insert order)
|
||||
var order []struct {
|
||||
DayKey string `db:"day_key"`
|
||||
}
|
||||
if err := app.DB().NewQuery("SELECT day_key FROM entries WHERE owner = {:owner} ORDER BY rowid").
|
||||
Bind(dbx.Params{"owner": user.Id}).All(&order); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var dayKeys []string
|
||||
for _, row := range order {
|
||||
dayKeys = append(dayKeys, row.DayKey)
|
||||
}
|
||||
if want := []string{"2023-11-14", "2023-11-15"}; !reflect.DeepEqual(dayKeys, want) {
|
||||
t.Fatalf("insert order: got %v, want %v", dayKeys, want)
|
||||
}
|
||||
|
||||
// importing again replaces the records instead of duplicating them
|
||||
summary, _ = importLegacy(t, app, path, user.Id, "", false)
|
||||
if summary != wantSummary {
|
||||
t.Fatalf("second import summary: got %+v, want %+v", summary, wantSummary)
|
||||
}
|
||||
assertCounts(map[string]int{
|
||||
"entries": 2, "closed_days": 1, "closed_weeks": 1, "settings_history": 2, "balance_adjustments": 1,
|
||||
})
|
||||
settings := owned(t, app, "settings_history", user.Id)
|
||||
// without --tz the legacy time zones are kept
|
||||
check(byKey(t, settings, "effective_from", "2000-01-01"), map[string]any{"timezone": "UTC"})
|
||||
check(byKey(t, settings, "effective_from", "2026-01-01"), map[string]any{"timezone": "America/New_York"})
|
||||
for _, collection := range []string{"entries", "closed_days", "closed_weeks", "settings_history", "balance_adjustments"} {
|
||||
for _, r := range owned(t, app, collection, user.Id) {
|
||||
if ids[r.Id] {
|
||||
t.Errorf("%s %s: id of the previous import was reused", collection, r.Id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportLeavesLegacyDirectoryUntouched(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
for _, journal := range []string{"delete", "wal"} {
|
||||
t.Run(journal, func(t *testing.T) {
|
||||
path := createLegacy(t, journal, legacySchema, legacyRows)
|
||||
before := readDir(t, filepath.Dir(path))
|
||||
if len(before) != 1 {
|
||||
t.Fatalf("fixture directory has %v, want only wotra.db", before)
|
||||
}
|
||||
for _, dryRun := range []bool{true, false} {
|
||||
if summary, _ := importLegacy(t, app, path, user.Id, "", dryRun); summary != wantSummary {
|
||||
t.Fatalf("dryRun=%v: summary %+v, want %+v", dryRun, summary, wantSummary)
|
||||
}
|
||||
if after := readDir(t, filepath.Dir(path)); !reflect.DeepEqual(after, before) {
|
||||
t.Fatalf("dryRun=%v: directory changed from %v to %v", dryRun, before, after)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportSkipsInvalidRows(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
path := createLegacy(t, "wal", legacySchema, invalidRows)
|
||||
|
||||
var (
|
||||
summary Summary
|
||||
err error
|
||||
)
|
||||
warnings := captureWarnings(t, func() {
|
||||
summary, err = Import(app, mustOpen(t, path), user.Id, "", false)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := Summary{ClosedDays: 1, Skipped: 11}
|
||||
if summary != want {
|
||||
t.Fatalf("summary: got %+v, want %+v", summary, want)
|
||||
}
|
||||
if got := strings.Count(warnings, "skipped legacy "); got != want.Skipped {
|
||||
t.Fatalf("printed %d warnings, want %d:\n%s", got, want.Skipped, warnings)
|
||||
}
|
||||
for _, expected := range []string{
|
||||
`skipped legacy entries row 1 (id "neg-start")`,
|
||||
`skipped legacy entries row 2 (id "bad-day")`,
|
||||
`skipped legacy entries row 3 (id "neg-end")`,
|
||||
`skipped legacy entries row 4: `,
|
||||
`skipped legacy closed_days row 2 (day_key "2023-11-15")`,
|
||||
`skipped legacy closed_weeks row 1 (week_key "2023-47")`,
|
||||
`skipped legacy settings_history row 2 (id "settings-tz")`,
|
||||
`skipped legacy settings_history row 3 (id "settings-from")`,
|
||||
`skipped legacy balance_adjustments row 1: `,
|
||||
} {
|
||||
if !strings.Contains(warnings, expected) {
|
||||
t.Errorf("warnings lack %q:\n%s", expected, warnings)
|
||||
}
|
||||
}
|
||||
for _, collection := range []string{"entries", "closed_weeks", "settings_history", "balance_adjustments"} {
|
||||
if records := owned(t, app, collection, user.Id); len(records) != 0 {
|
||||
t.Errorf("%s: %d invalid rows were imported", collection, len(records))
|
||||
}
|
||||
}
|
||||
if records := owned(t, app, "closed_days", user.Id); len(records) != 1 || records[0].GetString("day_key") != "2023-11-16" {
|
||||
t.Fatalf("closed_days: got %+v, want only 2023-11-16", records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportRejectsOldSchema(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "before 003",
|
||||
path: createLegacy(t, "wal", legacySchemaBefore003, ""),
|
||||
want: "legacy database predates migration 003, start the old wotra once to upgrade it",
|
||||
},
|
||||
{
|
||||
name: "before 002",
|
||||
path: createLegacy(t, "wal", legacySchemaBefore002, ""),
|
||||
want: "legacy database has no balance_adjustments table, start the old wotra once to upgrade it",
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, err := Import(app, mustOpen(t, c.path), user.Id, "", false)
|
||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||
t.Fatalf("got err=%v, want it to contain %q", err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyOpen(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
path, _ := filepath.Abs(createLegacy(t, "wal", legacySchema, legacyRows))
|
||||
|
||||
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec("CREATE TABLE probe (x)"); err == nil || !strings.Contains(err.Error(), "readonly") {
|
||||
t.Fatalf("a write on a mode=ro connection must fail, got err=%v", err)
|
||||
}
|
||||
summary, err := Import(app, db, user.Id, "", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary != wantSummary {
|
||||
t.Fatalf("summary: got %+v, want %+v", summary, wantSummary)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenLegacyFallsBackToCopy(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
path := createCrashedLegacy(t)
|
||||
before := readDir(t, filepath.Dir(path))
|
||||
|
||||
legacy, err := openLegacy(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = legacy.Close() })
|
||||
if legacy.tmpDir == "" {
|
||||
t.Fatal("expected the file to be read from a temporary copy")
|
||||
}
|
||||
// the copy also sees the rows that only exist in the -wal file
|
||||
summary, err := Import(app, legacy.db, user.Id, "", false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if summary != wantSummary {
|
||||
t.Fatalf("summary: got %+v, want %+v", summary, wantSummary)
|
||||
}
|
||||
tmpDir := legacy.tmpDir
|
||||
if err := legacy.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(tmpDir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("temporary copy %s was not removed, err=%v", tmpDir, err)
|
||||
}
|
||||
if after := readDir(t, filepath.Dir(path)); !reflect.DeepEqual(after, before) {
|
||||
t.Fatalf("directory changed from %v to %v", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenLegacyMissingFile(t *testing.T) {
|
||||
_, err := openLegacy(filepath.Join(t.TempDir(), "missing.db"))
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("got err=%v, want a not-exist error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func runCommand(t *testing.T, app core.App, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
root := &cobra.Command{Use: "wotra"}
|
||||
Register(app, root)
|
||||
var out bytes.Buffer
|
||||
root.SetOut(&out)
|
||||
root.SetErr(&out)
|
||||
root.SetArgs(args)
|
||||
err := root.Execute()
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func line(name string, count int, status string) string {
|
||||
return fmt.Sprintf("%-20s %d %s", name, count, status)
|
||||
}
|
||||
|
||||
func TestImportCommand(t *testing.T) {
|
||||
path := createLegacy(t, "wal", legacySchema, legacyRows)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
out []string
|
||||
wantErr string
|
||||
check func(t *testing.T, app *tests.TestApp, user *core.Record)
|
||||
}{
|
||||
{
|
||||
name: "import",
|
||||
args: []string{"import-legacy", "--db", path, "--email", " IMPORT@Example.com ", "--tz", "Europe/Berlin"},
|
||||
out: []string{
|
||||
line("settings_history", 2, "imported"),
|
||||
line("entries", 2, "imported"),
|
||||
line("closed_days", 1, "imported"),
|
||||
line("closed_weeks", 1, "imported"),
|
||||
line("balance_adjustments", 1, "imported"),
|
||||
"skipped 1 invalid legacy rows",
|
||||
},
|
||||
check: func(t *testing.T, app *tests.TestApp, user *core.Record) {
|
||||
t.Helper()
|
||||
records := owned(t, app, "settings_history", user.Id)
|
||||
if len(records) != 2 {
|
||||
t.Fatalf("settings_history: got %d records, want 2", len(records))
|
||||
}
|
||||
for _, r := range records {
|
||||
if r.GetString("timezone") != "Europe/Berlin" {
|
||||
t.Fatalf("timezone is %q, want Europe/Berlin", r.GetString("timezone"))
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "dry run",
|
||||
args: []string{"import-legacy", "--db", path, "--email", "import@example.com", "--dry-run"},
|
||||
out: []string{
|
||||
line("entries", 2, "dry run, nothing written"),
|
||||
line("balance_adjustments", 1, "dry run, nothing written"),
|
||||
},
|
||||
check: func(t *testing.T, app *tests.TestApp, user *core.Record) {
|
||||
t.Helper()
|
||||
for _, collection := range legacyTables {
|
||||
if records := owned(t, app, collection, user.Id); len(records) != 0 {
|
||||
t.Fatalf("%s: dry run wrote %d records", collection, len(records))
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unknown user",
|
||||
args: []string{"import-legacy", "--db", path, "--email", "nobody@example.com"},
|
||||
wantErr: `no user with email "nobody@example.com", sign up in the app first`,
|
||||
},
|
||||
{
|
||||
name: "missing file",
|
||||
args: []string{"import-legacy", "--db", filepath.Join(t.TempDir(), "missing.db"), "--email", "import@example.com"},
|
||||
wantErr: "no such file or directory",
|
||||
},
|
||||
{
|
||||
name: "invalid time zone",
|
||||
args: []string{"import-legacy", "--db", path, "--email", "import@example.com", "--tz", "Mars/Olympus"},
|
||||
wantErr: `invalid --tz "Mars/Olympus"`,
|
||||
},
|
||||
{
|
||||
name: "required flags",
|
||||
args: []string{"import-legacy"},
|
||||
wantErr: `required flag(s) "db", "email" not set`,
|
||||
},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
app, user, _ := setup(t)
|
||||
out, err := runCommand(t, app, c.args...)
|
||||
if c.wantErr != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), c.wantErr) {
|
||||
t.Fatalf("got err=%v, want it to contain %q", err, c.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, line := range c.out {
|
||||
if !strings.Contains(out, line) {
|
||||
t.Errorf("output lacks %q:\n%s", line, out)
|
||||
}
|
||||
}
|
||||
c.check(t, app, user)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportCommandMixedCaseEmail(t *testing.T) {
|
||||
app, _, _ := setup(t)
|
||||
// PocketBase stores the email as it was typed on sign up
|
||||
users, err := app.FindCollectionByNameOrId("users")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := core.NewRecord(users)
|
||||
user.SetEmail("Mixed@Example.com")
|
||||
user.SetPassword("password123456")
|
||||
if err := app.Save(user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
path := createLegacy(t, "wal", legacySchema, legacyRows)
|
||||
out, err := runCommand(t, app, "import-legacy", "--db", path, "--email", " mixed@example.COM ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, line("entries", 2, "imported")) {
|
||||
t.Fatalf("output lacks %q:\n%s", line("entries", 2, "imported"), out)
|
||||
}
|
||||
if records := owned(t, app, "entries", user.Id); len(records) != 2 {
|
||||
t.Fatalf("entries: got %d records, want 2", len(records))
|
||||
}
|
||||
}
|
||||
|
||||
func mustOpen(t *testing.T, path string) *sql.DB {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", "file:"+path+"?mode=ro")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
return db
|
||||
}
|
||||
Reference in New Issue
Block a user