diff --git a/PLAN.md b/PLAN.md index b9b4cd2..2b6a494 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2002,6 +2002,41 @@ than planned: rather than helpers in every query, the SQL stays as it is server would. - The backup loop stays as it is: it's the local edition's, with one copy. +**Part 7 built 2026-11-25** on `phase9`. **Phase 9 is built.** +- `internal/transfer`: an export is a `.tar.gz` with: + - a manifest (format, schema, app version, rows per table, secrets) + - each table's rows as JSON lines + - with `--with-secrets`, the keys and tokens + + It's written from either database and loaded into either. Left out: + running copies, locks, sign-ins under way, the schema bookkeeping. +- An import is checked before loading: + - The target must be empty, apart from the IndexNow key a new install + writes at start, which the export's replaces: the website publishes + the old one. + - The target must be at the same schema. + - Every table in the export must exist there. + + Then everything loads in one transaction, parents before children, in + batches. Each table's row count is checked against the manifest, and + Postgres' identity counters are moved past the imported ids. +- `supermarket export [--with-secrets]` writes to the file storage + (`files/exports/` on the local edition). `supermarket import ` + takes a path or an export's name; the host's command copies a file from + elsewhere into the data folder first. +- Checked on Federated's install: 112,543 rows in 39 tables, 3.4 MB. + - Imported into Postgres in 4 seconds, with every table's count and + sample totals the same. + - Imported into a new SQLite too. All 57 pages (with each signal's) + render the same from both, by `TestPagesOnRealData`. +- That comparison found order that wasn't settled, now fixed: + - Two campaigns named alike but for case. + - Two Stripe customers with the same name and email. + - The invoice lines and payments behind Metrics. Read in any order, their + float sums put one figure at −$280 or −$281. +- Moving a local install into multi-tenant as a new team comes with + Phase 13. + 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 cd35de0..83a938b 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,14 @@ File storage (`internal/storage`) is tested on a folder, and on an S3-compatible bucket when `SUPERMARKET_TEST_S3` names one, such as a Garage in Docker: `SUPERMARKET_TEST_S3='http://ACCESS_KEY:SECRET_KEY@127.0.0.1:3900/bucket'`. +To check every page renders the same from real data on both databases: +`supermarket export`, import the file into a new Postgres database and a new +SQLite one (`supermarket import`, with each edition's settings), then +`SUPERMARKET_TEST_PAGES_DB=postgres://… SUPERMARKET_TEST_PAGES_SQLITE=…/app.db +go test -run TestPagesOnRealData ./internal/web`. Queries whose rows are +summed or shown in order need an `ORDER BY` that settles every tie: the two +databases break ties differently. + **Changing the schema.** Add a `db.Migration` to `both` in `internal/db/migrations.go`, written in SQLite's SQL. Postgres gets the same statements translated (`INTEGER` → `BIGINT`, `INTEGER PRIMARY KEY` → an identity @@ -262,6 +270,8 @@ together), and each is recorded in `schema_migrations`. | `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/transfer` | Export and import: a whole Supermarket as a `.tar.gz`, between SQLite and Postgres | +| `internal/jobs` | Locks shared by copies of the app, so only one does each job | | `internal/storage` | Files that must last (exports, uploads): a folder, or an S3 bucket (Garage) | | `internal/web` | Pages (Go templates + [htmx](https://htmx.org), no JavaScript build) | | `internal/profile`, `internal/inventory` | The company profile and the inventory | diff --git a/TEST.md b/TEST.md index d3f36e1..f47f120 100644 --- a/TEST.md +++ b/TEST.md @@ -809,3 +809,8 @@ Throughout, also notice: now. While an audit runs, `audit:` shows under *Under way*. - [ ] Connecting a social account or Search Console still works (sign-ins under way are now kept in the database). +- [ ] `supermarket export` writes `files/exports/supermarket-.tar.gz` + in the data folder, readable only by you, and says keys and tokens + aren't in it. With `--with-secrets`, it says how many are, and warns. +- [ ] `supermarket import ` on this install refuses: the database + isn't empty. Nothing changes. diff --git a/bin/supermarket b/bin/supermarket index 51d0f17..440e44c 100755 --- a/bin/supermarket +++ b/bin/supermarket @@ -20,6 +20,9 @@ Usage: supermarket [command] token Print the token agents use to reach Supermarket's MCP endpoint data Print where its data is kept config Show its edition and settings, and any problems with them + export [--with-secrets] Export everything (to move to a server, or + another computer); with --with-secrets, keys and tokens too + import Load an export into a new, empty Supermarket backup [note] Back up the database now (it also backs up daily) backup --with-secrets The same, with your keys and tokens, for moving to another computer (keep the file safe) @@ -64,7 +67,30 @@ case "${1:-open}" in logs) compose logs -f --tail 200 ;; hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;; token) cat "$DATA/mcp-token" ;; - backup|backups|config) + import) + if ! docker exec supermarket true 2> /dev/null; then + echo "Supermarket isn't running: start it first (supermarket start)." + exit 1 + fi + if [ -z "${2:-}" ]; then + echo "Usage: supermarket import " + exit 1 + fi + target="$2" + # A file elsewhere on this computer is copied in, where the app sees it. + if [ -f "$target" ]; then + case "$(realpath "$target")" in + "$(realpath "$DATA")"/*) ;; + *) + mkdir -p "$DATA/files/imports" + install -m 600 "$target" "$DATA/files/imports/$(basename "$target")" + target="imports/$(basename "$target")" + ;; + esac + fi + docker exec supermarket supermarket import "$target" + ;; + backup|backups|config|export) if ! docker exec supermarket true 2> /dev/null; then echo "Supermarket isn't running: start it first (supermarket start)." exit 1 diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index d9d1ea0..ce61da9 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -25,6 +25,7 @@ import ( "encoding/hex" "errors" "fmt" + "io" "log/slog" "net/http" "os" @@ -47,6 +48,7 @@ import ( "supermarket/internal/mcpserver" "supermarket/internal/secrets" "supermarket/internal/storage" + "supermarket/internal/transfer" "supermarket/internal/web" ) @@ -70,6 +72,13 @@ func main() { if len(os.Args) > 1 && os.Args[1] == "config" { os.Exit(configCommand()) } + if len(os.Args) > 1 && (os.Args[1] == "export" || os.Args[1] == "import") { + if err := transferCommand(os.Args[1], os.Args[2:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") { if err := backupCommand(os.Args[1], os.Args[2:]); err != nil { fmt.Fprintln(os.Stderr, err) @@ -461,3 +470,152 @@ func backupCommand(cmd string, args []string) error { fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20)) return nil } + +// openForCommand opens the edition's database and secrets, for commands +// run beside the app (export, import). +func openForCommand(cfg *config.Config) (*db.DB, *secrets.Store, error) { + if cfg.Edition == config.Local { + d, err := db.OpenSQLite(filepath.Join(cfg.DataDir, "app.db")) + if err != nil { + return nil, nil, err + } + sec, err := secrets.Open(filepath.Join(cfg.DataDir, "secrets.json")) + if err != nil { + d.Close() + return nil, nil, err + } + return d, sec, nil + } + db.AppVersion = version + d, err := db.OpenPostgres(cfg.DatabaseURL) + if err != nil { + return nil, nil, err + } + sec, err := secrets.OpenDB(d, cfg.SecretKey, cfg.OldKey) + if err != nil { + d.Close() + return nil, nil, err + } + return d, sec, nil +} + +// hostPath is where a stored file is on the host, for the local edition's +// folder; else its name in the store. +func hostPath(cfg *config.Config, key string) string { + if !cfg.Storage.S3() && cfg.Storage.Dir == filepath.Join(cfg.DataDir, "files") { + return filepath.Join(cfg.HostData, "files", filepath.FromSlash(key)) + } + if !cfg.Storage.S3() { + return filepath.Join(cfg.Storage.Dir, filepath.FromSlash(key)) + } + return cfg.Storage.String() + "/" + key +} + +// transferCommand runs `supermarket export [--with-secrets]` and +// `supermarket import `. +func transferCommand(cmd string, args []string) error { + cfg, err := config.Load(os.Getenv) + if err != nil { + return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err) + } + files, err := storage.Open(cfg.Storage) + if err != nil { + return err + } + d, sec, err := openForCommand(cfg) + if err != nil { + return err + } + defer d.Close() + ctx := context.Background() + + if cmd == "export" { + withSecrets := len(args) > 0 && args[0] == "--with-secrets" + if len(args) > 1 || (len(args) == 1 && !withSecrets) { + return errors.New("usage: supermarket export [--with-secrets]") + } + tmp, err := os.CreateTemp("", "export-*.tar.gz") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) + defer tmp.Close() + var from *secrets.Store + if withSecrets { + from = sec + } + m, err := transfer.Export(ctx, d, from, version, tmp) + if err != nil { + return err + } + size, _ := tmp.Seek(0, io.SeekCurrent) + tmp.Seek(0, io.SeekStart) + key := "exports/supermarket-" + time.Now().Format("20060102-150405") + if withSecrets { + key += "-with-secrets" + } + key += ".tar.gz" + if err := files.Put(ctx, key, tmp, size); err != nil { + return err + } + rows := 0 + for _, n := range m.Tables { + rows += n + } + fmt.Printf("Exported %d rows from %d tables (schema %d) to %s (%.1f MB)\n", rows, len(m.Tables), m.Schema, hostPath(cfg, key), float64(size)/(1<<20)) + if withSecrets { + fmt.Printf("It holds %d keys and tokens: keep it as safe as they are, and delete it once you've moved.\n", m.Secrets) + } else { + fmt.Println("Keys and tokens aren't in it: add --with-secrets to take them too, or enter them again after the move.") + } + return nil + } + + if len(args) != 1 { + return errors.New("usage: supermarket import ") + } + open, where, err := exportOpener(ctx, cfg, files, args[0]) + if err != nil { + return err + } + res, err := transfer.Import(ctx, d, sec, open) + if err != nil { + return err + } + rows := 0 + for _, n := range res.Tables { + rows += n + } + fmt.Printf("Imported %d rows into %d tables, and %d keys and tokens, from %s (made %s on %s, schema %d).\n", + rows, len(res.Tables), res.Secrets, where, res.Manifest.Created.Local().Format("2 Jan 2006 15:04"), res.Manifest.From, res.Manifest.Schema) + if cfg.Edition == config.Local { + fmt.Println("Restart Supermarket to see it: supermarket restart") + } + return nil +} + +// exportOpener finds an export: a file, or a name in the file storage +// (as supermarket export printed it, or under exports/ or imports/). +func exportOpener(ctx context.Context, cfg *config.Config, files storage.Store, arg string) (func() (io.ReadCloser, error), string, error) { + // A path on the host, in the data folder, is /data inside the container. + p := arg + if rel, err := filepath.Rel(cfg.HostData, arg); err == nil && filepath.IsAbs(arg) && !strings.HasPrefix(rel, "..") { + p = filepath.Join(cfg.DataDir, rel) + } + if fi, err := os.Stat(p); err == nil && !fi.IsDir() { + return func() (io.ReadCloser, error) { return os.Open(p) }, arg, nil + } + name := filepath.ToSlash(arg) + if i := strings.Index(name, "/files/"); i >= 0 { // as export printed it + name = name[i+len("/files/"):] + } + for _, key := range []string{name, "exports/" + name, "imports/" + name} { + if storage.CheckKey(key) != nil { + continue + } + if _, err := files.Stat(ctx, key); err == nil { + return func() (io.ReadCloser, error) { return files.Get(ctx, key) }, hostPath(cfg, key), nil + } + } + return nil, "", fmt.Errorf("no export at %s", arg) +} diff --git a/internal/metrics/clv.go b/internal/metrics/clv.go index 51a904b..259d6eb 100644 --- a/internal/metrics/clv.go +++ b/internal/metrics/clv.go @@ -94,7 +94,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) { var out []revenueEvent 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) + WHERE kind = 'invoice' AND status = 'paid' AND currency = ? AND customer != '' ORDER BY id`, currency) if err != nil { return nil, err } @@ -110,7 +110,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) { } rows.Close() rows, err = d.Query(`SELECT customer, created, amount FROM stripe_objects - WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != ''`, currency) + WHERE kind = 'refund' AND status = 'succeeded' AND currency = ? AND customer != '' ORDER BY id`, currency) if err != nil { return nil, err } @@ -125,7 +125,7 @@ func cashFlows(d *db.DB, currency string) ([]revenueEvent, error) { } rows.Close() rows, err = d.Query(`SELECT customer, created, data FROM stripe_objects - WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != ''`, currency) + WHERE kind = 'credit_note' AND status = 'issued' AND currency = ? AND customer != '' ORDER BY id`, currency) if err != nil { return nil, err } diff --git a/internal/metrics/crmmatch.go b/internal/metrics/crmmatch.go index 05a5c20..7d33a74 100644 --- a/internal/metrics/crmmatch.go +++ b/internal/metrics/crmmatch.go @@ -266,7 +266,10 @@ func Matches(d *db.DB, model *Model) ([]Match, error) { case a.MRR < b.MRR: return 1 } - return strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email)) + if c := strings.Compare(strings.ToLower(a.Customer.Name+a.Customer.Email), strings.ToLower(b.Customer.Name+b.Customer.Email)); c != 0 { + return c + } + return strings.Compare(a.Customer.ID, b.Customer.ID) // the same name and email twice: a stable order }) return out, nil } diff --git a/internal/metrics/mrr.go b/internal/metrics/mrr.go index ac5a454..6dc4c5b 100644 --- a/internal/metrics/mrr.go +++ b/internal/metrics/mrr.go @@ -51,7 +51,7 @@ func (l line) monthly() float64 { func loadLines(d *db.DB, currency string) ([]line, error) { rows, err := d.Query(`SELECT customer, amount, period_start, period_end, interval, interval_count, proration, product FROM stripe_invoice_lines WHERE recurring = 1 AND status IN ('paid', 'open') AND currency = ? AND customer != '' - AND period_end > period_start`, currency) + AND period_end > period_start ORDER BY invoice, id`, currency) // a fixed order: float sums come out the same everywhere if err != nil { return nil, err } diff --git a/internal/signals/funnel.go b/internal/signals/funnel.go index a36bfc0..f86ef4b 100644 --- a/internal/signals/funnel.go +++ b/internal/signals/funnel.go @@ -285,7 +285,7 @@ func AssignCampaign(d *db.DB, source, id string, signalID int64) error { // Campaigns lists the outside campaigns, unassigned first, newest sync first. func Campaigns(d *db.DB) ([]Campaign, error) { rows, err := d.Query(`SELECT source, id, name, status, coalesce(signal_id, 0), spend_cents, stats, synced_at - FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE`) + FROM outside_campaigns ORDER BY signal_id IS NOT NULL, source, name COLLATE NOCASE, id`) if err != nil { return nil, err } diff --git a/internal/signals/signals.go b/internal/signals/signals.go index ec5a4dc..34822f5 100644 --- a/internal/signals/signals.go +++ b/internal/signals/signals.go @@ -186,7 +186,7 @@ func Get(d *db.DB, id int64) (*Signal, error) { // retired; by name within each. func List(d *db.DB) ([]Signal, error) { rows, err := d.Query(`SELECT ` + columns + ` FROM signals ORDER BY - CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE`) + CASE status WHEN 'testing' THEN 0 WHEN 'idea' THEN 1 WHEN 'proven' THEN 2 ELSE 3 END, name COLLATE NOCASE, id`) if err != nil { return nil, err } diff --git a/internal/transfer/rewrite_test.go b/internal/transfer/rewrite_test.go new file mode 100644 index 0000000..d120ed4 --- /dev/null +++ b/internal/transfer/rewrite_test.go @@ -0,0 +1,34 @@ +package transfer + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "io" + "testing" + "time" +) + +// rewrite replaces one file in an export. +func rewrite(t *testing.T, export []byte, name, body string) []byte { + t.Helper() + var out bytes.Buffer + gz := gzip.NewWriter(&out) + tw := tar.NewWriter(gz) + err := walk(bytes.NewReader(export), func(n string, r io.Reader) error { + raw, err := io.ReadAll(r) + if err != nil { + return err + } + if n == name { + raw = []byte(body) + } + return addFile(tw, n, raw, time.Now()) + }) + if err != nil { + t.Fatal(err) + } + tw.Close() + gz.Close() + return out.Bytes() +} diff --git a/internal/transfer/transfer.go b/internal/transfer/transfer.go new file mode 100644 index 0000000..21463a1 --- /dev/null +++ b/internal/transfer/transfer.go @@ -0,0 +1,543 @@ +// Package transfer moves a whole Supermarket from one database to +// another: an export is a .tar.gz of every table's rows (as JSON lines), +// a manifest, and, if asked for, the secrets. It reads from SQLite or +// Postgres and loads into either, so a local install can move to a +// server. +package transfer + +import ( + "archive/tar" + "bufio" + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "slices" + "strings" + "time" + + "supermarket/internal/db" + "supermarket/internal/secrets" +) + +// Format is this export format's version. +const Format = 1 + +// Manifest describes an export. +type Manifest struct { + Format int `json:"format"` + Schema int `json:"schema"` + App string `json:"app"` + From string `json:"from"` // SQLite, Postgres + Created time.Time `json:"created"` + Tables map[string]int `json:"tables"` // rows per table + Secrets int `json:"secrets"` +} + +// skipped are tables about the database or machine itself, not the +// company's data. Secrets go in secrets.json, opened, if asked for. +var skipped = map[string]bool{ + "instances": true, "locks": true, "schema_version": true, "schema_migrations": true, "secrets": true, +} + +// startupSettings are settings a new install writes when it first starts: +// a database holding only those is still empty, and the export's values +// replace them (the IndexNow key the website publishes is the old one). +var startupSettings = []string{"seo:indexnow-key"} + +// skipRow leaves out settings only meaningful where they were made. +func skipRow(table string, row map[string]any) bool { + if table != "settings" { + return false + } + k, _ := row["key"].(string) + return strings.HasPrefix(k, "oauth:flow:") +} + +// Tables are the database's tables to move, parents before children +// (by foreign keys). +func Tables(d *db.DB) ([]string, error) { + var q string + if d.Dialect == db.Postgres { + q = `SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE'` + } else { + q = `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'` + } + names, err := strs(d, q) + if err != nil { + return nil, err + } + deps := map[string][]string{} + for _, t := range names { + if d.Dialect == db.Postgres { + deps[t], err = strs(d, `SELECT DISTINCT ccu.table_name FROM information_schema.table_constraints tc + JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema + WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = current_schema() AND tc.table_name = ?`, t) + } else { + deps[t], err = strs(d, `SELECT DISTINCT "table" FROM pragma_foreign_key_list(?)`, t) + } + if err != nil { + return nil, err + } + } + slices.Sort(names) + var out []string + done := map[string]bool{} + var visit func(t string, stack []string) error + visit = func(t string, stack []string) error { + if done[t] { + return nil + } + if slices.Contains(stack, t) { + return fmt.Errorf("tables refer to each other in a loop: %v", append(stack, t)) + } + for _, p := range deps[t] { + if p != t { + if err := visit(p, append(stack, t)); err != nil { + return err + } + } + } + done[t] = true + if !skipped[t] { + out = append(out, t) + } + return nil + } + for _, t := range names { + if err := visit(t, nil); err != nil { + return nil, err + } + } + return out, nil +} + +func strs(d *db.DB, q string, args ...any) ([]string, error) { + rows, err := d.Query(q, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []string + for rows.Next() { + var s string + if err := rows.Scan(&s); err != nil { + return nil, err + } + out = append(out, s) + } + return out, rows.Err() +} + +// columns are a table's columns, in order. +func columns(d *db.DB, table string) ([]string, error) { + if d.Dialect == db.Postgres { + return strs(d, `SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position`, table) + } + return strs(d, `SELECT name FROM pragma_table_info(?) ORDER BY cid`, table) +} + +// quote quotes a name for SQL (both databases). +func quote(name string) string { return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` } + +// Export writes d's data to w as a .tar.gz; with sec, its secrets too +// (opened: the file holds credentials). +func Export(ctx context.Context, d *db.DB, sec *secrets.Store, app string, w io.Writer) (*Manifest, error) { + version, err := d.SchemaVersion() + if err != nil { + return nil, err + } + m := &Manifest{Format: Format, Schema: version, App: app, From: d.Dialect.String(), Created: time.Now().UTC(), Tables: map[string]int{}} + tables, err := Tables(d) + if err != nil { + return nil, err + } + gz := gzip.NewWriter(w) + tw := tar.NewWriter(gz) + for _, t := range tables { + if err := ctx.Err(); err != nil { + return nil, err + } + n, err := exportTable(d, t, tw, m.Created) + if err != nil { + return nil, fmt.Errorf("%s: %w", t, err) + } + m.Tables[t] = n + } + if sec != nil { + vals := map[string]string{} + for _, name := range sec.Names() { + vals[name] = sec.Get(name) + } + m.Secrets = len(vals) + raw, _ := json.MarshalIndent(vals, "", " ") + if err := addFile(tw, "secrets.json", raw, m.Created); err != nil { + return nil, err + } + } + raw, _ := json.MarshalIndent(m, "", " ") + if err := addFile(tw, "manifest.json", raw, m.Created); err != nil { + return nil, err + } + if err := tw.Close(); err != nil { + return nil, err + } + return m, gz.Close() +} + +// exportTable writes a table's rows as JSON lines. They're spooled to a +// temporary file first: tar needs the size before the contents. +func exportTable(d *db.DB, table string, tw *tar.Writer, at time.Time) (int, error) { + cols, err := columns(d, table) + if err != nil { + return 0, err + } + tmp, err := os.CreateTemp("", "export-*.jsonl") + if err != nil { + return 0, err + } + defer os.Remove(tmp.Name()) + defer tmp.Close() + bw := bufio.NewWriter(tmp) + enc := json.NewEncoder(bw) + quoted := make([]string, len(cols)) + for i, c := range cols { + quoted[i] = quote(c) + } + rows, err := d.Query(`SELECT ` + strings.Join(quoted, ", ") + ` FROM ` + quote(table)) + if err != nil { + return 0, err + } + defer rows.Close() + n := 0 + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } + for rows.Next() { + if err := rows.Scan(ptrs...); err != nil { + return n, err + } + row := make(map[string]any, len(cols)) + for i, c := range cols { + v := vals[i] + if b, ok := v.([]byte); ok { // SQLite text read as bytes + v = string(b) + } + row[c] = v + } + if skipRow(table, row) { + continue + } + if err := enc.Encode(row); err != nil { + return n, err + } + n++ + } + if err := rows.Err(); err != nil { + return n, err + } + if err := bw.Flush(); err != nil { + return n, err + } + size, err := tmp.Seek(0, io.SeekCurrent) + if err != nil { + return n, err + } + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + return n, err + } + if err := tw.WriteHeader(&tar.Header{Name: "tables/" + table + ".jsonl", Mode: 0o600, Size: size, ModTime: at}); err != nil { + return n, err + } + _, err = io.Copy(tw, tmp) + return n, err +} + +func addFile(tw *tar.Writer, name string, raw []byte, at time.Time) error { + if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(raw)), ModTime: at}); err != nil { + return err + } + _, err := tw.Write(raw) + return err +} + +// ReadManifest reads an export's manifest without loading it. +func ReadManifest(r io.Reader) (*Manifest, error) { + var m *Manifest + err := walk(r, func(name string, body io.Reader) error { + if name == "manifest.json" { + m = &Manifest{} + return json.NewDecoder(body).Decode(m) + } + return nil + }) + if err == nil && m == nil { + err = errors.New("not a Supermarket export: it has no manifest") + } + return m, err +} + +func walk(r io.Reader, fn func(name string, body io.Reader) error) error { + gz, err := gzip.NewReader(r) + if err != nil { + return fmt.Errorf("not a Supermarket export (.tar.gz): %w", err) + } + tr := tar.NewReader(gz) + for { + h, err := tr.Next() + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + if err := fn(h.Name, tr); err != nil { + return fmt.Errorf("%s: %w", h.Name, err) + } + } +} + +// Imported says what an import did. +type Imported struct { + Manifest *Manifest + Tables map[string]int + Secrets int +} + +// batchParams keeps a multi-row INSERT under both databases' limits on +// parameters (SQLite 32766, Postgres 65535). +const batchParams = 30000 + +// Import loads an export into d, which must be empty and at the same +// schema version; with sec, its secrets go there too. It reads the file +// twice (the manifest is last), so it takes a way to open it. Everything +// happens in one transaction: a failure leaves d as it was. +func Import(ctx context.Context, d *db.DB, sec *secrets.Store, open func() (io.ReadCloser, error)) (*Imported, error) { + f, err := open() + if err != nil { + return nil, err + } + m, err := ReadManifest(f) + f.Close() + if err != nil { + return nil, err + } + if m.Format != Format { + return nil, fmt.Errorf("the export is in format %d; this version reads format %d", m.Format, Format) + } + version, err := d.SchemaVersion() + if err != nil { + return nil, err + } + if m.Schema != version { + return nil, fmt.Errorf("the export is at schema %d and this database at %d: export and import with the same version of Supermarket", m.Schema, version) + } + tables, err := Tables(d) + if err != nil { + return nil, err + } + for _, t := range tables { + var n int + q, args := `SELECT count(*) FROM `+quote(t), []any{} + if t == "settings" { + q += ` WHERE key NOT IN (` + strings.TrimSuffix(strings.Repeat("?, ", len(startupSettings)), ", ") + `)` + for _, k := range startupSettings { + args = append(args, k) + } + } + if err := d.QueryRow(q, args...).Scan(&n); err != nil { + return nil, err + } + if n > 0 { + return nil, fmt.Errorf("this database isn't empty (%s has %d rows): import into a new one", t, n) + } + } + for t := range m.Tables { + if !slices.Contains(tables, t) { + return nil, fmt.Errorf("the export has a table %s that this database doesn't", t) + } + } + + // Read the tables (they're small enough to hold: Federated's 110,000 + // rows are some 30 MB), then insert them parents first. + data := map[string][]byte{} + var secretVals map[string]string + f, err = open() + if err != nil { + return nil, err + } + err = walk(f, func(name string, body io.Reader) error { + switch { + case strings.HasPrefix(name, "tables/") && strings.HasSuffix(name, ".jsonl"): + raw, err := io.ReadAll(body) + data[strings.TrimSuffix(strings.TrimPrefix(name, "tables/"), ".jsonl")] = raw + return err + case name == "secrets.json": + return json.NewDecoder(body).Decode(&secretVals) + } + return nil + }) + f.Close() + if err != nil { + return nil, err + } + + // Every table's columns, read now: SQLite has one connection, which + // the transaction will hold. + cols := map[string][]string{} + for _, t := range tables { + if cols[t], err = columns(d, t); err != nil { + return nil, err + } + } + res := &Imported{Manifest: m, Tables: map[string]int{}} + tx, err := d.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + for _, t := range tables { + raw, ok := data[t] + if !ok { + continue + } + if err := ctx.Err(); err != nil { + return nil, err + } + n, err := importTable(tx, t, cols[t], raw) + if err != nil { + return nil, fmt.Errorf("%s: %w", t, err) + } + if n != m.Tables[t] { + return nil, fmt.Errorf("%s: read %d rows, the manifest says %d", t, n, m.Tables[t]) + } + res.Tables[t] = n + } + if d.Dialect == db.Postgres { + if err := resetIdentities(tx); err != nil { + return nil, err + } + } + if err := tx.Commit(); err != nil { + return nil, err + } + if sec != nil && len(secretVals) > 0 { + if err := sec.Set(secretVals); err != nil { + return res, fmt.Errorf("the data is in, but not the secrets: %w", err) + } + res.Secrets = len(secretVals) + } + return res, nil +} + +// importTable inserts a table's JSON lines, in batches. +func importTable(tx *db.Tx, table string, cols []string, raw []byte) (int, error) { + have := map[string]bool{} + quoted := make([]string, len(cols)) + for i, c := range cols { + have[c] = true + quoted[i] = quote(c) + } + per := max(1, batchParams/len(cols)) + one := "(" + strings.TrimSuffix(strings.Repeat("?, ", len(cols)), ", ") + ")" + var batch []any + rowsIn, n := 0, 0 + flush := func() error { + if rowsIn == 0 { + return nil + } + q := `INSERT INTO ` + quote(table) + ` (` + strings.Join(quoted, ", ") + `) VALUES ` + + strings.TrimSuffix(strings.Repeat(one+", ", rowsIn), ", ") + if table == "settings" { // replacing what a new install wrote at start + q += ` ON CONFLICT (key) DO UPDATE SET value = excluded.value` + } + if _, err := tx.Exec(q, batch...); err != nil { + return err + } + batch, rowsIn = batch[:0], 0 + return nil + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + for { + var row map[string]any + if err := dec.Decode(&row); errors.Is(err, io.EOF) { + break + } else if err != nil { + return n, fmt.Errorf("row %d: %w", n+1, err) + } + for c := range row { + if !have[c] { + return n, fmt.Errorf("the export has a column %s this database doesn't", c) + } + } + for _, c := range cols { + v, err := value(row[c]) + if err != nil { + return n, fmt.Errorf("row %d, %s: %w", n+1, c, err) + } + batch = append(batch, v) + } + rowsIn++ + n++ + if rowsIn == per { + if err := flush(); err != nil { + return n, err + } + } + } + return n, flush() +} + +// value turns a JSON value back into what the database takes. +func value(v any) (any, error) { + switch x := v.(type) { + case json.Number: + if i, err := x.Int64(); err == nil { + return i, nil + } + return x.Float64() + case string: + if strings.ContainsRune(x, 0) { + return strings.ReplaceAll(x, "\x00", ""), nil // Postgres' text can't hold NUL + } + return x, nil + case nil, bool: + return x, nil + } + return nil, fmt.Errorf("unexpected %T", v) +} + +// resetIdentities moves Postgres' identity counters past the imported +// ids, so new rows don't collide with them. +func resetIdentities(tx *db.Tx) error { + rows, err := tx.Query(`SELECT table_name, column_name FROM information_schema.columns + WHERE table_schema = current_schema() AND is_identity = 'YES'`) + if err != nil { + return err + } + type col struct{ table, column string } + var cols []col + for rows.Next() { + var c col + if err := rows.Scan(&c.table, &c.column); err != nil { + rows.Close() + return err + } + cols = append(cols, c) + } + rows.Close() + for _, c := range cols { + if _, err := tx.Exec(`SELECT setval(pg_get_serial_sequence(?, ?), coalesce((SELECT max(`+quote(c.column)+`) FROM `+quote(c.table)+`), 0) + 1, false)`, + quote(c.table), c.column); err != nil { + return fmt.Errorf("%s: %w", c.table, err) + } + } + return nil +} diff --git a/internal/transfer/transfer_test.go b/internal/transfer/transfer_test.go new file mode 100644 index 0000000..891f32a --- /dev/null +++ b/internal/transfer/transfer_test.go @@ -0,0 +1,167 @@ +package transfer + +import ( + "bytes" + "context" + "io" + "path/filepath" + "strings" + "testing" + "time" + + "supermarket/internal/db" + "supermarket/internal/prospects" + "supermarket/internal/secrets" + "supermarket/internal/signals" +) + +func open(t *testing.T, sqlite bool) *db.DB { + t.Helper() + path := filepath.Join(t.TempDir(), "app.db") + var d *db.DB + var err error + if sqlite { + d, err = db.OpenSQLite(path) + } else { + d, err = db.Open(path) // Postgres when tests run on it + } + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Close() }) + return d +} + +// A local install (SQLite) moves to the test database (Postgres when the +// tests run on it), with its rows, ids, case-insensitive text, and +// secrets. +func TestExportImport(t *testing.T) { + src := open(t, true) + now := time.Date(2026, 11, 25, 9, 0, 0, 0, time.UTC) + sig := &signals.Signal{Name: "Leaving M365", Spot: "m365 alternative"} + if err := signals.Save(src, sig); err != nil { + t.Fatal(err) + } + co, _, err := prospects.AddCompany(src, prospects.Company{Name: "Acme", Domain: "Acme.com", Source: "manual", SignalID: sig.ID}, now) + if err != nil { + t.Fatal(err) + } + if _, _, err := prospects.AddContact(src, prospects.Contact{CompanyID: co, FirstName: "Ann", Email: "Ann@Acme.com", Source: "manual", SignalID: sig.ID}, now); err != nil { + t.Fatal(err) + } + src.PutJSON("test:setting", map[string]any{"big": int64(9007199254740993), "f": 1.5, "s": "it's \"quoted\"\nand ünïcode"}) + src.PutJSON("oauth:flow:abc", map[string]string{"left": "out"}) + srcSec, _ := secrets.Open(filepath.Join(t.TempDir(), "secrets.json")) + srcSec.Set(map[string]string{secrets.StripeAPIKey: "rk_1", secrets.GiteaToken: "gt"}) + + var buf bytes.Buffer + m, err := Export(context.Background(), src, srcSec, "test", &buf) + if err != nil { + t.Fatal(err) + } + if m.Tables["signals"] != 1 || m.Tables["prospect_contacts"] != 1 || m.Secrets != 2 || m.From != "SQLite" || m.Schema != db.Schema() { + t.Fatalf("manifest: %+v", m) + } + if _, ok := m.Tables["locks"]; ok { + t.Error("exported the locks") + } + openBuf := func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(buf.Bytes())), nil } + + dst := open(t, false) + var dstSec *secrets.Store + if dst.Dialect == db.Postgres { + dstSec, err = secrets.OpenDB(dst, []byte("0123456789abcdef0123456789abcdef"), nil) + } else { + dstSec, err = secrets.Open(filepath.Join(t.TempDir(), "secrets.json")) + } + if err != nil { + t.Fatal(err) + } + dst.PutJSON("seo:indexnow-key", "written-at-start") // as a new install does + src.PutJSON("seo:indexnow-key", "the-sites-key") + buf.Reset() + if _, err := Export(context.Background(), src, srcSec, "test", &buf); err != nil { + t.Fatal(err) + } + res, err := Import(context.Background(), dst, dstSec, openBuf) + if err != nil { + t.Fatal(err) + } + if res.Tables["prospect_companies"] != 1 || res.Secrets != 2 || dstSec.Get(secrets.StripeAPIKey) != "rk_1" { + t.Fatalf("imported: %+v", res) + } + // The rows came across as they were, and still ignore case. + var name, email string + var signal int64 + if err := dst.QueryRow(`SELECT c.first_name, c.email, c.signal_id FROM prospect_contacts c JOIN prospect_companies p ON p.id = c.company_id + WHERE c.email = 'ann@acme.com' AND p.domain = 'acme.com'`).Scan(&name, &email, &signal); err != nil { + t.Fatal(err) + } + if name != "Ann" || email != "ann@acme.com" || signal != sig.ID { + t.Errorf("contact: %s %s %d", name, email, signal) + } + var key string + if dst.GetJSON("seo:indexnow-key", &key); key != "the-sites-key" { + t.Errorf("IndexNow key: %q", key) + } + var got map[string]any + dst.GetJSON("test:setting", &got) + if got["s"] != "it's \"quoted\"\nand ünïcode" || got["f"] != 1.5 { + t.Errorf("setting: %#v", got) + } + var raw string + dst.QueryRow(`SELECT value FROM settings WHERE key = 'test:setting'`).Scan(&raw) + if !strings.Contains(raw, "9007199254740993") { + t.Errorf("a large number changed: %s", raw) + } + if ok, _ := dst.GetJSON("oauth:flow:abc", &got); ok { + t.Error("a sign-in under way came across") + } + // New rows get new ids, past the imported ones. + sig2 := &signals.Signal{Name: "Another", Spot: "x"} + if err := signals.Save(dst, sig2); err != nil || sig2.ID <= sig.ID { + t.Errorf("a new row after the import: id %d, %v", sig2.ID, err) + } + + // Only into an empty database, at the same schema. + if _, err := Import(context.Background(), dst, nil, openBuf); err == nil || !strings.Contains(err.Error(), "isn't empty") { + t.Errorf("into a full database: %v", err) + } + if _, err := Import(context.Background(), open(t, true), nil, func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader("not an export")), nil + }); err == nil || !strings.Contains(err.Error(), "not a Supermarket export") { + t.Errorf("a stray file: %v", err) + } + + // Without secrets, there are none in the file. + buf.Reset() + if m, _ := Export(context.Background(), src, nil, "test", &buf); m.Secrets != 0 || bytes.Contains(buf.Bytes(), []byte("rk_1")) { + t.Error("secrets exported when not asked for") + } +} + +// A failed import leaves the database empty. +func TestImportAllOrNothing(t *testing.T) { + src := open(t, true) + signals.Save(src, &signals.Signal{Name: "A", Spot: "a"}) + var buf bytes.Buffer + if _, err := Export(context.Background(), src, nil, "test", &buf); err != nil { + t.Fatal(err) + } + // Break one table's rows: the manifest says 1, give none. + broken := rewrite(t, buf.Bytes(), "tables/signals.jsonl", "") + dst := open(t, false) + _, err := Import(context.Background(), dst, nil, func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(broken)), nil }) + if err == nil || !strings.Contains(err.Error(), "manifest says 1") { + t.Fatalf("import: %v", err) + } + var n int + dst.QueryRow(`SELECT count(*) FROM settings`).Scan(&n) + tables, _ := Tables(dst) + for _, tb := range tables { + dst.QueryRow(`SELECT count(*) FROM ` + quote(tb)).Scan(&n) + if n != 0 { + t.Errorf("%s has %d rows after a failed import", tb, n) + } + } +} diff --git a/internal/web/realdata_test.go b/internal/web/realdata_test.go new file mode 100644 index 0000000..e7b48f7 --- /dev/null +++ b/internal/web/realdata_test.go @@ -0,0 +1,109 @@ +package web + +import ( + "io" + "log/slog" + "net/http" + "os" + "regexp" + "strings" + "testing" + + "supermarket/internal/db" + "supermarket/internal/secrets" +) + +// TestPagesOnRealData opens every page on a database with real data in +// it, such as a local install imported into Postgres (supermarket +// import), and checks each renders. Only run when asked: +// +// SUPERMARKET_TEST_PAGES_DB=postgres://…/federated go test -run TestPagesOnRealData ./internal/web +func TestPagesOnRealData(t *testing.T) { + url := os.Getenv("SUPERMARKET_TEST_PAGES_DB") + if url == "" { + t.Skip("set SUPERMARKET_TEST_PAGES_DB to a database with data") + } + d, err := db.OpenPostgres(url) + if err != nil { + t.Fatal(err) + } + defer d.Close() + sec, err := secrets.OpenDB(d, []byte("0123456789abcdef0123456789abcdef"), nil) + if err != nil { + t.Fatal(err) + } + s := &Server{DB: d, Secrets: sec, DataDir: t.TempDir(), PublicURL: "http://localhost:8470", Version: "test", + Log: slog.New(slog.NewTextHandler(io.Discard, nil))} + h, err := s.Handler() + if err != nil { + t.Fatal(err) + } + pages := []string{"/", "/market", "/market/new", "/posts", "/content", "/content/scheduled", "/content/published", + "/signals", "/signals/new", "/prospects", "/prospects/new", "/outreach", "/prospects/suppressed", "/crm", "/crm/reach", + "/seo/check", "/seo/report", "/seo", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/audit", "/seo/engines", "/seo/next", "/seo/links", + "/metrics", "/metrics/spend", "/metrics/clv", "/metrics/customers", "/metrics/publish", + "/sites", "/sites/pages", "/sites/previews", "/sites/publishing", "/sites/forms", "/sites/new", + "/settings/profile", "/settings/accounts", "/settings/core", "/settings/sources", "/settings/email", "/settings/ai", + "/settings/backups", "/settings/search", "/settings/tracking", "/settings/about", "/search?q=federated"} + // Each signal's page too. + rows, err := d.Query(`SELECT id FROM signals`) + if err != nil { + t.Fatal(err) + } + for rows.Next() { + var id string + rows.Scan(&id) + pages = append(pages, "/signals/"+id) + } + rows.Close() + // The same export imported into SQLite: every page should be the same. + var lite http.Handler + if path := os.Getenv("SUPERMARKET_TEST_PAGES_SQLITE"); path != "" { + ld, err := db.OpenSQLite(path) + if err != nil { + t.Fatal(err) + } + defer ld.Close() + lsec, _ := secrets.Open(t.TempDir() + "/secrets.json") + ls := &Server{DB: ld, Secrets: lsec, DataDir: s.DataDir, PublicURL: s.PublicURL, Version: "test", Log: s.Log} + if lite, err = ls.Handler(); err != nil { + t.Fatal(err) + } + } + volatile := regexp.MustCompile(`[0-9a-f]{12}|\b\d+ (seconds?|minutes?) ago\b|just now|nonce="[^"]*"|value="[0-9a-f]{32,}"`) + // Chart coordinates: the same sums, added in another order, differ in + // the 14th decimal place. + long := regexp.MustCompile(`(\d+\.\d{6})\d+`) + for _, p := range pages { + rec := do(h, http.MethodGet, p, nil, nil) + if lite != nil && rec.Code == http.StatusOK && p != "/settings/about" { // About lists the copies running + a := long.ReplaceAllString(volatile.ReplaceAllString(rec.Body.String(), ""), "$1") + b := long.ReplaceAllString(volatile.ReplaceAllString(do(lite, http.MethodGet, p, nil, nil).Body.String(), ""), "$1") + if a != b { + al, bl := strings.Split(a, "\n"), strings.Split(b, "\n") + for i := 0; i < min(len(al), len(bl)); i++ { + if al[i] != bl[i] { + t.Errorf("%s differs at line %d:\n Postgres %s\n SQLite %s", p, i+1, strings.TrimSpace(al[i]), strings.TrimSpace(bl[i])) + break + } + } + if len(al) != len(bl) { + t.Errorf("%s: %d lines on Postgres, %d on SQLite", p, len(al), len(bl)) + } + } + } + body := rec.Body.String() + if rec.Code != http.StatusOK || strings.Contains(body, "Something went wrong") || strings.Contains(body, "SQLSTATE") { + i := strings.Index(body, "Something went wrong") + if i < 0 { + i = strings.Index(body, "SQLSTATE") + } + snippet := "" + if i >= 0 { + snippet = body[max(0, i-100):min(len(body), i+300)] + } + t.Errorf("%s: %d %s", p, rec.Code, snippet) + } + } + t.Logf("%d pages", len(pages)) +}