Migrations from schema 30 on are one list (internal/db/migrations.go), written in SQLite's SQL and translated for Postgres (db.PostgresSQL) unless one gives its own. On Postgres the whole migration is one transaction under an advisory lock, and each step is recorded in schema_migrations. TestSchemasMatch compares the two schemas (tables, columns, types, NOT NULL, nocase, indexes), with and without a new migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
314 lines
9.3 KiB
Go
314 lines
9.3 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"slices"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestPostgresSQL(t *testing.T) {
|
|
in := `CREATE TABLE t (
|
|
id INTEGER PRIMARY KEY,
|
|
n INTEGER NOT NULL DEFAULT 0,
|
|
score REAL,
|
|
raw BLOB,
|
|
email TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
|
|
name TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
|
slug TEXT COLLATE NOCASE NOT NULL,
|
|
at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
|
PRIMARY KEY (n, name)
|
|
);
|
|
CREATE INDEX t_by_name ON t (name COLLATE NOCASE);
|
|
ALTER TABLE t ADD COLUMN size INTEGER NOT NULL DEFAULT 0;`
|
|
want := `CREATE TABLE t (
|
|
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
n BIGINT NOT NULL DEFAULT 0,
|
|
score DOUBLE PRECISION,
|
|
raw BYTEA,
|
|
email TEXT COLLATE nocase NOT NULL DEFAULT '',
|
|
name TEXT COLLATE nocase NOT NULL UNIQUE,
|
|
slug TEXT COLLATE nocase NOT NULL,
|
|
at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')),
|
|
PRIMARY KEY (n, name)
|
|
);
|
|
CREATE INDEX t_by_name ON t (name COLLATE nocase);
|
|
ALTER TABLE t ADD COLUMN size BIGINT NOT NULL DEFAULT 0;`
|
|
if got := PostgresSQL(in); got != want {
|
|
t.Errorf("got:\n%s\nwant:\n%s", got, want)
|
|
}
|
|
}
|
|
|
|
// withMigration adds a migration (schema 30, …) for one test.
|
|
func withMigration(t *testing.T, m Migration) {
|
|
t.Helper()
|
|
saved := both
|
|
both = append(slices.Clone(both), m)
|
|
t.Cleanup(func() { both = saved })
|
|
}
|
|
|
|
var testMigration = Migration{
|
|
Note: "test: a table",
|
|
SQLite: `CREATE TABLE test_widgets (
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL DEFAULT '' COLLATE NOCASE,
|
|
at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
|
);
|
|
CREATE INDEX test_widgets_by_name ON test_widgets (name);
|
|
ALTER TABLE settings ADD COLUMN test_flag INTEGER NOT NULL DEFAULT 0;`,
|
|
}
|
|
|
|
// A migration after schema 29 runs on SQLite, new and existing.
|
|
func TestMigrationOnSQLite(t *testing.T) {
|
|
dir := t.TempDir()
|
|
old, err := OpenSQLite(filepath.Join(dir, "old.db")) // at the current schema
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
old.Close()
|
|
withMigration(t, testMigration)
|
|
for _, name := range []string{"old.db", "new.db"} {
|
|
d, err := OpenSQLite(filepath.Join(dir, name))
|
|
if err != nil {
|
|
t.Fatal(name, err)
|
|
}
|
|
if v, _ := d.SchemaVersion(); v != Schema() {
|
|
t.Errorf("%s: schema %d, want %d", name, v, Schema())
|
|
}
|
|
if want := map[string]int{"old.db": Schema() - 1, "new.db": 0}[name]; d.MigratedFrom != want {
|
|
t.Errorf("%s: migrated from %d, want %d", name, d.MigratedFrom, want)
|
|
}
|
|
if _, err := d.Exec(`INSERT INTO test_widgets (name) VALUES ('A')`); err != nil {
|
|
t.Error(name, err)
|
|
}
|
|
var n int
|
|
if err := d.QueryRow(`SELECT count(*) FROM test_widgets WHERE name = 'a'`).Scan(&n); err != nil || n != 1 {
|
|
t.Errorf("%s: %d %v", name, n, err)
|
|
}
|
|
d.Close()
|
|
}
|
|
}
|
|
|
|
// pgTestSchema makes an empty schema in the test Postgres, and the
|
|
// address that opens it; it's dropped after the test.
|
|
func pgTestSchema(t *testing.T) string {
|
|
t.Helper()
|
|
base := os.Getenv(TestPostgres)
|
|
if base == "" {
|
|
t.Skip("set " + TestPostgres + " to test on Postgres")
|
|
}
|
|
admin, err := sql.Open("pgx", base)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
schema := fmt.Sprintf("test_m_%d", os.Getpid())
|
|
admin.Exec(`DROP SCHEMA IF EXISTS ` + schema + ` CASCADE`)
|
|
if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
|
|
admin.Close()
|
|
})
|
|
u, _ := url.Parse(base)
|
|
q := u.Query()
|
|
q.Set("search_path", schema)
|
|
u.RawQuery = q.Encode()
|
|
return u.String()
|
|
}
|
|
|
|
// A migration after schema 29 runs on Postgres, on a database made by an
|
|
// earlier version, and each step is recorded.
|
|
func TestMigrationOnPostgres(t *testing.T) {
|
|
addr := pgTestSchema(t)
|
|
d, err := OpenPostgres(addr) // made at the current schema
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if d.MigratedFrom != 0 {
|
|
t.Errorf("a new database was migrated from %d", d.MigratedFrom)
|
|
}
|
|
d.Close()
|
|
withMigration(t, testMigration)
|
|
d, err = OpenPostgres(addr)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer d.Close()
|
|
if v, _ := d.SchemaVersion(); v != Schema() || d.MigratedFrom != Schema()-1 {
|
|
t.Errorf("schema %d, migrated from %d", v, d.MigratedFrom)
|
|
}
|
|
if _, err := d.Exec(`INSERT INTO test_widgets (name) VALUES ('A')`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var n int
|
|
if err := d.QueryRow(`SELECT count(*) FROM test_widgets WHERE name = 'a' AND at LIKE '20%Z'`).Scan(&n); err != nil || n != 1 {
|
|
t.Errorf("%d %v", n, err)
|
|
}
|
|
var steps []string
|
|
rows, err := d.SQL.Query(`SELECT version, note FROM schema_migrations ORDER BY version`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for rows.Next() {
|
|
var v int
|
|
var note string
|
|
rows.Scan(&v, ¬e)
|
|
steps = append(steps, fmt.Sprint(v, " ", note))
|
|
}
|
|
rows.Close()
|
|
if len(steps) < 2 || !strings.HasPrefix(steps[0], "29 created") || steps[len(steps)-1] != fmt.Sprint(Schema(), " test: a table") {
|
|
t.Errorf("recorded: %q", steps)
|
|
}
|
|
|
|
// A migration that fails leaves the database as it was.
|
|
withMigration(t, Migration{Note: "test: broken", SQLite: `CREATE TABLE test_ok (id INTEGER); CREATE TABLE settings (x TEXT);`})
|
|
if _, err := OpenPostgres(addr); err == nil || !strings.Contains(err.Error(), "test: broken") {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
var exists bool
|
|
d.QueryRow(`SELECT to_regclass('test_ok') IS NOT NULL`).Scan(&exists)
|
|
if v, _ := d.SchemaVersion(); exists || v != Schema()-1 {
|
|
t.Errorf("after a failed migration: schema %d, test_ok %v", v, exists)
|
|
}
|
|
}
|
|
|
|
// column is one column of a table, as both databases can say it.
|
|
type column struct {
|
|
Name, Type string
|
|
NotNull bool
|
|
NoCase bool
|
|
}
|
|
|
|
// sqliteColumns are SQLite's tables and their columns.
|
|
func sqliteColumns(t *testing.T, d *DB) (map[string][]column, []string) {
|
|
t.Helper()
|
|
tables := map[string][]column{}
|
|
rows, err := d.SQL.Query(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defs := map[string]string{}
|
|
for rows.Next() {
|
|
var name, def string
|
|
rows.Scan(&name, &def)
|
|
defs[name] = def
|
|
}
|
|
rows.Close()
|
|
types := map[string]string{"INTEGER": "bigint", "TEXT": "text", "REAL": "double precision", "BLOB": "bytea"}
|
|
for name, def := range defs {
|
|
cols, err := d.SQL.Query(`SELECT name, type, "notnull", pk FROM pragma_table_info(?)`, name)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for cols.Next() {
|
|
var c column
|
|
var ty string
|
|
var notNull, pk int
|
|
cols.Scan(&c.Name, &ty, ¬Null, &pk)
|
|
c.Type = types[strings.ToUpper(ty)]
|
|
c.NotNull = notNull == 1 || pk > 0
|
|
// Its definition, up to the next column: does it ignore case?
|
|
re := regexp.MustCompile(`(?i)(?:^|[(,\n])\s*"?` + regexp.QuoteMeta(c.Name) + `"?\s+[^,\n]*COLLATE\s+NOCASE`)
|
|
c.NoCase = re.MatchString(def)
|
|
tables[name] = append(tables[name], c)
|
|
}
|
|
cols.Close()
|
|
}
|
|
var indexes []string
|
|
rows, err = d.SQL.Query(`SELECT name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for rows.Next() {
|
|
var n string
|
|
rows.Scan(&n)
|
|
indexes = append(indexes, n)
|
|
}
|
|
rows.Close()
|
|
slices.Sort(indexes)
|
|
return tables, indexes
|
|
}
|
|
|
|
// postgresColumns are Postgres' tables and their columns.
|
|
func postgresColumns(t *testing.T, d *DB) (map[string][]column, []string) {
|
|
t.Helper()
|
|
tables := map[string][]column{}
|
|
rows, err := d.SQL.Query(`SELECT table_name, column_name, data_type, is_nullable = 'NO', coalesce(collation_name, '') = 'nocase'
|
|
FROM information_schema.columns WHERE table_schema = current_schema()
|
|
AND table_name NOT IN ('schema_version', 'schema_migrations') ORDER BY table_name, ordinal_position`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for rows.Next() {
|
|
var table string
|
|
var c column
|
|
rows.Scan(&table, &c.Name, &c.Type, &c.NotNull, &c.NoCase)
|
|
tables[table] = append(tables[table], c)
|
|
}
|
|
rows.Close()
|
|
var indexes []string
|
|
rows, err = d.SQL.Query(`SELECT i.relname FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
|
|
JOIN pg_namespace n ON n.oid = i.relnamespace
|
|
WHERE n.nspname = current_schema() AND NOT x.indisprimary
|
|
AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = x.indexrelid)`)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for rows.Next() {
|
|
var n string
|
|
rows.Scan(&n)
|
|
indexes = append(indexes, n)
|
|
}
|
|
rows.Close()
|
|
slices.Sort(indexes)
|
|
return tables, indexes
|
|
}
|
|
|
|
// The two databases have the same schema: tables, columns in order, their
|
|
// types, NOT NULL, which ignore case, and named indexes. With a migration
|
|
// added too, as a new one would be.
|
|
func TestSchemasMatch(t *testing.T) {
|
|
for _, extra := range []bool{false, true} {
|
|
t.Run(fmt.Sprint("with a migration: ", extra), func(t *testing.T) {
|
|
addr := pgTestSchema(t)
|
|
if extra {
|
|
withMigration(t, testMigration)
|
|
}
|
|
lite, err := OpenSQLite(filepath.Join(t.TempDir(), "app.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer lite.Close()
|
|
pg, err := OpenPostgres(addr)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer pg.Close()
|
|
lt, li := sqliteColumns(t, lite)
|
|
pt, pi := postgresColumns(t, pg)
|
|
for name, cols := range lt {
|
|
if !slices.Equal(cols, pt[name]) {
|
|
t.Errorf("table %s:\n SQLite %v\n Postgres %v", name, cols, pt[name])
|
|
}
|
|
}
|
|
for name := range pt {
|
|
if _, ok := lt[name]; !ok {
|
|
t.Errorf("table %s is only on Postgres", name)
|
|
}
|
|
}
|
|
if !slices.Equal(li, pi) {
|
|
t.Errorf("indexes:\n SQLite %v\n Postgres %v", li, pi)
|
|
}
|
|
if len(lt) < 39 {
|
|
t.Errorf("only %d tables", len(lt))
|
|
}
|
|
})
|
|
}
|
|
}
|