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
+5 -5
View File
@@ -42,9 +42,9 @@ func SaveItems(d *db.DB, items []models.ContentItem) (int, error) {
defer tx.Rollback()
n := 0
for _, it := range items {
res, err := tx.Exec(`INSERT OR IGNORE INTO content_items
res, err := tx.Exec(`INSERT INTO content_items
(id, inventory_name, source, author, author_handle, title, body, url, published_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`,
it.ID, it.AppName, string(it.Source), it.Author, it.AuthorHandle, it.Title, it.Body, it.URL,
formatTime(it.PublishedAt))
if err != nil {
@@ -118,7 +118,7 @@ func GetItems(d *db.DB, ids []string) ([]Item, error) {
func Counts(d *db.DB) (map[string]int, error) {
rows, err := d.Query(`SELECT c.inventory_name, count(*)` + itemFrom + `
WHERE d.item_id IS NULL AND c.used_at IS NULL AND c.source != 'Product'
GROUP BY c.inventory_name COLLATE NOCASE`)
GROUP BY c.inventory_name`) // the column ignores case
if err != nil {
return nil, err
}
@@ -138,7 +138,7 @@ func Counts(d *db.DB) (map[string]int, error) {
// Dismiss hides items from the list for good (until restored).
func Dismiss(d *db.DB, ids []string) error {
for _, id := range ids {
if _, err := d.Exec(`INSERT OR IGNORE INTO dismissed (item_id) VALUES (?)`, id); err != nil {
if _, err := d.Exec(`INSERT INTO dismissed (item_id) VALUES (?) ON CONFLICT DO NOTHING`, id); err != nil {
return err
}
}
@@ -155,7 +155,7 @@ func Restore(d *db.DB, ids []string) error {
return nil
}
func markUsed(tx *sql.Tx, ids []string) error {
func markUsed(tx *db.Tx, ids []string) error {
for _, id := range ids {
if _, err := tx.Exec(`UPDATE content_items SET used_at = ? WHERE id = ? AND used_at IS NULL`,
formatTime(time.Now()), id); err != nil {