Nothing said how a migration run ended. On failure, the CLI printed the PostgreSQL error with the failing SQL, but not which migration failed or whether anything was saved. After a failed run, the reporter asks PostgreSQL how the transaction ended (`pg_xact_status` on the captured transaction ID, plus the saved schema version). Every run logs one outcome line: committed, rolled back, committed before failure, unknown, lock timeout, dirty schema, or failed before start. Every failure line has an `error` field. The error names the failed migration and gives PostgreSQL's short message and SQLSTATE, without the SQL or detail text, which can contain row values. ``` [info] committed database migrations status=success count=2 from_version=1 final_version=3 transaction_status=committed total_duration_ms=0 [erro] migration failed, transaction rolled back, no changes saved status=failure count=1 version=3 name=step_3 final_version=1 sqlstate=23505 transaction_status=aborted total_duration_ms=0 failed_duration_ms=0 error="migration 3 (step_3): migration failed: duplicate key value violates unique constraint \"a_pkey\" (sqlstate=23505)" ``` Closes ENT-236 _Written with Claude Code and Coder Agents, reviewed and tested by @kirstaeff._
199 lines
5.2 KiB
Go
199 lines
5.2 KiB
Go
package migrations
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"io"
|
|
"strings"
|
|
|
|
"github.com/golang-migrate/migrate/v4/database"
|
|
"github.com/lib/pq"
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
const (
|
|
lockID = int64(1037453835920848937)
|
|
migrationsTableName = "schema_migrations"
|
|
)
|
|
|
|
// pgTxnDriver is a Postgres migration driver that runs all migrations in a
|
|
// single transaction. This is done to prevent users from being locked out of
|
|
// their deployment if a migration fails, since the schema will simply revert
|
|
// back to the previous version.
|
|
type pgTxnDriver struct {
|
|
ctx context.Context
|
|
db *sql.DB
|
|
tx *sql.Tx
|
|
|
|
reporter *reporter
|
|
// phase is phaseSetup while creating schema_migrations and phaseBatch
|
|
// otherwise. Only used for reporting.
|
|
phase string
|
|
}
|
|
|
|
func (*pgTxnDriver) Open(string) (database.Driver, error) {
|
|
panic("not implemented")
|
|
}
|
|
|
|
func (*pgTxnDriver) Close() error {
|
|
return nil
|
|
}
|
|
|
|
func (d *pgTxnDriver) Lock() error {
|
|
var err error
|
|
|
|
d.reporter.lockStarted()
|
|
d.tx, err = d.db.BeginTx(d.ctx, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Name the connection and identify the transaction before waiting, so the
|
|
// heartbeat can find the migration backend in pg_stat_activity.
|
|
if _, err := d.tx.ExecContext(d.ctx, `SELECT set_config('application_name', $1, true)`, d.reporter.appName); err != nil {
|
|
return xerrors.Errorf("set application name: %w", err)
|
|
}
|
|
var (
|
|
pid int
|
|
xid string
|
|
)
|
|
if err := d.tx.QueryRowContext(d.ctx, `SELECT pg_backend_pid(), pg_current_xact_id()::text`).Scan(&pid, &xid); err != nil {
|
|
return xerrors.Errorf("identify migration transaction: %w", err)
|
|
}
|
|
d.reporter.setBackend(pid, xid)
|
|
|
|
d.reporter.lockWaitStarted(d.phase)
|
|
_, err = d.tx.ExecContext(d.ctx, `SELECT pg_advisory_xact_lock($1)`, lockID)
|
|
if err != nil {
|
|
d.reporter.stopHeartbeat()
|
|
return xerrors.Errorf("exec select: %w", err)
|
|
}
|
|
d.reporter.lockAcquired(d.phase)
|
|
return nil
|
|
}
|
|
|
|
func (d *pgTxnDriver) Unlock() error {
|
|
// A step that failed before it was applied still has its heartbeat.
|
|
d.reporter.stopHeartbeat()
|
|
err := d.tx.Commit()
|
|
d.tx = nil
|
|
if err != nil {
|
|
return xerrors.Errorf("commit tx on unlock: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *pgTxnDriver) Run(migration io.Reader) error {
|
|
migr, err := io.ReadAll(migration)
|
|
if err != nil {
|
|
return xerrors.Errorf("read migration: %w", err)
|
|
}
|
|
err = d.runStatement(migr)
|
|
if err != nil {
|
|
return xerrors.Errorf("run statement: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *pgTxnDriver) runStatement(statement []byte) error {
|
|
ctx := context.Background()
|
|
query := string(statement)
|
|
if strings.TrimSpace(query) == "" {
|
|
return nil
|
|
}
|
|
if _, err := d.tx.ExecContext(ctx, query); err != nil {
|
|
d.reporter.statementFailed(err)
|
|
var pgErr *pq.Error
|
|
if xerrors.As(err, &pgErr) {
|
|
var line uint
|
|
message := fmt.Sprintf("migration failed: %s", pgErr.Message)
|
|
if pgErr.Detail != "" {
|
|
message += ", " + pgErr.Detail
|
|
}
|
|
return database.Error{OrigErr: err, Err: message, Query: statement, Line: line}
|
|
}
|
|
return database.Error{OrigErr: err, Err: "migration failed", Query: statement}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
//nolint:revive
|
|
func (d *pgTxnDriver) SetVersion(version int, dirty bool) error {
|
|
query := `TRUNCATE ` + migrationsTableName
|
|
if _, err := d.tx.Exec(query); err != nil {
|
|
return &database.Error{OrigErr: err, Query: []byte(query)}
|
|
}
|
|
|
|
if version >= 0 {
|
|
query = `INSERT INTO ` + migrationsTableName + ` (version, dirty) VALUES ($1, $2)`
|
|
if _, err := d.tx.Exec(query, version, dirty); err != nil {
|
|
return &database.Error{OrigErr: err, Query: []byte(query)}
|
|
}
|
|
}
|
|
|
|
if dirty {
|
|
d.reporter.stepStarted(version)
|
|
} else {
|
|
d.reporter.stepApplied(version)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *pgTxnDriver) Version() (version int, dirty bool, err error) {
|
|
// If the transaction is valid (we hold the exclusive lock), use the txn for
|
|
// the query.
|
|
var q interface {
|
|
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
|
} = d.tx
|
|
// If we don't hold the lock just use the database. This only happens in the
|
|
// `Stepper` function and is only used in tests.
|
|
if d.tx == nil {
|
|
q = d.db
|
|
}
|
|
|
|
query := `SELECT version, dirty FROM ` + migrationsTableName + ` LIMIT 1`
|
|
err = q.QueryRowContext(context.Background(), query).Scan(&version, &dirty)
|
|
switch {
|
|
case err == sql.ErrNoRows:
|
|
version, dirty = database.NilVersion, false
|
|
|
|
case err != nil:
|
|
var pgErr *pq.Error
|
|
if !xerrors.As(err, &pgErr) || pgErr.Code.Name() != "undefined_table" {
|
|
return 0, false, &database.Error{OrigErr: err, Query: []byte(query)}
|
|
}
|
|
version, dirty = database.NilVersion, false
|
|
}
|
|
|
|
if d.tx != nil && !dirty {
|
|
d.reporter.versionRead(version)
|
|
}
|
|
return version, dirty, nil
|
|
}
|
|
|
|
func (*pgTxnDriver) Drop() error {
|
|
panic("not implemented")
|
|
}
|
|
|
|
func (d *pgTxnDriver) ensureVersionTable() error {
|
|
d.phase = phaseSetup
|
|
defer func() { d.phase = phaseBatch }()
|
|
|
|
err := d.Lock()
|
|
if err != nil {
|
|
return xerrors.Errorf("acquire migration lock: %w", err)
|
|
}
|
|
|
|
const query = `CREATE TABLE IF NOT EXISTS ` + migrationsTableName + ` (version bigint not null primary key, dirty boolean not null)`
|
|
if _, err := d.tx.ExecContext(context.Background(), query); err != nil {
|
|
return &database.Error{OrigErr: err, Query: []byte(query)}
|
|
}
|
|
|
|
err = d.Unlock()
|
|
if err != nil {
|
|
return xerrors.Errorf("release migration lock: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|