Schema 32 adds users, memberships and sessions, on both databases. internal/users keeps accounts (Argon2id passwords), roles and modules, and sessions whose rows hold only a hash of the cookie's value; they end after a week unused or 30 days. On the server edition, every page but the public ones needs a session and sends others to /signin. Every edition's forms now carry a CSRF token (a cookie repeated in each form, added as pages render; htmx sends it as a header), besides the same-origin check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
545 lines
15 KiB
Go
545 lines
15 KiB
Go
// 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,
|
|
"sessions": 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
|
|
}
|