From 1b2947de7cd423d4bed06840daed044177a5e06e Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 07:10:44 -0700 Subject: [PATCH] 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 --- PLAN.md | 31 ++ README.md | 20 ++ go.mod | 4 + go.sum | 13 + internal/backlinks/backlinks.go | 4 +- internal/content/items.go | 10 +- internal/db/db.go | 21 +- internal/db/db_test.go | 2 +- internal/db/dialect.go | 257 ++++++++++++++ internal/db/dialect_test.go | 38 ++ internal/db/migrate_hook_test.go | 8 +- internal/db/postgres.go | 162 +++++++++ internal/db/postgres.sql | 583 +++++++++++++++++++++++++++++++ internal/discovery/discovery.go | 3 +- internal/enrich/enrich.go | 4 +- internal/inventory/inventory.go | 9 +- internal/legacy/legacy.go | 4 +- internal/metrics/clv.go | 4 +- internal/metrics/mrr_test.go | 2 +- internal/outreach/message.go | 4 +- internal/prospects/lists.go | 2 +- internal/prospects/prospects.go | 14 +- internal/seo/audit.go | 6 +- internal/seo/briefs.go | 4 +- internal/seo/changes.go | 4 +- internal/seo/keywords.go | 2 +- internal/signals/signals.go | 4 +- internal/sites/pages.go | 6 +- internal/tracking/referrers.go | 7 +- internal/web/backups.go | 9 +- internal/web/backups_test.go | 14 +- internal/web/engines_test.go | 2 +- 32 files changed, 1188 insertions(+), 69 deletions(-) create mode 100644 internal/db/dialect.go create mode 100644 internal/db/dialect_test.go create mode 100644 internal/db/postgres.go create mode 100644 internal/db/postgres.sql diff --git a/PLAN.md b/PLAN.md index d4a5b3d..59b5b0b 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1878,6 +1878,37 @@ them work are done. S3 storage takes `SUPERMARKET_S3_ENDPOINT`, mail takes `SUPERMARKET_MAIL_URL` (`smtp://` with STARTTLS, or `smtps://`) and `SUPERMARKET_MAIL_FROM`. +**Part 2 built 2026-11-25** on `phase9`. It took less change to the SQL +than planned: rather than helpers in every query, the SQL stays as it is +(SQLite's, with `?`), and Postgres is made to understand it. +- `db.DB` wraps `database/sql` for either database. On Postgres, each + statement's `?`s become `$1, $2…` and `LIKE` ignores case as SQLite's + does (`x COLLATE nocase LIKE y`), skipping strings and comments. Go + booleans go in as 0 and 1, and times as SQLite's driver writes them. +- The Postgres schema (`internal/db/postgres.sql`, schema 29 as a whole, + so part of part 3 came early, to have something to test on) adds: + - SQLite's `instr`, `json_extract` and two-argument `max`/`min`, as SQL + functions + - a case-insensitive, ICU-based `nocase` collation, so `COLLATE NOCASE` + means the same in both, in columns and in queries + - 64-bit integers, identity columns for `INTEGER PRIMARY KEY`, and the + tables in an order Postgres accepts + + It needs Postgres 18 or later, for `LIKE` with that collation. +- What changed in the packages: + - 11 `LastInsertId`s became `db.Insert` (`RETURNING id`) + - 4 `INSERT OR IGNORE`s became `ON CONFLICT DO NOTHING` + - 4 upserts got table-qualified columns + - 3 queries were grouped by every column they use + - 2 JSON values are cast to numbers + - 1 `strftime` moved to Go +- `SUPERMARKET_TEST_POSTGRES` runs the whole test suite on Postgres, a new + schema per test. Every test passes on both databases. The tests that + test SQLite itself (its migrations) open SQLite with `db.OpenSQLite`; + the backup page's tests skip on Postgres. +- Left for part 3: migrations after schema 29 on both databases, and what + replaces SQLite's backup before a migration. + Nothing changes for the local user; this makes the rest possible. A commit after each part; the whole test suite runs against both SQLite and Postgres from part 2 on. diff --git a/README.md b/README.md index d3ccdad..dc1fc49 100644 --- a/README.md +++ b/README.md @@ -223,9 +223,29 @@ go test ./... SUPERMARKET_DATA=/tmp/cm SUPERMARKET_ADDR=127.0.0.1:8470 go run ./cmd/supermarket ``` +The tests also run on Postgres (the server and multi-tenant editions' +database), each test in a new schema that's dropped afterwards. Postgres 18 +or later is needed: + +``` +docker run -d --name sm-pgtest --rm -e POSTGRES_PASSWORD=test -e POSTGRES_DB=sm \ + -p 127.0.0.1:55432:5432 --tmpfs /var/lib/postgresql postgres:18-alpine +SUPERMARKET_TEST_POSTGRES='postgres://postgres:test@127.0.0.1:55432/sm?sslmode=disable' go test ./... +``` + +The SQL is written for SQLite, with `?` parameters. On Postgres, `internal/db` +numbers the parameters and makes `LIKE` ignore case as SQLite's does, and +the Postgres schema (`internal/db/postgres.sql`) adds SQLite's `instr`, +`json_extract` and two-argument `max`/`min`, plus a case-insensitive `nocase` +collation. New SQL should run on both: use `db.Insert` (not `LastInsertId`), +`ON CONFLICT … DO NOTHING` (not `INSERT OR IGNORE`), table-qualified columns +in an upsert's `DO UPDATE`, and every selected column in `GROUP BY`. + | Path | What | |------|------| | `cmd/supermarket` | The server | +| `internal/config` | The edition (local, server, multi-tenant) and its settings | +| `internal/db` | The database: SQLite or Postgres, the schema and its migrations | | `internal/web` | Pages (Go templates + [htmx](https://htmx.org), no JavaScript build) | | `internal/profile`, `internal/inventory` | The company profile and the inventory | | `internal/ai` | AI providers: Anthropic (official Go SDK) and OpenAI-compatible servers | diff --git a/go.mod b/go.mod index dca98c9..df5fede 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/anthropics/anthropic-sdk-go/v2 v2.11.0 github.com/emersion/go-imap v1.2.1 github.com/emersion/go-message v0.18.2 + github.com/jackc/pgx/v5 v5.13.0 github.com/modelcontextprotocol/go-sdk v1.8.0 golang.org/x/net v0.63.0 golang.org/x/text v0.44.0 @@ -23,6 +24,9 @@ require ( github.com/google/jsonschema-go v0.4.3 // indirect github.com/google/uuid v1.6.0 // indirect github.com/invopop/jsonschema v0.14.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect diff --git a/go.sum b/go.sum index 6d5dbbc..dadfc94 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,7 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= @@ -81,6 +82,14 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= +github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -105,6 +114,9 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI= github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= @@ -200,6 +212,7 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntN gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.30.6-0.20261101114202-1b9d1a076f6b h1:WE5SLOURcNd8s6uPR/n4WV4weQxxYKi5OpEZkfNVvdE= diff --git a/internal/backlinks/backlinks.go b/internal/backlinks/backlinks.go index 96ac19d..efff379 100644 --- a/internal/backlinks/backlinks.go +++ b/internal/backlinks/backlinks.go @@ -138,8 +138,8 @@ func upsert(d *db.DB, site, source, target, anchor, origin, day string) error { } _, err := d.Exec(`INSERT INTO backlinks (site, source_url, target, anchor, origin, first_seen, last_seen) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (site, source_url, target) DO UPDATE SET - last_seen = max(last_seen, excluded.last_seen), - anchor = CASE WHEN anchor = '' THEN excluded.anchor ELSE anchor END`, + last_seen = max(backlinks.last_seen, excluded.last_seen), + anchor = CASE WHEN backlinks.anchor = '' THEN excluded.anchor ELSE backlinks.anchor END`, site, source, target, anchor, origin, day, day) return err } diff --git a/internal/content/items.go b/internal/content/items.go index 06763a8..e98e145 100644 --- a/internal/content/items.go +++ b/internal/content/items.go @@ -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 { diff --git a/internal/db/db.go b/internal/db/db.go index d452173..4249614 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -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 } diff --git a/internal/db/db_test.go b/internal/db/db_test.go index 4af87f3..c219569 100644 --- a/internal/db/db_test.go +++ b/internal/db/db_test.go @@ -29,7 +29,7 @@ func TestMigratePostsToDrafts(t *testing.T) { } old.Close() - d, err := Open(path) + d, err := OpenSQLite(path) if err != nil { t.Fatal(err) } diff --git a/internal/db/dialect.go b/internal/db/dialect.go new file mode 100644 index 0000000..6231688 --- /dev/null +++ b/internal/db/dialect.go @@ -0,0 +1,257 @@ +package db + +import ( + "database/sql" + "strconv" + "strings" + "sync" + "time" +) + +// Dialect is which database a DB is. +type Dialect int + +const ( + // SQLite is the local edition's database: one file. + SQLite Dialect = iota + // Postgres is the server and multi-tenant editions' database. + Postgres +) + +func (d Dialect) String() string { + if d == Postgres { + return "Postgres" + } + return "SQLite" +} + +// DB is the app's database. Its SQL is written for SQLite, with ? for +// parameters; on Postgres each statement is adjusted on the way (see +// rebind), and the schema adds the SQLite functions the app uses +// (postgres.sql), so the same SQL runs on both. +type DB struct { + // SQL is the database itself, for what only works on one dialect + // (SQLite's backups). + SQL *sql.DB + Dialect Dialect + + closeHook func() error // tests on Postgres: drop the test's schema +} + +func (d *DB) query(q string) string { + if d.Dialect == Postgres { + return rebind(q) + } + return q +} + +func (d *DB) args(a []any) []any { + if d.Dialect == Postgres { + return pgArgs(a) + } + return a +} + +// Exec runs a statement. +func (d *DB) Exec(q string, args ...any) (sql.Result, error) { + return d.SQL.Exec(d.query(q), d.args(args)...) +} + +// Query runs a query that returns rows. +func (d *DB) Query(q string, args ...any) (*sql.Rows, error) { + return d.SQL.Query(d.query(q), d.args(args)...) +} + +// QueryRow runs a query that returns at most one row. +func (d *DB) QueryRow(q string, args ...any) *sql.Row { + return d.SQL.QueryRow(d.query(q), d.args(args)...) +} + +// Begin starts a transaction. +func (d *DB) Begin() (*Tx, error) { + tx, err := d.SQL.Begin() + if err != nil { + return nil, err + } + return &Tx{tx: tx, d: d}, nil +} + +// Close closes the database. +func (d *DB) Close() error { + err := d.SQL.Close() + if d.closeHook != nil { + if herr := d.closeHook(); err == nil { + err = herr + } + d.closeHook = nil + } + return err +} + +// Tx is a transaction. +type Tx struct { + tx *sql.Tx + d *DB +} + +// Exec runs a statement in the transaction. +func (t *Tx) Exec(q string, args ...any) (sql.Result, error) { + return t.tx.Exec(t.d.query(q), t.d.args(args)...) +} + +// Query runs a query in the transaction. +func (t *Tx) Query(q string, args ...any) (*sql.Rows, error) { + return t.tx.Query(t.d.query(q), t.d.args(args)...) +} + +// QueryRow runs a one-row query in the transaction. +func (t *Tx) QueryRow(q string, args ...any) *sql.Row { + return t.tx.QueryRow(t.d.query(q), t.d.args(args)...) +} + +// Commit commits it. +func (t *Tx) Commit() error { return t.tx.Commit() } + +// Rollback abandons it. +func (t *Tx) Rollback() error { return t.tx.Rollback() } + +var rebound sync.Map // SQLite SQL → Postgres SQL + +// rebind turns SQLite's SQL into Postgres': ? parameters become $1, $2…, +// and LIKE ignores case as SQLite's does (x COLLATE nocase LIKE y). +// Strings, quoted names and comments are left as they are. +func rebind(q string) string { + if v, ok := rebound.Load(q); ok { + return v.(string) + } + var b strings.Builder + b.Grow(len(q) + 16) + n := 0 + lastWord, lastWordAt := "", 0 // the last keyword or name, and where it starts in b + for i := 0; i < len(q); { + c := q[i] + switch { + case c == '\'' || c == '"': // a string, or a quoted name + j := i + 1 + for j < len(q) { + if q[j] == c { + if j+1 < len(q) && q[j+1] == c { // '' inside a string + j += 2 + continue + } + break + } + j++ + } + end := min(j+1, len(q)) + b.WriteString(q[i:end]) + i = end + lastWord = "" + case c == '-' && i+1 < len(q) && q[i+1] == '-': // a comment to the end of the line + j := strings.IndexByte(q[i:], '\n') + if j < 0 { + j = len(q) - i + } + b.WriteString(q[i : i+j]) + i += j + case c == '/' && i+1 < len(q) && q[i+1] == '*': + j := strings.Index(q[i+2:], "*/") + end := len(q) + if j >= 0 { + end = i + 2 + j + 2 + } + b.WriteString(q[i:end]) + i = end + case c == '?': + n++ + b.WriteByte('$') + b.WriteString(strconv.Itoa(n)) + i++ + lastWord = "" + case isWordByte(c): + j := i + for j < len(q) && isWordByte(q[j]) { + j++ + } + word := q[i:j] + if strings.EqualFold(word, "LIKE") { + if strings.EqualFold(lastWord, "NOT") { // x NOT LIKE y → x COLLATE nocase NOT LIKE y + s := b.String() + b.Reset() + b.WriteString(s[:lastWordAt]) + b.WriteString("COLLATE nocase ") + b.WriteString(s[lastWordAt:]) + } else { + b.WriteString("COLLATE nocase ") + } + } + lastWord, lastWordAt = word, b.Len() + b.WriteString(word) + i = j + default: + b.WriteByte(c) + i++ + if c != ' ' && c != '\t' && c != '\n' && c != '\r' { + lastWord = "" + } + } + } + out := b.String() + rebound.Store(q, out) + return out +} + +func isWordByte(c byte) bool { + return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80 +} + +// timeFormat is how the SQLite driver writes a time.Time. +const timeFormat = "2006-01-02 15:04:05.999999999-07:00" + +// pgArgs gives Postgres parameters as SQLite would store them: booleans +// as 0 and 1 (the schema keeps them in integer columns), and times as +// the SQLite driver's text. +func pgArgs(a []any) []any { + var out []any + for i, v := range a { + var conv any + switch x := v.(type) { + case bool: + conv = int64(0) + if x { + conv = int64(1) + } + case time.Time: + conv = x.Format(timeFormat) + case *time.Time: + if x != nil { + conv = x.Format(timeFormat) + } + default: + continue + } + if out == nil { + out = append([]any(nil), a...) + } + out[i] = conv + } + if out == nil { + return a + } + return out +} + +// Insert runs an INSERT and returns the new row's id (RETURNING id, which +// both databases support; Postgres' driver has no LastInsertId). +func (d *DB) Insert(q string, args ...any) (int64, error) { + var id int64 + err := d.QueryRow(q+" RETURNING id", args...).Scan(&id) + return id, err +} + +// Insert runs an INSERT in the transaction and returns the new row's id. +func (t *Tx) Insert(q string, args ...any) (int64, error) { + var id int64 + err := t.QueryRow(q+" RETURNING id", args...).Scan(&id) + return id, err +} diff --git a/internal/db/dialect_test.go b/internal/db/dialect_test.go new file mode 100644 index 0000000..42b941a --- /dev/null +++ b/internal/db/dialect_test.go @@ -0,0 +1,38 @@ +package db + +import ( + "testing" + "time" +) + +func TestRebind(t *testing.T) { + for in, want := range map[string]string{ + `SELECT a FROM t WHERE b = ? AND c = ?`: `SELECT a FROM t WHERE b = $1 AND c = $2`, + `SELECT '?' || "a?" FROM t WHERE x = ? -- why?` + "\n" + `AND y = ?`: `SELECT '?' || "a?" FROM t WHERE x = $1 -- why?` + "\n" + `AND y = $2`, + `SELECT 'it''s ?' WHERE a = ? /* ? */ AND b = ?`: `SELECT 'it''s ?' WHERE a = $1 /* ? */ AND b = $2`, + `WHERE email LIKE '%@' || ?`: `WHERE email COLLATE nocase LIKE '%@' || $1`, + `WHERE url NOT LIKE 'http%' AND k like ?`: `WHERE url COLLATE nocase NOT LIKE 'http%' AND k COLLATE nocase like $1`, + `WHERE page LIKE ? ESCAPE '\'`: `WHERE page COLLATE nocase LIKE $1 ESCAPE '\'`, + `SELECT 'LIKE', likely FROM t`: `SELECT 'LIKE', likely FROM t`, + } { + if got := rebind(in); got != want { + t.Errorf("rebind(%q)\n got %q\nwant %q", in, got, want) + } + } +} + +func TestPgArgs(t *testing.T) { + at := time.Date(2026, 11, 25, 8, 0, 0, 0, time.UTC) + in := []any{true, false, at, "x", int64(3), nil} + got := pgArgs(in) + if got[0] != int64(1) || got[1] != int64(0) || got[2] != "2026-11-25 08:00:00+00:00" || got[3] != "x" || got[4] != int64(3) || got[5] != nil { + t.Fatalf("%#v", got) + } + if in[0] != true { + t.Fatal("changed the caller's slice") + } + plain := []any{"a", 1} + if out := pgArgs(plain); &out[0] != &plain[0] { + t.Error("copied args that needed no change") + } +} diff --git a/internal/db/migrate_hook_test.go b/internal/db/migrate_hook_test.go index b8f09b3..aefed38 100644 --- a/internal/db/migrate_hook_test.go +++ b/internal/db/migrate_hook_test.go @@ -20,13 +20,13 @@ func TestBeforeMigrate(t *testing.T) { } dir := t.TempDir() // A new database: nothing to back up. - d, err := Open(filepath.Join(dir, "new.db")) + d, err := OpenSQLite(filepath.Join(dir, "new.db")) if err != nil { t.Fatal(err) } d.Close() // Already current: nothing either. - d, _ = Open(filepath.Join(dir, "new.db")) + d, _ = OpenSQLite(filepath.Join(dir, "new.db")) d.Close() if len(calls) != 0 { t.Fatalf("called for a new or current database: %v", calls) @@ -41,7 +41,7 @@ func TestBeforeMigrate(t *testing.T) { } raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1)) raw.Close() - d, err = Open(old) + d, err = OpenSQLite(old) if err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func TestBeforeMigrate(t *testing.T) { 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 := Open(old); err == nil || !strings.Contains(err.Error(), "disk full") { + if _, err := OpenSQLite(old); err == nil || !strings.Contains(err.Error(), "disk full") { t.Errorf("open: %v", err) } } diff --git a/internal/db/postgres.go b/internal/db/postgres.go new file mode 100644 index 0000000..25e1792 --- /dev/null +++ b/internal/db/postgres.go @@ -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 } diff --git a/internal/db/postgres.sql b/internal/db/postgres.sql new file mode 100644 index 0000000..a8e08dc --- /dev/null +++ b/internal/db/postgres.sql @@ -0,0 +1,583 @@ +-- Supermarket's schema on Postgres: SQLite's schema 29 as a whole, with +-- the functions and collation that let the same SQL run on both. Created +-- by db.Open on an empty database (or schema); later migrations follow it. +-- +-- SQLite's case-insensitive text: equal ignoring case, in comparisons, +-- unique keys, ORDER BY and LIKE (Postgres 18 or later). +CREATE COLLATION nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false); + +-- SQLite's scalar max(a, b) and min(a, b): NULL when either is NULL. The +-- one-argument aggregates are Postgres' own. +CREATE FUNCTION max(a anycompatible, b anycompatible) RETURNS anycompatible LANGUAGE sql IMMUTABLE + AS $$ SELECT CASE WHEN a IS NULL OR b IS NULL THEN NULL WHEN a >= b THEN a ELSE b END $$; +CREATE FUNCTION min(a anycompatible, b anycompatible) RETURNS anycompatible LANGUAGE sql IMMUTABLE + AS $$ SELECT CASE WHEN a IS NULL OR b IS NULL THEN NULL WHEN a <= b THEN a ELSE b END $$; + +-- SQLite's instr(haystack, needle): the 1-based position, or 0. +CREATE FUNCTION instr(h text, n text) RETURNS integer LANGUAGE sql IMMUTABLE + AS $$ SELECT strpos(h, n) $$; + +-- SQLite's json_extract(json, '$.a.b') for plain object paths, as text. +CREATE FUNCTION json_extract(j text, p text) RETURNS text LANGUAGE sql IMMUTABLE + AS $$ SELECT (j::jsonb) #>> string_to_array(substr(p, 3), '.') $$; + +CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +CREATE TABLE inventory ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name TEXT COLLATE nocase NOT NULL UNIQUE, + relationship TEXT NOT NULL CHECK (relationship IN ('partner', 'competitor', 'watch')), + data TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + updated_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) +); + +CREATE TABLE fetch_state ( + key TEXT PRIMARY KEY, + last_checked TEXT NOT NULL +); + +CREATE TABLE dismissed ( + item_id TEXT PRIMARY KEY, + dismissed_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) +); + +CREATE TABLE bridge_checkins ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + agent TEXT NOT NULL, + mcphub_tools TEXT NOT NULL DEFAULT '[]', + note TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE content_items ( + id TEXT PRIMARY KEY, -- the source's own ID (tweet, video), or rss: + inventory_name TEXT COLLATE nocase NOT NULL, + source TEXT NOT NULL, + author TEXT NOT NULL DEFAULT '', + author_handle TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL DEFAULT '', + url TEXT NOT NULL DEFAULT '', + published_at TEXT NOT NULL, + fetched_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + used_at TEXT -- when a draft was written from it +); + +CREATE TABLE signals ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, -- used as utm_campaign + name TEXT NOT NULL, + hypothesis TEXT NOT NULL DEFAULT '', + spot TEXT NOT NULL DEFAULT '', -- how to find it: queries, keywords, one per line + angle TEXT NOT NULL DEFAULT '', -- the pain and promise for messages and content + status TEXT NOT NULL DEFAULT 'idea', -- idea, testing, proven, retired + created_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + updated_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) +, discover_every_days BIGINT NOT NULL DEFAULT 0, explee_definition TEXT NOT NULL DEFAULT ''); + +CREATE TABLE drafts ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + batch TEXT NOT NULL, + inventory_name TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL, -- partner, competitor, watch (later: product) + channel TEXT NOT NULL, -- x, linkedin (later: reddit) + content TEXT NOT NULL, + source_url TEXT NOT NULL DEFAULT '', + item_ids TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'draft', -- draft, publishing, published, failed, discarded + error TEXT NOT NULL DEFAULT '', + post_url TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + updated_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + published_at TEXT +, publish_at TEXT, title TEXT NOT NULL DEFAULT '', target TEXT NOT NULL DEFAULT '', signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL, linkedin_as TEXT NOT NULL DEFAULT ''); + +CREATE TABLE subreddits ( + name TEXT COLLATE nocase PRIMARY KEY, + data TEXT NOT NULL, + fetched_at TEXT NOT NULL +); + +CREATE TABLE crm_actions ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + key TEXT NOT NULL UNIQUE, -- one action per key, however often it's queued + kind TEXT NOT NULL, -- create (later: update, note) + entity TEXT NOT NULL, -- Lead, Account, Contact… + fields TEXT NOT NULL, -- JSON: the record's fields + match TEXT NOT NULL DEFAULT '{}', -- JSON: fields that identify an existing record + origin TEXT NOT NULL DEFAULT '', -- what queued it, e.g. test, prospect:12 + status TEXT NOT NULL DEFAULT 'pending', -- pending, claimed, done, failed, cancelled + outcome TEXT NOT NULL DEFAULT '', -- created, existing + espo_id TEXT NOT NULL DEFAULT '', + error TEXT NOT NULL DEFAULT '', + attempts BIGINT NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + claimed_at TEXT, + done_at TEXT +); + +CREATE TABLE crm_records ( + entity TEXT NOT NULL, + espo_id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT '', + email TEXT COLLATE nocase NOT NULL DEFAULT '', + domain TEXT COLLATE nocase NOT NULL DEFAULT '', -- of the website, or the email + data TEXT NOT NULL, -- JSON: the fields Hermes sent + modified_at TEXT NOT NULL DEFAULT '', + synced_at TEXT NOT NULL, + PRIMARY KEY (entity, espo_id) +); + +CREATE TABLE prospect_companies ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + name TEXT NOT NULL, + domain TEXT COLLATE nocase NOT NULL DEFAULT '', -- one company per domain + website TEXT NOT NULL DEFAULT '', + linkedin TEXT NOT NULL DEFAULT '', + industry TEXT NOT NULL DEFAULT '', + size TEXT NOT NULL DEFAULT '', + location TEXT NOT NULL DEFAULT '', + why TEXT NOT NULL DEFAULT '', -- why it fits the targets + source TEXT NOT NULL, -- manual, discovery, hunter, csv… + source_detail TEXT NOT NULL DEFAULT '', -- a URL or note: where exactly + found_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected + decided_at TEXT, + action_id BIGINT -- the CRM action that adds it as an Account +, signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL); + +CREATE TABLE prospect_contacts ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + company_id BIGINT REFERENCES prospect_companies (id) ON DELETE SET NULL, + first_name TEXT NOT NULL DEFAULT '', + last_name TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + email TEXT COLLATE nocase NOT NULL DEFAULT '', -- one contact per email + email_status TEXT NOT NULL DEFAULT '', -- '', valid, risky, invalid (from verification) + linkedin TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL, + source_detail TEXT NOT NULL DEFAULT '', + found_at TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'new', -- new, accepted, rejected + decided_at TEXT, + action_id BIGINT -- the CRM action that adds them as a Lead +, signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL); + +CREATE TABLE suppressions ( + kind TEXT NOT NULL, -- email or domain + value TEXT COLLATE nocase NOT NULL, + reason TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')), + PRIMARY KEY (kind, value) +); + +CREATE TABLE outside_campaigns ( + source TEXT NOT NULL, -- origami, explee + id TEXT NOT NULL, + name TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT '', + signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL, + spend_cents BIGINT NOT NULL DEFAULT 0, -- lifetime, as the tool reports it + stats TEXT NOT NULL DEFAULT '{}', -- JSON: the tool's own numbers + synced_at TEXT NOT NULL, + PRIMARY KEY (source, id) +); + +CREATE TABLE funnel_events ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL, + stage TEXT NOT NULL, -- found, contacted, replied, interested, booked, visited, signed_up, paid + channel TEXT NOT NULL, -- email, linkedin, social, blog, website, origami, explee, other + subject TEXT NOT NULL DEFAULT '', -- who: contact:12, company:3, explee:… + email TEXT COLLATE nocase NOT NULL DEFAULT '', -- to tie it to the CRM and Stripe later + campaign TEXT NOT NULL DEFAULT '', -- origami:, explee:; its signal is set there + source TEXT NOT NULL, -- supermarket, manual, origami, explee + external_id TEXT NOT NULL DEFAULT '', -- dedupes imports + count BIGINT NOT NULL DEFAULT 1, -- for aggregate numbers (visits) + value_cents BIGINT NOT NULL DEFAULT 0, -- for paid + note TEXT NOT NULL DEFAULT '', + at TEXT NOT NULL +); + +CREATE TABLE discovery_runs ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + signal_id BIGINT NOT NULL REFERENCES signals (id) ON DELETE CASCADE, + source TEXT NOT NULL, -- claude, explee + status TEXT NOT NULL DEFAULT 'running', -- running, done, failed + started_at TEXT NOT NULL, + finished_at TEXT, + found BIGINT NOT NULL DEFAULT 0, -- companies reported + added BIGINT NOT NULL DEFAULT 0, -- new prospects + existing BIGINT NOT NULL DEFAULT 0, -- already prospects + skipped BIGINT NOT NULL DEFAULT 0, -- suppressed, ours, or without a source it read + searches BIGINT NOT NULL DEFAULT 0, -- web searches (each billed) + error TEXT NOT NULL DEFAULT '', + notes TEXT NOT NULL DEFAULT '[]' -- JSON: why companies were skipped +); + +CREATE TABLE enrich_runs ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + kind TEXT NOT NULL, -- people (at a company), email (for a person), verify + subject TEXT NOT NULL, -- company:3, contact:12 + at TEXT NOT NULL, + found BIGINT NOT NULL DEFAULT 0, + added BIGINT NOT NULL DEFAULT 0, + credits DOUBLE PRECISION NOT NULL DEFAULT 0, -- Hunter.io credits used + result TEXT NOT NULL DEFAULT '', -- what happened, in words + error TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE outreach ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + contact_id BIGINT NOT NULL REFERENCES prospect_contacts (id) ON DELETE CASCADE, + signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL, + channel TEXT NOT NULL, -- email, linkedin + status TEXT NOT NULL DEFAULT 'draft', -- draft, queued, sent, failed, bounced, discarded + subject TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL DEFAULT '', + to_addr TEXT COLLATE nocase NOT NULL DEFAULT '', + message_id TEXT NOT NULL DEFAULT '', -- the email's Message-ID, to match replies + created_at TEXT NOT NULL, + queued_at TEXT, + sent_at TEXT, + replied_at TEXT, + reply TEXT NOT NULL DEFAULT '', -- the start of their reply + error TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE stripe_customers ( + id TEXT PRIMARY KEY, -- cus_… + email TEXT COLLATE nocase NOT NULL DEFAULT '', + name TEXT NOT NULL DEFAULT '', + signal_id BIGINT REFERENCES signals (id) ON DELETE SET NULL, + subject TEXT NOT NULL DEFAULT '', -- contact:12 when they're a prospect + channel TEXT NOT NULL DEFAULT '', + utm_campaign TEXT NOT NULL DEFAULT '', + utm_source TEXT NOT NULL DEFAULT '', + utm_medium TEXT NOT NULL DEFAULT '', + first_seen TEXT NOT NULL +); + +CREATE TABLE gsc_site_days ( + site TEXT NOT NULL, -- the Search Console property + date TEXT NOT NULL, -- YYYY-MM-DD + clicks BIGINT NOT NULL, + impressions BIGINT NOT NULL, + pos_sum DOUBLE PRECISION NOT NULL, + PRIMARY KEY (site, date) +); + +CREATE TABLE gsc_page_days ( + site TEXT NOT NULL, + date TEXT NOT NULL, + page TEXT NOT NULL, + clicks BIGINT NOT NULL, + impressions BIGINT NOT NULL, + pos_sum DOUBLE PRECISION NOT NULL, + PRIMARY KEY (site, date, page) +); + +CREATE TABLE gsc_query_days ( + site TEXT NOT NULL, + date TEXT NOT NULL, + page TEXT NOT NULL, + query TEXT NOT NULL, + clicks BIGINT NOT NULL, + impressions BIGINT NOT NULL, + pos_sum DOUBLE PRECISION NOT NULL, + PRIMARY KEY (site, date, page, query) +); + +CREATE TABLE seo_reports ( + site TEXT NOT NULL, + week_to TEXT NOT NULL, -- the week's last day of final data + created_at TEXT NOT NULL, + data TEXT NOT NULL, -- the report, as JSON + PRIMARY KEY (site, week_to) +); + +CREATE TABLE seo_audits ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, -- the website's address + status TEXT NOT NULL DEFAULT 'running', -- running, done, failed + started_at TEXT NOT NULL, + finished_at TEXT, + error TEXT NOT NULL DEFAULT '', + data TEXT NOT NULL DEFAULT '{}' -- pages, issues and checks, as JSON +); + +CREATE TABLE seo_changes ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, -- the website's address + property TEXT NOT NULL DEFAULT '', + page TEXT NOT NULL, + cur_title TEXT NOT NULL DEFAULT '', + new_title TEXT NOT NULL DEFAULT '', + cur_description TEXT NOT NULL DEFAULT '', + new_description TEXT NOT NULL DEFAULT '', + why TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'proposed', + repo TEXT NOT NULL DEFAULT '', + file TEXT NOT NULL DEFAULT '', + branch TEXT NOT NULL DEFAULT '', + pr_number BIGINT NOT NULL DEFAULT 0, + pr_url TEXT NOT NULL DEFAULT '', + diff TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + error TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + decided_at TEXT, + merged_at TEXT, + live_at TEXT +); + +CREATE TABLE seo_keywords ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, + keyword TEXT NOT NULL, + intent TEXT NOT NULL DEFAULT 'info', -- buyer, info + sources TEXT NOT NULL DEFAULT '[]', -- where it came from + impressions BIGINT NOT NULL DEFAULT 0, -- Search Console, 90 days + position DOUBLE PRECISION NOT NULL DEFAULT 0, + shown_on TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'new', -- new, picked, dismissed + top TEXT NOT NULL DEFAULT '[]', -- the live top results, when read + top_at TEXT, + searches BIGINT NOT NULL DEFAULT 0, -- web searches used + created_at TEXT NOT NULL, + picked_at TEXT, + UNIQUE (site, keyword) +); + +CREATE TABLE seo_briefs ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, + property TEXT NOT NULL DEFAULT '', + keyword TEXT NOT NULL, + page TEXT NOT NULL DEFAULT '', -- a rewrite's page; a new page's once it's live + status TEXT NOT NULL DEFAULT 'brief', + shown_for TEXT NOT NULL DEFAULT '[]', -- Search Console: what the page is shown for + top TEXT NOT NULL DEFAULT '[]', -- the live top results + plan TEXT NOT NULL DEFAULT '{}', -- the brief + answers TEXT NOT NULL DEFAULT '[]', -- the user's answers to its questions + draft TEXT NOT NULL DEFAULT '', -- the page, Markdown + claims TEXT NOT NULL DEFAULT '[]', -- sentences claiming an experience + path TEXT NOT NULL DEFAULT '', -- a new page's address + file TEXT NOT NULL DEFAULT '', + pr_number BIGINT NOT NULL DEFAULT 0, + pr_url TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + error TEXT NOT NULL DEFAULT '', + searches BIGINT NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + merged_at TEXT, + live_at TEXT +); + +CREATE TABLE stripe_objects ( + kind TEXT NOT NULL, -- customer, invoice, credit_note, refund + id TEXT NOT NULL, + customer TEXT NOT NULL DEFAULT '', + created BIGINT NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT '', + currency TEXT NOT NULL DEFAULT '', + amount BIGINT NOT NULL DEFAULT 0, -- invoice: total; credit note: total; refund: amount + data TEXT NOT NULL, + PRIMARY KEY (kind, id) +); + +CREATE TABLE stripe_invoice_lines ( + invoice TEXT NOT NULL, + id TEXT NOT NULL, + customer TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT '', -- the invoice's + currency TEXT NOT NULL DEFAULT '', + amount BIGINT NOT NULL DEFAULT 0, -- after discounts, before tax + period_start BIGINT NOT NULL DEFAULT 0, + period_end BIGINT NOT NULL DEFAULT 0, + subscription TEXT NOT NULL DEFAULT '', + price TEXT NOT NULL DEFAULT '', + product TEXT NOT NULL DEFAULT '', + interval TEXT NOT NULL DEFAULT '', + interval_count BIGINT NOT NULL DEFAULT 0, + quantity BIGINT NOT NULL DEFAULT 0, + proration BIGINT NOT NULL DEFAULT 0, + recurring BIGINT NOT NULL DEFAULT 0, description TEXT NOT NULL DEFAULT '', + PRIMARY KEY (invoice, id) +); + +CREATE TABLE crm_matches ( + customer TEXT PRIMARY KEY, -- cus_… + espo_id TEXT NOT NULL DEFAULT '', -- the Account; '' means "not in the CRM" + set_at TEXT NOT NULL +); + +CREATE TABLE spend ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + month TEXT NOT NULL, -- YYYY-MM + channel TEXT NOT NULL, -- a funnel channel, or general + amount_cents BIGINT NOT NULL, + note TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL DEFAULT 'manual', -- manual, csv, origami, explee + created_at TEXT NOT NULL +); + +CREATE TABLE spend_seen ( + source TEXT NOT NULL, + campaign TEXT NOT NULL, + spend_cents BIGINT NOT NULL, + PRIMARY KEY (source, campaign) +); + +CREATE TABLE site_pages ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, -- the website's URL, from the profile + repo TEXT NOT NULL DEFAULT '', -- owner/name + kind TEXT NOT NULL, -- landing, product, alternative, comparison, blog + source TEXT NOT NULL DEFAULT '{}', -- JSON: what it was built from + notes TEXT NOT NULL DEFAULT '', -- what the user asked for + path TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL DEFAULT '', + description TEXT NOT NULL DEFAULT '', + sections TEXT NOT NULL DEFAULT '', -- YAML, as in the page's front matter + needs TEXT NOT NULL DEFAULT '[]', + warnings TEXT NOT NULL DEFAULT '[]', + claims TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL DEFAULT 'draft', + branch TEXT NOT NULL DEFAULT '', + file TEXT NOT NULL DEFAULT '', + pr_number BIGINT NOT NULL DEFAULT 0, + pr_url TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', -- what the build check found + error TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + merged_at TEXT +, removal_branch TEXT NOT NULL DEFAULT '', removal_pr_number BIGINT NOT NULL DEFAULT 0, removal_pr_url TEXT NOT NULL DEFAULT '', live_at TEXT, gone_at TEXT, checked_at TEXT, live_note TEXT NOT NULL DEFAULT ''); + +CREATE TABLE page_days ( + site TEXT NOT NULL, -- the Plausible site + date TEXT NOT NULL, -- YYYY-MM-DD + page TEXT NOT NULL, -- the entry page's path, e.g. /freescout/ + visitors BIGINT NOT NULL DEFAULT 0, + signups BIGINT NOT NULL DEFAULT 0, -- visitors who clicked a sign-up link + leads BIGINT NOT NULL DEFAULT 0, -- visitors who sent a form (the Lead goal) + PRIMARY KEY (site, date, page) +); + +CREATE TABLE referrer_days ( + site TEXT NOT NULL, -- the Plausible site + date TEXT NOT NULL, -- YYYY-MM-DD + source TEXT NOT NULL, -- the referring site, as Plausible names it + referrer TEXT NOT NULL DEFAULT '', -- the linking page, when Plausible has it + page TEXT NOT NULL, -- the entry page's path + visitors BIGINT NOT NULL DEFAULT 0, + signups BIGINT NOT NULL DEFAULT 0, + leads BIGINT NOT NULL DEFAULT 0, + PRIMARY KEY (site, date, source, referrer, page) +); + +CREATE TABLE backlinks ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, -- the website's URL, from the profile + source_url TEXT NOT NULL, -- the page that links + target TEXT NOT NULL DEFAULT '', -- our page it links to (a path), when known + anchor TEXT NOT NULL DEFAULT '', + origin TEXT NOT NULL, -- plausible, bing, manual + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'unchecked', -- unchecked, kept, gone, page-gone, target-404 + checked_at TEXT, + note TEXT NOT NULL DEFAULT '', + UNIQUE (site, source_url, target) +); + +CREATE TABLE link_opportunities ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + site TEXT NOT NULL, -- the website's URL, from the profile + kind TEXT NOT NULL, -- partner, alternatives + about TEXT NOT NULL DEFAULT '', -- the partner or competitor, by name + page_url TEXT NOT NULL, + title TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', -- why it's an opportunity + status TEXT NOT NULL DEFAULT 'open', -- open, asked, won, listed, dismissed + found_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE (site, page_url) +); + +CREATE TABLE list_members ( + contact_id BIGINT NOT NULL REFERENCES prospect_contacts (id) ON DELETE CASCADE, + list_id BIGINT NOT NULL, -- Listmonk's + list_name TEXT NOT NULL, + confirmed BIGINT NOT NULL DEFAULT 0, -- 1: added as agreed; 0: Listmonk asked them to confirm + at TEXT NOT NULL, + PRIMARY KEY (contact_id, list_id) +); + +CREATE INDEX content_items_by_entry ON content_items (inventory_name, published_at); + +CREATE INDEX drafts_by_status ON drafts (status, created_at); + +CREATE INDEX drafts_due ON drafts (status, publish_at); + +CREATE INDEX crm_actions_by_status ON crm_actions (status, id); + +CREATE INDEX crm_records_by_email ON crm_records (email); + +CREATE INDEX crm_records_by_domain ON crm_records (domain); + +CREATE UNIQUE INDEX prospect_companies_by_domain ON prospect_companies (domain) WHERE domain != ''; + +CREATE INDEX prospect_companies_by_status ON prospect_companies (status, id); + +CREATE UNIQUE INDEX prospect_contacts_by_email ON prospect_contacts (email) WHERE email != ''; + +CREATE INDEX prospect_contacts_by_company ON prospect_contacts (company_id); + +CREATE UNIQUE INDEX funnel_events_external ON funnel_events (source, external_id) WHERE external_id != ''; + +CREATE INDEX funnel_events_by_signal ON funnel_events (signal_id, stage, at); + +CREATE INDEX funnel_events_by_subject ON funnel_events (subject); + +CREATE INDEX funnel_events_by_campaign ON funnel_events (campaign); + +CREATE INDEX discovery_runs_by_signal ON discovery_runs (signal_id, id); + +CREATE INDEX enrich_runs_by_subject ON enrich_runs (subject, id); + +CREATE INDEX enrich_runs_by_time ON enrich_runs (at); + +CREATE INDEX outreach_by_status ON outreach (status, id); + +CREATE INDEX outreach_by_contact ON outreach (contact_id); + +CREATE INDEX outreach_by_to ON outreach (to_addr); + +CREATE UNIQUE INDEX outreach_message_id ON outreach (message_id) WHERE message_id != ''; + +CREATE INDEX drafts_by_signal ON drafts (signal_id) WHERE signal_id IS NOT NULL; + +CREATE INDEX gsc_query_days_by_query ON gsc_query_days (site, query, date); + +CREATE INDEX seo_audits_by_site ON seo_audits (site, id); + +CREATE INDEX seo_changes_by_site ON seo_changes (site, id); + +CREATE INDEX seo_changes_by_status ON seo_changes (status); + +CREATE INDEX seo_briefs_by_site ON seo_briefs (site, id); + +CREATE INDEX stripe_objects_by_customer ON stripe_objects (kind, customer); + +CREATE INDEX stripe_invoice_lines_by_customer ON stripe_invoice_lines (customer, period_start); + +CREATE INDEX spend_by_month ON spend (month); + +CREATE INDEX site_pages_by_site ON site_pages (site, created_at); diff --git a/internal/discovery/discovery.go b/internal/discovery/discovery.go index c5fd43d..57f99fc 100644 --- a/internal/discovery/discovery.go +++ b/internal/discovery/discovery.go @@ -78,12 +78,11 @@ func start(d *db.DB, signalID int64, source string, now time.Time) (*Run, func() if _, busy := running.LoadOrStore(key, true); busy { return nil, nil, ErrRunning } - res, err := d.Exec(`INSERT INTO discovery_runs (signal_id, source, started_at) VALUES (?, ?, ?)`, signalID, source, formatTime(now)) + id, err := d.Insert(`INSERT INTO discovery_runs (signal_id, source, started_at) VALUES (?, ?, ?)`, signalID, source, formatTime(now)) if err != nil { running.Delete(key) return nil, nil, err } - id, _ := res.LastInsertId() return &Run{ID: id, SignalID: signalID, Source: source, Status: "running", StartedAt: now}, func() { running.Delete(key) }, nil } diff --git a/internal/enrich/enrich.go b/internal/enrich/enrich.go index 8951b8c..e403355 100644 --- a/internal/enrich/enrich.go +++ b/internal/enrich/enrich.go @@ -114,13 +114,13 @@ type Run struct { const timeFormat = time.RFC3339 func record(d *db.DB, r *Run) error { - res, err := d.Exec(`INSERT INTO enrich_runs (kind, subject, at, found, added, credits, result, error) + newID, err := d.Insert(`INSERT INTO enrich_runs (kind, subject, at, found, added, credits, result, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, r.Kind, r.Subject, r.At.UTC().Format(timeFormat), r.Found, r.Added, r.Credits, r.Result, r.Error) if err != nil { return err } - r.ID, err = res.LastInsertId() + r.ID = newID return err } diff --git a/internal/inventory/inventory.go b/internal/inventory/inventory.go index 005a295..18002ac 100644 --- a/internal/inventory/inventory.go +++ b/internal/inventory/inventory.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "strings" + "time" "gopkg.in/yaml.v3" @@ -186,16 +187,16 @@ func Save(d *db.DB, e *Entry) error { return err } if e.ID == 0 { - res, err := d.Exec(`INSERT INTO inventory (name, relationship, data) VALUES (?, ?, ?)`, e.Name, e.Relationship, string(raw)) + newID, err := d.Insert(`INSERT INTO inventory (name, relationship, data) VALUES (?, ?, ?)`, e.Name, e.Relationship, string(raw)) if err != nil { return err } - e.ID, err = res.LastInsertId() + e.ID = newID return err } res, err := d.Exec(`UPDATE inventory SET name = ?, relationship = ?, data = ?, - updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?`, - e.Name, e.Relationship, string(raw), e.ID) + updated_at = ? WHERE id = ?`, + e.Name, e.Relationship, string(raw), time.Now().UTC().Format("2006-01-02T15:04:05Z"), e.ID) if err != nil { return err } diff --git a/internal/legacy/legacy.go b/internal/legacy/legacy.go index 3e84a58..e1d636b 100644 --- a/internal/legacy/legacy.go +++ b/internal/legacy/legacy.go @@ -239,7 +239,7 @@ func importState(d *db.DB, path string) (int, error) { } n := 0 for name, t := range st.LastChecked { - if _, err := d.Exec(`INSERT OR IGNORE INTO fetch_state (key, last_checked) VALUES (?, ?)`, + if _, err := d.Exec(`INSERT INTO fetch_state (key, last_checked) VALUES (?, ?) ON CONFLICT DO NOTHING`, "inventory:"+name, t.UTC().Format(time.RFC3339)); err != nil { return n, err } @@ -309,7 +309,7 @@ func importDismissed(d *db.DB, path string) (int, error) { if !dismissed { continue } - 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 n, err } n++ diff --git a/internal/metrics/clv.go b/internal/metrics/clv.go index d0bfb4b..51a904b 100644 --- a/internal/metrics/clv.go +++ b/internal/metrics/clv.go @@ -92,8 +92,8 @@ type revenueEvent struct { // Pre-payment credit notes already lowered the amount paid. func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) { var out []revenueEvent - rows, err := d.Query(`SELECT customer, coalesce(json_extract(data, '$.status_transitions.paid_at'), created), - coalesce(json_extract(data, '$.amount_paid'), 0) FROM stripe_objects + rows, err := d.Query(`SELECT customer, coalesce(CAST(json_extract(data, '$.status_transitions.paid_at') AS BIGINT), created), + coalesce(CAST(json_extract(data, '$.amount_paid') AS BIGINT), 0) FROM stripe_objects WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != ''`, currency) if err != nil { return nil, err diff --git a/internal/metrics/mrr_test.go b/internal/metrics/mrr_test.go index dabd492..5c5e6d1 100644 --- a/internal/metrics/mrr_test.go +++ b/internal/metrics/mrr_test.go @@ -37,7 +37,7 @@ func addLines(t *testing.T, d *db.DB, ls ...ln) { t.Fatal(err) } } - d.Exec(`INSERT OR IGNORE INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_x', 'usd', '{}')`) + d.Exec(`INSERT INTO stripe_objects (kind, id, currency, data) VALUES ('invoice', 'in_x', 'usd', '{}') ON CONFLICT DO NOTHING`) } // monthly bills a customer $amount a month on the 10th, from one month to diff --git a/internal/outreach/message.go b/internal/outreach/message.go index ee5ada0..e0e81ba 100644 --- a/internal/outreach/message.go +++ b/internal/outreach/message.go @@ -208,13 +208,13 @@ func ForContacts(d *db.DB, ids []int64) (map[int64][]Message, error) { // insert stores a new draft. func insert(d *db.DB, m *Message) error { - res, err := d.Exec(`INSERT INTO outreach (contact_id, signal_id, channel, status, subject, body, to_addr, created_at) + newID, err := d.Insert(`INSERT INTO outreach (contact_id, signal_id, channel, status, subject, body, to_addr, created_at) VALUES (?, ?, ?, 'draft', ?, ?, ?, ?)`, m.ContactID, nullID(m.SignalID), m.Channel, m.Subject, m.Body, m.To, formatTime(m.CreatedAt)) if err != nil { return err } - m.ID, err = res.LastInsertId() + m.ID = newID m.Status = StatusDraft return err } diff --git a/internal/prospects/lists.go b/internal/prospects/lists.go index 1e4a59e..ac00dff 100644 --- a/internal/prospects/lists.go +++ b/internal/prospects/lists.go @@ -21,7 +21,7 @@ func AddedToList(d *db.DB, contactID, listID int64, list string, confirmed bool, c = 1 } _, err := d.Exec(`INSERT INTO list_members (contact_id, list_id, list_name, confirmed, at) VALUES (?, ?, ?, ?, ?) - ON CONFLICT (contact_id, list_id) DO UPDATE SET list_name = excluded.list_name, confirmed = max(confirmed, excluded.confirmed)`, + ON CONFLICT (contact_id, list_id) DO UPDATE SET list_name = excluded.list_name, confirmed = max(list_members.confirmed, excluded.confirmed)`, contactID, listID, list, c, now.UTC().Format(time.RFC3339)) return err } diff --git a/internal/prospects/prospects.go b/internal/prospects/prospects.go index 215f138..29793db 100644 --- a/internal/prospects/prospects.go +++ b/internal/prospects/prospects.go @@ -167,16 +167,14 @@ func AddCompany(d *db.DB, c Company, now time.Time) (id int64, added bool, err e WHERE id = ?`, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, id) return id, false, err } - res, err := d.Exec(`INSERT INTO prospect_companies (name, domain, website, linkedin, industry, size, location, why, + newID, err := d.Insert(`INSERT INTO prospect_companies (name, domain, website, linkedin, industry, size, location, why, source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, c.Name, c.Domain, c.Website, c.LinkedIn, c.Industry, c.Size, c.Location, c.Why, c.Source, c.SourceDetail, formatTime(now), nullID(c.SignalID)) if err != nil { return 0, false, err } - if id, err = res.LastInsertId(); err != nil { - return 0, false, err - } + id = newID return id, true, found(d, "company", id, c.SignalID, c.Source, "", now) } @@ -274,16 +272,14 @@ func AddContact(d *db.DB, c Contact, now time.Time) (id int64, added bool, err e WHERE id = ?`, company, c.Email, c.FirstName, c.LastName, c.Title, c.EmailStatus, c.EmailStatus, c.LinkedIn, c.Phone, id) return id, false, err } - res, err := d.Exec(`INSERT INTO prospect_contacts (company_id, first_name, last_name, title, email, email_status, + newID, err := d.Insert(`INSERT INTO prospect_contacts (company_id, first_name, last_name, title, email, email_status, linkedin, phone, source, source_detail, found_at, signal_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, company, c.FirstName, c.LastName, c.Title, c.Email, c.EmailStatus, c.LinkedIn, c.Phone, c.Source, c.SourceDetail, formatTime(now), nullID(c.SignalID)) if err != nil { return 0, false, err } - if id, err = res.LastInsertId(); err != nil { - return 0, false, err - } + id = newID if c.CompanyID == 0 { err = found(d, "contact", id, c.SignalID, c.Source, c.Email, now) } @@ -900,7 +896,7 @@ func Suppress(d *db.DB, kind, value, reason string, now time.Time) error { return err } if _, err := d.Exec(`INSERT INTO suppressions (kind, value, reason) VALUES (?, ?, ?) - ON CONFLICT (kind, value) DO UPDATE SET reason = CASE WHEN excluded.reason != '' THEN excluded.reason ELSE reason END`, + ON CONFLICT (kind, value) DO UPDATE SET reason = CASE WHEN excluded.reason != '' THEN excluded.reason ELSE suppressions.reason END`, kind, value, strings.TrimSpace(reason)); err != nil { return err } diff --git a/internal/seo/audit.go b/internal/seo/audit.go index ba44037..95b434f 100644 --- a/internal/seo/audit.go +++ b/internal/seo/audit.go @@ -742,11 +742,7 @@ func siteChecks(a *Audit, rob *robots, llms *fetched, mapErr error, mapped int) // StartAudit records that an audit began. func StartAudit(d *db.DB, site string, now time.Time) (int64, error) { - res, err := d.Exec(`INSERT INTO seo_audits (site, status, started_at) VALUES (?, 'running', ?)`, site, now.UTC().Format(time.RFC3339)) - if err != nil { - return 0, err - } - return res.LastInsertId() + return d.Insert(`INSERT INTO seo_audits (site, status, started_at) VALUES (?, 'running', ?)`, site, now.UTC().Format(time.RFC3339)) } // FinishAudit stores an audit's result, or its error. diff --git a/internal/seo/briefs.go b/internal/seo/briefs.go index 801940b..2beb0d7 100644 --- a/internal/seo/briefs.go +++ b/internal/seo/briefs.go @@ -299,13 +299,13 @@ Answer with JSON only, in this shape: if page == "" { b.Path = "/" + slugify(b.Keyword) + "/" } - r, err := d.Exec(`INSERT INTO seo_briefs (site, property, keyword, page, status, shown_for, top, plan, answers, path, searches, created_at) + newID, err := d.Insert(`INSERT INTO seo_briefs (site, property, keyword, page, status, shown_for, top, plan, answers, path, searches, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, b.Site, b.Property, b.Keyword, b.Page, b.Status, js(b.ShownFor), js(b.Top), js(b.Plan), js(b.Answers), b.Path, b.Searches, now.UTC().Format(time.RFC3339)) if err != nil { return nil, err } - b.ID, _ = r.LastInsertId() + b.ID = newID return b, nil } diff --git a/internal/seo/changes.go b/internal/seo/changes.go index fcd815d..99df145 100644 --- a/internal/seo/changes.go +++ b/internal/seo/changes.go @@ -150,13 +150,13 @@ func ChangesIn(d *db.DB, statuses ...string) ([]Change, error) { } func insertChange(d *db.DB, c *Change) error { - res, err := d.Exec(`INSERT INTO seo_changes (site, property, page, cur_title, new_title, cur_description, new_description, why, + newID, err := d.Insert(`INSERT INTO seo_changes (site, property, page, cur_title, new_title, cur_description, new_description, why, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, c.Site, c.Property, c.Page, c.CurTitle, c.NewTitle, c.CurDescription, c.NewDescription, c.Why, ChangeProposed, c.CreatedAt.UTC().Format(time.RFC3339)) if err != nil { return err } - c.ID, err = res.LastInsertId() + c.ID = newID c.Status = ChangeProposed return err } diff --git a/internal/seo/keywords.go b/internal/seo/keywords.go index bd9246d..d544f82 100644 --- a/internal/seo/keywords.go +++ b/internal/seo/keywords.go @@ -171,7 +171,7 @@ func FindKeywords(ctx context.Context, d *db.DB, site, property string, p *profi rows, err := d.Query(`SELECT query, sum(impressions), sum(pos_sum), (SELECT page FROM gsc_query_days q2 WHERE q2.site = q.site AND q2.query = q.query AND q2.date BETWEEN ? AND ? GROUP BY page ORDER BY sum(impressions) DESC LIMIT 1) - FROM gsc_query_days q WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY query + FROM gsc_query_days q WHERE `+cond+` AND date BETWEEN ? AND ? GROUP BY site, query HAVING sum(impressions) >= 20 AND sum(pos_sum) / sum(impressions) > 20 ORDER BY sum(impressions) DESC LIMIT 200`, append(args, from, to)...) if err != nil { diff --git a/internal/signals/signals.go b/internal/signals/signals.go index 1614384..ec5a4dc 100644 --- a/internal/signals/signals.go +++ b/internal/signals/signals.go @@ -119,13 +119,13 @@ func Save(d *db.DB, s *Signal) error { } now := formatTime(time.Now()) if s.ID == 0 { - res, err := d.Exec(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at, + newID, err := d.Insert(`INSERT INTO signals (slug, name, hypothesis, spot, angle, status, created_at, updated_at, discover_every_days, explee_definition) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, s.Slug, s.Name, s.Hypothesis, s.Spot, s.Angle, s.Status, now, now, s.DiscoverEveryDays, s.ExpleeDefinition) if err != nil { return err } - s.ID, err = res.LastInsertId() + s.ID = newID return err } res, err := d.Exec(`UPDATE signals SET slug = ?, name = ?, hypothesis = ?, spot = ?, angle = ?, status = ?, updated_at = ?, diff --git a/internal/sites/pages.go b/internal/sites/pages.go index c322c88..0077bc9 100644 --- a/internal/sites/pages.go +++ b/internal/sites/pages.go @@ -211,7 +211,7 @@ func Pages(d *db.DB, site string) ([]SitePage, error) { // SignalPages lists a buying signal's pages, on every site, oldest first // (so variants follow the page they're made from). func SignalPages(d *db.DB, signal int64) ([]SitePage, error) { - rows, err := d.Query(`SELECT `+pageCols+` FROM site_pages WHERE json_extract(source, '$.signal') = ? ORDER BY id`, signal) + rows, err := d.Query(`SELECT `+pageCols+` FROM site_pages WHERE CAST(json_extract(source, '$.signal') AS BIGINT) = ? ORDER BY id`, signal) if err != nil { return nil, err } @@ -274,7 +274,7 @@ func SavePage(d *db.DB, p *SitePage) error { if p.Status == "" { p.Status = PageDraft } - res, err := d.Exec(`INSERT INTO site_pages (site, repo, kind, source, notes, path, title, description, sections, needs, warnings, + newID, err := d.Insert(`INSERT INTO site_pages (site, repo, kind, source, notes, path, title, description, sections, needs, warnings, claims, status, branch, file, pr_number, pr_url, note, error, created_at, updated_at, merged_at, removal_branch, removal_pr_number, removal_pr_url, live_at, gone_at, checked_at, live_note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, @@ -285,7 +285,7 @@ func SavePage(d *db.DB, p *SitePage) error { if err != nil { return err } - p.ID, err = res.LastInsertId() + p.ID = newID return err } res, err := d.Exec(`UPDATE site_pages SET site = ?, repo = ?, kind = ?, source = ?, notes = ?, path = ?, title = ?, description = ?, diff --git a/internal/tracking/referrers.go b/internal/tracking/referrers.go index 94c6080..945cfc8 100644 --- a/internal/tracking/referrers.go +++ b/internal/tracking/referrers.go @@ -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 } diff --git a/internal/web/backups.go b/internal/web/backups.go index 93a5b19..c953cae 100644 --- a/internal/web/backups.go +++ b/internal/web/backups.go @@ -32,6 +32,9 @@ func (s *Server) RunBackups(ctx context.Context) { } func (s *Server) dailyBackup(now time.Time) { + if s.DB.Dialect != db.SQLite { + return // Postgres is backed up by whoever runs it + } due, err := backup.DueDaily(s.backupDir(), now) if err != nil { s.Log.Warn("backups: listing", "err", err) @@ -40,7 +43,7 @@ func (s *Server) dailyBackup(now time.Time) { if !due { return } - if _, err := backup.Make(s.DB.DB, s.backupDir(), backup.Daily, "", now); err != nil { + if _, err := backup.Make(s.DB.SQL, s.backupDir(), backup.Daily, "", now); err != nil { s.Log.Error("backups: the daily backup failed", "err", err) return } @@ -85,7 +88,7 @@ func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) { } switch r.PathValue("action") { case "now": - b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, r.PostFormValue("note"), time.Now()) + b, err := backup.Make(s.DB.SQL, s.backupDir(), backup.Manual, r.PostFormValue("note"), time.Now()) if err != nil { s.renderBackups(w, r, err.Error(), "") return @@ -136,7 +139,7 @@ func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) { // apply it. Without a way to restart (tests, or not under Docker) it's // left staged for the next start. func (s *Server) restore(w http.ResponseWriter, r *http.Request, path string) { - res, err := backup.Stage(s.DB.DB, s.DataDir, path, db.Schema(), time.Now()) + res, err := backup.Stage(s.DB.SQL, s.DataDir, path, db.Schema(), time.Now()) if err != nil { s.renderBackups(w, r, "Not restored: "+err.Error(), "") return diff --git a/internal/web/backups_test.go b/internal/web/backups_test.go index 33a0b8b..26f5803 100644 --- a/internal/web/backups_test.go +++ b/internal/web/backups_test.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "strings" + "supermarket/internal/db" "sync/atomic" "testing" "time" @@ -16,6 +17,9 @@ import ( ) func TestBackupsPage(t *testing.T) { + if db.OnPostgres() { + t.Skip("SQLite's own backups") + } s, h := newTestServer(t, nil) if body := do(h, http.MethodGet, "/settings/backups", nil, nil).Body.String(); !strings.Contains(body, "No backups yet") { t.Errorf("empty: %s", body) @@ -58,9 +62,12 @@ func TestBackupsPage(t *testing.T) { } func TestRestoreFromThePage(t *testing.T) { + if db.OnPostgres() { + t.Skip("SQLite's own backups") + } s, h := newTestServer(t, nil) s.DB.PutJSON("test:value", "before") - b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, "good", time.Now().Add(-time.Hour)) + b, err := backup.Make(s.DB.SQL, s.backupDir(), backup.Manual, "good", time.Now().Add(-time.Hour)) if err != nil { t.Fatal(err) } @@ -89,8 +96,11 @@ func TestRestoreFromThePage(t *testing.T) { } func TestBackupUpload(t *testing.T) { + if db.OnPostgres() { + t.Skip("SQLite's own backups") + } s, h := newTestServer(t, nil) - b, _ := backup.Make(s.DB.DB, t.TempDir(), backup.Manual, "elsewhere", time.Now()) + b, _ := backup.Make(s.DB.SQL, t.TempDir(), backup.Manual, "elsewhere", time.Now()) raw, _ := os.ReadFile(b.Path) upload := func(name string, content []byte) string { var buf bytes.Buffer diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go index b61e051..c7719f6 100644 --- a/internal/web/engines_test.go +++ b/internal/web/engines_test.go @@ -64,7 +64,7 @@ func TestEnginesPage(t *testing.T) { func TestMarginsForm(t *testing.T) { s, h := newTestServer(t, nil) s.DB.Exec(`INSERT INTO stripe_invoice_lines (invoice, id, status, currency, amount, period_start, product, description) - VALUES ('in_1', 'il_1', 'paid', 'usd', 4900, strftime('%s', 'now'), 'prod_core', '1 × Federated Core (at $49.00 / month)')`) + VALUES ('in_1', 'il_1', 'paid', 'usd', 4900, ?, 'prod_core', '1 × Federated Core (at $49.00 / month)')`, time.Now().Unix()) if body := do(h, http.MethodGet, "/metrics", nil, nil).Body.String(); !strings.Contains(body, "Federated Core") || !strings.Contains(body, `placeholder="60"`) { t.Fatal("the margin table isn't shown") }