Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/plan-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ consumer rendering either into a shared surface must clamp and escape them.
| `publications` | array of strings | a `CREATE TABLE` refused with cause `published-without-key` | The publications, sorted by name, that publish the updates or deletes of every new table in the target schema, `FOR ALL TABLES` or `FOR TABLES IN SCHEMA`, and so would publish this table with no key to decode them by. They are the target's own, so a database without them plans the same file. The fingerprint does not cover it. |
| `uniqueness_kept_by` | string | `diff` source, a `drop-index` of a unique index or a `drop-constraint` of a unique constraint | Another unique index or unique or primary key of the desired table that rejects every duplicate the dropped object rejects, and is in place when the drop runs: the live table already has it as the file declares it, or the plan builds it before the drop. Its key is plain columns that the dropped key also compares, with the same collation and operator class; it covers at least the rows the dropped object covers; it treats NULLs as equal wherever the dropped object does; and it is checked no later: it is deferrable only where the dropped key is, and `INITIALLY DEFERRED` only where the dropped key is. So no row written after the drop repeats the values the dropped object kept unique. A key on a column the plan retypes is never named, since the new type decides what counts as equal, and neither is a key pg-sprite cannot read, such as a temporal `WITHOUT OVERLAPS` key; the field is then absent. The drop still removes an object, so it stays destructive. The fingerprint covers the statements that build the object it names, not this field. |
| `lookups_kept_by` | string | `diff` source, a `drop-index`, or a `drop-constraint` of a unique constraint | Another index or unique or primary key of the desired table that answers every lookup the dropped index, or the dropped constraint's index, answers, and is in place when the drop runs: the live table already has it as the file declares it, or the plan builds it before the drop, and the drop waits for that build. Both are btree indexes; the dropped key is plain columns that lead the other key in the same order, each with the same collation, operator class, and ordering; the other covers at least the rows the dropped index covers; and the dropped index carries no `INCLUDE` columns. So a query planned on the dropped index has an index to use the moment it goes. A unique index or constraint the file relaxes to a plain index waits for that build too, and its `uniqueness_kept_by` stays absent, since the plain index keeps no rule. An index on a column the plan retypes is never named, and the field is then absent. The drop still removes an index, so it stays destructive. The fingerprint covers the statements that build the object it names, not this field. |
| `exec_sql` | array | native route; a refused `drop-index` of a partitioned table's index | The ordered SQL the native backend would run — the safer sequence when the planner constructed one, or the statement as written for a table that does not exist yet (the greenfield create path runs plain builds; see Fingerprint). A `DETACH PARTITION` of a partition an earlier concurrent detach left detach-pending carries the `ALTER TABLE ... DETACH PARTITION ... FINALIZE` that finishes it in place of the concurrent detach, read from the catalog when the plan is made; the run reads the partition again and decides from that reading. That `FINALIZE` runs in autocommit, as the statement's `execution` says, and is not a statement to hand back to pg-sprite: `migrate` refuses it as submitted, and `executor.RunSequence` would run it as an ordinary brief step inside a transaction rather than as the detach. A consumer that hands the work back submits the original `DETACH PARTITION`, which finishes the pending detach. A refused statement carries it only as the plain `DROP INDEX` of a partitioned table's index, with `execution` `blocking-index-drop`: the one form a run that accepts the blocking lock executes. Absent for non-native routes: an `execute` statement whose `backend` is `copy-and-swap` runs no literal SQL a consumer could replay — the shadow-table change is one engine step — so a consumer that runs statements itself must hand such a statement back to pg-sprite rather than treat the absence as "nothing to run". |
| `exec_sql` | array | native route; a refused `drop-index` of a partitioned table's index | The ordered SQL the native backend would run — the safer sequence when the planner constructed one, or the statement as written for a table that does not exist yet (the greenfield create path runs plain builds; see Fingerprint). A `DETACH PARTITION` of a partition an earlier concurrent detach left detach-pending carries the `ALTER TABLE ... DETACH PARTITION ... FINALIZE` that finishes it in place of the concurrent detach, read from the catalog when the plan is made; the run reads the partition again and decides from that reading. That `FINALIZE` runs in autocommit, as the statement's `execution` says, and is not a statement to hand back to pg-sprite: `migrate` refuses it as submitted, and `executor.RunSequence` refuses a sequence that carries it with `ErrUnsupportedSequenceStep` before any of its steps runs. A consumer that hands the work back submits the original `DETACH PARTITION`, which finishes the pending detach. A refused statement carries it only as the plain `DROP INDEX` of a partitioned table's index, with `execution` `blocking-index-drop`: the one form a run that accepts the blocking lock executes. Absent for non-native routes: an `execute` statement whose `backend` is `copy-and-swap` runs no literal SQL a consumer could replay — the shadow-table change is one engine step — so a consumer that runs statements itself must hand such a statement back to pg-sprite rather than treat the absence as "nothing to run". |
| `execution` | string | with `exec_sql` | The typed execution contract for `exec_sql` (see Execution contracts). A consumer that runs the statements itself branches on this — it is what says the steps must not be wrapped in a transaction block. Present exactly when `exec_sql` is. |
| `guidance` | string | `rewrite-required` only | The typed manual path for a rewrite-required refusal, drawn from the [suggest report's Guidance vocabulary](suggest-report.md#guidance-guidance). The engine will not run the statement; this names what to do instead (`split-statement`, `add-column-then-constraint`, …). Present exactly when `disposition` is `rewrite-required`. Explanatory: excluded from the fingerprint. |
| `resumes` | object | `alter` source, the statement of a stopped copy-and-swap run | The copy-and-swap run stopped on the table whose recorded statement this is, which the run resumes rather than route the statement against the table's current shape: `phase`, the phase the run stopped in (`copying`, `catching_up`, `reconciling`, `verifying`, or `cutover`); `mode`, how the run handled the table's writes, which a resume must match (`offline`, blocking them under `--block-writes`, or `live`, streaming them through a replication slot), absent when the row records neither; and `last_saved`, when the run last saved its row (RFC 3339), which says how long ago it stopped. The statement then carries the `copy-and-swap` route and backend and `execute`, with no `exec_sql`, `execution`, or refusal fields, whatever the planner's `decisions` say of the current shape — a run stopped after its swap committed has already put the statement's shape live. The row is read without the table's lock; the run reads it again under the lock and carries on from the phase it finds then. Absent under `--restart`, which discards the stopped run and starts over; the plan then shows the statement against the table's current shape, and is not a forecast for a run stopped in `cutover` whose swap committed, which the run refuses with `restart-swap-committed`. `migrate.ResumesStoppedRun` is the library's read of it, and `plan.ResumeStoppedRun` marks a report with it. Explanatory: excluded from the fingerprint, which covers the route and backend it sets. |
Expand Down
28 changes: 28 additions & 0 deletions pkg/executor/detach_partition_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,34 @@ func detachFixture(t *testing.T) (*pgxpool.Pool, string) {
return pool, schema
}

// A DETACH PARTITION ... FINALIZE, the step a dry run plans for a partition
// left detach-pending, is not a step RunSequence runs: it would run as a
// brief step rather than as the detach. Admission refuses the sequence
// before its first step, so the column the step before it adds is never
// added and the partition stays attached.
func TestRunSequenceRefusesADetachFinalizeBeforeAnythingRuns(t *testing.T) {
pool, schema := detachFixture(t)
pt := mustPreflight(t, pool, schema, "events")

rep, err := executor.RunSequence(t.Context(), pool, pt, []string{
fmt.Sprintf("ALTER TABLE %s.events ADD COLUMN note text", schema),
fmt.Sprintf("ALTER TABLE %[1]s.events DETACH PARTITION %[1]s.events_2024 FINALIZE", schema),
}, runBudget, executor.RetryPolicy{MaxAttempts: 1})
require.ErrorIs(t, err, executor.ErrUnsupportedSequenceStep)
assert.Empty(t, rep.Steps, "no step ran")

var noteAdded, attached bool
require.NoError(t, pool.QueryRow(t.Context(), `
SELECT EXISTS (SELECT 1 FROM pg_attribute
WHERE attrelid = (quote_ident($1) || '.events')::regclass
AND attname = 'note'),
EXISTS (SELECT 1 FROM pg_inherits
WHERE inhrelid = (quote_ident($1) || '.events_2024')::regclass
AND NOT inhdetachpending)`, schema).Scan(&noteAdded, &attached))
assert.False(t, noteAdded, "the step before the FINALIZE did not run")
assert.True(t, attached, "the partition is still attached")
}

// A table that was never a partition of events but carries the name the
// detach names and exactly the columns of events looks, in the catalog,
// like a partition an earlier run detached: PostgreSQL keeps no record of a
Expand Down
10 changes: 9 additions & 1 deletion pkg/executor/sequence.go
Original file line number Diff line number Diff line change
Expand Up @@ -606,8 +606,16 @@ func admitStepShape(sql string) (sequenceStep, error) {
// class: in a multi-operation ALTER the validation shares its transaction
// with the other subcommands, so the whole statement must prove itself
// under the brief budgets instead. A lone DETACH PARTITION ... CONCURRENTLY
// gets the detach class; any other CONCURRENTLY subcommand is refused.
// gets the detach class; any other CONCURRENTLY subcommand is refused. A
// DETACH PARTITION ... FINALIZE is refused too: it finishes a pending detach
// only as the detach step runs it, after reading the partition's state, so
// a step that replays it is pointed at the concurrent detach that finishes
// it rather than run as a brief step.
func admitAlterTableStep(st statement.Statement, sql string) (sequenceStep, error) {
if st.FinalizesDetach() {
return sequenceStep{}, fmt.Errorf("DETACH PARTITION ... FINALIZE: run the DETACH PARTITION ... CONCURRENTLY "+
"that started the detach again, which finishes it: %w", ErrUnsupportedSequenceStep)
}
detaches, err := isConcurrentDetach(st)
if err != nil {
return sequenceStep{}, err
Expand Down
31 changes: 31 additions & 0 deletions pkg/executor/sequence_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,37 @@ func TestAdmitSequenceNamesTheOffendingStep(t *testing.T) {
assert.False(t, errors.As(err, &stepErr), "an admission refusal is not a step failure: nothing executed")
}

// A DETACH PARTITION ... FINALIZE, the step a dry run plans for a partition
// left detach-pending, finishes the detach only as the detach step runs it,
// after reading the partition's state. Replayed as a step it would run as a
// brief step instead, so admission refuses the whole sequence before its
// first step runs, while the concurrent detach that finishes the same
// pending detach keeps its detach class beside an ordinary brief step.
func TestAdmitSequenceRefusesAReplayedDetachFinalize(t *testing.T) {
admitted, err := admitSequence("s", "t", []string{
`ALTER TABLE s.t ADD COLUMN note text`,
`ALTER TABLE s.t DETACH PARTITION s.p FINALIZE`,
})
require.ErrorIs(t, err, ErrUnsupportedSequenceStep)
assert.ErrorContains(t, err, "DETACH PARTITION ... FINALIZE")
assert.ErrorContains(t, err, "sequence step 2 of 2")
assert.Nil(t, admitted, "no step is admitted, the brief one before it included")
var stepErr *SequenceStepError
assert.False(t, errors.As(err, &stepErr), "an admission refusal is not a step failure: nothing executed")

require.ErrorIs(t, AdmitSequenceShape([]string{`ALTER TABLE s.t DETACH PARTITION s.p FINALIZE`}),
ErrUnsupportedSequenceStep, "a dry run's admission refuses it as the run does")

admitted, err = admitSequence("s", "t", []string{
`ALTER TABLE s.t ADD COLUMN note text`,
`ALTER TABLE s.t DETACH PARTITION s.p CONCURRENTLY`,
})
require.NoError(t, err)
require.Len(t, admitted, 2)
assert.Equal(t, StepBrief, admitted[0].kind)
assert.Equal(t, StepDetachPartition, admitted[1].kind)
}

// AdmitSequenceShape is the target-free half of admission: it refuses the
// same shapes RunSequence refuses, names the offending step, and does not
// mind which table a step targets — that proof needs a preflight.
Expand Down