diff --git a/internal/legacyimport/legacyimport.go b/internal/legacyimport/legacyimport.go index 648910e..55ced9c 100644 --- a/internal/legacyimport/legacyimport.go +++ b/internal/legacyimport/legacyimport.go @@ -17,6 +17,8 @@ import ( "github.com/pocketbase/pocketbase/core" "github.com/spf13/cobra" _ "modernc.org/sqlite" + + "github.com/wotra/wotra/internal/collections" ) // Summary reports the outcome of an import. @@ -35,8 +37,11 @@ func Register(app core.App, rootCmd *cobra.Command) { // Every imported row gets a new id, rev 1 and client_updated_at set to the // legacy updated_at. Rows that fail the PocketBase field validation are // skipped with a printed warning and counted in Summary.Skipped. Unless -// dryRun is set, all existing records of the owner in the synced collections -// are deleted and the mapped rows inserted in one transaction. +// dryRun is set, the existing records of the owner in the synced collections +// are replaced by the mapped rows in one transaction. Existing rows become +// tombstones so that the clients learn about the replacement, except closed +// days and weeks whose key an imported row has: they are overwritten in place +// because of their unique index. func Import(app core.App, db *sql.DB, owner string, tzOverride string, dryRun bool) (Summary, error) { var summary Summary if err := checkSchema(db); err != nil { @@ -86,18 +91,12 @@ func Import(app core.App, db *sql.DB, owner string, tzOverride string, dryRun bo } err := app.RunInTransaction(func(tx core.App) error { + now := time.Now().UnixMilli() for _, t := range tables { - if err := deleteOwned(tx, t.collection, owner); err != nil { + if err := replaceOwned(tx, t.collection, t.records, owner, now); err != nil { return err } } - for _, t := range tables { - for _, record := range t.records { - if err := tx.Save(record); err != nil { - return fmt.Errorf("insert %s: %w", t.collection, err) - } - } - } return nil }) if err != nil { @@ -395,19 +394,72 @@ func loadAdjustments(app core.App, db *sql.DB, owner string) ([]*core.Record, in }) } -func deleteOwned(tx core.App, collection, owner string) error { +// keyField names the field that identifies a row of a collection with a unique +// index per owner. The other synced collections have no such key. +var keyField = map[string]string{"closed_days": "day_key", "closed_weeks": "week_key"} + +// replaceOwned makes every existing record of the owner a tombstone and inserts +// the imported records of the collection. +// +// The existing rows are not hard deleted because clients only pull changed rows: +// a row they already have would never learn about the delete and survive as a +// ghost. A closed day or week whose key an imported record has is overwritten in +// place instead, because the unique (owner, day_key) and (owner, week_key) indexes +// leave no room for a second row with the same key. +func replaceOwned(tx core.App, collection string, imported []*core.Record, owner string, now int64) error { records, err := tx.FindAllRecords(collection, dbx.HashExp{"owner": owner}) if err != nil { return fmt.Errorf("find %s: %w", collection, err) } + key := keyField[collection] + byKey := make(map[string]*core.Record, len(imported)) + for _, r := range imported { + if key != "" { + byKey[r.GetString(key)] = r + } + } + + overwritten := make(map[*core.Record]bool) for _, record := range records { - if err := tx.Delete(record); err != nil { - return fmt.Errorf("delete %s %s: %w", collection, record.Id, err) + var match *core.Record + if key != "" { + match = byKey[record.GetString(key)] + } + if match != nil { + overwritten[match] = true + overwrite(record, match) + } else { + record.Set("deleted", true) + record.Set("client_updated_at", now) + } + record.Set("rev", record.GetInt("rev")+1) + if err := tx.Save(record); err != nil { + return fmt.Errorf("update %s %s: %w", collection, record.Id, err) + } + } + + for _, record := range imported { + if overwritten[record] { + continue + } + if err := tx.Save(record); err != nil { + return fmt.Errorf("insert %s: %w", collection, err) } } return nil } +// overwrite copies the data of the imported record onto record, which keeps its id. +// The client_updated_at is newer than the one of the client's copy of the row so +// that the client takes the imported values. +func overwrite(record, imported *core.Record) { + for _, field := range collections.DataFields[record.Collection().Name] { + record.Set(field, imported.GetRaw(field)) + } + record.Set("deleted", false) + record.Set("client_updated_at", max(imported.GetInt64("client_updated_at"), record.GetInt64("client_updated_at")+1)) +} + const legacyCopyName = "legacy.db" type legacyFile struct { diff --git a/internal/legacyimport/legacyimport_test.go b/internal/legacyimport/legacyimport_test.go index 4982592..3c07f5d 100644 --- a/internal/legacyimport/legacyimport_test.go +++ b/internal/legacyimport/legacyimport_test.go @@ -12,6 +12,7 @@ import ( "regexp" "strings" "testing" + "time" "github.com/pocketbase/dbx" "github.com/pocketbase/pocketbase/core" @@ -346,32 +347,96 @@ func captureWarnings(t *testing.T, fn func()) string { 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", }) - 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) { + existing := []*core.Record{stale, seeded, oldDay, oldWeek} + untouched := func() { t.Helper() - if got := counts(); !reflect.DeepEqual(got, want) { - t.Fatalf("counts: got %v, want %v", got, want) + 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")) } } - // dry run: reports the rows but writes nothing and deletes nothing + 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) @@ -379,53 +444,38 @@ func TestImport(t *testing.T) { 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}) + 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) } - // 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) - } + assertLive(imported) - 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 + // 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) - entries := all["entries"] + // 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 { @@ -445,6 +495,52 @@ func TestImport(t *testing.T) { } } } + 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, @@ -455,14 +551,8 @@ func TestImport(t *testing.T) { "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(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), @@ -480,8 +570,8 @@ func TestImport(t *testing.T) { 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 { + 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 @@ -497,20 +587,110 @@ func TestImport(t *testing.T) { 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) + 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"}) - for _, collection := range []string{"entries", "closed_days", "closed_weeks", "settings_history", "balance_adjustments"} { + + // 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) { - if ids[r.Id] { - t.Errorf("%s %s: id of the previous import was reused", collection, r.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) {