Files
2026-12-01 21:25:01 +01:00

1283 lines
42 KiB
Go

package dbcopy
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/app"
"github.com/phishingclub/phishingclub/data"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/database/dbengine"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/seed"
"github.com/phishingclub/phishingclub/testdb"
"go.uber.org/zap"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
// fileSum is the sha256 of a file
func fileSum(t testing.TB, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
// targetRowCounts returns the rows of every application table of the target
func targetRowCounts(t testing.TB, db *gorm.DB) map[string]int64 {
t.Helper()
tables, err := expectedTables(db)
if err != nil {
t.Fatal(err)
}
out := map[string]int64{}
for _, name := range tables {
var n int64
if err := db.Table(name).Count(&n).Error; err != nil {
t.Fatalf("count %s: %v", name, err)
}
out[name] = n
}
return out
}
// assertTargetEmpty fails when an application table of the target has rows
func assertTargetEmpty(t testing.TB, db *gorm.DB) {
t.Helper()
for name, n := range targetRowCounts(t, db) {
if n != 0 {
t.Errorf("target table %s has %d rows, want none", name, n)
}
}
}
// normalize turns a field value into text that compares the two engines:
// times in UTC to the microsecond postgres keeps, text cleaned as postgres
// stores it
func normalize(v any) string {
rv := reflect.ValueOf(v)
for rv.IsValid() && rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return "<nil>"
}
rv = rv.Elem()
}
if !rv.IsValid() {
return "<nil>"
}
switch x := rv.Interface().(type) {
case time.Time:
return x.UTC().Truncate(time.Microsecond).Format(time.RFC3339Nano)
case uuid.UUID:
return x.String()
case string:
return dbengine.CleanText(x)
case gorm.DeletedAt:
if !x.Valid {
return "<nil>"
}
return x.Time.UTC().Truncate(time.Microsecond).Format(time.RFC3339Nano)
}
if rv.Kind() == reflect.String {
return dbengine.CleanText(rv.String())
}
return fmt.Sprintf("%#v", rv.Interface())
}
// readModel reads every row of a model table through gorm, as the
// application reads it, and returns each row as its normalized fields keyed
// by the primary key, or by all fields for a table without one
func readModel(t testing.TB, db *gorm.DB, m any) (map[string]map[string]string, *schema.Schema) {
t.Helper()
s, err := schema.Parse(m, &sync.Map{}, db.NamingStrategy)
if err != nil {
t.Fatal(err)
}
slice := reflect.New(reflect.SliceOf(reflect.TypeOf(m).Elem()))
if err := db.Unscoped().Find(slice.Interface()).Error; err != nil {
t.Fatalf("read %s: %v", s.Table, err)
}
out := map[string]map[string]string{}
rows := slice.Elem()
for i := 0; i < rows.Len(); i++ {
row := rows.Index(i)
fields := map[string]string{}
var names []string
for _, f := range s.Fields {
if f.DBName == "" {
continue
}
v, _ := f.ValueOf(context.Background(), row)
fields[f.DBName] = normalize(v)
names = append(names, f.DBName)
}
var keyParts []string
if len(s.PrimaryFields) > 0 {
for _, f := range s.PrimaryFields {
keyParts = append(keyParts, fields[f.DBName])
}
} else {
sort.Strings(names)
for _, n := range names {
keyParts = append(keyParts, n+"="+fields[n])
}
}
key := strings.Join(keyParts, "|")
if _, dup := out[key]; dup {
t.Fatalf("%s: two rows with key %s", s.Table, key)
}
out[key] = fields
}
return out, s
}
// compareCopied compares every row and field of the source and the target
// through the entities, as the application reads them, and the tables
// without an entity as raw rows. Sessions must not be copied.
func compareCopied(t *testing.T, src, target *gorm.DB, rep *Report, facts *fixtureFacts) {
t.Helper()
// every row and field, through the entities
covered := map[string]bool{}
for _, m := range seed.SchemaTables() {
want, s := readModel(t, src, m)
got, _ := readModel(t, target, m)
covered[s.Table] = true
if s.Table == database.SESSION_TABLE {
if len(want) == 0 || len(got) != 0 {
t.Errorf("sessions: %d in sqlite, %d in postgres, want none copied", len(want), len(got))
}
continue
}
if len(want) != len(got) {
t.Errorf("%s: %d rows in sqlite, %d in postgres", s.Table, len(want), len(got))
continue
}
for key, wf := range want {
gf, ok := got[key]
if !ok {
t.Errorf("%s: row %s missing in postgres", s.Table, key)
continue
}
for col, wv := range wf {
if s.Table == database.INSTALLED_RESOURCE_TABLE && col == "installed_content_hash" && strings.Contains(key, facts.uneditedResource) {
continue
}
if gf[col] != wv {
t.Errorf("%s row %s column %s: sqlite %q, postgres %q", s.Table, key, col, wv, gf[col])
}
}
}
}
// tables without an entity, compared as raw rows
for _, tr := range rep.Tables {
if covered[tr.Name] {
continue
}
var want, got []map[string]any
if err := src.Table(tr.Name).Find(&want).Error; err != nil {
t.Fatal(err)
}
if err := target.Table(tr.Name).Find(&got).Error; err != nil {
t.Fatal(err)
}
norm := func(rows []map[string]any) []string {
var out []string
for _, r := range rows {
var parts []string
for k, v := range r {
if s, ok := v.(string); ok {
if u, err := uuid.Parse(s); err == nil {
v = u.String()
}
}
parts = append(parts, k+"="+normalize(v))
}
sort.Strings(parts)
out = append(out, strings.Join(parts, ","))
}
sort.Strings(out)
return out
}
if !reflect.DeepEqual(norm(want), norm(got)) {
t.Errorf("%s: raw rows differ", tr.Name)
}
}
}
// TestCopyFullFixture copies a sqlite database with rows in every table and
// compares every row field by field through the gorm entities, checks seq
// against the rowids, the Bait Box baselines, that new rows continue the
// sequences, that the application starts on the copy and that the sqlite
// file was not changed
func TestCopyFullFixture(t *testing.T) {
srcPath, facts := newSource(t)
before := fileSum(t, srcPath)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, nil)
if err != nil {
t.Fatalf("copy: %v", err)
}
if !rep.Committed {
t.Fatal("not committed")
}
// guard: a new entity without fixture rows fails here
for _, tr := range rep.Tables {
if tr.SourceRows == 0 {
t.Errorf("fixture has no rows in %s, add them in buildFixture", tr.Name)
}
if tr.NotCopied != "" {
if tr.Name != database.SESSION_TABLE || tr.Copied != 0 {
t.Errorf("%s: not copied (%s), %d copied", tr.Name, tr.NotCopied, tr.Copied)
}
continue
}
if tr.Copied != tr.SourceRows || tr.Skipped != 0 {
t.Errorf("%s: %d of %d copied, %d left out", tr.Name, tr.Copied, tr.SourceRows, tr.Skipped)
}
}
if len(rep.Tables) < 60 {
t.Fatalf("only %d tables in the plan", len(rep.Tables))
}
if len(rep.Invalid) != 0 || len(rep.Orphans) != 0 || len(rep.UnknownTables) != 0 || len(rep.UnknownColumns) != 0 {
t.Fatalf("unexpected report items: %+v %+v %+v %+v", rep.Invalid, rep.Orphans, rep.UnknownTables, rep.UnknownColumns)
}
cleaned := map[string]int64{}
for _, c := range rep.Cleaned {
cleaned[c.Table+"."+c.Column] = c.Count
}
if cleaned["pages.content"] != 2 || cleaned["campaign_events.user_agent"] != 1 {
t.Fatalf("cleaned values %v", cleaned)
}
// the fixture times carry nanoseconds
if rep.TimesTruncated == 0 {
t.Error("no time with digits below a microsecond reported")
}
// the packages of both Bait Box pages with cleaned text are listed
var wantPackages []string
err = target.Raw(
"SELECT DISTINCT p.package_id FROM installed_packages p JOIN installed_resources r ON r.installed_package_id = p.id "+
"WHERE r.id IN (?, ?) ORDER BY p.package_id",
facts.uneditedResource, facts.editedResource,
).Scan(&wantPackages).Error
if err != nil {
t.Fatal(err)
}
var gotPackages []string
for _, pk := range rep.PackagesNotClean {
gotPackages = append(gotPackages, pk.PackageID)
if pk.Version == "" {
t.Errorf("package %s listed without its version", pk.PackageID)
}
}
if len(wantPackages) == 0 || !reflect.DeepEqual(wantPackages, gotPackages) {
t.Errorf("packages not clean %v, want %v", gotPackages, wantPackages)
}
var printed strings.Builder
rep.Print(&printed)
for _, want := range []string{"not copied: everyone signs in again", "digits below a microsecond", "publishes a UTF-8 version", "Copied and committed"} {
if !strings.Contains(printed.String(), want) {
t.Errorf("the report lacks %q:\n%s", want, printed.String())
}
}
src, err := OpenSource(srcPath)
if err != nil {
t.Fatal(err)
}
defer func() {
if sqlDB, err := src.DB(); err == nil {
_ = sqlDB.Close()
}
}()
compareCopied(t, src, target, rep, facts)
// seq is the rowid
for _, table := range database.RowOrderTables() {
type pair struct {
ID string
Seq int64
}
var want, got []pair
if err := src.Raw("SELECT id, rowid AS seq FROM ? ORDER BY rowid", clauseTable(table)).Scan(&want).Error; err != nil {
t.Fatal(err)
}
if err := target.Raw("SELECT id::text AS id, seq FROM ? ORDER BY seq", clauseTable(table)).Scan(&got).Error; err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(want, got) {
t.Errorf("%s: seq order differs from rowid order:\n%v\n%v", table, want, got)
}
}
// Bait Box: the unedited page got the postgres baseline, the edited one
// kept its own
var hashes []struct {
ID string
InstalledContentHash string
}
if err := target.Raw("SELECT id::text AS id, installed_content_hash FROM installed_resources").Scan(&hashes).Error; err != nil {
t.Fatal(err)
}
for _, h := range hashes {
switch h.ID {
case facts.uneditedResource:
if want := sqliteFingerprint("Login", dbengine.CleanText(latin1Page)); h.InstalledContentHash != want {
t.Errorf("unedited baseline %s, want the cleaned page hash %s", h.InstalledContentHash, want)
}
case facts.editedResource:
if h.InstalledContentHash != facts.editedBaseline {
t.Errorf("edited baseline changed to %s", h.InstalledContentHash)
}
}
}
if rep.BaselinesRebased != 1 {
t.Errorf("%d baselines rebased, want 1", rep.BaselinesRebased)
}
keptEdited := false
for _, k := range rep.BaselinesKept {
if k.ResourceID == facts.edited {
keptEdited = true
}
}
if !keptEdited {
t.Errorf("the edited page is not reported as kept: %+v", rep.BaselinesKept)
}
// the application starts on the copy, the seeds add nothing to the
// seeded tables
counts := targetRowCounts(t, target)
if err := seed.StartupMigration(target, app.NewRepositories(target), zap.NewExample().Sugar()); err != nil {
t.Fatalf("startup migration: %v", err)
}
after := targetRowCounts(t, target)
for name, n := range counts {
if after[name] < n {
t.Errorf("%s lost rows in the startup migration: %d to %d", name, n, after[name])
}
}
for _, name := range []string{"options", "roles", database.EVENT_TABLE, database.CAMPAIGN_EVENT_TABLE, database.RECIPIENT_TABLE, database.PAGE_TABLE} {
if after[name] != counts[name] {
t.Errorf("the startup migration changed %s from %d to %d rows", name, counts[name], after[name])
}
}
ctx := context.Background()
repos := app.NewRepositories(target)
if _, err := repos.Option.GetByKey(ctx, data.OptionKeyDevelopmentSeeded); err != nil {
t.Fatalf("read option: %v", err)
}
var maxSeq int64
if err := target.Raw("SELECT MAX(seq) FROM campaign_events").Scan(&maxSeq).Error; err != nil {
t.Fatal(err)
}
latest, err := (&repository.Program{DB: target}).LatestCampaignEventRowID(ctx)
if err != nil || latest != maxSeq {
t.Fatalf("latest event row id %d %v, want %d", latest, err, maxSeq)
}
// new rows continue the sequences
for _, table := range database.RowOrderTables() {
var max int64
if err := target.Raw("SELECT MAX(seq) FROM ?", clauseTable(table)).Scan(&max).Error; err != nil {
t.Fatal(err)
}
id := uuid.New()
err := target.Transaction(func(tx *gorm.DB) error {
now := time.Now()
switch table {
case database.CAMPAIGN_EVENT_TABLE:
var ref database.CampaignEvent
if err := tx.Order("created_at").First(&ref).Error; err != nil {
return err
}
ref.ID = &id
ref.CreatedAt = &now
return tx.Create(&ref).Error
default:
var ref database.Recipient
if err := tx.Order("created_at").First(&ref).Error; err != nil {
return err
}
ref.ID = &id
ref.CreatedAt = &now
ref.UpdatedAt = &now
email := "new-" + id.String() + "@example.test"
ref.Email = &email
return tx.Create(&ref).Error
}
})
if err != nil {
t.Fatalf("insert into %s: %v", table, err)
}
var seq int64
if err := target.Raw("SELECT seq FROM ? WHERE id = ?", clauseTable(table), id).Scan(&seq).Error; err != nil {
t.Fatal(err)
}
if seq != max+1 {
t.Errorf("%s: new row got seq %d, want %d", table, seq, max+1)
}
}
// the source is unchanged
if sqlDB, err := src.DB(); err == nil {
_ = sqlDB.Close()
}
if got := fileSum(t, srcPath); got != before {
t.Error("the sqlite file changed")
}
// a second copy into the now filled target is refused
if _, err := runCopy(t, srcPath, target, nil); !errors.Is(err, ErrTargetNotEmpty) {
t.Fatalf("second copy: want ErrTargetNotEmpty, got %v", err)
}
}
// TestCopyDryRun runs everything and leaves the target empty
func TestCopyDryRun(t *testing.T) {
srcPath, _ := newSource(t)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, func(o *Options) { o.DryRun = true })
if err != nil {
t.Fatalf("dry run: %v", err)
}
if rep.Committed {
t.Fatal("dry run committed")
}
source, copied := rep.Rows()
var notCopied int64
for _, tr := range rep.Tables {
if tr.NotCopied != "" {
notCopied += tr.SourceRows
}
}
if source == 0 || copied+notCopied != source {
t.Fatalf("dry run copied %d of %d, %d not copied on purpose", copied, source, notCopied)
}
var out strings.Builder
rep.Print(&out)
if !strings.Contains(out.String(), "would be copied") || !strings.Contains(out.String(), "Dry run: every row was rolled back. The target keeps the empty schema") {
t.Fatalf("dry run report:\n%s", out.String())
}
assertTargetEmpty(t, target)
// the schema stays and a real copy runs on it
if rep, err := runCopy(t, srcPath, target, nil); err != nil || !rep.Committed {
t.Fatalf("copy after the dry run: %v", err)
}
}
// TestCopyRefusesNonEmptyTarget refuses a target with a row and leaves it
// as it was
func TestCopyRefusesNonEmptyTarget(t *testing.T) {
srcPath, _ := newSource(t)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
if err := target.Exec("CREATE TABLE notes (body text)").Error; err != nil {
t.Fatal(err)
}
if err := target.Exec("INSERT INTO notes VALUES ('x')").Error; err != nil {
t.Fatal(err)
}
_, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrTargetNotEmpty) || !strings.Contains(err.Error(), "notes") {
t.Fatalf("want ErrTargetNotEmpty naming notes, got %v", err)
}
tables, err := targetTables(target)
if err != nil {
t.Fatal(err)
}
if len(tables) != 1 || tables[0] != "notes" {
t.Fatalf("the refused copy changed the target: %v", tables)
}
// an empty table of another program is only listed
if err := target.Exec("DELETE FROM notes").Error; err != nil {
t.Fatal(err)
}
rep, err := runCopy(t, srcPath, target, func(o *Options) { o.DryRun = true })
if err != nil || len(rep.ExtraTarget) != 1 || rep.ExtraTarget[0] != "notes" {
t.Fatalf("empty extra table: %v %v", rep.ExtraTarget, err)
}
}
// TestCopyRefusesNotUTF8Target refuses a database that does not store UTF8
func TestCopyRefusesNotUTF8Target(t *testing.T) {
srcPath, _ := newSource(t)
admin := adminSQL(t)
b := make([]byte, 8)
_, _ = rand.Read(b)
name := "pctest_" + hex.EncodeToString(b)
// test only, the name is the random one made here
if _, err := admin.Exec("CREATE DATABASE " + name + " ENCODING 'SQL_ASCII' LC_COLLATE 'C' LC_CTYPE 'C' TEMPLATE template0"); err != nil {
t.Fatalf("create: %v", err)
}
t.Cleanup(func() { _, _ = admin.Exec("DROP DATABASE IF EXISTS " + name + " WITH (FORCE)") })
dsn := strings.Replace(os.Getenv(testdb.EnvPostgresDSN), "/postgres?", "/"+name+"?", 1)
target := openTarget(t, dsn)
_, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrTarget) || !strings.Contains(err.Error(), "SQL_ASCII") {
t.Fatalf("want the encoding refused, got %v", err)
}
}
// TestCopyRefusesInvalidValues writes each kind of value that can not be
// copied and checks the first pass refuses it, names it without its value,
// and writes nothing, also with --force
func TestCopyRefusesInvalidValues(t *testing.T) {
plan := scratchPlan(t)
find := func(match func(t *table, c *column) bool) (string, string) {
for _, t := range plan {
for _, c := range t.read {
if match(t, c) {
return t.name, c.name
}
}
}
return "", ""
}
boolTable, boolCol := find(func(t *table, c *column) bool { return c.kind == kindBool })
intTable, intCol := find(func(t *table, c *column) bool { return c.kind == kindInt && c.intBits == 32 })
cases := []struct {
name, table, column string
value any
kind invalidKind
secret string
}{
{"time text", "campaign_events", "created_at", "not a time SECRETVALUE", invalidTime, "SECRETVALUE"},
{"empty uuid", "campaigns", "company_id", "", invalidUUID, ""},
{"upper case uuid", "campaigns", "company_id", strings.ToUpper(uuid.NewString()), invalidUUID, ""},
{"int range", intTable, intCol, int64(1) << 40, invalidRange, ""},
}
if boolCol != "" {
cases = append(cases, struct {
name, table, column string
value any
kind invalidKind
secret string
}{"bool 2", boolTable, boolCol, int64(2), invalidBool, ""})
}
_, facts := newSource(t)
if facts.varcharTable != "" {
var limit int
for _, tb := range plan {
for _, c := range tb.read {
if tb.name == facts.varcharTable && c.name == facts.varcharColumn {
limit = c.maxLen
}
}
}
cases = append(cases, struct {
name, table, column string
value any
kind invalidKind
secret string
}{"too long", facts.varcharTable, facts.varcharColumn, strings.Repeat("é", limit+1), invalidTooLong, ""})
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if tc.table == "" {
t.Skip("no such column in this schema")
}
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
if err := w.Exec("PRAGMA foreign_keys = OFF").Error; err != nil {
t.Fatal(err)
}
if err := w.Exec("UPDATE ? SET ? = ? WHERE rowid = 1", clauseTable(tc.table), clauseColumn(tc.column), tc.value).Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
for _, force := range []bool{false, true} {
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, func(o *Options) { o.Force = force })
if !errors.Is(err, ErrInvalidValues) {
t.Fatalf("force %v: want ErrInvalidValues, got %v", force, err)
}
found := false
for _, it := range rep.Invalid {
if it.Table == tc.table && it.Column == tc.column && it.Kind == string(tc.kind) && len(it.RowIDs) > 0 && it.RowIDs[0] == 1 {
found = true
}
}
if !found {
t.Fatalf("report does not name %s.%s %s: %+v", tc.table, tc.column, tc.kind, rep.Invalid)
}
var out strings.Builder
rep.Print(&out)
if tc.secret != "" && (strings.Contains(out.String(), tc.secret) || strings.Contains(err.Error(), tc.secret)) {
t.Fatal("the report shows the value")
}
assertTargetEmpty(t, target)
}
})
}
}
// closeDB closes a gorm handle
func closeDB(t testing.TB, db *gorm.DB) {
t.Helper()
sqlDB, err := db.DB()
if err != nil {
t.Fatal(err)
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
}
// TestCopyOrphans removes a company that campaigns point at: refused
// without --force, with --force the rows of the company, the campaigns and
// the rows under them are left out and reported, and the rest is committed
func TestCopyOrphans(t *testing.T) {
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
if err := w.Exec("PRAGMA foreign_keys = OFF").Error; err != nil {
t.Fatal(err)
}
var companyID string
if err := w.Raw("SELECT company_id FROM campaigns WHERE rowid = 1").Scan(&companyID).Error; err != nil {
t.Fatal(err)
}
if err := w.Exec("DELETE FROM companies WHERE id = ?", companyID).Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrOrphans) {
t.Fatalf("want ErrOrphans, got %v", err)
}
assertTargetEmpty(t, target)
named := false
for _, o := range rep.Orphans {
if o.Parent == "companies" && o.Column == "company_id" {
for _, e := range o.Examples {
if e.MissingKey == companyID {
named = true
}
}
}
}
if !named {
t.Fatalf("rows of the missing company not reported: %+v", rep.Orphans)
}
rep, err = runCopy(t, srcPath, target, func(o *Options) { o.Force = true })
if err != nil || !rep.Committed {
t.Fatalf("force: %v", err)
}
counts := targetRowCounts(t, target)
var skipped int64
for _, tr := range rep.Tables {
if tr.NotCopied != "" {
continue
}
if counts[tr.Name] != tr.Copied || tr.Copied+tr.Skipped != tr.SourceRows {
t.Errorf("%s: %d in the target, report %+v", tr.Name, counts[tr.Name], tr)
}
skipped += tr.Skipped
}
byTable := map[string]int64{}
for _, tr := range rep.Tables {
byTable[tr.Name] = tr.Skipped
}
if byTable["campaigns"] == 0 || byTable["campaign_events"] == 0 {
t.Fatalf("the campaign and its events were not left out: %v", byTable)
}
var n int64
if err := target.Table("campaigns").Where("company_id = ?", companyID).Count(&n).Error; err != nil || n != 0 {
t.Fatalf("orphan campaigns copied: %d %v", n, err)
}
}
// TestCopyUnknownData refuses unknown source tables and columns that hold
// data, also with --force, and only lists empty ones
func TestCopyUnknownData(t *testing.T) {
for _, tc := range []struct {
name string
setup []string
ok bool
}{
{"table with rows", []string{"CREATE TABLE allow_listing_ledger (id text)", "INSERT INTO allow_listing_ledger VALUES ('x')"}, false},
{"empty table", []string{"CREATE TABLE allow_listing_ledger (id text)"}, true},
{"column with values", []string{"ALTER TABLE pages ADD COLUMN old_flag text", "UPDATE pages SET old_flag = 'x'"}, false},
{"empty column", []string{"ALTER TABLE pages ADD COLUMN old_flag text"}, true},
} {
t.Run(tc.name, func(t *testing.T) {
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
for _, s := range tc.setup {
if err := w.Exec(s).Error; err != nil {
t.Fatal(err)
}
}
closeDB(t, w)
for _, force := range []bool{false, true} {
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, func(o *Options) { o.Force = force; o.DryRun = true })
if tc.ok {
if err != nil {
t.Fatalf("force %v: %v", force, err)
}
} else if !errors.Is(err, ErrUnknownData) {
t.Fatalf("force %v: want ErrUnknownData, got %v", force, err)
}
if len(rep.UnknownTables)+len(rep.UnknownColumns) != 1 {
t.Fatalf("not listed: %+v %+v", rep.UnknownTables, rep.UnknownColumns)
}
assertTargetEmpty(t, target)
}
})
}
}
// TestCopyOlderSource refuses a sqlite database that lacks a column
func TestCopyOlderSource(t *testing.T) {
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
if err := w.Exec("ALTER TABLE pages DROP COLUMN content").Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
_, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrSourceOlder) || !strings.Contains(err.Error(), "pages.content") || !strings.Contains(err.Error(), "start the server once") {
t.Fatalf("want ErrSourceOlder naming pages.content, got %v", err)
}
}
// TestCopyFailureHalfway fails an insert in the middle of the copy: every
// table stays empty, and a rerun on the left schema succeeds
func TestCopyFailureHalfway(t *testing.T) {
srcPath, _ := newSource(t)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
if err := seed.MigrateSchema(target, zap.NewNop().Sugar()); err != nil {
t.Fatal(err)
}
// a check no row passes, the copy accepts no function in the schema
if err := target.Exec("ALTER TABLE campaign_events ADD CONSTRAINT pctest_fail CHECK (false) NOT VALID").Error; err != nil {
t.Fatal(err)
}
_, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrCopy) {
t.Fatalf("want ErrCopy, got %v", err)
}
assertTargetEmpty(t, target)
if err := target.Exec("ALTER TABLE campaign_events DROP CONSTRAINT pctest_fail").Error; err != nil {
t.Fatal(err)
}
rep, err := runCopy(t, srcPath, target, nil)
if err != nil || !rep.Committed {
t.Fatalf("rerun: %v", err)
}
}
// TestCopySourceWritten writes to the sqlite file between the passes, as a
// server still running would, and checks the copy is refused
func TestCopySourceWritten(t *testing.T) {
srcPath, _ := newSource(t)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
_, err := runCopy(t, srcPath, target, func(o *Options) {
o.afterFirstPass = func() {
w, err := gorm.Open(sqlite.Open("file:"+srcPath+"?_busy_timeout=5000"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Error(err)
return
}
defer closeDB(t, w)
if err := w.Exec("UPDATE options SET value = 'changed' WHERE key = ?", data.OptionKeyDevelopmentSeeded).Error; err != nil {
t.Error(err)
}
}
})
if !errors.Is(err, ErrSourceChanged) {
t.Fatalf("want ErrSourceChanged, got %v", err)
}
assertTargetEmpty(t, target)
}
// TestCopyUniqueCollision makes two company names that differ only in bytes
// postgres can not store: the copy is refused with the constraint name and
// the cleaning hint, without the values
func TestCopyUniqueCollision(t *testing.T) {
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
if err := w.Exec("UPDATE companies SET name = ? WHERE rowid = 1", "SECRETCO\x00").Error; err != nil {
t.Fatal(err)
}
if err := w.Exec("UPDATE companies SET name = ? WHERE rowid = 2", "SECRETCO\xff").Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrCopy) || !strings.Contains(err.Error(), "23505") || !strings.Contains(err.Error(), "cleaned") {
t.Fatalf("want a unique violation with the cleaning hint, got %v", err)
}
if !strings.Contains(err.Error(), "constraint ") {
t.Fatalf("the constraint is not named: %v", err)
}
var out strings.Builder
rep.Print(&out)
if strings.Contains(err.Error(), "SECRETCO") || strings.Contains(out.String(), "SECRETCO") {
t.Fatal("the value is shown")
}
assertTargetEmpty(t, target)
}
// TestOpenSourceKeepsEngine opens the source in a process whose engine is
// postgres: the engine stays postgres and the file is not changed
func TestOpenSourceKeepsEngine(t *testing.T) {
srcPath, _ := newSource(t)
_ = openTarget(t, testdb.NewPostgresDatabase(t, true))
before := fileSum(t, srcPath)
src, err := OpenSource(srcPath)
if err != nil {
t.Fatal(err)
}
if !dbengine.IsPostgres() {
t.Fatal("opening the source changed the process engine")
}
if err := src.Exec("UPDATE options SET value = 'x'").Error; err == nil {
t.Fatal("the source accepted a write")
}
closeDB(t, src)
if fileSum(t, srcPath) != before {
t.Fatal("the sqlite file changed")
}
if _, err := OpenSource(srcPath + ".missing"); err == nil {
t.Fatal("a missing file opened")
}
if _, err := os.Stat(srcPath + ".missing"); !errors.Is(err, os.ErrNotExist) {
t.Fatal("opening a missing file made it")
}
}
// TestCopyBigTable copies a million campaign events and checks the heap
// stays bounded. Opt in with PC_TEST_BIG=1, it takes minutes.
func TestCopyBigTable(t *testing.T) {
if os.Getenv("PC_TEST_BIG") != "1" {
t.Skip("set PC_TEST_BIG=1 to run")
}
const events = 1000000
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
cols, err := sourceColumns(w, database.CAMPAIGN_EVENT_TABLE)
if err != nil {
t.Fatal(err)
}
var into, from []clause.Expression
for _, c := range cols {
into = append(into, clause.Expr{SQL: "?", Vars: []any{clause.Column{Name: c.Name}}})
if c.Name == "id" {
// a new canonical uuid text per row
from = append(from, clause.Expr{SQL: "lower(substr(h, 1, 8) || '-' || substr(h, 9, 4) || '-4' || substr(h, 14, 3) || '-a' || substr(h, 18, 3) || '-' || substr(h, 21, 12))"})
continue
}
from = append(from, clause.Expr{SQL: "?", Vars: []any{clause.Column{Table: "e", Name: c.Name}}})
}
err = w.Exec(
"INSERT INTO campaign_events (?) WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?) "+
"SELECT ? FROM (SELECT hex(randomblob(16)) AS h FROM n), campaign_events e WHERE e.rowid = 1",
clause.CommaExpression{Exprs: into}, events, clause.CommaExpression{Exprs: from},
).Error
if err != nil {
t.Fatalf("insert: %v", err)
}
if err := w.Exec("PRAGMA wal_checkpoint(TRUNCATE)").Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
stop := make(chan struct{})
peak := make(chan uint64)
go func() {
var max uint64
var ms runtime.MemStats
tick := time.NewTicker(100 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-stop:
peak <- max
return
case <-tick.C:
runtime.ReadMemStats(&ms)
if ms.HeapAlloc > max {
max = ms.HeapAlloc
}
}
}
}()
start := time.Now()
rep, err := runCopy(t, srcPath, target, nil)
close(stop)
max := <-peak
if err != nil || !rep.Committed {
t.Fatalf("copy: %v", err)
}
_, copied := rep.Rows()
took := time.Since(start)
t.Logf("copied %d rows in %s, %.0f rows per second, peak heap %d MB", copied, took.Round(time.Second), float64(copied)/took.Seconds(), max>>20)
if max > 200<<20 {
t.Fatalf("peak heap %d MB, want under 200 MB", max>>20)
}
}
// adminSQL opens the admin connection of the postgres tests
func adminSQL(t *testing.T) *sql.DB {
t.Helper()
admin, err := sql.Open("pgx", os.Getenv(testdb.EnvPostgresDSN))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = admin.Close() })
return admin
}
// newRole makes a login role with a random name and password, dropped when
// the test ends, and runs the extra statements for it. Test only: the name
// and password are the random ones made here.
func newRole(t *testing.T, admin *sql.DB, extra ...string) (string, string) {
t.Helper()
b := make([]byte, 12)
if _, err := rand.Read(b); err != nil {
t.Fatal(err)
}
role := "pctest_role_" + hex.EncodeToString(b[:6])
password := "pw" + hex.EncodeToString(b[6:])
if _, err := admin.Exec("CREATE ROLE " + role + " LOGIN PASSWORD '" + password + "'"); err != nil {
t.Fatal(err)
}
// cleanups run last added first, so the database goes before the role
t.Cleanup(func() { _, _ = admin.Exec("DROP ROLE IF EXISTS " + role) })
for _, stmt := range extra {
if _, err := admin.Exec(fmt.Sprintf(stmt, role)); err != nil {
t.Fatal(err)
}
}
return role, password
}
// idleRoleDatabase makes a test database owned by the role, whose sessions
// end after one idle second, and returns its DSN for the role
func idleRoleDatabase(t *testing.T, admin *sql.DB, role, password string) string {
t.Helper()
u, err := url.Parse(testdb.NewPostgresDatabase(t, true))
if err != nil {
t.Fatal(err)
}
name := strings.TrimPrefix(u.Path, "/")
if _, err := admin.Exec("ALTER DATABASE " + name + " OWNER TO " + role); err != nil {
t.Fatal(err)
}
if _, err := admin.Exec("ALTER DATABASE " + name + " SET idle_session_timeout = '1s'"); err != nil {
t.Fatal(err)
}
u.User = url.UserPassword(role, password)
return u.String()
}
// TestCopyIdleSessionTimeout copies into a database whose sessions end
// after one idle second. The lock session sets its own longer timeout and
// the copy transaction turns it off, so a copy with a pause longer than one
// second still commits.
func TestCopyIdleSessionTimeout(t *testing.T) {
srcPath, _ := newSource(t)
admin := adminSQL(t)
role, password := newRole(t, admin)
dsn := idleRoleDatabase(t, admin, role, password)
// the timeout is in force for a plain session of the role
plain, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
defer plain.Close()
conn, err := plain.Conn(context.Background())
if err != nil {
t.Fatal(err)
}
if _, err := conn.ExecContext(context.Background(), "SELECT 1"); err != nil {
t.Fatal(err)
}
time.Sleep(2500 * time.Millisecond)
if _, err := conn.ExecContext(context.Background(), "SELECT 1"); err == nil {
t.Fatal("the idle session timeout did not end an idle session, the test proves nothing")
}
_ = conn.Close()
target := openTarget(t, dsn)
rep, err := runCopy(t, srcPath, target, func(o *Options) {
o.afterFirstPass = func() { time.Sleep(2500 * time.Millisecond) }
})
if err != nil || !rep.Committed {
t.Fatalf("copy with an idle pause: %v", err)
}
}
// TestCopyCancelled stops the copy from outside: Ctrl+C reports a
// cancelled run without a copied count, a lost lock reports the lock, and
// nothing is committed
func TestCopyCancelled(t *testing.T) {
srcPath, _ := newSource(t)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
ctx, cancel := context.WithCancel(context.Background())
rep, err := runCopyCtx(t, ctx, srcPath, target, func(o *Options) { o.afterFirstPass = cancel })
if !errors.Is(err, ErrCancelled) {
t.Fatalf("want ErrCancelled, got %v", err)
}
var out strings.Builder
rep.Print(&out)
if !strings.Contains(out.String(), "Cancelled, every row was rolled back") || !strings.Contains(out.String(), "none committed") {
t.Fatalf("report:\n%s", out.String())
}
assertTargetEmpty(t, target)
lockCtx, lost := context.WithCancelCause(context.Background())
_, err = runCopyCtx(t, lockCtx, srcPath, target, func(o *Options) {
o.afterFirstPass = func() { lost(fmt.Errorf("%w: session ended", ErrLockLost)) }
})
if !errors.Is(err, ErrLockLost) || !strings.Contains(err.Error(), "load balancer or firewall") {
t.Fatalf("want ErrLockLost with the hint, got %v", err)
}
assertTargetEmpty(t, target)
}
// TestCopyRowIDTooLarge refuses a seq table whose rowid leaves postgres no
// room to number new rows
func TestCopyRowIDTooLarge(t *testing.T) {
srcPath, _ := newSource(t)
w := openSQLiteFile(t, srcPath)
big := maxSeqRowID + 1
if err := w.Exec("UPDATE recipients SET rowid = ? WHERE rowid = 1", big).Error; err != nil {
t.Fatal(err)
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, func(o *Options) { o.Force = true })
if !errors.Is(err, ErrInvalidValues) {
t.Fatalf("want ErrInvalidValues, got %v", err)
}
found := false
for _, it := range rep.Invalid {
if it.Table == database.RECIPIENT_TABLE && it.Kind == string(invalidRowID) && it.RowIDs[0] == big {
found = true
}
}
var out strings.Builder
rep.Print(&out)
if !found || !strings.Contains(out.String(), "2^62") {
t.Fatalf("rowid not reported: %+v\n%s", rep.Invalid, out.String())
}
assertTargetEmpty(t, target)
}
// TestCopyRefusesForeignObjects refuses a target schema with objects the
// copy does not make, objects of another role, and index records that do not
// name an index of the application, and accepts the schema of a dry run
func TestCopyRefusesForeignObjects(t *testing.T) {
srcPath, _ := newSource(t)
admin := adminSQL(t)
other, _ := newRole(t, admin)
cases := []struct {
name string
setup func(t *testing.T, db *gorm.DB)
want string
}{
{"function", func(t *testing.T, db *gorm.DB) {
mustExec(t, db, "CREATE FUNCTION pc_extra() RETURNS int LANGUAGE sql AS 'SELECT 1'")
}, "function pc_extra"},
{"view", func(t *testing.T, db *gorm.DB) {
mustExec(t, db, "CREATE VIEW pc_view AS SELECT 1 AS one")
}, "relation pc_view"},
{"table of another role", func(t *testing.T, db *gorm.DB) {
mustExec(t, db, "CREATE TABLE junk (id int)")
mustExec(t, db, "ALTER TABLE junk OWNER TO "+other)
}, "relation junk"},
{"record of a dropped index", func(t *testing.T, db *gorm.DB) {
dryRun(t, srcPath, db)
mustExec(t, db, "DROP TABLE campaign_recipients CASCADE")
}, "idx_campaign_recipients_lure_code"},
{"record of an index on another table", func(t *testing.T, db *gorm.DB) {
dryRun(t, srcPath, db)
mustExec(t, db, "DROP INDEX idx_campaign_recipients_lure_code")
mustExec(t, db, "CREATE TABLE junk (lure_code text)")
mustExec(t, db, "CREATE INDEX idx_campaign_recipients_lure_code ON junk (lure_code)")
}, "idx_campaign_recipients_lure_code"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
tc.setup(t, target)
_, err := runCopy(t, srcPath, target, nil)
if !errors.Is(err, ErrTargetNotEmpty) || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("want ErrTargetNotEmpty naming %s, got %v", tc.want, err)
}
})
}
// the schema a dry run leaves, index records included, is accepted
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
dryRun(t, srcPath, target)
if rep, err := runCopy(t, srcPath, target, nil); err != nil || !rep.Committed {
t.Fatalf("copy after a dry run: %v", err)
}
}
// mustExec runs a test statement
func mustExec(t *testing.T, db *gorm.DB, stmt string) {
t.Helper()
if err := db.Exec(stmt).Error; err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
// dryRun runs a dry run that must succeed
func dryRun(t *testing.T, srcPath string, target *gorm.DB) {
t.Helper()
if _, err := runCopy(t, srcPath, target, func(o *Options) { o.DryRun = true }); err != nil {
t.Fatalf("dry run: %v", err)
}
}
// legacySchemaFile is the schema a fresh v1.9.1 install made on sqlite: the
// gorm AutoMigrate of that release and its startup migration, dumped from
// sqlite_master. It still has the four rate columns of campaign_stats,
// removed in v1.10.0.
const legacySchemaFile = "testdata/v1.9.1_schema.sql"
// loadLegacySchema runs the statements of the v1.9.1 schema
func loadLegacySchema(db *gorm.DB) error {
b, err := os.ReadFile(legacySchemaFile)
if err != nil {
return err
}
for _, stmt := range strings.Split(string(b), "\n;") {
if strings.TrimSpace(stmt) == "" {
continue
}
if err := db.Exec(stmt).Error; err != nil {
return err
}
}
return nil
}
// TestCopyLegacySchema copies an install made by v1.9.1 and upgraded by the
// schema build of this version, as a server start upgrades it. The columns
// v1.10.0 removed are kept by sqlite with a value in every row; they are
// left out and listed, not refused. A column declared BOOLEAN is read as
// the application reads it: an integer above 0 is true. The startup
// migration adds some columns as BOOLEAN, the schema build of the next
// start turns them into numeric, so the column is made BOOLEAN after it.
func TestCopyLegacySchema(t *testing.T) {
testdb.SkipUnlessPostgres(t)
srcPath := filepath.Join(t.TempDir(), "legacy.db")
facts, err := buildFixtureOn(t, srcPath, loadLegacySchema)
if err != nil {
t.Fatalf("fixture: %v", err)
}
w := openSQLiteFile(t, srcPath)
for _, stmt := range []string{
"ALTER TABLE email_attachments DROP COLUMN is_inline",
"ALTER TABLE email_attachments ADD COLUMN is_inline BOOLEAN NOT NULL DEFAULT 0",
} {
if err := w.Exec(stmt).Error; err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
var declared string
if err := w.Raw("SELECT type FROM pragma_table_info('email_attachments') WHERE name = 'is_inline'").Scan(&declared).Error; err != nil || declared != "BOOLEAN" {
t.Fatalf("is_inline declared %q, %v", declared, err)
}
for _, stmt := range []string{
"UPDATE campaign_stats SET open_rate = 0.5, click_rate = 0.25, submission_rate = 0.125, report_rate = 1",
"UPDATE email_attachments SET is_inline = 2 WHERE rowid = 1",
"UPDATE email_attachments SET is_inline = 0 WHERE rowid = 2",
} {
if err := w.Exec(stmt).Error; err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
closeDB(t, w)
target := openTarget(t, testdb.NewPostgresDatabase(t, true))
rep, err := runCopy(t, srcPath, target, nil)
if err != nil || !rep.Committed {
t.Fatalf("copy of an upgraded v1.9.1 install: %v", err)
}
if len(rep.UnknownColumns) != 0 || len(rep.UnknownTables) != 0 {
t.Fatalf("unknown data: %+v %+v", rep.UnknownColumns, rep.UnknownTables)
}
legacy := map[string]int64{}
for _, c := range rep.LegacyColumns {
legacy[c.Table+"."+c.Column] = c.Values
}
var stats int64
for _, tr := range rep.Tables {
if tr.Name == "campaign_stats" {
stats = tr.SourceRows
}
}
for _, col := range legacyColumns["campaign_stats"] {
if n := legacy["campaign_stats."+col]; stats == 0 || n != stats {
t.Errorf("campaign_stats.%s: %d values listed, %d rows", col, n, stats)
}
}
var out strings.Builder
rep.Print(&out)
if !strings.Contains(out.String(), "Left over from earlier versions") || !strings.Contains(out.String(), "campaign_stats.open_rate") {
t.Fatalf("report:\n%s", out.String())
}
src, err := OpenSource(srcPath)
if err != nil {
t.Fatal(err)
}
defer closeDB(t, src)
compareCopied(t, src, target, rep, facts)
var inline []bool
if err := target.Raw("SELECT is_inline FROM email_attachments ORDER BY email_id, attachment_id").Scan(&inline).Error; err != nil {
t.Fatal(err)
}
var app []database.EmailAttachment
if err := src.Order("email_id").Order("attachment_id").Find(&app).Error; err != nil {
t.Fatal(err)
}
trues := 0
for i := range app {
if app[i].IsInline != inline[i] {
t.Errorf("email_attachments row %d: sqlite reads %v, postgres has %v", i, app[i].IsInline, inline[i])
}
if inline[i] {
trues++
}
}
if trues == 0 {
t.Fatal("the BOOLEAN column with 2 was not copied as true")
}
}