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
+14 -7
View File
@@ -685,12 +685,7 @@ CREATE TABLE list_members (
`,
}
// DB wraps the database with the settings helpers every package uses.
type DB struct {
*sql.DB
}
// Open opens (creating if needed) the database at path and migrates it.
// BeforeMigrate, if set, runs before an existing database is migrated to
// a newer schema (from and to are the schema versions): the app backs it
// up. A new, empty database isn't backed up.
@@ -699,7 +694,19 @@ var BeforeMigrate func(d *sql.DB, from, to int) error
// Schema is the schema version this build migrates databases to.
func Schema() int { return len(migrations) }
// Open opens (creating if needed) the SQLite database at path and
// migrates it. In tests run with SUPERMARKET_TEST_POSTGRES set, it opens a
// new Postgres schema instead (see TestPostgres).
func Open(path string) (*DB, error) {
if base := testPostgres(); base != "" {
return openTestSchema(base)
}
return OpenSQLite(path)
}
// OpenSQLite opens the SQLite database at path, even in tests run on
// Postgres: for what tests SQLite itself (its migrations, its backups).
func OpenSQLite(path string) (*DB, error) {
// WAL lets the web UI read while a background job writes; busy_timeout
// waits out short write locks instead of failing.
dsn := "file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(ON)"
@@ -714,7 +721,7 @@ func Open(path string) (*DB, error) {
sqldb.Close()
return nil, fmt.Errorf("opening %s: %w", path, err)
}
d := &DB{sqldb}
d := &DB{SQL: sqldb, Dialect: SQLite}
if BeforeMigrate != nil {
var version int
if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
@@ -744,7 +751,7 @@ func (d *DB) migrate() error {
return fmt.Errorf("the database is from a newer Supermarket (schema %d, this version knows %d); update Supermarket", version, len(migrations))
}
for i := version; i < len(migrations); i++ {
tx, err := d.Begin()
tx, err := d.SQL.Begin()
if err != nil {
return err
}