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>
This commit is contained in:
@@ -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 <file>`.
|
||||
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 <export file, or its name from supermarket export>")
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user