package legacyimport import ( "bytes" "crypto/sha256" "database/sql" "errors" "fmt" "os" "path/filepath" "reflect" "regexp" "strings" "testing" "time" "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() } // liveOwned returns the records of the owner that are not tombstones. func liveOwned(t *testing.T, app core.App, collection, owner string) []*core.Record { t.Helper() var live []*core.Record for _, r := range owned(t, app, collection, owner) { if !r.GetBool("deleted") { live = append(live, r) } } return live } func load(t *testing.T, app core.App, collection, id string) *core.Record { t.Helper() r, err := app.FindRecordById(collection, id) if err != nil { t.Fatal(err) } return r } func wantInt(t testing.TB, rec *core.Record, field string, want int64) { t.Helper() if got := rec.GetInt64(field); got != want { t.Errorf("%s %s: %s is %d, want %d", rec.Collection().Name, rec.Id, field, got, want) } } func wantBool(t testing.TB, rec *core.Record, field string, want bool) { t.Helper() if got := rec.GetBool(field); got != want { t.Errorf("%s %s: %s is %t, want %t", rec.Collection().Name, rec.Id, field, got, want) } } func TestImport(t *testing.T) { app, user, other := setup(t) path := createLegacy(t, "wal", legacySchema, legacyRows) // Rows the client pulled before the import: an entry, the settings row seeded // at sign up and a closed day and week that share their key with an imported row. stale := seed(t, app, "entries", user.Id, map[string]any{ "start_time": 1, "end_time": 2, "day_key": "2020-01-01", "note": "stale", }) seeded := seed(t, app, "settings_history", user.Id, map[string]any{ "effective_from": "2000-01-01", "hours_per_week": 40.0, "workdays_mask": 31, "timezone": "UTC", }) oldDay := seed(t, app, "closed_days", user.Id, map[string]any{ "day_key": "2023-11-14", "worked_ms": 5, "kind": "sick", "closed_at": 7, }) oldWeek := seed(t, app, "closed_weeks", user.Id, map[string]any{ "week_key": "2023-W47", "expected_ms": 1, "worked_ms": 2, "delta_ms": 1, "closed_at": 7, }) // The clock of the client is ahead of the legacy updated_at. oldWeek.Set("client_updated_at", 1700050000001+500) if err := app.Save(oldWeek); err != nil { t.Fatal(err) } foreign := seed(t, app, "entries", other.Id, map[string]any{ "start_time": 1, "end_time": 2, "day_key": "2020-01-01", "note": "foreign", }) existing := []*core.Record{stale, seeded, oldDay, oldWeek} untouched := func() { t.Helper() for _, r := range existing { got := load(t, app, r.Collection().Name, r.Id) wantBool(t, got, "deleted", false) wantInt(t, got, "rev", 1) wantInt(t, got, "client_updated_at", r.GetInt64("client_updated_at")) } } live := func() map[string]int { return map[string]int{ "entries": len(liveOwned(t, app, "entries", user.Id)), "closed_days": len(liveOwned(t, app, "closed_days", user.Id)), "closed_weeks": len(liveOwned(t, app, "closed_weeks", user.Id)), "settings_history": len(liveOwned(t, app, "settings_history", user.Id)), "balance_adjustments": len(liveOwned(t, app, "balance_adjustments", user.Id)), } } // One of the two imported entries is soft deleted in the legacy database. imported := map[string]int{"entries": 1, "closed_days": 1, "closed_weeks": 1, "settings_history": 2, "balance_adjustments": 1} assertLive := func(want map[string]int) { t.Helper() if got := live(); !reflect.DeepEqual(got, want) { t.Fatalf("live counts: got %v, want %v", got, want) } } // dry run: reports the rows but writes nothing, no tombstone either 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) } assertLive(map[string]int{"entries": 1, "closed_days": 1, "closed_weeks": 1, "settings_history": 1, "balance_adjustments": 0}) untouched() before := time.Now().UnixMilli() summary, tmpDir = importLegacy(t, app, path, user.Id, "Europe/Berlin", false) after := time.Now().UnixMilli() 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) } assertLive(imported) // The rows of the owner are tombstoned, not deleted: the client only pulls // changed rows and would never learn about a hard delete. The row of another // user is kept. for _, r := range []*core.Record{stale, seeded} { got := load(t, app, r.Collection().Name, r.Id) wantBool(t, got, "deleted", true) wantInt(t, got, "rev", 2) if cua := got.GetInt64("client_updated_at"); cua < before || cua > after { t.Errorf("%s %s: client_updated_at is %d, want a time between %d and %d", got.Collection().Name, got.Id, cua, before, after) } } got := load(t, app, "entries", foreign.Id) wantBool(t, got, "deleted", false) wantInt(t, got, "rev", 1) // A closed day or week with the key of an imported row is overwritten in place // so that the unique index holds: one live row with the imported values. 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) } } } day := load(t, app, "closed_days", oldDay.Id) check(day, map[string]any{ "day_key": "2023-11-14", "worked_ms": int64(3600000), "kind": "work", "closed_at": int64(1700003600000), "deleted": false, "rev": int64(2), "client_updated_at": int64(1700003600002), // the legacy updated_at is ahead of the existing one }) week := load(t, app, "closed_weeks", oldWeek.Id) check(week, map[string]any{ "week_key": "2023-W47", "expected_ms": int64(14400000), "worked_ms": int64(3600000), "delta_ms": int64(-10800000), "closed_at": int64(1700050000000), "deleted": false, "rev": int64(2), "client_updated_at": int64(1700050000001 + 501), // the existing client_updated_at is ahead: one more }) all := map[string][]*core.Record{ "entries": liveOwned(t, app, "entries", user.Id), "closed_days": liveOwned(t, app, "closed_days", user.Id), "closed_weeks": liveOwned(t, app, "closed_weeks", user.Id), "settings_history": liveOwned(t, app, "settings_history", user.Id), "balance_adjustments": liveOwned(t, app, "balance_adjustments", user.Id), } if len(all["closed_days"]) != 1 || all["closed_days"][0].Id != oldDay.Id { t.Errorf("closed_days: got %+v, want only the overwritten row %s", all["closed_days"], oldDay.Id) } if len(all["closed_weeks"]) != 1 || all["closed_weeks"][0].Id != oldWeek.Id { t.Errorf("closed_weeks: got %+v, want only the overwritten row %s", all["closed_weeks"], oldWeek.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 && r.Id != oldDay.Id && r.Id != oldWeek.Id { 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 := owned(t, app, "entries", user.Id) // 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(day, map[string]any{"client_updated_at": int64(1700003600002)}) check(week, map[string]any{"client_updated_at": int64(1700050000001 + 501)}) 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} AND id != {:stale} ORDER BY rowid"). Bind(dbx.Params{"owner": user.Id, "stale": stale.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) } assertLive(imported) settings := liveOwned(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"}) // The rows of the previous import are tombstones that keep their id, the new // rows have new ids. The closed day and week are overwritten in place again. for _, collection := range []string{"entries", "settings_history", "balance_adjustments"} { var liveRows, tombstones int for _, r := range owned(t, app, collection, user.Id) { switch { case ids[r.Id]: wantBool(t, r, "deleted", true) wantInt(t, r, "rev", 2) tombstones++ case !r.GetBool("deleted"): liveRows++ } } if liveRows != imported[collection] || tombstones != len(all[collection]) { t.Errorf("%s: got %d live rows and %d tombstoned rows of the previous import, want %d and %d", collection, liveRows, tombstones, imported[collection], len(all[collection])) } } for _, r := range []*core.Record{oldDay, oldWeek} { rows := owned(t, app, r.Collection().Name, user.Id) if len(rows) != 1 || rows[0].Id != r.Id { t.Errorf("%s: got %d rows, want only the overwritten row %s", r.Collection().Name, len(rows), r.Id) continue } wantBool(t, rows[0], "deleted", false) wantInt(t, rows[0], "rev", 3) } } // A client only pulls changed rows, so rows it already pulled must be tombstoned // instead of deleted when the import replaces them. func TestImportTombstonesRowsTheClientPulled(t *testing.T) { app, user, _ := setup(t) path := createLegacy(t, "wal", legacySchema, legacyRows) // The settings row seeded at sign up and a closed day with the key of an imported row. seeded := seed(t, app, "settings_history", user.Id, map[string]any{ "effective_from": "2000-01-01", "hours_per_week": 40.0, "workdays_mask": 31, "timezone": "UTC", }) day := seed(t, app, "closed_days", user.Id, map[string]any{ "day_key": "2023-11-14", "worked_ms": 1, "kind": "vacation", "closed_at": 2, }) // A dry run leaves both rows alone. importLegacy(t, app, path, user.Id, "", true) for _, r := range []*core.Record{seeded, day} { got := load(t, app, r.Collection().Name, r.Id) wantBool(t, got, "deleted", false) wantInt(t, got, "rev", 1) wantInt(t, got, "client_updated_at", 1000) } before := time.Now().UnixMilli() importLegacy(t, app, path, user.Id, "", false) // The seeded settings row is a tombstone, the imported rows exist next to it. got := load(t, app, "settings_history", seeded.Id) wantBool(t, got, "deleted", true) wantInt(t, got, "rev", 2) if cua := got.GetInt64("client_updated_at"); cua < before { t.Errorf("tombstone client_updated_at is %d, want at least %d", cua, before) } live := liveOwned(t, app, "settings_history", user.Id) if len(live) != 2 { t.Fatalf("settings_history: got %d live rows, want the 2 imported ones", len(live)) } for _, r := range live { if r.Id == seeded.Id { t.Errorf("the seeded settings row %s is still live", seeded.Id) } wantInt(t, r, "rev", 1) } // Exactly one live closed day with the imported values, in the row the client // already knows. days := liveOwned(t, app, "closed_days", user.Id) if len(days) != 1 || days[0].Id != day.Id { t.Fatalf("closed_days: got %d live rows, want only the overwritten row %s", len(days), day.Id) } check := func(field string, want any) { t.Helper() var got any switch want.(type) { case string: got = days[0].GetString(field) case int64: got = days[0].GetInt64(field) } if got != want { t.Errorf("closed_days %s: %s is %v, want %v", day.Id, field, got, want) } } check("day_key", "2023-11-14") check("worked_ms", int64(3600000)) check("kind", "work") check("closed_at", int64(1700003600000)) check("rev", int64(2)) check("client_updated_at", int64(1700003600002)) // the legacy updated_at is newer than the existing one } 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 }