diff --git a/internal/legacyimport/legacyimport.go b/internal/legacyimport/legacyimport.go index 064713a..648910e 100644 --- a/internal/legacyimport/legacyimport.go +++ b/internal/legacyimport/legacyimport.go @@ -1,9 +1,530 @@ +// Package legacyimport copies the legacy wotra SQLite database into the +// PocketBase records of a single user. package legacyimport import ( + "database/sql" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + "github.com/pocketbase/dbx" "github.com/pocketbase/pocketbase/core" "github.com/spf13/cobra" + _ "modernc.org/sqlite" ) +// Summary reports the outcome of an import. +type Summary struct { + Entries, ClosedDays, ClosedWeeks, Settings, Adjustments int // imported rows + Skipped int // invalid legacy rows +} + // Register adds the import-legacy command to the root command. -func Register(app core.App, rootCmd *cobra.Command) {} +func Register(app core.App, rootCmd *cobra.Command) { + rootCmd.AddCommand(newImportCommand(app)) +} + +// Import copies the legacy rows in db into the records of owner. +// +// 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. +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 { + return summary, err + } + + type table struct { + collection string + records []*core.Record + } + loaders := []struct { + collection string + imported *int + load func() ([]*core.Record, int, error) + }{ + {"settings_history", &summary.Settings, func() ([]*core.Record, int, error) { + return loadSettings(app, db, owner, tzOverride) + }}, + {"entries", &summary.Entries, func() ([]*core.Record, int, error) { + return loadEntries(app, db, owner) + }}, + {"closed_days", &summary.ClosedDays, func() ([]*core.Record, int, error) { + return loadClosedDays(app, db, owner) + }}, + {"closed_weeks", &summary.ClosedWeeks, func() ([]*core.Record, int, error) { + return loadClosedWeeks(app, db, owner) + }}, + {"balance_adjustments", &summary.Adjustments, func() ([]*core.Record, int, error) { + return loadAdjustments(app, db, owner) + }}, + } + + // the insert order: settings first, then the data that depends on them + var tables []table + for _, l := range loaders { + records, skipped, err := l.load() + if err != nil { + return Summary{}, err + } + *l.imported = len(records) + summary.Skipped += skipped + tables = append(tables, table{l.collection, records}) + } + + if dryRun { + return summary, nil + } + + err := app.RunInTransaction(func(tx core.App) error { + for _, t := range tables { + if err := deleteOwned(tx, t.collection, owner); 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 { + return Summary{}, err + } + return summary, nil +} + +func newImportCommand(app core.App) *cobra.Command { + command := &cobra.Command{ + Use: "import-legacy --db --email
[--tz ] [--dry-run]", + Short: "Import the legacy wotra.db into the records of one user", + Long: `Import the legacy wotra.db into the PocketBase records of one user. + +The legacy file is only read, never modified. The import replaces every +existing record of the user, so running it again does not duplicate rows.`, + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(command *cobra.Command, args []string) error { + return runImport(app, command) + }, + } + flags := command.Flags() + flags.String("db", "", "path to the legacy SQLite database") + flags.String("email", "", "email of the user to import for") + flags.String("tz", "", "IANA time zone written into every imported settings row") + flags.Bool("dry-run", false, "only print what would be imported") + _ = command.MarkFlagRequired("db") + _ = command.MarkFlagRequired("email") + return command +} + +func runImport(app core.App, command *cobra.Command) error { + dbPath, _ := command.Flags().GetString("db") + email, _ := command.Flags().GetString("email") + tz, _ := command.Flags().GetString("tz") + dryRun, _ := command.Flags().GetBool("dry-run") + + if !app.IsBootstrapped() { + if err := app.Bootstrap(); err != nil { + return err + } + } + tz = strings.TrimSpace(tz) + if tz != "" { + if _, err := time.LoadLocation(tz); err != nil { + return fmt.Errorf("invalid --tz %q: %w", tz, err) + } + } + email = strings.ToLower(strings.TrimSpace(email)) + user, err := findUser(app, email) + if err != nil { + return err + } + + legacy, err := openLegacy(dbPath) + if err != nil { + return err + } + defer legacy.Close() + + summary, err := Import(app, legacy.db, user.Id, tz, dryRun) + if err != nil { + return err + } + printSummary(command.OutOrStdout(), summary, dryRun) + return nil +} + +func findUser(app core.App, email string) (*core.Record, error) { + user, err := app.FindFirstRecordByData("users", "email", email) + if errors.Is(err, sql.ErrNoRows) { + // PocketBase stores the email as it was typed, so a user who signed + // up with upper case letters is only found by a case-insensitive match. + user = &core.Record{} + err = app.RecordQuery("users"). + AndWhere(dbx.NewExp("[[email]] = {:email} COLLATE NOCASE", dbx.Params{"email": email})). + Limit(1). + One(user) + } + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("no user with email %q, sign up in the app first", email) + } + if err != nil { + return nil, err + } + return user, nil +} + +func printSummary(w io.Writer, summary Summary, dryRun bool) { + status := "imported" + if dryRun { + status = "dry run, nothing written" + } + lines := []struct { + name string + count int + }{ + {"settings_history", summary.Settings}, + {"entries", summary.Entries}, + {"closed_days", summary.ClosedDays}, + {"closed_weeks", summary.ClosedWeeks}, + {"balance_adjustments", summary.Adjustments}, + } + for _, line := range lines { + fmt.Fprintf(w, "%-20s %d %s\n", line.name, line.count, status) + } + if summary.Skipped > 0 { + fmt.Fprintf(w, "skipped %d invalid legacy rows, see the warnings above\n", summary.Skipped) + } +} + +var warnf = func(format string, a ...any) { + fmt.Fprintf(os.Stderr, "warning: "+format+"\n", a...) +} + +var legacyTables = []string{"entries", "closed_days", "closed_weeks", "settings_history", "balance_adjustments"} + +func checkSchema(db *sql.DB) error { + for _, name := range legacyTables { + var n int + err := db.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?`, name).Scan(&n) + if err != nil { + return fmt.Errorf("read legacy schema: %w", err) + } + if n == 0 { + return fmt.Errorf("legacy database has no %s table, start the old wotra once to upgrade it", name) + } + } + + rows, err := db.Query(`SELECT name FROM pragma_table_info('settings_history')`) + if err != nil { + return fmt.Errorf("read legacy schema: %w", err) + } + defer rows.Close() + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return fmt.Errorf("read legacy schema: %w", err) + } + if name == "updated_at" { + return rows.Close() + } + } + if err := rows.Err(); err != nil { + return fmt.Errorf("read legacy schema: %w", err) + } + return errors.New("legacy database predates migration 003, start the old wotra once to upgrade it") +} + +func mapRows(app core.App, db *sql.DB, collection, query string, mapRow func(*core.Collection, *sql.Rows) (*core.Record, string, error)) ([]*core.Record, int, error) { + // rows that cannot be read or that fail the PocketBase field validation + // are skipped with a warning and counted in the second return value + col, err := app.FindCachedCollectionByNameOrId(collection) + if err != nil { + return nil, 0, err + } + rows, err := db.Query(query) + if err != nil { + return nil, 0, err + } + defer rows.Close() + + var records []*core.Record + skipped := 0 + for n := 1; rows.Next(); n++ { + record, key, err := mapRow(col, rows) + if err == nil { + err = app.Validate(record) + } + if err != nil { + skipped++ + // PocketBase appends a period to every validation message + warnf("skipped legacy %s row %d%s: %s", collection, n, key, strings.TrimSuffix(err.Error(), ".")) + continue + } + records = append(records, record) + } + return records, skipped, rows.Err() +} + +func newRecord(col *core.Collection, owner string, updatedAt int64, deleted bool) *core.Record { + r := core.NewRecord(col) + r.Id = core.GenerateDefaultRandomId() + r.Set("owner", owner) + r.Set("client_updated_at", updatedAt) + r.Set("rev", 1) + r.Set("deleted", deleted) + return r +} + +func loadSettings(app core.App, db *sql.DB, owner string, tzOverride string) ([]*core.Record, int, error) { + return mapRows(app, db, "settings_history", ` + SELECT id, effective_from, hours_per_week, workdays_mask, timezone, updated_at + FROM settings_history + ORDER BY effective_from, id`, + func(col *core.Collection, rows *sql.Rows) (*core.Record, string, error) { + var id, effectiveFrom, timezone sql.NullString + var hours sql.NullFloat64 + var mask, updatedAt sql.NullInt64 + if err := rows.Scan(&id, &effectiveFrom, &hours, &mask, &timezone, &updatedAt); err != nil { + return nil, "", err + } + tz := timezone.String + if tzOverride != "" { + tz = tzOverride + } + r := newRecord(col, owner, updatedAt.Int64, false) + r.Set("effective_from", effectiveFrom.String) + r.Set("hours_per_week", hours.Float64) + r.Set("workdays_mask", mask.Int64) + r.Set("timezone", tz) + return r, fmt.Sprintf(" (id %q)", id.String), nil + }) +} + +func loadEntries(app core.App, db *sql.DB, owner string) ([]*core.Record, int, error) { + return mapRows(app, db, "entries", ` + SELECT id, start_time, end_time, auto_stopped, note, day_key, updated_at, deleted_at + FROM entries + ORDER BY start_time, id`, + func(col *core.Collection, rows *sql.Rows) (*core.Record, string, error) { + var id, note, dayKey sql.NullString + var start, end, autoStopped, updatedAt, deletedAt sql.NullInt64 + if err := rows.Scan(&id, &start, &end, &autoStopped, ¬e, &dayKey, &updatedAt, &deletedAt); err != nil { + return nil, "", err + } + r := newRecord(col, owner, updatedAt.Int64, deletedAt.Valid) + r.Set("start_time", start.Int64) + r.Set("end_time", end.Int64) + r.Set("auto_stopped", autoStopped.Int64 != 0) + r.Set("note", note.String) + r.Set("day_key", dayKey.String) + return r, fmt.Sprintf(" (id %q)", id.String), nil + }) +} + +func loadClosedDays(app core.App, db *sql.DB, owner string) ([]*core.Record, int, error) { + return mapRows(app, db, "closed_days", ` + SELECT day_key, worked_ms, kind, closed_at, updated_at + FROM closed_days + ORDER BY day_key`, + func(col *core.Collection, rows *sql.Rows) (*core.Record, string, error) { + var dayKey, kind sql.NullString + var workedMs, closedAt, updatedAt sql.NullInt64 + if err := rows.Scan(&dayKey, &workedMs, &kind, &closedAt, &updatedAt); err != nil { + return nil, "", err + } + r := newRecord(col, owner, updatedAt.Int64, false) + r.Set("day_key", dayKey.String) + r.Set("worked_ms", workedMs.Int64) + r.Set("kind", kind.String) + r.Set("closed_at", closedAt.Int64) + return r, fmt.Sprintf(" (day_key %q)", dayKey.String), nil + }) +} + +func loadClosedWeeks(app core.App, db *sql.DB, owner string) ([]*core.Record, int, error) { + return mapRows(app, db, "closed_weeks", ` + SELECT week_key, expected_ms, worked_ms, delta_ms, closed_at, updated_at + FROM closed_weeks + ORDER BY week_key`, + func(col *core.Collection, rows *sql.Rows) (*core.Record, string, error) { + var weekKey sql.NullString + var expectedMs, workedMs, deltaMs, closedAt, updatedAt sql.NullInt64 + if err := rows.Scan(&weekKey, &expectedMs, &workedMs, &deltaMs, &closedAt, &updatedAt); err != nil { + return nil, "", err + } + r := newRecord(col, owner, updatedAt.Int64, false) + r.Set("week_key", weekKey.String) + r.Set("expected_ms", expectedMs.Int64) + r.Set("worked_ms", workedMs.Int64) + r.Set("delta_ms", deltaMs.Int64) + r.Set("closed_at", closedAt.Int64) + return r, fmt.Sprintf(" (week_key %q)", weekKey.String), nil + }) +} + +func loadAdjustments(app core.App, db *sql.DB, owner string) ([]*core.Record, int, error) { + return mapRows(app, db, "balance_adjustments", ` + SELECT id, delta_ms, note, effective_at, updated_at + FROM balance_adjustments + ORDER BY effective_at, id`, + func(col *core.Collection, rows *sql.Rows) (*core.Record, string, error) { + var id, note sql.NullString + var deltaMs, effectiveAt, updatedAt sql.NullInt64 + if err := rows.Scan(&id, &deltaMs, ¬e, &effectiveAt, &updatedAt); err != nil { + return nil, "", err + } + r := newRecord(col, owner, updatedAt.Int64, false) + r.Set("delta_ms", deltaMs.Int64) + r.Set("note", note.String) + r.Set("effective_at", effectiveAt.Int64) + return r, fmt.Sprintf(" (id %q)", id.String), nil + }) +} + +func deleteOwned(tx core.App, collection, owner string) error { + records, err := tx.FindAllRecords(collection, dbx.HashExp{"owner": owner}) + if err != nil { + return fmt.Errorf("find %s: %w", collection, err) + } + for _, record := range records { + if err := tx.Delete(record); err != nil { + return fmt.Errorf("delete %s %s: %w", collection, record.Id, err) + } + } + return nil +} + +const legacyCopyName = "legacy.db" + +type legacyFile struct { + db *sql.DB + tmpDir string // set when a temporary copy is read instead of the user's file +} + +func (f *legacyFile) Close() error { + err := f.db.Close() + if f.tmpDir != "" { + err = errors.Join(err, os.RemoveAll(f.tmpDir)) + } + return err +} + +func openLegacy(path string) (*legacyFile, error) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + if _, err := os.Stat(abs); err != nil { + return nil, fmt.Errorf("legacy database: %w", err) + } + + // SQLite has to create -wal/-shm files next to a WAL mode database unless + // it is told that the file is immutable. That is only safe when nothing + // writes to it, in which case sidecar files would exist. + db, err := openVerified(readOnlyDSN(abs, !hasSidecars(abs))) + if err == nil { + return &legacyFile{db: db}, nil + } + + // The file cannot be read in place (for example un-checkpointed WAL data + // on read-only media): read a temporary copy instead. + tmpDir, err := copyLegacy(abs) + if err != nil { + return nil, err + } + db, copyErr := openVerified(filepath.Join(tmpDir, legacyCopyName)) + if copyErr != nil { + _ = os.RemoveAll(tmpDir) + return nil, errors.Join(err, copyErr) + } + return &legacyFile{db: db, tmpDir: tmpDir}, nil +} + +func readOnlyDSN(path string, immutable bool) string { + p := filepath.ToSlash(path) + if !strings.HasPrefix(p, "/") { + p = "/" + p // Windows drive letter + } + dsn := url.URL{Scheme: "file", Path: p, RawQuery: "mode=ro"} + if immutable { + dsn.RawQuery += "&immutable=1" + } + return dsn.String() +} + +func openVerified(dsn string) (*sql.DB, error) { + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + // sql.Open does not touch the file, the first query does. + var n int + if err := db.QueryRow(`SELECT count(*) FROM sqlite_master`).Scan(&n); err != nil { + _ = db.Close() + return nil, err + } + return db, nil +} + +func hasSidecars(path string) bool { + for _, suffix := range []string{"-wal", "-shm", "-journal"} { + if fileExists(path + suffix) { + return true + } + } + return false +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +func copyLegacy(path string) (string, error) { + dir, err := os.MkdirTemp("", "wotra-import-legacy-") + if err != nil { + return "", err + } + for _, suffix := range []string{"", "-wal", "-shm", "-journal"} { + if !fileExists(path + suffix) { + continue + } + if err := copyFile(path+suffix, filepath.Join(dir, legacyCopyName+suffix)); err != nil { + _ = os.RemoveAll(dir) + return "", err + } + } + return dir, nil +} + +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + out, err := os.Create(dst) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + _ = out.Close() + return err + } + return out.Close() +}