Files
2026-12-01 21:27:39 +01:00

965 lines
33 KiB
Go

package seed
import (
"errors"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/app"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/repository"
"github.com/phishingclub/phishingclub/testdb"
"go.uber.org/zap"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)
// TestInstallTwice runs the startup install and migration twice on an empty
// database with foreign keys on, the way the server opens it. The second run
// must work and, on postgres, must keep the indexes the first run made.
func TestInstallTwice(t *testing.T) {
dsn := filepath.Join(t.TempDir(), "install.db") + "?_foreign_keys=ON"
db, err := testdb.Open(t, dsn)
if err != nil {
t.Fatalf("open: %v", err)
}
repos := app.NewRepositories(db)
log := zap.NewNop().Sugar()
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("first install: %v", err)
}
before := postgresIndexOIDs(t, db)
capture := &captureSQL{}
capture.register(t, db)
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("second install: %v", err)
}
// varchar columns are text on postgres from the first install on, the
// second start changes no column type
if alters := alterTypes(capture.take()); testdb.IsPostgres() && len(alters) != 0 {
t.Errorf("the second install changed column types: %v", alters)
}
after := postgresIndexOIDs(t, db)
for name, oid := range before {
if after[name] != oid {
t.Errorf("index %s was rebuilt on the second run", name)
}
}
if testdb.IsPostgres() {
if len(before) == 0 {
t.Fatal("no indexes made by ensureIndex found")
}
var definition string
if err := db.Raw(`SELECT indexdef FROM pg_indexes WHERE schemaname = current_schema() AND indexname = 'idx_campaign_recipients_lure_code_custom'`).Scan(&definition).Error; err != nil {
t.Fatalf("index definition: %v", err)
}
if definition == "" {
t.Fatal("custom lure code index missing")
}
// postgres has no integer to boolean compare, the predicate is = true
if !strings.Contains(definition, "lure_code_custom = true") {
t.Fatalf("custom lure code index definition %q, want lure_code_custom = true", definition)
}
// a changed ddl rebuilds the index once, the next start keeps it
const name = "idx_campaign_recipients_unsent"
if err := db.Model(&database.SchemaIndexVersion{}).
Where(&database.SchemaIndexVersion{Name: name}).
Update("ddl_sha256", "0000").Error; err != nil {
t.Fatalf("change record: %v", err)
}
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("third install: %v", err)
}
rebuilt := postgresIndexOIDs(t, db)
if rebuilt[name] == after[name] {
t.Errorf("index %s with a changed ddl record was not rebuilt", name)
}
for n, oid := range after {
if n != name && rebuilt[n] != oid {
t.Errorf("index %s was rebuilt although its ddl did not change", n)
}
}
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("fourth install: %v", err)
}
again := postgresIndexOIDs(t, db)
if again[name] != rebuilt[name] {
t.Errorf("index %s was rebuilt a second time", name)
}
// an index of the recorded name on other keys or another table is
// not the index of the record, the next start makes the real one
for _, decoy := range []string{
`CREATE INDEX idx_campaign_recipients_lure_code ON campaign_recipients (campaign_id)`,
`CREATE TABLE pc_decoy (lure_code text)`,
`CREATE INDEX idx_campaign_recipients_lure_code ON pc_decoy (lure_code)`,
} {
if strings.HasPrefix(decoy, "CREATE INDEX") {
if err := db.Exec(`DROP INDEX idx_campaign_recipients_lure_code`).Error; err != nil {
t.Fatal(err)
}
}
if err := db.Exec(decoy).Error; err != nil {
t.Fatalf("%s: %v", decoy, err)
}
if !strings.HasPrefix(decoy, "CREATE INDEX") {
continue
}
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("install after a decoy index: %v", err)
}
var definition string
if err := db.Raw(`SELECT indexdef FROM pg_indexes WHERE schemaname = current_schema() AND indexname = 'idx_campaign_recipients_lure_code'`).Scan(&definition).Error; err != nil {
t.Fatal(err)
}
if !strings.Contains(definition, "UNIQUE INDEX") || !strings.Contains(definition, "campaign_recipients USING btree (lure_code)") {
t.Errorf("after the decoy %q the index is %q", decoy, definition)
}
}
}
}
// postgresIndexOIDs returns the oid of every index that ensureIndex recorded,
// empty on sqlite
func postgresIndexOIDs(t *testing.T, db *gorm.DB) map[string]int64 {
t.Helper()
out := map[string]int64{}
if !testdb.IsPostgres() {
return out
}
var rows []struct {
Name string `gorm:"column:index_name"`
IndexOID int64 `gorm:"column:index_oid"`
}
if err := db.Raw(`SELECT c.relname::text AS index_name, c.oid::bigint AS index_oid FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN schema_index_versions v ON v.name = c.relname
WHERE c.relkind = 'i' AND n.nspname = current_schema()`).Scan(&rows).Error; err != nil {
t.Fatalf("indexes: %v", err)
}
for _, r := range rows {
if r.IndexOID == 0 {
t.Fatalf("index %s read without its oid", r.Name)
}
out[r.Name] = r.IndexOID
}
return out
}
// TestLureCodeDuplicatesReleased checks the migration keeps a duplicated lure
// code on the first row only, when the unique index has to be built over
// rows that already hold the same code
func TestLureCodeDuplicatesReleased(t *testing.T) {
dsn := filepath.Join(t.TempDir(), "lure.db")
db, err := testdb.Open(t, dsn)
if err != nil {
t.Fatalf("open: %v", err)
}
if err := initialInstallAndSeed(db, app.NewRepositories(db), zap.NewNop().Sugar(), false); err != nil {
t.Fatalf("install: %v", err)
}
// the rows below have no campaign, the install turns foreign keys on
sqlDB, err := db.DB()
if err != nil {
t.Fatal(err)
}
sqlDB.SetMaxOpenConns(1)
if err := testdb.SetForeignKeys(db, false); err != nil {
t.Fatalf("foreign keys: %v", err)
}
if err := db.Exec(`DROP INDEX idx_campaign_recipients_lure_code`).Error; err != nil {
t.Fatalf("drop index: %v", err)
}
code := "DUPLICATE1"
start := time.Now().UTC().Add(-time.Hour)
ids := []uuid.UUID{}
for i := 0; i < 3; i++ {
id, campaignID := uuid.New(), uuid.New()
at := start.Add(time.Duration(i) * time.Minute)
if err := db.Create(&database.CampaignRecipient{
ID: &id, CreatedAt: &at, UpdatedAt: &at, CampaignID: &campaignID, LureCode: &code,
}).Error; err != nil {
t.Fatalf("insert: %v", err)
}
ids = append(ids, id)
}
if err := (database.CampaignRecipient{}).Migrate(db); err != nil {
t.Fatalf("migrate: %v", err)
}
var holders []uuid.UUID
if err := db.Model(&database.CampaignRecipient{}).Where("lure_code = ?", code).Pluck("id", &holders).Error; err != nil {
t.Fatalf("holders: %v", err)
}
if len(holders) != 1 || holders[0] != ids[0] {
t.Fatalf("holders %v, want only the first row %v", holders, ids[0])
}
if ok, err := testdb.HasIndex(db, "idx_campaign_recipients_lure_code"); err != nil || !ok {
t.Fatalf("unique index must exist again: %v %v", ok, err)
}
}
// recipientIndexes returns the definition of every index of the recipients
// table by name
func recipientIndexes(t *testing.T, db *gorm.DB) map[string]string {
t.Helper()
var rows []struct {
Name string `gorm:"column:name"`
Def string `gorm:"column:def"`
}
query := `SELECT name, COALESCE(sql, '') AS def FROM sqlite_master WHERE type = 'index' AND tbl_name = 'recipients'`
if testdb.IsPostgres() {
query = `SELECT indexname AS name, indexdef AS def FROM pg_indexes WHERE schemaname = current_schema() AND tablename = 'recipients'`
}
if err := db.Raw(query).Scan(&rows).Error; err != nil {
t.Fatalf("indexes: %v", err)
}
out := map[string]string{}
for _, r := range rows {
out[r.Name] = r.Def
}
return out
}
func sortedKeys(m map[string]string) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// TestRecipientEmailIndexUpgrade starts from the schema where the email was
// unique across every company, with data, and runs the migration. The old
// index is gone, the per company and the shared indexes exist, the indexes
// are exactly those of a new install, and the rows keep their rules.
func TestRecipientEmailIndexUpgrade(t *testing.T) {
log := zap.NewNop().Sugar()
fresh, err := testdb.Open(t, filepath.Join(t.TempDir(), "fresh.db"))
if err != nil {
t.Fatal(err)
}
if err := MigrateSchema(fresh, log); err != nil {
t.Fatalf("fresh migrate: %v", err)
}
want := recipientIndexes(t, fresh)
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "old.db"))
if err != nil {
t.Fatal(err)
}
if err := MigrateSchema(db, log); err != nil {
t.Fatalf("migrate: %v", err)
}
// the schema before: one unique index on the email, named by gorm
for _, stmt := range []string{
`DROP INDEX idx_recipients_company_id_email`,
`DROP INDEX idx_recipients_email_shared`,
`CREATE UNIQUE INDEX idx_recipients_email ON recipients (email)`,
} {
if err := db.Exec(stmt).Error; err != nil {
t.Fatalf("%s: %v", stmt, err)
}
}
if testdb.IsPostgres() {
if err := db.Exec(`DELETE FROM schema_index_versions WHERE name = ?`, "idx_recipients_email_shared").Error; err != nil {
t.Fatal(err)
}
}
now := time.Now().UTC()
a, b := uuid.New(), uuid.New()
for _, id := range []uuid.UUID{a, b} {
if err := db.Create(&database.Company{ID: id, CreatedAt: &now, UpdatedAt: &now, Name: id.String(), AssetsKey: id.String()}).Error; err != nil {
t.Fatalf("company: %v", err)
}
}
insert := func(email *string, companyID *uuid.UUID) error {
id := uuid.New()
return db.Create(&database.Recipient{ID: &id, CreatedAt: &now, UpdatedAt: &now, Email: email, CompanyID: companyID}).Error
}
str := func(s string) *string { return &s }
for _, r := range []struct {
email *string
companyID *uuid.UUID
}{
{str("kate@corp.test"), &a},
{str("Bob@corp.test"), &b},
{str("bob@corp.test"), &a},
{str("shared@corp.test"), nil},
{nil, nil},
{nil, nil},
{nil, &a},
{nil, &a},
} {
if err := insert(r.email, r.companyID); err != nil {
t.Fatalf("old data: %v", err)
}
}
if err := insert(str("kate@corp.test"), &b); !repository.IsUniqueViolation(err, repository.AnyUniqueKey) {
t.Fatalf("the old index must refuse the email in another company, got %v", err)
}
if err := MigrateSchema(db, log); err != nil {
t.Fatalf("upgrade: %v", err)
}
got := recipientIndexes(t, db)
if strings.Join(sortedKeys(got), ",") != strings.Join(sortedKeys(want), ",") {
t.Fatalf("indexes after the upgrade\n%v\nwant those of a new install\n%v", sortedKeys(got), sortedKeys(want))
}
if _, ok := got["idx_recipients_email"]; ok {
t.Fatal("the old unique index is still there")
}
perCompany := got["idx_recipients_company_id_email"]
if !strings.Contains(perCompany, "UNIQUE") || !strings.Contains(perCompany, "company_id") || !strings.Contains(perCompany, "email") {
t.Fatalf("per company index %q", perCompany)
}
shared := got["idx_recipients_email_shared"]
if !strings.Contains(shared, "UNIQUE") || !strings.Contains(shared, "company_id IS NULL") {
t.Fatalf("shared index %q", shared)
}
if testdb.IsPostgres() {
var n int64
if err := db.Raw(`SELECT COUNT(*) FROM schema_index_versions WHERE name = ?`, "idx_recipients_email_shared").Scan(&n).Error; err != nil || n != 1 {
t.Fatalf("shared index record %d %v", n, err)
}
}
// the rules after the upgrade
if err := insert(str("kate@corp.test"), &b); err != nil {
t.Fatalf("the email in another company: %v", err)
}
if err := insert(str("kate@corp.test"), &a); !repository.IsUniqueViolation(err, repository.AnyUniqueKey) {
t.Fatalf("the email twice in a company: want a unique violation, got %v", err)
}
if err := insert(str("shared@corp.test"), nil); !repository.IsUniqueViolation(err, repository.AnyUniqueKey) {
t.Fatalf("two shared recipients with one email: want a unique violation, got %v", err)
}
if err := insert(nil, nil); err != nil {
t.Fatalf("recipients without an email: %v", err)
}
// a second start keeps the indexes as they are
if err := MigrateSchema(db, log); err != nil {
t.Fatalf("second start: %v", err)
}
again := recipientIndexes(t, db)
for name, def := range got {
if again[name] != def {
t.Errorf("index %s changed on the second start: %q, was %q", name, again[name], def)
}
}
}
// TestRowOrderColumn checks the seq column of the postgres migration: added
// to tables that already hold rows, which get numbers, kept by a second
// install, never written by gorm, given out on insert, and with its unique
// index. sqlite gets no such column.
func TestRowOrderColumn(t *testing.T) {
db, err := testdb.Open(t, filepath.Join(t.TempDir(), "roworder.db"))
if err != nil {
t.Fatalf("open: %v", err)
}
if testdb.IsPostgres() {
// the test helper adds the column when gorm creates the table, the
// migration must add it without that help
if err := db.Exec("DROP EVENT TRIGGER pctest_row_order").Error; err != nil {
t.Fatalf("drop helper trigger: %v", err)
}
}
// rows from before the column existed
if err := db.AutoMigrate(&database.CampaignEvent{}, &database.Recipient{}); err != nil {
t.Fatalf("automigrate: %v", err)
}
now := time.Now().UTC()
for i := 0; i < 3; i++ {
id := uuid.New()
campaign := uuid.New()
event := uuid.New()
if err := db.Create(&database.CampaignEvent{
ID: &id, CreatedAt: &now, UpdatedAt: &now, CampaignID: &campaign, EventID: &event,
}).Error; err != nil {
t.Fatalf("insert event: %v", err)
}
}
repos := app.NewRepositories(db)
log := zap.NewNop().Sugar()
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("install: %v", err)
}
if !testdb.IsPostgres() {
for _, table := range []string{database.CAMPAIGN_EVENT_TABLE, database.RECIPIENT_TABLE} {
if db.Migrator().HasColumn(table, database.ROW_ORDER_COLUMN) {
t.Errorf("sqlite table %s has a seq column", table)
}
}
return
}
seqs := func() []int64 {
t.Helper()
var out []int64
if err := db.Table(database.CAMPAIGN_EVENT_TABLE).Order("seq").Pluck("seq", &out).Error; err != nil {
t.Fatalf("read seq: %v", err)
}
return out
}
if got := seqs(); len(got) != 3 || got[0] != 1 || got[1] != 2 || got[2] != 3 {
t.Fatalf("existing rows numbered %v, want [1 2 3]", got)
}
// a second install keeps the column and its numbers
if err := initialInstallAndSeed(db, repos, log, false); err != nil {
t.Fatalf("second install: %v", err)
}
campaignID := uuid.New()
eventID := uuid.New()
newID := uuid.New()
if err := db.Create(&database.CampaignEvent{
ID: &newID, CreatedAt: &now, UpdatedAt: &now, CampaignID: &campaignID, EventID: &eventID,
}).Error; err != nil {
t.Fatalf("insert event: %v", err)
}
if got := seqs(); len(got) != 4 || got[3] != 4 {
t.Fatalf("seq after insert %v, want 4 numbers ending in 4", got)
}
// a struct read ignores the column gorm does not know
var rows []database.CampaignEvent
if err := db.Find(&rows).Error; err != nil || len(rows) != 4 {
t.Fatalf("read events: %d rows, %v", len(rows), err)
}
for _, index := range []string{"idx_campaign_events_seq", "idx_recipients_seq", "idx_recipients_company_seq"} {
if ok, err := testdb.HasIndex(db, index); err != nil || !ok {
t.Errorf("index %s missing: %v", index, err)
}
}
if !db.Migrator().HasColumn(database.RECIPIENT_TABLE, database.ROW_ORDER_COLUMN) {
t.Error("recipients has no seq column")
}
// the unique index refuses a number twice
dup := uuid.New()
err = db.Exec("INSERT INTO campaign_events (id, created_at, updated_at, data, campaign_id, event_id, seq) VALUES (?, ?, ?, '', ?, ?, 1)",
dup, now, now, campaignID, eventID).Error
if !errors.Is(err, gorm.ErrDuplicatedKey) {
t.Fatalf("a second row with seq 1: %v, want a duplicate key error", err)
}
}
// declaredVarchar matches a field declared type:varchar(n)
var declaredVarchar = regexp.MustCompile(`(?i)^varchar\(\d+\)$`)
// alterType matches the statement gorm runs to change a column type
var alterType = regexp.MustCompile(`(?is)^\s*ALTER TABLE .* ALTER COLUMN .* TYPE `)
// varcharColumn is a column an entity declares as varchar(n)
type varcharColumn struct {
table, column string
primaryKey bool
}
// declaredVarcharColumns returns every column the install tables declare as
// varchar(n), read from a fresh parse of the entities, so a new varchar
// field is checked without a list in the test
func declaredVarcharColumns(t *testing.T, db *gorm.DB) []varcharColumn {
t.Helper()
models := append(SchemaTables(), &database.SchemaIndexVersion{})
cache := &sync.Map{}
seen := map[string]bool{}
var out []varcharColumn
for _, m := range models {
s, err := schema.Parse(m, cache, db.NamingStrategy)
if err != nil {
t.Fatalf("parse %T: %v", m, err)
}
for _, f := range s.Fields {
if f.DBName == "" || !declaredVarchar.MatchString(string(f.DataType)) {
continue
}
key := s.Table + "." + f.DBName
if seen[key] {
continue
}
seen[key] = true
out = append(out, varcharColumn{table: s.Table, column: f.DBName, primaryKey: f.PrimaryKey})
}
}
sort.Slice(out, func(i, j int) bool {
return out[i].table+"."+out[i].column < out[j].table+"."+out[j].column
})
return out
}
// columnTypes returns the information_schema data type of every column of
// the current schema, keyed by table.column
func columnTypes(t *testing.T, db *gorm.DB) map[string]string {
t.Helper()
var rows []struct {
TableName string
ColumnName string
DataType string
}
if err := db.Raw(`SELECT table_name::text AS table_name, column_name::text AS column_name, data_type::text AS data_type
FROM information_schema.columns WHERE table_schema = current_schema()`).Scan(&rows).Error; err != nil {
t.Fatalf("column types: %v", err)
}
out := map[string]string{}
for _, r := range rows {
out[r.TableName+"."+r.ColumnName] = r.DataType
}
return out
}
// checkWidenedColumns checks every declared varchar column is text on
// postgres, a primary key column keeps character varying, and no other
// column of the database is character varying
func checkWidenedColumns(t *testing.T, db *gorm.DB) {
t.Helper()
declared := declaredVarcharColumns(t, db)
if len(declared) < 30 {
t.Fatalf("only %d declared varchar columns found, the parse missed some", len(declared))
}
types := columnTypes(t, db)
keys := map[string]bool{}
for _, c := range declared {
key := c.table + "." + c.column
want := "text"
if c.primaryKey {
want = "character varying"
keys[key] = true
}
if got := types[key]; got != want {
t.Errorf("%s is %q, want %q", key, got, want)
}
}
if len(keys) != 3 {
t.Errorf("primary key varchar columns %v, want the two language route match keys and the index name", keys)
}
for key, typ := range types {
if typ == "character varying" && !keys[key] {
t.Errorf("%s is character varying and not a declared primary key", key)
}
}
}
// captureSQL records the SQL text of every statement db runs through gorm
type captureSQL struct {
mu sync.Mutex
list []string
// afterAlter runs after each statement that changes a column type,
// inside its transaction
afterAlter func(tx *gorm.DB)
}
func (c *captureSQL) register(t *testing.T, db *gorm.DB) {
t.Helper()
write := func(tx *gorm.DB) {
sql := tx.Statement.SQL.String()
c.mu.Lock()
c.list = append(c.list, sql)
after := c.afterAlter
c.mu.Unlock()
if after != nil && alterType.MatchString(sql) {
after(tx)
}
}
cb := db.Callback()
for _, err := range []error{
cb.Raw().After("gorm:raw").Register("p5test:capture", write),
cb.Row().After("gorm:row").Register("p5test:capture", write),
cb.Query().After("gorm:query").Register("p5test:capture", write),
cb.Create().After("gorm:create").Register("p5test:capture", write),
cb.Update().After("gorm:update").Register("p5test:capture", write),
} {
if err != nil {
t.Fatalf("capture: %v", err)
}
}
}
// take returns the statements recorded so far and starts a new list
func (c *captureSQL) take() []string {
c.mu.Lock()
defer c.mu.Unlock()
out := c.list
c.list = nil
return out
}
// alterTypes returns the statements that change a column type
func alterTypes(statements []string) []string {
var out []string
for _, s := range statements {
if alterType.MatchString(s) {
out = append(out, strings.Join(strings.Fields(s), " "))
}
}
return out
}
// relfilenodes returns the storage file of every table and index of the
// current schema; a rewrite gives a new one
func relfilenodes(t *testing.T, db *gorm.DB) map[string]int64 {
t.Helper()
out, err := readRelfilenodes(db)
if err != nil {
t.Fatalf("relfilenodes: %v", err)
}
return out
}
// readRelfilenodes is relfilenodes without a test, for a gorm callback
func readRelfilenodes(db *gorm.DB) (map[string]int64, error) {
var rows []struct {
Name string
Node int64
}
if err := db.Raw(`SELECT c.relname::text AS name, c.relfilenode::bigint AS node FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = current_schema() AND c.relkind IN ('r', 'i')`).Scan(&rows).Error; err != nil {
return nil, err
}
out := map[string]int64{}
for _, r := range rows {
out[r.Name] = r.Node
}
return out, nil
}
// rebuildCounter counts per table and index how often its storage changed,
// read after every statement that changes a column type. A statement can
// build an index once at most, so a count above one means two statements
// built it.
type rebuildCounter struct {
mu sync.Mutex
last map[string]int64
counts map[string]int
errs []error
}
func (r *rebuildCounter) afterAlter(tx *gorm.DB) {
nodes, err := readRelfilenodes(tx.Session(&gorm.Session{NewDB: true}))
r.mu.Lock()
defer r.mu.Unlock()
if err != nil {
r.errs = append(r.errs, err)
return
}
for name, node := range nodes {
if before, ok := r.last[name]; ok && before != node {
r.counts[name]++
}
}
r.last = nodes
}
// tableRows returns every row of the table as JSON text, sorted
func tableRows(t *testing.T, db *gorm.DB, table string) []string {
t.Helper()
var rows []string
if err := db.Table("? AS t", clause.Table{Name: table}).
Select("row_to_json(t)::text AS r").Order("r").Scan(&rows).Error; err != nil {
t.Fatalf("rows of %s: %v", table, err)
}
return rows
}
// TestInstallVarcharAsText checks a new postgres install makes every
// declared varchar column text, except primary keys. On sqlite the entity
// keeps its declared type.
func TestInstallVarcharAsText(t *testing.T) {
db, err := testdb.Open(t, t.TempDir()+"/install.db?_foreign_keys=ON")
if err != nil {
t.Fatalf("open: %v", err)
}
if err := initialInstallAndSeed(db, app.NewRepositories(db), zap.NewNop().Sugar(), false); err != nil {
t.Fatalf("install: %v", err)
}
if !testdb.IsPostgres() {
// sqlite runs the gorm sqlite dialector as it is, no text cleaning
// and no type change
if _, ok := db.Dialector.(*sqlite.Dialector); !ok {
t.Fatalf("sqlite dialector is %T", db.Dialector)
}
// sqlite parses and creates the declared type
s, err := schema.Parse(&database.CampaignRecipient{}, &sync.Map{}, db.NamingStrategy)
if err != nil {
t.Fatal(err)
}
var ddl string
if err := db.Raw(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?`, s.Table).Scan(&ddl).Error; err != nil {
t.Fatal(err)
}
if !strings.Contains(ddl, "`message_id` varchar(512)") {
t.Fatalf("sqlite table keeps varchar(512): %s", ddl)
}
stmt := &gorm.Statement{DB: db}
if err := stmt.Parse(&database.CampaignRecipient{}); err != nil {
t.Fatal(err)
}
if f := stmt.Schema.LookUpField("message_id"); f == nil || string(f.DataType) != "varchar(512)" {
t.Fatalf("sqlite schema field type changed: %v", f)
}
return
}
checkWidenedColumns(t, db)
}
// TestUpgradeVarcharToText installs the way the code did before varchar
// became text on postgres, adds rows, makes two not null columns nullable
// with a NULL in them, then starts the current code twice: the first start
// changes each declared varchar column to text once, in one statement per
// table, without a table rewrite, builds each partial index on a changed
// column once, keeps nullability and the rows as they were; the second
// start changes nothing.
func TestUpgradeVarcharToText(t *testing.T) {
testdb.SkipUnlessPostgres(t)
dsn := testdb.NewPostgresDatabase(t, true)
log := zap.NewNop().Sugar()
// the gorm postgres dialector without the application changes
old, err := gorm.Open(postgres.New(postgres.Config{DSN: dsn}), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
TranslateError: true,
})
if err != nil {
t.Fatalf("open old: %v", err)
}
if err := initialInstallAndSeed(old, app.NewRepositories(old), log, false); err != nil {
t.Fatalf("old install: %v", err)
}
declared := declaredVarcharColumns(t, old)
types := columnTypes(t, old)
widened := map[string]bool{}
for _, c := range declared {
key := c.table + "." + c.column
if types[key] != "character varying" {
t.Fatalf("old install: %s is %q, want character varying", key, types[key])
}
if !c.primaryKey {
widened[key] = true
}
}
now := time.Now().UTC()
providerID, inboxID := uuid.New(), uuid.New()
if err := old.Create(&database.OAuthProvider{
ID: providerID, CreatedAt: &now, UpdatedAt: &now, Name: "upgrade",
AuthURL: "https://login.example.com/authorize", TokenURL: "https://login.example.com/token",
Scopes: "openid offline_access", ClientID: "client", ClientSecret: "secret",
AccessToken: strings.Repeat("a", 4000), RefreshToken: strings.Repeat("r", 4000),
AuthorizedEmail: "ops@example.com",
}).Error; err != nil {
t.Fatalf("old provider: %v", err)
}
if err := old.Create(&database.ReportInbox{
ID: &inboxID, CreatedAt: &now, UpdatedAt: &now, AuthMode: "app", Mailbox: "report@example.com",
TenantID: "contoso.onmicrosoft.com", ClientID: uuid.NewString(), ClientSecret: "secret",
}).Error; err != nil {
t.Fatalf("old inbox: %v", err)
}
// a schema that drifted from the entities: nullable columns the entity
// declares not null, holding a NULL, one with a default and one without.
// The upgrade only changes the type, so the start must not fail on them.
for _, column := range []string{"result", "state_token"} {
if err := old.Exec("ALTER TABLE ? ALTER COLUMN ? DROP NOT NULL",
clause.Table{Name: database.OAUTH_STATE_TABLE}, clause.Column{Name: column}).Error; err != nil {
t.Fatalf("drop not null %s: %v", column, err)
}
}
if err := old.Exec(`INSERT INTO ? (id, created_at, state_token, o_auth_provider_id, expires_at, used, result)
VALUES (?, ?, NULL, ?, ?, false, NULL)`,
clause.Table{Name: database.OAUTH_STATE_TABLE}, uuid.New(), now, providerID, now).Error; err != nil {
t.Fatalf("old state with NULL: %v", err)
}
tables := map[string]bool{}
for key := range widened {
tables[strings.SplitN(key, ".", 2)[0]] = true
}
rowsBefore := map[string][]string{}
for table := range tables {
rowsBefore[table] = tableRows(t, old, table)
}
nodesBefore := relfilenodes(t, old)
oldSQL, err := old.DB()
if err != nil {
t.Fatal(err)
}
if err := oldSQL.Close(); err != nil {
t.Fatal(err)
}
db, err := testdb.OpenPostgresDSN(t, dsn)
if err != nil {
t.Fatalf("open: %v", err)
}
counter := &rebuildCounter{last: nodesBefore, counts: map[string]int{}}
capture := &captureSQL{afterAlter: counter.afterAlter}
capture.register(t, db)
if err := initialInstallAndSeed(db, app.NewRepositories(db), log, false); err != nil {
t.Fatalf("upgrade install: %v", err)
}
checkWidenedColumns(t, db)
// one statement per table, naming each widened column of it once, and
// no other column change
statements := capture.take()
for _, st := range statements {
if otherColumnChange.MatchString(st) {
t.Errorf("the upgrade changed more than the type: %s", st)
}
}
alters := alterTypes(statements)
altered := map[string]int{}
perTable := map[string]int{}
for _, a := range alters {
m := widenAlter.FindStringSubmatch(a)
if m == nil {
t.Errorf("unexpected type change: %s", a)
continue
}
perTable[m[1]]++
for _, c := range widenColumn.FindAllStringSubmatch(a, -1) {
altered[m[1]+"."+c[1]]++
}
}
for key := range widened {
if altered[key] != 1 {
t.Errorf("%s changed %d times, want once", key, altered[key])
}
}
for key := range altered {
if !widened[key] {
t.Errorf("%s changed, it is not a widened column", key)
}
}
for table := range tables {
if perTable[table] != 1 {
t.Errorf("table %s got %d type change statements, want one", table, perTable[table])
}
}
if len(alters) != len(tables) {
t.Errorf("%d type change statements for %d tables: %v", len(alters), len(tables), alters)
}
// postgres keeps the storage of the tables and of every index, except a
// partial index whose WHERE names a changed column: it is built again
// once, with the same name and definition, also when its WHERE names two
// changed columns
if len(counter.errs) != 0 {
t.Fatalf("relfilenodes after a type change: %v", counter.errs)
}
rebuilt := partialIndexesOn(t, db, widened)
if len(rebuilt) == 0 {
t.Fatal("no partial index on a changed column found, the check below proves nothing for them")
}
if !rebuilt["idx_campaign_recipients_unlinked_code"] {
t.Fatal("idx_campaign_recipients_unlinked_code no longer names a changed column, the once check below proves less")
}
for name, n := range counter.counts {
if !rebuilt[name] {
t.Errorf("%s was rewritten %d times by the upgrade", name, n)
} else if n != 1 {
t.Errorf("%s was built %d times by the upgrade, want once", name, n)
}
}
for name := range rebuilt {
if counter.counts[name] != 1 {
t.Errorf("%s was built %d times by the upgrade, want once", name, counter.counts[name])
}
}
nodesAfter := relfilenodes(t, db)
for name, node := range nodesBefore {
after, ok := nodesAfter[name]
if !ok {
t.Errorf("%s is gone after the upgrade", name)
continue
}
if after != node && !rebuilt[name] {
t.Errorf("%s was rewritten by the upgrade", name)
}
if counter.last[name] != after {
t.Errorf("%s changed outside a type change statement", name)
}
}
// the drifted columns keep their nullability, gorm never sets NOT NULL
var nullable []string
if err := db.Raw(`SELECT column_name::text FROM information_schema.columns
WHERE table_schema = current_schema() AND table_name = ? AND is_nullable = 'YES' AND column_name IN ?
ORDER BY column_name`, database.OAUTH_STATE_TABLE, []string{"result", "state_token"}).Scan(&nullable).Error; err != nil {
t.Fatal(err)
}
if strings.Join(nullable, ",") != "result,state_token" {
t.Errorf("nullable drifted columns after the upgrade %v, want result and state_token", nullable)
}
for table, before := range rowsBefore {
after := tableRows(t, db, table)
if strings.Join(after, "\n") != strings.Join(before, "\n") {
t.Errorf("rows of %s changed by the upgrade:\nbefore %v\nafter %v", table, before, after)
}
}
// the next start finds text and changes no type
if err := initialInstallAndSeed(db, app.NewRepositories(db), log, false); err != nil {
t.Fatalf("second start: %v", err)
}
if again := alterTypes(capture.take()); len(again) != 0 {
t.Errorf("the second start changed types: %v", again)
}
if nodes := relfilenodes(t, db); len(nodes) != len(nodesAfter) {
t.Errorf("tables or indexes changed on the second start")
} else {
for name, node := range nodesAfter {
if nodes[name] != node {
t.Errorf("%s was rewritten on the second start", name)
}
}
}
}
// partialIndexesOn returns the partial indexes whose WHERE names one of the
// columns, keyed by index name
func partialIndexesOn(t *testing.T, db *gorm.DB, columns map[string]bool) map[string]bool {
t.Helper()
var rows []struct {
Table string
Name string
Def string
}
if err := db.Raw(`SELECT tablename::text AS "table", indexname::text AS name, indexdef AS def
FROM pg_indexes WHERE schemaname = current_schema()`).Scan(&rows).Error; err != nil {
t.Fatalf("indexes: %v", err)
}
out := map[string]bool{}
for _, r := range rows {
_, where, ok := strings.Cut(r.Def, " WHERE ")
if !ok {
continue
}
for key := range columns {
table, column, _ := strings.Cut(key, ".")
if table == r.Table && regexp.MustCompile(`\b`+regexp.QuoteMeta(column)+`\b`).MatchString(where) {
out[r.Name] = true
}
}
}
return out
}
// widenAlter is the one statement the upgrade runs per table: only type
// changes to text, no USING, no NOT NULL or default change
var widenAlter = regexp.MustCompile(`^ALTER TABLE "([^"]+)" ALTER COLUMN "[^"]+" TYPE text(, ALTER COLUMN "[^"]+" TYPE text)*$`)
// widenColumn finds each column of a widenAlter statement
var widenColumn = regexp.MustCompile(`ALTER COLUMN "([^"]+)" TYPE text`)
// otherColumnChange matches a statement that changes nullability or a default
var otherColumnChange = regexp.MustCompile(`(?i)\b(SET|DROP) (NOT NULL|DEFAULT)\b`)