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
+3 -4
View File
@@ -2,7 +2,6 @@ package tracking
import (
"context"
"database/sql"
"fmt"
"net/url"
"regexp"
@@ -179,7 +178,7 @@ func linkingPage(ref string) bool {
// noteBacklink records a linking page that sent a visitor (when first and
// last seen), and says whether it's new.
func noteBacklink(tx *sql.Tx, site, source, target, day string) (bool, error) {
func noteBacklink(tx *db.Tx, site, source, target, day string) (bool, error) {
if u, err := url.Parse(source); err == nil {
u.Fragment = ""
source = u.String()
@@ -190,7 +189,7 @@ func noteBacklink(tx *sql.Tx, site, source, target, day string) (bool, error) {
}
_, err := tx.Exec(`INSERT INTO backlinks (site, source_url, target, origin, first_seen, last_seen) VALUES (?, ?, ?, 'plausible', ?, ?)
ON CONFLICT (site, source_url, target) DO UPDATE SET
first_seen = min(first_seen, excluded.first_seen), last_seen = max(last_seen, excluded.last_seen)`,
first_seen = min(backlinks.first_seen, excluded.first_seen), last_seen = max(backlinks.last_seen, excluded.last_seen)`,
site, source, target, day, day)
return n == 0, err
}
@@ -230,7 +229,7 @@ func Referrers(d *db.DB, w profile.Website, days int) (list []Referrer, ok bool,
weekAgo := t.AddDate(0, 0, -6).Format(dayFormat)
rows, err := d.Query(`SELECT source, referrer, page, sum(visitors), sum(signups) + sum(leads),
(SELECT min(date) FROM referrer_days r2 WHERE r2.site = r.site AND r2.source = r.source)
FROM referrer_days r WHERE site = ? AND date BETWEEN ? AND ? GROUP BY source, referrer, page`, site, from, through)
FROM referrer_days r WHERE site = ? AND date BETWEEN ? AND ? GROUP BY site, source, referrer, page`, site, from, through)
if err != nil {
return nil, false, err
}