Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion migrator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |

Expand Down
2 changes: 1 addition & 1 deletion migrator/cmd/migrate/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 2 additions & 2 deletions migrator/cmd/migrate/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions migrator/cmd/migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ Commands:
status Print the applied/pending state of all migrations
generate <name> 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)
Expand Down
17 changes: 14 additions & 3 deletions migrator/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ package migrator

import (
"database/sql"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
}

Expand All @@ -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),
)
Expand Down
105 changes: 105 additions & 0 deletions migrator/migrator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"

_ "modernc.org/sqlite"
)
Expand Down Expand Up @@ -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)
}
}