Files
davidandClaude Opus 5.5 5f1b8d59ce Phase 9, part 7: export and import, between SQLite and Postgres
supermarket export [--with-secrets] writes a whole Supermarket as a
.tar.gz (a manifest, each table as JSON lines, secrets if asked for) to
the file storage. supermarket import loads one into an empty database at
the same schema, SQLite or Postgres, in one transaction, parents first,
checking row counts and moving Postgres' identity counters past the
imported ids.

Checked on Federated's 112,543 rows: imported into Postgres and SQLite,
every table and total matches, and TestPagesOnRealData renders all 57
pages the same from both. That found unsettled ordering (case-alike
campaigns, customers with the same name, metrics' float sums), now fixed
with ORDER BY and tie-breakers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:09:14 -07:00

168 lines
5.8 KiB
Go

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)
}
}
}