Phase 9, part 2: one database layer for SQLite and Postgres

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>
This commit is contained in:
2026-11-25 07:10:44 -07:00
co-authored by Claude Opus 5.5
parent 7a857c7346
commit 1b2947de7c
32 changed files with 1188 additions and 69 deletions
+162
View File
@@ -0,0 +1,162 @@
package db
import (
"crypto/rand"
"database/sql"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"net/url"
"os"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
// pgSchema is the whole schema at pgBaseline, for a new Postgres database.
//
//go:embed postgres.sql
var pgSchema string
// pgBaseline is the SQLite schema version postgres.sql matches.
const pgBaseline = 29
// OpenPostgres opens the Postgres database at url (postgres://…), creating
// the schema in an empty one.
func OpenPostgres(url string) (*DB, error) {
sqldb, err := sql.Open("pgx", url)
if err != nil {
return nil, err
}
sqldb.SetMaxOpenConns(20)
sqldb.SetMaxIdleConns(5)
sqldb.SetConnMaxIdleTime(5 * time.Minute)
if err := sqldb.Ping(); err != nil {
sqldb.Close()
return nil, fmt.Errorf("opening Postgres: %w", err)
}
d := &DB{SQL: sqldb, Dialect: Postgres}
if err := d.migratePostgres(); err != nil {
sqldb.Close()
return nil, err
}
return d, nil
}
// migratePostgres creates the schema in an empty database, and checks an
// existing one isn't newer than this version knows. One copy of the app
// at a time does it (an advisory lock), so several can start together.
func (d *DB) migratePostgres() error {
tx, err := d.SQL.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421)`); err != nil { // any fixed number: "the schema"
return err
}
var exists bool
if err := tx.QueryRow(`SELECT to_regclass('schema_version') IS NOT NULL`).Scan(&exists); err != nil {
return err
}
if !exists {
if _, err := tx.Exec(pgSchema); err != nil {
return fmt.Errorf("creating the schema: %w", err)
}
if _, err := tx.Exec(`CREATE TABLE schema_version (version integer NOT NULL)`); err != nil {
return err
}
if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES ($1)`, pgBaseline); err != nil {
return err
}
return tx.Commit()
}
var version int
if err := tx.QueryRow(`SELECT version FROM schema_version`).Scan(&version); err != nil {
return err
}
if version > Schema() {
return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, Schema())
}
if version < Schema() {
return fmt.Errorf("the database is at schema %d and this version needs %d, but Postgres has no migrations past %d yet", version, Schema(), pgBaseline)
}
return tx.Commit()
}
// SchemaVersion is the database's schema version.
func (d *DB) SchemaVersion() (int, error) {
var v int
if d.Dialect == Postgres {
err := d.SQL.QueryRow(`SELECT version FROM schema_version`).Scan(&v)
return v, err
}
err := d.SQL.QueryRow(`PRAGMA user_version`).Scan(&v)
return v, err
}
// TestPostgres, set to a Postgres address, makes Open give each test its
// own new schema in that database instead of a SQLite file, so the whole
// suite runs on Postgres:
//
// SUPERMARKET_TEST_POSTGRES=postgres://postgres:test@localhost:55432/sm go test ./...
//
// The schema is dropped when the test closes the database.
const TestPostgres = "SUPERMARKET_TEST_POSTGRES"
// openTestSchema opens a new, empty schema in the test database.
func openTestSchema(base string) (*DB, error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, err
}
schema := "test_" + hex.EncodeToString(b)
admin, err := sql.Open("pgx", base)
if err != nil {
return nil, err
}
if _, err := admin.Exec(`CREATE SCHEMA ` + schema); err != nil {
admin.Close()
return nil, err
}
u, err := url.Parse(base)
if err != nil {
admin.Close()
return nil, err
}
q := u.Query()
q.Set("search_path", schema)
u.RawQuery = q.Encode()
d, err := OpenPostgres(u.String())
if err != nil {
admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
admin.Close()
return nil, err
}
d.SQL.SetMaxOpenConns(4)
d.closeHook = func() error {
defer admin.Close()
_, err := admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
return err
}
return d, nil
}
// testPostgres is the test database's address, when tests run on Postgres.
func testPostgres() string {
if !testing.Testing() {
return ""
}
return os.Getenv(TestPostgres)
}
// OnPostgres says whether tests are running on Postgres, for the few that
// test SQLite itself (backups).
func OnPostgres() bool { return testPostgres() != "" }
var errSQLiteOnly = errors.New("this works only on the local edition's SQLite database")
// SQLiteOnly is the error for what only works on SQLite.
func SQLiteOnly() error { return errSQLiteOnly }