diff --git a/docs/guides/updating.mdx b/docs/guides/updating.mdx index 1b7ad661b..9f650c778 100644 --- a/docs/guides/updating.mdx +++ b/docs/guides/updating.mdx @@ -169,6 +169,16 @@ transform storage instead — when budgets and rate limits gained scopes, their tables were rebuilt and the old ones dropped. Both are safe going forward, which is what makes the reverse direction worth care. +On PostgreSQL, a start that finds the schema up to date changes nothing and +takes no table locks, so starting or restarting a replica does not stall the +others. A migration that does add a table, column, or index waits for its table +half a second at a time, for about a minute per statement. If a long-running +statement holds the table for that whole minute, a table or column migration +fails the start instead of queueing traffic behind it. A request log index +that cannot get its table is skipped with a logged warning, along with the +request log indexes after it, and the start continues; the next start creates +them. + After v0.2.5 the request log's storage was renamed from `audit_logs` to `request_logs`: the tables on SQLite and PostgreSQL, the collection on MongoDB. The rename happens in place and copies no rows; on SQLite and @@ -235,6 +245,7 @@ docker run --rm -v gomodel_data:/data -v "$PWD":/backup alpine \ | --- | --- | | Dashboard is empty after the update: no keys, no usage, no logs | The database was not on a volume, or `SQLITE_PATH` resolved somewhere else. Compare the `storage configured` path before and after. | | Gateway will not start after the update | Read the first error line. Configuration that was previously ignored can become validated; the release notes list breaking changes. | +| Start fails with `schema change could not lock its table` | A long-running statement or index build held the table for the minute the migration waited. Start again once it has finished. Columns added earlier in the same start stay in place and are skipped next time. | | The version did not change | The old container is still running (`docker ps`), or a second `gomodel` binary earlier in `PATH` is being launched. | Still stuck? Ask on [Discord](https://discord.gg/gaEB9BQSPH) or open a diff --git a/internal/requestlog/store_sql.go b/internal/requestlog/store_sql.go index 4500c3712..681d3cafe 100644 --- a/internal/requestlog/store_sql.go +++ b/internal/requestlog/store_sql.go @@ -2,6 +2,7 @@ package requestlog import ( "context" + "errors" "fmt" "log/slog" "strings" @@ -241,8 +242,17 @@ func ensureSQLSchema(ctx context.Context, db sqlx.DB) error { if db.Dialect() != sqlx.PostgreSQL { indexes = append(indexes, modelIndexStatements(db.Dialect())...) } + // One Schema call per statement keeps them best-effort, and on PostgreSQL + // skips the indexes that already exist instead of queueing each for a + // lock on request_logs. A statement that gave up on that lock ends the + // loop: each of the rest would wait it out again, a minute at a time. for _, statement := range indexes { - if _, err := db.Exec(ctx, statement); err != nil { + err := db.Schema(ctx, statement) + if errors.Is(err, sqlx.ErrTableLocked) { + slog.Warn("request log table is locked; the remaining indexes are left for the next start", "error", err) + break + } + if err != nil { slog.Warn("failed to create index", "error", err) } } diff --git a/internal/storage/sqlx/export_test.go b/internal/storage/sqlx/export_test.go new file mode 100644 index 000000000..f594c5730 --- /dev/null +++ b/internal/storage/sqlx/export_test.go @@ -0,0 +1,13 @@ +package sqlx + +import "time" + +// SetLockWait shortens how long db's schema changes wait for a table lock, so +// a test of a blocked change does not wait out the production bounds. +func SetLockWait(db DB, timeout, pause time.Duration, attempts int) { + db.(*postgresDB).lockWait = lockWait{timeout: timeout, pause: pause, attempts: attempts} +} + +// SchemaLockKey is the advisory lock a schema change holds, for a test that +// plays the replica holding it. +const SchemaLockKey = postgresSchemaLockKey diff --git a/internal/storage/sqlx/postgres.go b/internal/storage/sqlx/postgres.go index 0b39719f9..8e18559a3 100644 --- a/internal/storage/sqlx/postgres.go +++ b/internal/storage/sqlx/postgres.go @@ -14,7 +14,8 @@ import ( // Queries arrive with `?` placeholders and are rebound to $1, $2, ... on the // way through. type postgresDB struct { - session pgSession + session pgSession + lockWait lockWait } // pgSession is the part of *pgxpool.Pool and *pgxpool.Conn postgresDB uses. @@ -28,7 +29,7 @@ func NewPostgreSQL(pool *pgxpool.Pool) (DB, error) { if pool == nil { return nil, fmt.Errorf("connection pool is required") } - return &postgresDB{session: pool}, nil + return &postgresDB{session: pool, lockWait: defaultLockWait}, nil } // NewPostgreSQLConn wraps one pooled connection, for store code that must @@ -39,7 +40,7 @@ func NewPostgreSQLConn(conn *pgxpool.Conn) (DB, error) { if conn == nil { return nil, fmt.Errorf("connection is required") } - return &postgresDB{session: conn}, nil + return &postgresDB{session: conn, lockWait: defaultLockWait}, nil } func (p *postgresDB) Dialect() Dialect { return PostgreSQL } @@ -68,7 +69,8 @@ func (p *postgresDB) QueryRow(ctx context.Context, query string, args ...any) Ro return pgQueryRow(ctx, p.session, query, args...) } -// postgresSchemaLockKey is the advisory lock every Schema call takes. One key +// postgresSchemaLockKey is the advisory lock every schema change takes; a +// Schema call that finds nothing to change takes none. One key // for the whole gateway is deliberate: each store's DDL is short, and the // alternative (a key per store) buys nothing while making the lock easy to // forget in a new store. @@ -82,12 +84,25 @@ const postgresSchemaLockKey int64 = 0x676f6d6f64656c // fresh database hit exactly that. The transaction-scoped lock serializes // them: the second replica waits, then finds every table present. // PostgreSQL DDL is transactional, so a failure leaves nothing half-applied. +// +// Indexes that already exist are skipped, and the rest wait only briefly for +// a table lock; see postgres_schema.go. func (p *postgresDB) Schema(ctx context.Context, statements ...string) error { - return p.InTx(ctx, func(q Querier) error { - if _, err := q.Exec(ctx, "SELECT pg_advisory_xact_lock(?)", postgresSchemaLockKey); err != nil { - return fmt.Errorf("acquire schema lock: %w", err) + // Checked without the lock first, so that a start against an up-to-date + // schema takes none. + pending, err := pendingSchema(ctx, p, statements) + if err != nil || len(pending) == 0 { + return err + } + return p.changeSchema(ctx, func(q Querier) error { + // Checked again under the lock, on every attempt: a replica that + // queued here behind another one finds the index built, and must not + // queue for the table to create nothing. + pending, err := pendingSchema(ctx, q, statements) + if err != nil { + return err } - return execSchema(ctx, q, PostgreSQL, statements) + return execSchema(ctx, q, PostgreSQL, pending) }) } diff --git a/internal/storage/sqlx/postgres_schema.go b/internal/storage/sqlx/postgres_schema.go new file mode 100644 index 000000000..9a09e4d6a --- /dev/null +++ b/internal/storage/sqlx/postgres_schema.go @@ -0,0 +1,140 @@ +package sqlx + +import ( + "context" + "errors" + "fmt" + "log/slog" + "regexp" + "slices" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" +) + +// Store constructors re-apply their whole schema on every start, and several +// replicas start against one database. AddColumns already leaves out the +// columns that exist. A `CREATE INDEX IF NOT EXISTS` that changes nothing has +// the same problem: it still queues for a SHARE lock on its table first, which +// waits for every write in progress, and every later write on the table then +// queues behind it. So the index statements that would change nothing are not +// sent at all, and the schema changes that are needed stop waiting for their +// lock after lockWait rather than hold the table's traffic up behind them. + +// lockWait bounds how long a schema change waits for a table lock. +type lockWait struct { + // timeout is how long one attempt waits. It stays below PostgreSQL's + // default deadlock_timeout of one second: a schema change and a + // CREATE INDEX CONCURRENTLY wait on each other, and the deadlock check + // would cancel the build, which loses minutes of work, rather than the + // schema change, which loses nothing. + timeout time.Duration + // pause lets the statements that queued behind a failed attempt run + // before the next one. + pause time.Duration + attempts int +} + +var defaultLockWait = lockWait{timeout: 500 * time.Millisecond, pause: time.Second, attempts: 40} + +// ErrTableLocked reports a schema change that gave up waiting for its table +// lock: a long-running statement or index build held the table throughout. +var ErrTableLocked = errors.New("schema change could not lock its table") + +// lockNotAvailable is the SQLSTATE of a statement cancelled by lock_timeout. +const lockNotAvailable = "55P03" + +const pgIdentifier = `(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)` + +var createIndexPattern = regexp.MustCompile(`(?is)^\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS\s+(` + + pgIdentifier + `)\s+ON\s+(` + pgIdentifier + `(?:\.` + pgIdentifier + `)?)\s*(?:\(|USING\b)`) + +// changeSchema runs fn in a transaction that holds the schema advisory lock +// and gives up waiting for a table lock after lockWait.timeout, retrying the +// whole transaction when it does. +func (p *postgresDB) changeSchema(ctx context.Context, fn func(Querier) error) error { + var err error + for attempt := 1; ; attempt++ { + err = p.InTx(ctx, func(q Querier) error { + if _, err := q.Exec(ctx, "SELECT pg_advisory_xact_lock(?)", postgresSchemaLockKey); err != nil { + return fmt.Errorf("acquire schema lock: %w", err) + } + // Set only once the advisory lock is held, so that it bounds + // the wait for a table and not the wait above: replicas queueing + // there to apply their schema is expected. + timeout := fmt.Sprintf("SET LOCAL lock_timeout = %d", p.lockWait.timeout.Milliseconds()) + if _, err := q.Exec(ctx, timeout); err != nil { + return fmt.Errorf("set lock timeout: %w", err) + } + return fn(q) + }) + if !isLockTimeout(err) || attempt >= p.lockWait.attempts { + break + } + if attempt == 1 { + slog.Warn("schema change is waiting for a table lock; retrying", "error", err) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(p.lockWait.pause): + } + } + if isLockTimeout(err) { + return fmt.Errorf("%w in %d attempts; a long-running statement or index build holds it: %w", + ErrTableLocked, p.lockWait.attempts, err) + } + return err +} + +func isLockTimeout(err error) bool { + pgErr, ok := errors.AsType[*pgconn.PgError](err) + return ok && pgErr.Code == lockNotAvailable +} + +// pendingSchema drops the CREATE INDEX IF NOT EXISTS statements whose index +// already exists. A statement it cannot parse is kept, so it runs as written, +// and so is an index an earlier statement of the batch names: that statement +// may drop it, and the catalog is read before any of them runs. +func pendingSchema(ctx context.Context, q Querier, statements []string) ([]string, error) { + pending := make([]string, 0, len(statements)) + for i, statement := range statements { + match := createIndexPattern.FindStringSubmatch(statement) + if match == nil || namedEarlier(statements[:i], identifierName(match[1])) { + pending = append(pending, statement) + continue + } + // IF NOT EXISTS looks for any relation of that name in the table's + // schema, so this does too. + var exists bool + err := q.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM pg_class i + JOIN pg_class t ON t.relnamespace = i.relnamespace + WHERE t.oid = to_regclass(?) AND i.relname = ? + )`, match[2], identifierName(match[1])).Scan(&exists) + if err != nil { + return nil, fmt.Errorf("look up index %s: %w", match[1], err) + } + if !exists { + pending = append(pending, statement) + } + } + return pending, nil +} + +func namedEarlier(statements []string, name string) bool { + return slices.ContainsFunc(statements, func(statement string) bool { + return strings.Contains(strings.ToLower(statement), strings.ToLower(name)) + }) +} + +// identifierName is the name PostgreSQL stores for an identifier as written +// in SQL: a quoted one verbatim, an unquoted one folded to lower case. +func identifierName(identifier string) string { + if strings.HasPrefix(identifier, `"`) { + return strings.ReplaceAll(identifier[1:len(identifier)-1], `""`, `"`) + } + return strings.ToLower(identifier) +} diff --git a/internal/storage/sqlx/postgres_schema_internal_test.go b/internal/storage/sqlx/postgres_schema_internal_test.go new file mode 100644 index 000000000..487a4c9a7 --- /dev/null +++ b/internal/storage/sqlx/postgres_schema_internal_test.go @@ -0,0 +1,50 @@ +package sqlx + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCreateIndexPattern(t *testing.T) { + tests := []struct { + name string + statement string + index string + table string + }{ + {name: "plain", statement: `CREATE INDEX IF NOT EXISTS idx_usage_model ON usage(model)`, index: "idx_usage_model", table: "usage"}, + {name: "unique across lines", statement: "\n\tCREATE UNIQUE INDEX IF NOT EXISTS idx_scope\n\t\tON workflow_versions (scope_key) WHERE active", index: "idx_scope", table: "workflow_versions"}, + {name: "access method", statement: `CREATE INDEX IF NOT EXISTS idx_gin ON usage USING GIN (raw_data)`, index: "idx_gin", table: "usage"}, + {name: "quoted", statement: `CREATE INDEX IF NOT EXISTS "Cache_idx" ON "my ""cache""" (expires_at)`, index: `"Cache_idx"`, table: `"my ""cache"""`}, + {name: "schema qualified", statement: `create index if not exists idx_a on public.items(a)`, index: "idx_a", table: "public.items"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + match := createIndexPattern.FindStringSubmatch(tt.statement) + require.NotNil(t, match) + assert.Equal(t, tt.index, match[1]) + assert.Equal(t, tt.table, match[2]) + }) + } + + // Without IF NOT EXISTS the statement must run: a skipped duplicate + // would hide the error the caller asked for. + for _, statement := range []string{ + `CREATE INDEX idx_usage_model ON usage(model)`, + `CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_usage_model ON usage(model)`, + `DROP INDEX IF EXISTS idx_usage_model`, + `CREATE TABLE IF NOT EXISTS usage (id TEXT)`, + // Names tenant.events, not the table tenant. + `CREATE INDEX IF NOT EXISTS uq_events ON tenant . events(id)`, + } { + assert.Nil(t, createIndexPattern.FindStringSubmatch(statement), statement) + } +} + +func TestIdentifierName(t *testing.T) { + assert.Equal(t, "idx_usage_model", identifierName("IDX_Usage_Model")) + assert.Equal(t, "Cache_idx", identifierName(`"Cache_idx"`)) + assert.Equal(t, `my "cache"`, identifierName(`"my ""cache"""`)) +} diff --git a/internal/storage/sqlx/postgres_schema_test.go b/internal/storage/sqlx/postgres_schema_test.go new file mode 100644 index 000000000..e98d2e436 --- /dev/null +++ b/internal/storage/sqlx/postgres_schema_test.go @@ -0,0 +1,211 @@ +package sqlx_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/enterpilot/gomodel/internal/storage/sqlx" + "github.com/enterpilot/gomodel/internal/storage/sqlx/sqlxtest" +) + +const lockedTable = `CREATE TABLE IF NOT EXISTS locked (id TEXT PRIMARY KEY, model TEXT)` + +// newLockedTable returns a PostgreSQL DB whose `locked` table has a row +// inserted by a transaction that stays open until release is called: the +// state of a table under a long-running write on another replica. +func newLockedTable(t *testing.T) (db sqlx.DB, release func()) { + t.Helper() + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return nil, nil + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx := context.Background() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN note TEXT`)) + + tx, err := pool.Begin(ctx) + require.NoError(t, err) + _, err = tx.Exec(ctx, `INSERT INTO locked (id) VALUES ('held')`) + require.NoError(t, err) + var once sync.Once + release = func() { + once.Do(func() { assert.NoError(t, tx.Rollback(ctx)) }) + } + t.Cleanup(release) + return db, release +} + +// A replica starting against an up-to-date schema must not queue for a table +// lock: the statements waiting behind it would stall every other replica. +func TestAppliedSchemaDoesNotWaitForTableLock(t *testing.T) { + db, _ := newLockedTable(t) + if db == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + started := time.Now() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + require.NoError(t, sqlx.AddColumns(ctx, db, + `ALTER TABLE locked ADD COLUMN note TEXT`, + `ALTER TABLE locked ADD COLUMN IF NOT EXISTS model TEXT`, + )) + assert.Less(t, time.Since(started), 2*time.Second) +} + +func TestSchemaChangeGivesUpOnAHeldTableLock(t *testing.T) { + db, release := newLockedTable(t) + if db == nil { + return + } + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 3) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + err := sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`) + require.ErrorContains(t, err, "could not lock its table") + require.ErrorIs(t, err, sqlx.ErrTableLocked) + err = db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`) + require.ErrorContains(t, err, "could not lock its table") + require.ErrorIs(t, err, sqlx.ErrTableLocked) + + // The failed change left nothing behind: read from the catalog, which + // needs no lock on the table, while it is still held. + columns, err := sqlx.Columns(ctx, db, "locked") + require.NoError(t, err) + require.NotContains(t, columns, "enabled") + + // Both go through once the table is free. + release() + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`)) + require.NoError(t, db.Schema(ctx, `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`)) + _, err = db.Exec(ctx, `INSERT INTO locked (id, enabled, note) VALUES (?, ?, ?)`, "a", true, "n") + require.NoError(t, err) +} + +func TestSchemaChangeRetriesUntilTheTableLockIsFree(t *testing.T) { + db, release := newLockedTable(t) + if db == nil { + return + } + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 200) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + time.AfterFunc(300*time.Millisecond, release) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN enabled `+sqlx.TypeBool+` NOT NULL DEFAULT FALSE`)) + _, err := db.Exec(ctx, `INSERT INTO locked (id, enabled) VALUES (?, ?)`, "a", true) + require.NoError(t, err) +} + +// Two replicas start during a migration. One applies it while the other waits +// its turn; a long write then takes the table. The second replica must see +// that there is nothing left to do rather than queue for the table, stall the +// writes behind it and fail its start on a change that is already applied. +func TestSchemaChangeRechecksAfterWaitingForAnotherReplica(t *testing.T) { + tests := []struct { + name string + statement string + apply func(ctx context.Context, db sqlx.DB, statement string) error + }{ + { + name: "index", + statement: `CREATE INDEX IF NOT EXISTS idx_locked_note ON locked(note)`, + apply: func(ctx context.Context, db sqlx.DB, statement string) error { return db.Schema(ctx, statement) }, + }, + { + name: "column", + statement: `ALTER TABLE locked ADD COLUMN IF NOT EXISTS enabled BOOLEAN NOT NULL DEFAULT FALSE`, + apply: func(ctx context.Context, db sqlx.DB, statement string) error { + return sqlx.AddColumns(ctx, db, statement) + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + require.NoError(t, db.Schema(ctx, lockedTable)) + require.NoError(t, sqlx.AddColumns(ctx, db, `ALTER TABLE locked ADD COLUMN note TEXT`)) + sqlx.SetLockWait(db, 50*time.Millisecond, 10*time.Millisecond, 3) + waiting := func(query string, args ...any) func() bool { + return func() bool { + var count int + err := pool.QueryRow(ctx, query, args...).Scan(&count) + return err == nil && count > 0 + } + } + + // The other replica holds the schema lock, and this one queues. + other, err := pool.Begin(ctx) + require.NoError(t, err) + defer func() { _ = other.Rollback(context.Background()) }() + _, err = other.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, sqlx.SchemaLockKey) + require.NoError(t, err) + applied := make(chan error, 1) + go func() { applied <- tt.apply(ctx, db, tt.statement) }() + require.Eventually(t, waiting( + `SELECT count(*) FROM pg_locks + WHERE locktype = 'advisory' AND NOT granted + AND database = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND classid = ($1::bigint >> 32) AND objid = ($1::bigint & 4294967295) AND objsubid = 1`, + sqlx.SchemaLockKey), 10*time.Second, 10*time.Millisecond, "this replica waits for the schema lock") + + // The other replica applies the change. A write queues for the + // table behind it, and holds the table from the moment it commits. + _, err = other.Exec(ctx, tt.statement) + require.NoError(t, err) + writer, err := pool.Begin(ctx) + require.NoError(t, err) + defer func() { _ = writer.Rollback(context.Background()) }() + wrote := make(chan error, 1) + go func() { + _, err := writer.Exec(ctx, `INSERT INTO locked (id) VALUES ('held')`) + wrote <- err + }() + require.Eventually(t, waiting( + `SELECT count(*) FROM pg_locks WHERE relation = 'locked'::regclass AND NOT granted`), + 10*time.Second, 10*time.Millisecond, "the write waits for the table") + require.NoError(t, other.Commit(ctx)) + require.NoError(t, <-wrote) + + require.NoError(t, <-applied, "a change another replica applied meanwhile is not attempted again") + }) + } +} + +// A batch that drops an index and creates it again must create it: the +// catalog is read before the drop runs, so the index still looks present. +func TestSchemaRecreatesAnIndexDroppedEarlierInTheBatch(t *testing.T) { + pool := sqlxtest.NewPostgresPool(t) + if pool == nil { + return + } + db, err := sqlx.NewPostgreSQL(pool) + require.NoError(t, err) + ctx := context.Background() + require.NoError(t, db.Schema(ctx, lockedTable, `CREATE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + + require.NoError(t, db.Schema(ctx, + `DROP INDEX IF EXISTS idx_locked_model`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_locked_model ON locked(model)`)) + + var unique bool + require.NoError(t, db.QueryRow(ctx, + `SELECT indisunique FROM pg_index WHERE indexrelid = to_regclass('idx_locked_model')`).Scan(&unique)) + assert.True(t, unique) +} diff --git a/internal/storage/sqlx/schema.go b/internal/storage/sqlx/schema.go index fe3979c16..b2eb99d12 100644 --- a/internal/storage/sqlx/schema.go +++ b/internal/storage/sqlx/schema.go @@ -3,6 +3,7 @@ package sqlx import ( "context" "fmt" + "slices" "strings" ) @@ -37,13 +38,13 @@ func execSchema(ctx context.Context, q Querier, dialect Dialect, statements []st // spelling (see addColumnStatement), because replicas starting together can // all see a column missing and race to add it. func AddColumns(ctx context.Context, db DB, statements ...string) error { - pending, err := missingColumnStatements(ctx, db, statements) + dialect := db.Dialect() + pending, err := missingColumnStatements(ctx, db, dialect, statements) if err != nil { return err } - dialect := db.Dialect() for _, statement := range pending { - _, err := db.Exec(ctx, dialect.addColumnStatement(statement)) + err := execAddColumn(ctx, db, dialect.addColumnStatement(statement)) if err != nil && !IsDuplicateColumnError(err) { return fmt.Errorf("apply migration %q: %w", statement, err) } @@ -51,10 +52,32 @@ func AddColumns(ctx context.Context, db DB, statements ...string) error { return nil } +// execAddColumn runs one column migration. On PostgreSQL it bounds the wait +// for the table lock (see postgresDB.changeSchema), one transaction per +// statement so a tolerated duplicate-column error ends only its own. +func execAddColumn(ctx context.Context, db DB, statement string) error { + p, ok := db.(*postgresDB) + if !ok { + _, err := db.Exec(ctx, statement) + return err + } + return p.changeSchema(ctx, func(q Querier) error { + // Checked again under the lock, on every attempt: a replica that + // queued here behind another one finds the column added, and must + // not queue for the table to add nothing. + pending, err := missingColumnStatements(ctx, q, PostgreSQL, []string{statement}) + if err != nil || len(pending) == 0 { + return err + } + _, err = q.Exec(ctx, statement) + return err + }) +} + // missingColumnStatements drops the statements whose column already exists, // reading each table's columns at most once. -func missingColumnStatements(ctx context.Context, db DB, statements []string) ([]string, error) { - existing := make(map[string]map[string]bool) +func missingColumnStatements(ctx context.Context, q Querier, dialect Dialect, statements []string) ([]string, error) { + existing := make(map[string][]string) pending := make([]string, 0, len(statements)) for _, statement := range statements { table, column, ok := parseAddColumn(statement) @@ -65,12 +88,12 @@ func missingColumnStatements(ctx context.Context, db DB, statements []string) ([ columns, seen := existing[table] if !seen { var err error - if columns, err = Columns(ctx, db, table); err != nil { + if columns, err = ColumnNames(ctx, q, dialect, table); err != nil { return nil, err } existing[table] = columns } - if !columns[column] { + if !slices.Contains(columns, column) { pending = append(pending, statement) } }