Files
2026-12-01 19:40:55 +01:00

345 lines
9.5 KiB
Go

package testdb
import (
"context"
"crypto/rand"
"database/sql"
"encoding/binary"
"encoding/hex"
"fmt"
"reflect"
"regexp"
"runtime"
"sync"
"testing"
"github.com/jackc/pgx/v5"
"gorm.io/gorm"
)
// Migration is the schema a test makes right after it opens its database,
// see OpenMigrated
type Migration struct {
// ForeignKeysOff turns foreign key checks off before the steps run, see
// SetForeignKeys
ForeignKeysOff bool
// Steps run in this order
Steps []Step
}
// Step is one part of a migration, see AutoMigrate and Func
type Step struct {
models []any
fn func(db *gorm.DB) error
}
// AutoMigrate is the step db.AutoMigrate(models...)
func AutoMigrate(models ...any) Step {
return Step{models: models}
}
// Func is the step fn(db). fn only changes the schema, it adds no rows, and
// it is a named function: a closure or method value is refused, as the
// template of a migration is found by the code of its steps.
func Func(fn func(db *gorm.DB) error) Step {
return Step{fn: fn}
}
// With returns m with steps added at the end
func (m Migration) With(steps ...Step) Migration {
all := make([]Step, 0, len(m.Steps)+len(steps))
all = append(all, m.Steps...)
m.Steps = append(all, steps...)
return m
}
// OpenMigrated opens the test database like Open and makes the schema of m
// in it: with ForeignKeysOff it calls SetForeignKeys(db, false), then it
// runs the steps in order.
//
// On sqlite it runs exactly these statements. On postgres they run once per
// test process in a template database, and every test gets its own new
// database made as a copy of that template, which holds the same schema as
// running the steps would and no rows. The copy is dropped when the test
// ends like any other test database. ForeignKeysOff, which is connection
// state and not schema, is set again on the copy.
// A package that uses it calls DropTemplates at the end of its TestMain.
func OpenMigrated(t testing.TB, sqliteDSN string, m Migration) (*gorm.DB, error) {
t.Helper()
return openMigrated(t, sqliteDSN, "", m)
}
// OpenMigratedWithExecMode is OpenMigrated with the pgx
// default_query_exec_mode set, see OpenWithExecMode
func OpenMigratedWithExecMode(t testing.TB, sqliteDSN string, execMode string, m Migration) (*gorm.DB, error) {
t.Helper()
return openMigrated(t, sqliteDSN, execMode, m)
}
func openMigrated(t testing.TB, sqliteDSN string, execMode string, m Migration) (*gorm.DB, error) {
t.Helper()
if err := m.check(); err != nil {
t.Fatalf("testdb: %v", err)
}
if !IsPostgres() {
db, err := open(t, sqliteDSN, execMode)
if err != nil {
return nil, err
}
if err := m.run(db); err != nil {
return nil, err
}
return db, nil
}
foreignKeys := sqliteForeignKeysOn(sqliteDSN)
template, err := migratedTemplate(t, foreignKeys, execMode, m)
if err != nil {
t.Fatalf("testdb: template database: %v", err)
}
dsn := newPostgresDatabase(t, foreignKeys, template)
db, err := openPostgresTest(t, dsn, execMode, false)
if err != nil {
return nil, err
}
if m.ForeignKeysOff {
if err := SetForeignKeys(db, false); err != nil {
return nil, err
}
}
return db, nil
}
// anonymousFuncPattern matches the runtime name of a closure (pkg.f.func1,
// pkg.glob..func1) or a method value (pkg.T.M-fm)
var anonymousFuncPattern = regexp.MustCompile(`(\.func[0-9]+(\.[0-9]+)*|-fm)$`)
// check refuses a step that is not exactly one of models or a named function
func (m Migration) check() error {
for i, s := range m.Steps {
if (s.fn == nil) == (len(s.models) == 0) {
return fmt.Errorf("migration step %d needs either models or a function", i)
}
if s.fn == nil {
continue
}
f := runtime.FuncForPC(reflect.ValueOf(s.fn).Pointer())
if f == nil || anonymousFuncPattern.MatchString(f.Name()) {
return fmt.Errorf("migration step %d is not a named function", i)
}
}
return nil
}
// run makes the schema of m in db
func (m Migration) run(db *gorm.DB) error {
if m.ForeignKeysOff {
if err := SetForeignKeys(db, false); err != nil {
return fmt.Errorf("foreign keys off: %w", err)
}
}
for _, s := range m.Steps {
if s.fn != nil {
if err := s.fn(db); err != nil {
return err
}
continue
}
if err := db.AutoMigrate(s.models...); err != nil {
return fmt.Errorf("migrate: %w", err)
}
}
return nil
}
// templateNamePattern is the only form of template database name the tests
// create and drop: pctpl_, the owner tag of the process, a counter
var templateNamePattern = regexp.MustCompile(`^pctpl_[0-9a-f]{16}_[0-9]{1,6}$`)
// templateKey is everything that makes the schema and connection setup of a
// template: the foreign key flag and exec mode of its DSN, the migration
// flag and every step, the exact model types in order or the function
type templateKey struct {
foreignKeys bool
execMode string
foreignKeysOff bool
steps []stepKey
}
type stepKey struct {
types []reflect.Type
fn uintptr
}
func newTemplateKey(foreignKeys bool, execMode string, m Migration) templateKey {
key := templateKey{
foreignKeys: foreignKeys,
execMode: execMode,
foreignKeysOff: m.ForeignKeysOff,
steps: make([]stepKey, len(m.Steps)),
}
for i, s := range m.Steps {
if s.fn != nil {
key.steps[i].fn = reflect.ValueOf(s.fn).Pointer()
continue
}
key.steps[i].types = make([]reflect.Type, len(s.models))
for j, model := range s.models {
key.steps[i].types[j] = reflect.TypeOf(model)
}
}
return key
}
func (k templateKey) equal(o templateKey) bool {
if k.foreignKeys != o.foreignKeys || k.execMode != o.execMode ||
k.foreignKeysOff != o.foreignKeysOff || len(k.steps) != len(o.steps) {
return false
}
for i := range k.steps {
a, b := k.steps[i], o.steps[i]
if a.fn != b.fn || len(a.types) != len(b.types) {
return false
}
for j := range a.types {
if a.types[j] != b.types[j] {
return false
}
}
}
return true
}
type templateEntry struct {
key templateKey
once sync.Once
name string
err error
}
var (
templatesMu sync.Mutex
templates []*templateEntry
// templateOwner holds a session advisory lock on the admin database for
// as long as the process lives, keyed by the owner tag in the names of
// its templates. A cleanup that can take the lock knows the process that
// made a template is gone, see scripts/test-postgres.sh.
ownerOnce sync.Once
ownerTag string
ownerConn *sql.Conn
ownerErr error
)
// migratedTemplate returns the template database of the migration, made on
// first use
func migratedTemplate(t testing.TB, foreignKeys bool, execMode string, m Migration) (string, error) {
t.Helper()
key := newTemplateKey(foreignKeys, execMode, m)
tag := templateOwnerTag(t)
templatesMu.Lock()
var entry *templateEntry
for _, e := range templates {
if e.key.equal(key) {
entry = e
break
}
}
if entry == nil {
entry = &templateEntry{key: key}
templates = append(templates, entry)
// the counter is the position in the list, fixed under the lock
entry.name = fmt.Sprintf("pctpl_%s_%d", tag, len(templates))
}
templatesMu.Unlock()
entry.once.Do(func() {
entry.err = createTemplate(t, entry.name, foreignKeys, execMode, m)
})
return entry.name, entry.err
}
// templateOwnerTag returns the owner tag of the process, taking the owner
// lock on first use
func templateOwnerTag(t testing.TB) string {
t.Helper()
admin := adminConnection(t)
ownerOnce.Do(func() {
b := make([]byte, 8)
if _, err := rand.Read(b); err != nil {
ownerErr = err
return
}
conn, err := admin.Conn(context.Background())
if err != nil {
ownerErr = err
return
}
// the same number as ('x' || tag)::bit(64)::bigint in the cleanup
key := int64(binary.BigEndian.Uint64(b))
if _, err := conn.ExecContext(context.Background(), "SELECT pg_advisory_lock($1)", key); err != nil {
_ = conn.Close()
ownerErr = err
return
}
ownerTag = hex.EncodeToString(b)
ownerConn = conn
})
if ownerErr != nil {
t.Fatalf("testdb: template owner lock: %v", ownerErr)
}
return ownerTag
}
// createTemplate makes the template database name and runs the migration in
// it the way a test did on its own new database
func createTemplate(t testing.TB, name string, foreignKeys bool, execMode string, m Migration) error {
t.Helper()
if !templateNamePattern.MatchString(name) {
return fmt.Errorf("invalid template name %q", name)
}
admin := adminConnection(t)
if _, err := admin.Exec("CREATE DATABASE " + quoteIdentifier(name)); err != nil {
return fmt.Errorf("create: %w", err)
}
db, sqlDB, err := openPostgres(databaseDSN(t, name, foreignKeys), execMode, true)
if err == nil {
logStatements(db)
err = m.run(db)
// a copy needs the template without connections
if closeErr := sqlDB.Close(); err == nil {
err = closeErr
}
}
if err != nil {
_, _ = admin.Exec("DROP DATABASE IF EXISTS " + quoteIdentifier(name) + " WITH (FORCE)")
return err
}
return nil
}
// DropTemplates drops the template databases this process made and frees
// its owner lock. TestMain calls it after m.Run, when no test runs anymore.
func DropTemplates() {
templatesMu.Lock()
defer templatesMu.Unlock()
if adminDB == nil {
return
}
for _, e := range templates {
if !templateNamePattern.MatchString(e.name) {
continue
}
_, _ = adminDB.Exec("DROP DATABASE IF EXISTS " + quoteIdentifier(e.name) + " WITH (FORCE)")
}
templates = nil
if ownerConn != nil {
_, _ = ownerConn.ExecContext(context.Background(), "SELECT pg_advisory_unlock_all()")
_ = ownerConn.Close()
ownerConn = nil
}
}
// quoteIdentifier quotes a database name made by this package
func quoteIdentifier(name string) string {
return pgx.Identifier{name}.Sanitize()
}