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:
+14
-7
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
@@ -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:<hash>
|
||||
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:<person>…
|
||||
email TEXT COLLATE nocase NOT NULL DEFAULT '', -- to tie it to the CRM and Stripe later
|
||||
campaign TEXT NOT NULL DEFAULT '', -- origami:<id>, explee:<id>; 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);
|
||||
Reference in New Issue
Block a user