db.DB wraps database/sql for either database. The SQL stays SQLite's: on Postgres each statement's ? become $n and LIKE ignores case as SQLite's does, and the Postgres schema (postgres.sql, schema 29 as a whole) adds SQLite's instr, json_extract and two-argument max/min, and a nocase ICU collation. Needs Postgres 18. LastInsertId became db.Insert (RETURNING id), INSERT OR IGNORE became ON CONFLICT DO NOTHING, upserts qualify their columns, and three queries group by every column they use. SUPERMARKET_TEST_POSTGRES runs the test suite on Postgres, a new schema per test; all tests pass on both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
62 lines
1.7 KiB
Go
62 lines
1.7 KiB
Go
package db
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestBeforeMigrate(t *testing.T) {
|
|
defer func() { BeforeMigrate = nil }()
|
|
var calls []string
|
|
BeforeMigrate = func(d *sql.DB, from, to int) error {
|
|
var n int
|
|
d.QueryRow(`PRAGMA user_version`).Scan(&n)
|
|
calls = append(calls, fmt.Sprintf("%d→%d at %d", from, to, n))
|
|
return nil
|
|
}
|
|
dir := t.TempDir()
|
|
// A new database: nothing to back up.
|
|
d, err := OpenSQLite(filepath.Join(dir, "new.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d.Close()
|
|
// Already current: nothing either.
|
|
d, _ = OpenSQLite(filepath.Join(dir, "new.db"))
|
|
d.Close()
|
|
if len(calls) != 0 {
|
|
t.Fatalf("called for a new or current database: %v", calls)
|
|
}
|
|
// One migration behind: backed up first, before the migration runs.
|
|
old := filepath.Join(dir, "old.db")
|
|
raw, _ := sql.Open("sqlite", "file:"+old)
|
|
for _, m := range migrations[:len(migrations)-1] {
|
|
if _, err := raw.Exec(m); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
|
|
raw.Close()
|
|
d, err = OpenSQLite(old)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d.Close()
|
|
want := fmt.Sprintf("%d→%d at %d", len(migrations)-1, len(migrations), len(migrations)-1)
|
|
if len(calls) != 1 || calls[0] != want || Schema() != len(migrations) {
|
|
t.Errorf("calls: %v, want %s", calls, want)
|
|
}
|
|
// A failed backup stops the migration.
|
|
raw, _ = sql.Open("sqlite", "file:"+old)
|
|
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
|
|
raw.Close()
|
|
BeforeMigrate = func(*sql.DB, int, int) error { return errors.New("disk full") }
|
|
if _, err := OpenSQLite(old); err == nil || !strings.Contains(err.Error(), "disk full") {
|
|
t.Errorf("open: %v", err)
|
|
}
|
|
}
|