From a495d940532e448785ea5fd1271d6f095256b9d1 Mon Sep 17 00:00:00 2001 From: Thanikan Date: Fri, 27 Nov 2026 10:25:05 +0530 Subject: [PATCH] fix(migrator): write SQLite applied_at in SQLite's format and rename the default database modernc.org/sqlite writes a Go time.Time as "2006-01-02 15:04:05 +0000 UTC", which SQLite's date functions can't read, so datetime(applied_at) was NULL. apply writes SQLite's own format for the sqlite driver, as agency's migrator did; PostgreSQL still gets a time.Time. The default SQLite path is ./migrator.db, the usage text and each file generate writes link to the migrator README, and generate creates a missing migrations directory again: the not-exist check didn't see through the wrapped error from loadFiles. --- migrator/README.md | 2 +- migrator/cmd/migrate/config.go | 2 +- migrator/cmd/migrate/config_test.go | 4 +- migrator/cmd/migrate/main.go | 5 +- migrator/migrator.go | 17 ++++- migrator/migrator_test.go | 105 ++++++++++++++++++++++++++++ 6 files changed, 126 insertions(+), 9 deletions(-) diff --git a/migrator/README.md b/migrator/README.md index 92d2e07..8680824 100644 --- a/migrator/README.md +++ b/migrator/README.md @@ -39,7 +39,7 @@ migrationDir: ./migrations | Field | Default | |-----------------------|----------------------------| | `db.driver` | `sqlite` | -| `db.sqlite.path` | `./agency_applications.db` | +| `db.sqlite.path` | `./migrator.db` | | `db.postgres.sslMode` | `require` | | `migrationDir` | `./migrations` | diff --git a/migrator/cmd/migrate/config.go b/migrator/cmd/migrate/config.go index 4613db2..6d2fea1 100644 --- a/migrator/cmd/migrate/config.go +++ b/migrator/cmd/migrate/config.go @@ -42,7 +42,7 @@ func LoadConfig() (Config, error) { cfg.DB.SQLite = &database.SQLiteConfig{} } if cfg.DB.SQLite.Path == "" { - cfg.DB.SQLite.Path = "./agency_applications.db" + cfg.DB.SQLite.Path = "./migrator.db" } if cfg.DB.Postgres != nil && cfg.DB.Postgres.SSLMode == "" { cfg.DB.Postgres.SSLMode = "require" diff --git a/migrator/cmd/migrate/config_test.go b/migrator/cmd/migrate/config_test.go index 0604dcd..a8c12fd 100644 --- a/migrator/cmd/migrate/config_test.go +++ b/migrator/cmd/migrate/config_test.go @@ -32,8 +32,8 @@ func TestLoadConfig_Defaults(t *testing.T) { if err != nil { t.Fatalf("expected no error, got %v", err) } - if cfg.DB.SQLite.Path != "./agency_applications.db" { - t.Errorf("DB.Path = %q, want ./agency_applications.db", cfg.DB.SQLite.Path) + if cfg.DB.SQLite.Path != "./migrator.db" { + t.Errorf("DB.Path = %q, want ./migrator.db", cfg.DB.SQLite.Path) } if cfg.Dir != "./migrations" { t.Errorf("Dir = %q, want ./migrations", cfg.Dir) diff --git a/migrator/cmd/migrate/main.go b/migrator/cmd/migrate/main.go index 375ff95..f38daaf 100644 --- a/migrator/cmd/migrate/main.go +++ b/migrator/cmd/migrate/main.go @@ -84,8 +84,9 @@ Commands: status Print the applied/pending state of all migrations generate Create a new migration file with the next version number -Configuration is read from a YAML file (see backend/config.example.yaml for -the full schema — this command only reads its db and migrationDir fields): +Configuration is read from the YAML file named by CONFIG_PATH. The command +uses only its db and migrationDir fields; their shape and defaults are in +https://github.com/OpenNSW/tools/tree/main/migrator#configuration Environment variables: CONFIG_PATH Path to the config.yaml file (default: ./config.yaml) diff --git a/migrator/migrator.go b/migrator/migrator.go index 4e9cd3d..0f601c1 100644 --- a/migrator/migrator.go +++ b/migrator/migrator.go @@ -5,7 +5,9 @@ package migrator import ( "database/sql" + "errors" "fmt" + "io/fs" "os" "path/filepath" "sort" @@ -20,6 +22,11 @@ type Migrator struct { driver string // "sqlite" or "postgres" } +// sqliteTimeLayout is SQLite's own date and time format. SQLite has no date +// type, so apply writes applied_at as text in this format, which SQLite's +// date functions read. +const sqliteTimeLayout = "2006-01-02 15:04:05.999999999-07:00" + type migrationRecord struct { version int64 name string @@ -221,13 +228,16 @@ func (m *Migrator) apply(mg *Migration) error { } } + now := time.Now().UTC() var insertQ string + var appliedAt any = now if m.driver == "postgres" { insertQ = `INSERT INTO __migrations (version, name, applied_at) VALUES ($1, $2, $3)` } else { insertQ = `INSERT INTO __migrations (version, name, applied_at) VALUES (?, ?, ?)` + appliedAt = now.Format(sqliteTimeLayout) } - if _, err := tx.Exec(insertQ, mg.Version, mg.Name, time.Now().UTC()); err != nil { + if _, err := tx.Exec(insertQ, mg.Version, mg.Name, appliedAt); err != nil { return err } return tx.Commit() @@ -268,7 +278,7 @@ func (m *Migrator) rollback(mg *Migration) error { // -- @UP and -- @DOWN block stubs. func (m *Migrator) Generate(name string) error { migrations, err := m.loadFiles() - if err != nil && !os.IsNotExist(err) { + if err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("reading migration dir: %w", err) } @@ -283,7 +293,8 @@ func (m *Migrator) Generate(name string) error { content := fmt.Sprintf( "-- Created at: %s\n"+ "-- Need Postgres- or SQLite-only SQL? Nest -- @postgres / -- @sqlite blocks\n"+ - "-- inside @UP or @DOWN -- see docs/migrations.md.\n\n"+ + "-- inside @UP or @DOWN: see\n"+ + "-- https://github.com/OpenNSW/tools/tree/main/migrator#driver-specific-sql\n\n"+ "-- @UP\n\n\n-- @DOWN\n\n", time.Now().UTC().Format(time.RFC3339), ) diff --git a/migrator/migrator_test.go b/migrator/migrator_test.go index 4b2efac..8aa22f7 100644 --- a/migrator/migrator_test.go +++ b/migrator/migrator_test.go @@ -8,7 +8,9 @@ import ( "os" "path/filepath" "reflect" + "strings" "testing" + "time" _ "modernc.org/sqlite" ) @@ -242,3 +244,106 @@ func TestUp_RollsBackOnFailure(t *testing.T) { t.Errorf("__migrations count = %d, want 0 after failed migration", count) } } + +// SQLite has no date type, so applied_at is text. It must be in SQLite's own +// format, which SQLite's date functions read, and the migrator must read it +// back as a time. +func TestUp_SQLiteAppliedAtFormat(t *testing.T) { + m, db := newTestMigrator(t, map[string]string{ + "000001_create_foo.sql": "-- @UP\nCREATE TABLE foo (id INTEGER PRIMARY KEY);\n-- @DOWN\nDROP TABLE foo;", + }) + + before := time.Now().UTC().Add(-time.Second) + if err := m.Up(); err != nil { + t.Fatalf("Up() error = %v", err) + } + after := time.Now().UTC().Add(time.Second) + + // "|| ''" makes the driver return the stored text, not a parsed time. + var raw string + var sqliteTime sql.NullString + if err := db.QueryRow(`SELECT applied_at || '', datetime(applied_at) FROM __migrations WHERE version = 1`).Scan(&raw, &sqliteTime); err != nil { + t.Fatal(err) + } + stored, err := time.Parse(sqliteTimeLayout, raw) + if err != nil { + t.Fatalf("applied_at %q is not in SQLite's format: %v", raw, err) + } + if !strings.HasSuffix(raw, "+00:00") { + t.Errorf("applied_at %q, want a UTC time ending in +00:00", raw) + } + if stored.Before(before) || stored.After(after) { + t.Errorf("applied_at = %v, want between %v and %v", stored, before, after) + } + if !sqliteTime.Valid { + t.Errorf("datetime(applied_at) is NULL for applied_at %q", raw) + } + + records, err := m.appliedMigrations() + if err != nil { + t.Fatalf("appliedMigrations() error = %v", err) + } + if got := records[1].appliedAt; !got.Equal(stored) { + t.Errorf("appliedMigrations()[1].appliedAt = %v, want %v", got, stored) + } +} + +// A row in the format agency's migrator wrote still reads back. +func TestAppliedMigrations_ReadsSQLiteFormat(t *testing.T) { + m, db := newTestMigrator(t, nil) + if err := m.initTable(); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO __migrations (version, name, applied_at) VALUES (1, 'create_foo', '2026-11-27 04:41:15.916498+00:00')`); err != nil { + t.Fatal(err) + } + + records, err := m.appliedMigrations() + if err != nil { + t.Fatalf("appliedMigrations() error = %v", err) + } + want := time.Date(2026, 11, 27, 4, 41, 15, 916498000, time.UTC) + if got := records[1].appliedAt; !got.Equal(want) { + t.Errorf("appliedAt = %v, want %v", got, want) + } +} + +func TestGenerate_WritesNextVersionWithStubs(t *testing.T) { + m, _ := newTestMigrator(t, map[string]string{ + "000001_create_foo.sql": "-- @UP\nCREATE TABLE foo (id INTEGER PRIMARY KEY);\n-- @DOWN\nDROP TABLE foo;", + }) + + if err := m.Generate("add_bar"); err != nil { + t.Fatalf("Generate() error = %v", err) + } + + content, err := os.ReadFile(filepath.Join(m.dir, "000002_add_bar.sql")) + if err != nil { + t.Fatalf("reading the generated file: %v", err) + } + for _, want := range []string{ + "-- @UP\n", + "-- @DOWN\n", + "https://github.com/OpenNSW/tools/tree/main/migrator#driver-specific-sql", + } { + if !strings.Contains(string(content), want) { + t.Errorf("generated file does not contain %q:\n%s", want, content) + } + } +} + +// generate needs no existing directory: it creates it and starts at 000001. +func TestGenerate_CreatesDirAndStartsAtOne(t *testing.T) { + dir := filepath.Join(t.TempDir(), "migrations") + m, err := New(nil, dir, "sqlite") + if err != nil { + t.Fatal(err) + } + + if err := m.Generate("init"); err != nil { + t.Fatalf("Generate() error = %v", err) + } + if _, err := os.Stat(filepath.Join(dir, "000001_init.sql")); err != nil { + t.Errorf("000001_init.sql not created: %v", err) + } +}