diff --git a/AGENTS.md b/AGENTS.md index 5e4aaba9..fc378443 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -126,6 +126,12 @@ is a smoke tour of the built binary, not a second test suite. Every other clause of such a file reaches the scratch table as the deparser prints it, not as written; a file with no `NOT VALID` constraint runs as written (see [docs/copy-and-swap-design.md](docs/copy-and-swap-design.md#d1--no-durable-scratch-database)). + A fourth executable-SQL edit is permitted for the online create of a partition: `CreatedPartition` + builds, from a bare `CREATE TABLE name PARTITION OF parent FOR VALUES ...`, the + `ALTER TABLE parent ATTACH PARTITION name FOR VALUES ...` that attaches a table of that name, + reusing the `CREATE`'s own relation and bound nodes unchanged, and reads the deparsed statement + back to confirm it names the same tables and bound. It refuses every other clause of the + `CREATE` rather than carry it. A separate comparison-only exception permits `RowSecurityChange.CanonicalSQLForNamespace` to erase only the validated operation target's schema on a fresh parsed tree. The comparison key must already include the canonical namespace and table. diff --git a/demo/tour.sh b/demo/tour.sh index 2449fc91..8099abf8 100755 --- a/demo/tour.sh +++ b/demo/tour.sh @@ -85,7 +85,7 @@ dry_run() { else assert_eq "dry-run refusal exit of [$sql]" 2 "$status" fi - assert_eq "plan format_version of [$sql]" 46 "$(jq -r '.format_version' <<<"$out")" + assert_eq "plan format_version of [$sql]" 47 "$(jq -r '.format_version' <<<"$out")" assert_eq "disposition of [$sql]" "$disposition" "$(jq -r '.disposition' <<<"$out")" assert_eq "route of [$sql]" "$route" "$(jq -r '.statements[0].route' <<<"$out")" assert_eq "reason of [$sql]" "$reason" "$(jq -r '.statements[0].decisions[0].reason' <<<"$out")" @@ -344,7 +344,7 @@ diff_plan() { if [ "$CHECK" = 1 ]; then out=$("$PGS" diff --url "$PG_DSN" --desired "$desired" --schema public --json) || status=$? assert_eq "diff exit of [$desired]" 0 "$status" - assert_eq "diff format_version of [$desired]" 46 "$(jq -r '.format_version' <<<"$out")" + assert_eq "diff format_version of [$desired]" 47 "$(jq -r '.format_version' <<<"$out")" assert_eq "statement count of [$desired]" "$count" "$(jq -r '.statements | length' <<<"$out")" case "$(jq -r '.statements[0].sql' <<<"$out")" in *"$fragment"*) ;; @@ -371,7 +371,7 @@ diff_advisory() { if [ "$CHECK" = 1 ]; then out=$("$PGS" diff --url "$PG_DSN" --desired "$desired" --schema public --json) || status=$? assert_eq "diff exit of [$desired]" 0 "$status" - assert_eq "diff format_version of [$desired]" 46 "$(jq -r '.format_version' <<<"$out")" + assert_eq "diff format_version of [$desired]" 47 "$(jq -r '.format_version' <<<"$out")" assert_eq "diff disposition of [$desired]" execute "$(jq -r '.disposition' <<<"$out")" assert_eq "statement count of [$desired]" "$count" "$(jq -r '.statements | length' <<<"$out")" assert_eq "advisory count of [$desired]" 1 "$(jq -r '.advisories | length' <<<"$out")" @@ -399,7 +399,7 @@ diff_refused() { if [ "$CHECK" = 1 ]; then out=$("$PGS" diff --url "$PG_DSN" --desired "$desired" --schema public --json) || status=$? assert_eq "diff refusal exit of [$desired]" 2 "$status" - assert_eq "diff format_version of [$desired]" 46 "$(jq -r '.format_version' <<<"$out")" + assert_eq "diff format_version of [$desired]" 47 "$(jq -r '.format_version' <<<"$out")" assert_eq "diff disposition of [$desired]" refuse "$(jq -r '.disposition' <<<"$out")" assert_eq "diff reason of [$desired]" unsupported-statement "$(jq -r '.statements[0].reason' <<<"$out")" assert_eq "diff class of [$desired]" "$class" "$(jq -r '.statements[0].class' <<<"$out")" @@ -439,7 +439,7 @@ run_pull() { out=$("$PGS" diff --url "$PG_DSN" --schema public --desired "$desired" --json) || status=$? assert_eq "diff exit of [$desired]" 0 "$status" # Plan report contract version (plan.FormatVersion), same pin as diff_plan. - assert_eq "diff format_version of [$desired]" 46 "$(jq -r '.format_version' <<<"$out")" + assert_eq "diff format_version of [$desired]" 47 "$(jq -r '.format_version' <<<"$out")" assert_eq "diff disposition of [$desired]" execute "$(jq -r '.disposition' <<<"$out")" case "$(basename "$desired")" in contacts.sql) diff --git a/docs/capabilities.md b/docs/capabilities.md index 7c2b1741..b24f3af7 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -215,7 +215,7 @@ are the canonical example. > `make gen-capabilities`; do not edit the generated regions below by hand. -**72 operations: 35 supported today (2 of them in preview), 15 planned behind a typed refusal, +**72 operations: 36 supported today (2 of them in preview), 14 planned behind a typed refusal, 17 out of scope by design, and 5 with no online mechanism for pg-sprite to build on.** @@ -280,7 +280,7 @@ or the only online form is a direct statement the operator runs). | Operation | Status | Engine path | Online-safety problem? | Behavior and why | | --- | --- | --- | --- | --- | -| `CREATE TABLE ... PARTITION OF` | 🟡 | native, planned flow | Yes | Typed refusal at both doors: the imperative door does not take `CREATE TABLE`, and the declarative create path refuses the form at plan time and re-checks it at apply — attaching a partition takes a brief `ACCESS EXCLUSIVE` on the **parent**, which the greenfield absence proof does not cover. A desired file for a partition that already exists is refused before planning builds anything, since the scratch build would attach to the live parent, and a desired file that declares several partitions, or a parent with its partitions, is refused at parse as a `capability-boundary`. The partition-aware flow is planned | +| `CREATE TABLE ... PARTITION OF` | ✅ | native, planned flow | Yes | Run as written, the statement takes `ACCESS EXCLUSIVE` on the **parent**, so it queues behind every reader of the tree and every query after it queues behind it. `migrate --alter` runs a bare `CREATE TABLE name PARTITION OF schema.parent FOR VALUES ...` as the online create of a partition instead: it creates the table standalone with `LIKE` the parent (its columns, defaults, generation expressions, storage, compression, and `CHECK`s; the parent's identity is taken on at the attach), which reads the parent without blocking it, then runs the online attach of that table with the statement's own bound (see the `ATTACH PARTITION` row), and reports the change on the parent. Running the same statement again resumes: an empty standalone table of that name is attached, and a partition already attached changes nothing; a table of that name holding rows is refused (`unsupported-statement`, `environmental`). A `DEFAULT` bound, an unqualified parent, and any clause beside the bound (a column list, constraints, `IF NOT EXISTS`, `UNLOGGED`, `WITH (...)`, `TABLESPACE`, `USING`, `PARTITION BY`) are refused (`unsupported-statement`, `capability-boundary`) before anything runs, as is a parent with a `DEFAULT` partition. Acknowledgements (`--force` included) are refused as usage errors. `--dry-run` plans it on the parent with the `online-create-partition` execution and refuses what the run refuses before it reads the parent; like the online attach's, it does not read the parent's `DEFAULT` partition, which only the run refuses. In a desired file, `PARTITION OF` is refused at plan time, since the scratch build would attach to the live parent, and a file that declares several partitions, or a parent with its partitions, is refused at parse as a `capability-boundary` | | `ATTACH PARTITION` | ✅ | native, planned flow | Yes | Run as written, the attach scans the new table under `ACCESS EXCLUSIVE` to validate its bound and builds the parent's indexes on it, so `migrate --alter` runs a lone `ATTACH PARTITION ... FOR VALUES` as the online attach instead: while writes continue, the table is given a validated `CHECK` proving the bound, the parent's `CHECK` constraints and `NOT NULL`s, the parent's indexes built concurrently (a unique one backing its constraint through `USING INDEX`), and each of the parent's foreign keys, validated; then the `ATTACH` runs in one brief transaction that scans and builds nothing, and the proof `CHECK` is dropped. Each step commits on its own, and running the same statement again resumes, or finds the table attached and changes nothing. A row outside the bound fails the run with nothing attached. A parent with a `DEFAULT` partition is refused (`unsupported-statement`, `capability-boundary`) before anything runs, since excluding the bound from it refuses writes inside the bound until the attach; an `ATTACH PARTITION ... DEFAULT` stays rewrite-required. `--force SCHEMA.TABLE` runs the blocking `ATTACH PARTITION` as submitted under bounded budgets and records the override. A desired schema cannot express an attach, so `diff` never produces one | | `DETACH PARTITION [CONCURRENTLY]` | ✅ | native, safer sequence | Yes | The plain form is rewritten to `DETACH PARTITION ... CONCURRENTLY`, which takes `SHARE UPDATE EXCLUSIVE` on the table, so reads and writes of the other partitions keep running. It runs outside a transaction block under the brief budgets: `--lock-timeout` bounds each lock wait, the wait for transactions that still read the partition through the table included, and `--statement-timeout` the whole statement. Flagged **destructive**, since the partition's rows leave the table: `migrate` refuses it with `destructive-change` unless `--allow-destructive` names the table. A detach that stops after its first transaction committed fails with `partition-detach-interrupted` and leaves the partition detach-pending; running the same statement again finishes it with `DETACH PARTITION ... FINALIZE`. A rerun that finds the partition already a table of its own with the table's columns, because an earlier run or a detach the server finished after its client went away detached it, runs nothing and exits 0 with `already_detached: true`; a same-named table with those columns that never was a partition gets the same verdict, since PostgreSQL keeps no record of a finished detach. PostgreSQL detaches one partition of a table at a time, so while another partition is detach-pending the detach fails with `partition-detach-pending` before anything runs, naming that partition and its `FINALIZE`. PostgreSQL refuses a concurrent detach from a table with a `DEFAULT` partition, so both forms are refused there (`unsupported-statement`, `by-design`, in `--dry-run` too) before anything runs; `--force SCHEMA.TABLE` runs the plain `DETACH PARTITION` as submitted under bounded budgets, taking `ACCESS EXCLUSIVE` on the table and the partition. The table may itself be a partition, and the partition may itself be partitioned, whose whole subtree then leaves with it; among table shapes, only a `DEFAULT` partition of the table detached from blocks the concurrent form, not one inside the detached subtree. A foreign key that references the table is checked before the first transaction commits: while a row still references the partition, the run fails with `execution-failed`, the server's error (SQLSTATE `23503`) reachable with `errors.As`, and the partition stays attached, not detach-pending. An unqualified partition name resolves with the table's schema first on the search path, in the rerun that finishes a pending detach too. `DETACH PARTITION ... FINALIZE` itself is refused with `unsupported-statement`: rerun the statement that started the detach. A desired schema cannot express a detach, so `diff` never produces one | | `SET TABLESPACE` on a **partitioned parent** | ✅ | native, as-is | Yes | Metadata-only: a partitioned parent has no storage, so PostgreSQL records the tablespace as the default for partitions created later, under a brief `ACCESS EXCLUSIVE` on the parent alone, and moves no existing partition or index. Runs as written under bounded locks. Moving an existing partition is a `SET TABLESPACE` on that partition, a rewrite refused as in the `SET TABLESPACE` row. `ALTER INDEX ... SET TABLESPACE` is not taken by the imperative front door. A desired file does not express a table's tablespace, so `diff` never produces one | diff --git a/docs/cli-output-examples.md b/docs/cli-output-examples.md index a340ecc0..79e77d86 100644 --- a/docs/cli-output-examples.md +++ b/docs/cli-output-examples.md @@ -205,7 +205,7 @@ itself. ```console $ pg-sprite migrate --alter 'ALTER TABLE users ADD COLUMN note text' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -247,7 +247,7 @@ plans the safer online sequence instead: the decision carries it in ```console $ pg-sprite migrate --alter 'ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email)' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -588,7 +588,7 @@ column first, then build the constraint as a separate, named ```console $ pg-sprite migrate --alter 'ALTER TABLE users ADD COLUMN nickname text UNIQUE' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -640,7 +640,7 @@ would not fit the declared free disk. ```console $ pg-sprite migrate --alter 'ALTER TABLE users ALTER COLUMN id TYPE text' --dry-run --copy-and-swap --free-disk 10GiB --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -781,7 +781,7 @@ column, a relocation — so the plan is `unavailable` and nothing executes. ```console $ pg-sprite migrate --alter 'ALTER TABLE users ADD COLUMN joined timestamptz DEFAULT clock_timestamp()' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -820,7 +820,7 @@ when it starts. ```console $ pg-sprite migrate --alter 'CREATE INDEX events_created_idx ON events (created)' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "events", @@ -916,7 +916,7 @@ cause is the report-level `reason`. ```console $ pg-sprite migrate --alter 'ALTER TABLE events ADD CONSTRAINT events_pkey PRIMARY KEY USING INDEX events_id_idx' --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "events", @@ -982,7 +982,7 @@ table. A mismatched acknowledgement executes nothing and exits 1. ```console $ pg-sprite migrate --alter 'ALTER TABLE users DROP COLUMN email' --dry-run --allow-destructive public.users --json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "public", "table": "users", @@ -1027,7 +1027,7 @@ object it removes, and the fingerprint covers it. ```console $ pg-sprite migrate --desired orders.sql --dry-run --json { - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "public", "table": "orders", @@ -1205,7 +1205,7 @@ CREATE TABLE users ( ```console $ pg-sprite diff --desired /tmp/users.sql --json { - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "public", "table": "users", diff --git a/docs/cli.md b/docs/cli.md index 220f6842..73ba8cdf 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1192,7 +1192,7 @@ and row, checksum, and catch-up counters directly; that snapshot is the $ pg-sprite migrate --dry-run --json --alter "ALTER TABLE orders ADD COLUMN ref text UNIQUE" > plan.json; echo $? 2 $ jq -c '{format_version, table, disposition}' plan.json -{"format_version": 46,"table":"orders","disposition":"rewrite-required"} +{"format_version": 47,"table":"orders","disposition":"rewrite-required"} ``` The exit code answers the question a pipeline asks first, without parsing diff --git a/docs/limitations.md b/docs/limitations.md index 7b898bb8..f2da1b5e 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -21,6 +21,7 @@ not escape hatches: | `RENAME COLUMN` and `RENAME TO` | Without `--force`, refused with `not-native-safe-rewrite-required`, nothing executed: the catalog flip is instant, but every running application instance that still queries the old name breaks the moment it commits, and no safer sequence can be built from the statement alone because the dual-write and the read switch live in the application. The plan report, `suggest`, and the verdict carry the manual path as typed guidance — `expand-contract-column` for a column (add the new column, dual-write and backfill, switch reads, drop the old column as its own reviewed change) and `coordinated-table-rename` for a table (coordinate the rename with the deploy that adopts the new name, or keep the old name readable through a view until every instance has moved) — and `lint` reports the rename as an error. `--force SCHEMA.TABLE` runs the submitted rename as a blind bounded attempt under the usual budgets and size guard, for the operator who has coordinated the deploy; on a table above `--max-table-size` (default 1 GiB) the forced rename is refused as `not-native-safe-table-too-large` until that threshold is raised. | | `ALTER INDEX ... RENAME TO` on an index that backs a primary-key, unique, or exclusion constraint | Refused with `not-native-safe-rewrite-required`, class `by-design`, guidance `coordinated-constraint-rename`, nothing executed: PostgreSQL renames the constraint with its index, and `ON CONFLICT ON CONSTRAINT` and error handling that name the old constraint break the moment it commits. `--force` does not apply to an index rename. A plain index rename runs. The refusal needs the catalog, so offline `lint` and `suggest` do not report it. | | `ATTACH PARTITION` on a parent with a `DEFAULT` partition, or with a `DEFAULT` bound | `migrate --alter` runs a lone `ATTACH PARTITION ... FOR VALUES` as the online attach, which constructs every proof below while writes continue and then attaches ([outcomes](schemabot-integration.md#outcomes-of-an-online-attach-partition)). On a parent with a `DEFAULT` partition it is refused with `unsupported-statement`, class `capability-boundary`, nothing added to either table (the refusal first drops an exclusion `CHECK` an earlier run with the window accepted left on the `DEFAULT` partition, waiting for its readers and writers to finish first): the proof that excludes the bound from the `DEFAULT` partition refuses writes inside the bound until the attach commits, and `migrate` does not yet take the operator's acceptance of that window. `migrate --dry-run` does not read the catalog for this, so it plans the attach as executing on such a parent too, and the run is the first to refuse it. `ATTACH PARTITION ... DEFAULT` has no online path and stays refused with `not-native-safe-rewrite-required`. For either, prove the attach unnecessary yourself, then run it directly: a validated `CHECK` for the bound on the new table, a validated `CHECK` excluding the bound on the parent's `DEFAULT` partition if it has one, each of the parent's indexes already on the new table, a unique one backing its constraint through `USING INDEX`, and each of the parent's foreign keys already on the new table, validated (`ADD ... NOT VALID`, then `VALIDATE`; one of the same definition under any name is reused). Without the second the attach scans the `DEFAULT` partition, without the third it builds the missing index, and without the fourth it creates the foreign key and checks every row against the referenced table, each under `ACCESS EXCLUSIVE` ([safe pattern](postgres-online-ddl-reference.md#safe-pattern-attach-a-partition-without-a-scan-or-an-index-build)). The new table must also carry the parent's `CHECK` constraints, under the same names and validated, and `NOT NULL` wherever the parent declares it, or the attach refuses it. `--force SCHEMA.TABLE` runs the blocking `ATTACH PARTITION` as submitted under bounded budgets, taking the blocking lock. | +| `CREATE TABLE ... PARTITION OF` in any form but a bare one with a `FOR VALUES` bound | `migrate --alter` runs a bare `CREATE TABLE name PARTITION OF schema.parent FOR VALUES ...` as the online create of a partition: the table is created standalone with `LIKE` the parent, which does not lock the parent against reads or writes, and then attached by the online attach (previous row), whose refusals it shares, a parent with a `DEFAULT` partition included. A `DEFAULT` bound, an unqualified parent, and any clause beside the bound (a column list, constraints, `IF NOT EXISTS`, `UNLOGGED`, `WITH (...)`, `TABLESPACE`, `USING`, `PARTITION BY`) are refused with `unsupported-statement`, class `capability-boundary`, before anything runs: create the table with `LIKE` the parent and submit the `ATTACH PARTITION`, or run the statement directly. A table of that name that already holds rows is refused as `environmental`. `--dry-run` plans the statement on the parent with the `online-create-partition` execution and refuses the same shapes, but does not read the parent's `DEFAULT` partition, so only the run refuses that parent. Every acknowledgement, `--force` included, is a usage error. | | `DETACH PARTITION` beside a `DEFAULT` partition | PostgreSQL refuses `DETACH PARTITION ... CONCURRENTLY` on a table with a `DEFAULT` partition in every supported version, so `migrate` refuses both forms there with `unsupported-statement`, class `by-design`, from the catalog before anything executes, in `--dry-run` too. The only detach left is the plain one, which holds `ACCESS EXCLUSIVE` on the table and the partition while it runs: `--force SCHEMA.TABLE` (with `--allow-destructive`) runs it as submitted under bounded budgets. Detaching the `DEFAULT` partition first, itself a plain detach, makes the concurrent one possible. `suggest` cannot see the table and marks its `CONCURRENTLY` rewrite `no-default-partition`. Elsewhere a detach runs concurrently under `--allow-destructive`; an interrupted one fails with `partition-detach-interrupted` and is finished by running the same statement again; a rerun that finds the partition already a table of its own with the table's columns runs nothing and reports `already_detached: true` (exit 0), which a same-named table with those columns that never was a partition also gets, since PostgreSQL keeps no record of a finished detach; the forced plain detach (`--force`) and `--dry-run` do not read the catalog first, so a forced rerun still fails with `execution-failed` and a dry run of the rerun previews a detach; and while another partition of the table is detach-pending one fails with `partition-detach-pending` before anything runs, since PostgreSQL detaches one partition of a table at a time. `DETACH PARTITION ... FINALIZE` itself is refused with `unsupported-statement`, because the parser's reprint of it names a different partition: rerun the statement that started the detach. | | Dropping what a replica identity index is built on | `REPLICA IDENTITY USING INDEX` outlives its index, so dropping the index, the primary key or unique constraint that owns it, or a column it covers leaves the table with no usable identity, and every `UPDATE` and `DELETE` on it fails while a publication publishes them. `REPLICA IDENTITY DEFAULT` keys on the primary key and fails the same way once it is dropped, so on a table a publication publishes updates or deletes for, the primary key counts as the identity index; on a table no publication publishes, it stays free to drop. The planner refuses such a drop with `replica-identity`, on the table and on what the drop reaches below it: a `DROP COLUMN` reaches partitions and inheritance children unless the statement says `ONLY`, and a `DROP CONSTRAINT` reaches partitions, whose indexes are attached under the parent's. The executor reads the identity again under the lock the drop takes, so an identity that moved onto the dropped object after planning still refuses the run before anything commits. `migrate --accept-blocking` makes the same check before a `DROP INDEX`. Point `REPLICA IDENTITY` at a unique index the drop leaves in place (`USING INDEX`), at a primary key it leaves in place (`DEFAULT`), or at the whole row (`FULL`, which logs every column of the old row) first, then re-plan. | | Adding a column or a table a logical replication subscriber does not have yet | A native subscriber applies each change as the publisher sends it, so the first change that carries a column it does not have, or names a table it does not have, stops its apply worker, which halts every table in the subscription while the publisher's slot keeps WAL. When a publication sends the change and a `pgoutput` slot may be reading it, the plan names both in `replicating_publications` and `replication_slots` and the text output warns: for an added column, every publication that publishes any change of the permanent table without a column list, deletes or truncates alone included, and for a stored generated column only those that send generated columns; for a new permanent table, every publication `FOR ALL TABLES` or `FOR TABLES IN SCHEMA` covering its schema. The warning does not change the route: the publisher cannot see whether each subscriber is ready, and a change-data-capture consumer may take the change as it comes. For a column, add it on each subscriber first, then run the change. For a table, create it on each subscriber first, run the change, then run `ALTER SUBSCRIPTION ... REFRESH PUBLICATION` on each subscriber; a refresh registers only tables the publisher already has, so running it earlier registers nothing. A slot does not record which publications it reads, so every `pgoutput` slot is named; a new partition's publications inherited from a parent listed by name are not read. | diff --git a/docs/plan-report.md b/docs/plan-report.md index 89d32a7f..235ae436 100644 --- a/docs/plan-report.md +++ b/docs/plan-report.md @@ -53,7 +53,7 @@ kinds, guidance, causes, classes, owners, advisory kinds) and the fingerprint se changing the fingerprint definition is a contract change and bumps `format_version`, even if no field is added or renamed. -The current version is **46**: version 46 added the statement-level `resumes` field, with its `phase`, `mode`, and `last_saved`, which the statement of a copy-and-swap run stopped on the table carries in a `migrate --dry-run` plan, with the `copy-and-swap` route and backend in place of the route against the table's current shape, and which the fingerprint does not cover (the route and backend it sets it does); version 45 added the `dependent-rule` reason and the `dependent_rules` decision field, which name the rewrite rules that read a column the change retypes or drops; version 44 added the `create-enum-type` kind, which a plan for a desired enum type file carries when the schema lacks the type, in place of the `enum-type-missing` refusal, and which the fingerprint covers like every statement; version 43 added the `online-attach` execution contract, which an `ALTER TABLE ... ATTACH PARTITION ... FOR VALUES` carries in a `migrate --dry-run` plan in place of `rewrite-required` and which the fingerprint covers; version 42 added the `catalog_only_steps` decision field, which lists the steps of a safer sequence that change only the catalog, and widened `proven_catalog_only` to every shape the server proves, such as a stored built-in default, a `SET DEFAULT`, a `NOT VALID` constraint, an unread binary-coercible type change, and a `SET NOT NULL` over a validated check; neither is covered by the fingerprint; version 41 added the `trigger_reads` and `unchecked_triggers` decision fields, which name the triggers whose function reads the column a retype or drop changes, a read PostgreSQL records no dependency for, and the triggers whose function cannot be checked for one; version 40 added the `replicating_publications` and `replication_slots` decision fields, which name the publications that send an added column or a new table to logical replication and the `pgoutput` slots that may be reading them, and which the fingerprint does not cover; version 39 added the `stops_subscriptions` and `may_stall_subscriptions` decision fields, which name the logical replication subscriptions writing the table whose replication the change stops or a later row can stall, leave the route unchanged, and which the fingerprint does not cover; version 38 added the statement-level `lookups_kept_by` field, which names the index or key that answers every lookup a dropped index or unique constraint answers, and which the fingerprint does not cover; version 37 added the `published-without-key` create-shape cause, which refuses the `CREATE TABLE` of a new permanent table that declares no primary key while a publication publishes the updates or deletes of every new table in its schema, and the statement-level `publications` field, which names those publications and which the fingerprint does not cover; version 36 added the statement-level `refusal_cause` field, which a refusal whose reason has a narrower cause carries, such as which kind of foreign-key drop a `declarative-foreign-key` refusal is, and which the fingerprint does not cover; version 35 added the statement-level `uniqueness_kept_by` field, which the fingerprint does not cover; version 34 added the `column-limit` reason and the `column_limit` decision field, which the fingerprint does not cover; version 33 added the `not_null_from_type` and `constrained_type` decision fields; version 32 added the `dependent-publication` reason and the `dependent_publications` decision field; version 31 also carries `replaced_by` on the drop of the old object when a unique constraint and a unique index of the same name swap kinds, a `drop-constraint` whose replacement is a standalone index or a `drop-index` whose replacement a constraint takes over; version 30 runs the `drop-foreign-key` kind instead of refusing it, and narrows the `declarative-foreign-key` reason to the drop of a foreign key a desired file cannot declare, or changes under the same name on a partitioned table or in a plan that also drops or retypes a column; version 29 added the `rename-index` kind and the statement-level `replaced_by` field, which a changed index the diff replaces carries on the drop of the old index, and which the fingerprint does not cover, and a `rename-index` decision carries `proven_catalog_only: true`; version 28 added the `partitioned-foreign-key-build` execution contract, which an `ALTER TABLE ... ADD FOREIGN KEY` on a partitioned table carries in a `migrate --dry-run` or `diff` plan on PostgreSQL 14–17 in place of its refusal and which the fingerprint covers; version 27 added the `partitioned-key-build` execution contract, which an `ALTER TABLE ... ADD PRIMARY KEY` or `ADD UNIQUE` on a partitioned table carries in a `migrate --dry-run` plan, and a key a desired file adds carries in a `diff` plan, in place of its refusal and which the fingerprint covers; version 26 runs the `add-foreign-key` and `validate-foreign-key` kinds instead of refusing them, so `declarative-foreign-key` now refuses only `drop-foreign-key`, and retires the `foreign-key` cause, since the create path creates a table with its foreign keys; version 25 added the `proven_catalog_only` decision field, which marks an operation PostgreSQL runs on the catalog alone and which the fingerprint does not cover; version 24 added the `blocking-index-drop` execution contract, which a refused `drop-index` of a partitioned table's index carries with its plain `DROP INDEX` as `exec_sql`, and which the fingerprint covers; version 23 added the `partitioned-index-build` execution contract, which a `CREATE INDEX` on a partitioned table carries in place of its refusal and which the fingerprint covers; version 22 added the statement-level `drops` field, with its `dependents`, which the fingerprint covers when it is present, and the report-level `pinnable_fingerprint` field; version 21 added the `add-integer-primary-key` guidance code (carried by a `copy-and-swap-pk-unsupported` refusal verdict for a table with no primary key, never by a report statement; no field changed, so a consumer that pins the version only moves its pin); version 20 added the `add-enum-value` kind and the report-level `type` field, which a plan for a desired enum type file carries in place of `table`; version 19 added the report-level `extension_schemas` field, which the fingerprint covers when it is present; version 18 added the `dependent-trigger`, `dependent-generated-column`, and `partition-key` reasons and the `dependent_triggers`, `dependent_generated_columns`, and `partition_key_tables` decision fields, and made each `dependent_*` field present whenever its dependents block the change, whatever the decision's reason; version 17 added the `not-null-without-default` reason; version 16 added the `dependent-policy` reason and the `dependent_policies` decision field; version 15 added the report-level `advisories` field and its +The current version is **47**: version 47 added the `online-create-partition` execution contract, which a `CREATE TABLE ... PARTITION OF ... FOR VALUES` carries in a `migrate --dry-run` plan on the partitioned parent, and which the fingerprint covers; version 46 added the statement-level `resumes` field, with its `phase`, `mode`, and `last_saved`, which the statement of a copy-and-swap run stopped on the table carries in a `migrate --dry-run` plan, with the `copy-and-swap` route and backend in place of the route against the table's current shape, and which the fingerprint does not cover (the route and backend it sets it does); version 45 added the `dependent-rule` reason and the `dependent_rules` decision field, which name the rewrite rules that read a column the change retypes or drops; version 44 added the `create-enum-type` kind, which a plan for a desired enum type file carries when the schema lacks the type, in place of the `enum-type-missing` refusal, and which the fingerprint covers like every statement; version 43 added the `online-attach` execution contract, which an `ALTER TABLE ... ATTACH PARTITION ... FOR VALUES` carries in a `migrate --dry-run` plan in place of `rewrite-required` and which the fingerprint covers; version 42 added the `catalog_only_steps` decision field, which lists the steps of a safer sequence that change only the catalog, and widened `proven_catalog_only` to every shape the server proves, such as a stored built-in default, a `SET DEFAULT`, a `NOT VALID` constraint, an unread binary-coercible type change, and a `SET NOT NULL` over a validated check; neither is covered by the fingerprint; version 41 added the `trigger_reads` and `unchecked_triggers` decision fields, which name the triggers whose function reads the column a retype or drop changes, a read PostgreSQL records no dependency for, and the triggers whose function cannot be checked for one; version 40 added the `replicating_publications` and `replication_slots` decision fields, which name the publications that send an added column or a new table to logical replication and the `pgoutput` slots that may be reading them, and which the fingerprint does not cover; version 39 added the `stops_subscriptions` and `may_stall_subscriptions` decision fields, which name the logical replication subscriptions writing the table whose replication the change stops or a later row can stall, leave the route unchanged, and which the fingerprint does not cover; version 38 added the statement-level `lookups_kept_by` field, which names the index or key that answers every lookup a dropped index or unique constraint answers, and which the fingerprint does not cover; version 37 added the `published-without-key` create-shape cause, which refuses the `CREATE TABLE` of a new permanent table that declares no primary key while a publication publishes the updates or deletes of every new table in its schema, and the statement-level `publications` field, which names those publications and which the fingerprint does not cover; version 36 added the statement-level `refusal_cause` field, which a refusal whose reason has a narrower cause carries, such as which kind of foreign-key drop a `declarative-foreign-key` refusal is, and which the fingerprint does not cover; version 35 added the statement-level `uniqueness_kept_by` field, which the fingerprint does not cover; version 34 added the `column-limit` reason and the `column_limit` decision field, which the fingerprint does not cover; version 33 added the `not_null_from_type` and `constrained_type` decision fields; version 32 added the `dependent-publication` reason and the `dependent_publications` decision field; version 31 also carries `replaced_by` on the drop of the old object when a unique constraint and a unique index of the same name swap kinds, a `drop-constraint` whose replacement is a standalone index or a `drop-index` whose replacement a constraint takes over; version 30 runs the `drop-foreign-key` kind instead of refusing it, and narrows the `declarative-foreign-key` reason to the drop of a foreign key a desired file cannot declare, or changes under the same name on a partitioned table or in a plan that also drops or retypes a column; version 29 added the `rename-index` kind and the statement-level `replaced_by` field, which a changed index the diff replaces carries on the drop of the old index, and which the fingerprint does not cover, and a `rename-index` decision carries `proven_catalog_only: true`; version 28 added the `partitioned-foreign-key-build` execution contract, which an `ALTER TABLE ... ADD FOREIGN KEY` on a partitioned table carries in a `migrate --dry-run` or `diff` plan on PostgreSQL 14–17 in place of its refusal and which the fingerprint covers; version 27 added the `partitioned-key-build` execution contract, which an `ALTER TABLE ... ADD PRIMARY KEY` or `ADD UNIQUE` on a partitioned table carries in a `migrate --dry-run` plan, and a key a desired file adds carries in a `diff` plan, in place of its refusal and which the fingerprint covers; version 26 runs the `add-foreign-key` and `validate-foreign-key` kinds instead of refusing them, so `declarative-foreign-key` now refuses only `drop-foreign-key`, and retires the `foreign-key` cause, since the create path creates a table with its foreign keys; version 25 added the `proven_catalog_only` decision field, which marks an operation PostgreSQL runs on the catalog alone and which the fingerprint does not cover; version 24 added the `blocking-index-drop` execution contract, which a refused `drop-index` of a partitioned table's index carries with its plain `DROP INDEX` as `exec_sql`, and which the fingerprint covers; version 23 added the `partitioned-index-build` execution contract, which a `CREATE INDEX` on a partitioned table carries in place of its refusal and which the fingerprint covers; version 22 added the statement-level `drops` field, with its `dependents`, which the fingerprint covers when it is present, and the report-level `pinnable_fingerprint` field; version 21 added the `add-integer-primary-key` guidance code (carried by a `copy-and-swap-pk-unsupported` refusal verdict for a table with no primary key, never by a report statement; no field changed, so a consumer that pins the version only moves its pin); version 20 added the `add-enum-value` kind and the report-level `type` field, which a plan for a desired enum type file carries in place of `table`; version 19 added the report-level `extension_schemas` field, which the fingerprint covers when it is present; version 18 added the `dependent-trigger`, `dependent-generated-column`, and `partition-key` reasons and the `dependent_triggers`, `dependent_generated_columns`, and `partition_key_tables` decision fields, and made each `dependent_*` field present whenever its dependents block the change, whatever the decision's reason; version 17 added the `not-null-without-default` reason; version 16 added the `dependent-policy` reason and the `dependent_policies` decision field; version 15 added the report-level `advisories` field and its closed kind vocabulary — the invalid indexes a `diff` observed and declined to drop; version 14 added the `alter-column-type-in-place` guidance code (carried by a `destructive-change` refusal verdict, never by a report statement); version 13 added the `coordinated-constraint-rename` guidance code and classifies the rename of an index that backs a primary-key, unique, or exclusion constraint as `app-breaking-rename`; version 12 added the `expand-contract-column` and `coordinated-table-rename` guidance codes and made `app-breaking-rename` decisions yield the `rewrite-required` disposition; version 11 added the `cascading-drop` reason; version 10 added the `dependent-view` reason and the `dependent_views` decision field; version 9 added the `validate-constraint` and `validate-foreign-key` kinds; version 8 added the `replica-identity` reason; version 7 added the `set-generated-expression` kind; version 6 added the `add-foreign-key` and `drop-foreign-key` kinds, the `foreign-key` cause, and the `declarative-foreign-key` reason; version 5 added `blocking_passthrough_eligible` to every refused statement; version 4 added the `class` and `owner` fields on the report @@ -242,6 +242,7 @@ and privilege checks because it needs no connection. | `blocking-index-drop` | Only on a refused `drop-index` statement whose table is partitioned: the one step is the plain `DROP INDEX` of the parent's index, which PostgreSQL cannot drop concurrently (`DROP INDEX CONCURRENTLY` fails with SQLSTATE `0A000`). It takes `ACCESS EXCLUSIVE` on the parent, every partition, and every partition's index for as long as it runs, so the statement stays `refuse` and the report's disposition with it. `migrate --desired` runs it only when the run pins this plan's fingerprint and names the table in `--allow-destructive` and `--accept-blocking`, with an explicit `--statement-timeout` longer than `--lock-timeout`: in one engine-owned transaction it requests the parent's lock under `lock_timeout`, reads the index again (still the parent's partitioned index, with the `drops` definition), drops it under `statement_timeout`, and reads back that the parent's index and every attached partition index are gone before it commits. It is never run `CONCURRENTLY` and never falls back to another form. A consumer that runs statements itself must not run it as an online step. | | `partitioned-key-build` | The one step is an `ALTER TABLE ... ADD PRIMARY KEY` or `ADD UNIQUE` on a partitioned table, and the executor runs it as the partitioned key build, never as the statement: each partition's unique index is built concurrently and given the constraint with `ADD CONSTRAINT ... USING INDEX`, then the parent's `ADD CONSTRAINT` adopts every partition's constraint in one brief transaction that builds nothing. The partitions are listed when the build runs, not when the plan is made, so they are not in `exec_sql`. The statement must not be run as written, which would build every partition's index under `ACCESS EXCLUSIVE` on the whole tree. A failed or interrupted run leaves the partition constraints finished so far; running the same statement again resumes from them. A `migrate --dry-run` plan carries it, and so does a `diff` plan for a key a desired file adds whose shape the build accepts; a desired key the build cannot carry, such as a `DEFERRABLE` one, is refused with `unsupported-partitioned-parent`. | | `online-attach` | The one step is an `ALTER TABLE ... ATTACH PARTITION ... FOR VALUES`, and the executor runs it as the online attach, never as the statement: under the parent's advisory lock the new table is given a validated `CHECK` that implies the bound, the parent's `CHECK`s and `NOT NULL`s, its indexes built concurrently and its keys, and its enforced foreign keys validated, all while writes go on; the parent's `DEFAULT` partition, if any, is given a validated `CHECK` that excludes the bound, though `migrate` refuses a parent with a `DEFAULT` partition before that step, and this plan, which reads no catalog for it, does not show the refusal; then the `ATTACH` runs as a catalog-only change and drops both proof `CHECK`s in its transaction. The statement must not be run as written, which scans the new table and the `DEFAULT` partition and builds the parent's indexes under `ACCESS EXCLUSIVE`. A failed or interrupted run leaves what earlier steps gave the new table; running the same statement again resumes from it. Only in a `migrate --dry-run` plan; `diff` never produces an attach | +| `online-create-partition` | The one step is a `CREATE TABLE ... PARTITION OF ... FOR VALUES`, and the executor runs it as the online create of a partition, never as the statement: under the parent's advisory lock the table is created standalone with `LIKE` the parent (its columns, defaults, generation expressions, storage, compression, and `CHECK`s), which does not lock the parent against reads or writes, and is then attached by the online attach (`online-attach`) with the statement's own bound. The report's `table` is the partitioned parent. The statement must not be run as written, which takes `ACCESS EXCLUSIVE` on the parent. A failed or interrupted run leaves the table and what the attach finished on it; running the same statement again resumes from it, and a table of that name that holds rows is refused. Like `online-attach`, this plan reads nothing the attach decides under its lock, such as a `DEFAULT` partition, which the run refuses. Only in a `migrate --dry-run` plan; `diff` never produces one | ### Dispositions (`disposition`) @@ -377,13 +378,13 @@ time is the consumer's side of the contract. The serialization is exact and pinned by test: for each statement in plan order, hash the canonical `sql`, `route`, `backend`, and `disposition`, then each `exec_sql` entry, then — only for a statement whose `execution` is `partitioned-index-build`, `partitioned-key-build`, -`partitioned-foreign-key-build`, `online-attach`, or `blocking-index-drop` — that `execution` value. Every field is +`partitioned-foreign-key-build`, `online-attach`, `online-create-partition`, or `blocking-index-drop` — that `execution` value. Every field is followed by a unit separator (`0x1F`), and each statement closes with a record separator -(`0x1E`). The `execution` is hashed for those five values because their `exec_sql` is the +(`0x1E`). The `execution` is hashed for those six values because their `exec_sql` is the statement as written: each flow's statement run literally (a `CREATE INDEX CONCURRENTLY` or an `ALTER TABLE ... ADD PRIMARY KEY` on a plain table, an `ALTER TABLE ... ADD FOREIGN KEY` that validates every partition under the tree's lock, an `ATTACH PARTITION` that scans the new table -under `ACCESS EXCLUSIVE`) is a different plan, and +under `ACCESS EXCLUSIVE`, a `CREATE TABLE ... PARTITION OF` that locks the parent `ACCESS EXCLUSIVE`) is a different plan, and a reviewed drop of a partitioned table's index pins the blocking form a run that accepts it executes, so the plan cannot switch drop forms unnoticed; a statement with any other `execution` hashes as it did before. Explanatory fields (`decisions`, `kind`, `destructive`, `reason`, `cause`, @@ -432,7 +433,7 @@ in `pkg/plan` — if the code drifts from this page, CI fails. ```json { - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "app", "table": "orders", @@ -476,7 +477,7 @@ A desired state that drops an index and adds a column with a constant default: ```json { - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "app", "table": "orders", @@ -544,7 +545,7 @@ A desired state for a table that does not exist yet, whose `CREATE TABLE` carrie ```json { - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "app", "table": "gadgets", diff --git a/docs/schemabot-integration.md b/docs/schemabot-integration.md index c94e246b..c7ab357b 100644 --- a/docs/schemabot-integration.md +++ b/docs/schemabot-integration.md @@ -1018,7 +1018,8 @@ serves the key build, which both route a lone `ADD PRIMARY KEY` or `ADD UNIQUE` partitioned table to (`partitioned-key-build`), and the foreign key build, which both route a foreign key on a partitioned table to before PostgreSQL 18 (`partitioned-foreign-key-build`), and the online attach, which `migrate.Run` routes a lone `ATTACH PARTITION ... FOR VALUES` to -(`online-attach`). +(`online-attach`), and the online create of a partition, which it routes a bare +`CREATE TABLE ... PARTITION OF ... FOR VALUES` to (`online-create-partition`). Each build takes the parent's table lock on a dedicated session, which the pool cannot supply, so the adapter sets `migrate.Options.Connection` to the `dbconn.Config` the pool was dialed with. It must diff --git a/internal/cli/dryrun.go b/internal/cli/dryrun.go index 41bc0e3d..1b31ef19 100644 --- a/internal/cli/dryrun.go +++ b/internal/cli/dryrun.go @@ -50,6 +50,11 @@ func (c *MigrateCmd) runDryRun(ctx context.Context, out io.Writer) error { if v, refused := migrate.Gate(st); refused && !migrate.GateReadsCatalog(st) { return c.emit(out, v) } + if st.Kind() == statement.KindCreateTable { + // Past the gate, a CREATE TABLE is a PARTITION OF, which the apply + // runs as the online create of a partition. + return c.runCreatePartitionDryRun(ctx, out, st) + } pool, err := dbconn.NewPool(ctx, c.Config()) if err != nil { diff --git a/internal/cli/dryrun_create_partition.go b/internal/cli/dryrun_create_partition.go new file mode 100644 index 00000000..b6d5b706 --- /dev/null +++ b/internal/cli/dryrun_create_partition.go @@ -0,0 +1,90 @@ +package cli + +import ( + "context" + "fmt" + "io" + + "github.com/block/pg-sprite/pkg/dbconn" + "github.com/block/pg-sprite/pkg/migrate" + "github.com/block/pg-sprite/pkg/plan" + "github.com/block/pg-sprite/pkg/planner" + "github.com/block/pg-sprite/pkg/router" + "github.com/block/pg-sprite/pkg/statement" + "github.com/block/pg-sprite/pkg/verdict" +) + +// runCreatePartitionDryRun is the dry run of a CREATE TABLE ... PARTITION +// OF the gate admitted, which the apply runs as the online create of a +// partition. It makes the checks the apply makes before it reads the parent +// (migrate.AdmitCreatePartition), and plans the statement on the +// partitioned parent with the online-create-partition execution. Like the +// online attach's dry run, it reads nothing the attach decides under its +// lock: the parent's DEFAULT partition, the bound's proof, and what the +// parent requires of the table are the run's. A parent that does not exist +// is reported as a missing table, which exits with the refusal code. +func (c *MigrateCmd) runCreatePartitionDryRun(ctx context.Context, out io.Writer, st statement.Statement) error { + logger := c.diag() + pool, err := dbconn.NewPool(ctx, c.Config()) + if err != nil { + return err + } + defer pool.Close() + + attach, v, refused, err := migrate.AdmitCreatePartition(ctx, pool, st, c.options(logger)) + if err != nil { + return err + } + if refused { + return c.emit(out, v) + } + facts, err := migrate.LiveFacts(ctx, pool, attach) + if err != nil { + return err + } + canonical, err := statement.Canonical(st.SQL()) + if err != nil { + return err + } + classified, err := planner.Classify(canonical, facts.Classifier) + if err != nil { + return err + } + routed := router.Route([]planner.Plan{classified}) + logger.Debug("statement routed", + "route", string(classified.Route), "disposition", string(routed.Disposition)) + + report := plan.NewReport(plan.SourceAlter) + report.Schema = facts.Schema + report.Table = facts.Table + report.TableExists = facts.TableExists + if report.ServerVersion, err = dbconn.ServerVersion(ctx, pool); err != nil { + return err + } + report.Disposition = routed.Disposition + for _, rs := range routed.Statements { + ps, err := plan.FromRouted(rs) + if err != nil { + return fmt.Errorf("plan statement %q: %w", rs.Statement, err) + } + report.Statements = append(report.Statements, ps) + } + if !tableMissing(report) { + if err := plan.RouteOnlineCreatePartition(&report); err != nil { + return err + } + } + report.Fingerprint = report.ComputeFingerprint() + + if c.JSON { + if err := writeJSON(out, report); err != nil { + return err + } + } else if err := writeDryRunTextWithCopySwapFlags(out, c.palette(out), report, c.copySwapFlags()); err != nil { + return err + } + if report.Disposition != router.DispositionExecute || tableMissing(report) { + return verdict.ErrRefused + } + return nil +} diff --git a/internal/cli/dryrun_text.go b/internal/cli/dryrun_text.go index 7a4c8ca2..be247da2 100644 --- a/internal/cli/dryrun_text.go +++ b/internal/cli/dryrun_text.go @@ -396,6 +396,11 @@ func writeExecutionNotes(w *stickyWriter, ps plan.Statement, runner, desiredTabl w.diag("note", "", "each step commits on its own, and an interrupted run is resumed by running the same statement again") return 1 } + if ps.Execution == planner.ExecutionOnlineCreatePartition { + w.diag("note", "", runner+" will create the partition online instead of running the statement: create the table standalone with the parent's columns, which does not lock the parent, then attach it online: give it the parent's indexes built concurrently and validated foreign keys while writes continue, and run the ATTACH, which scans and builds nothing in one brief transaction") + w.diag("note", "", "each step commits on its own, and an interrupted run is resumed by running the same statement again") + return 1 + } if substituted(ps) { w.diag("note", "", runner+" will run a safer online sequence instead:") for n, sql := range ps.ExecSQL { diff --git a/internal/cli/migrate_online_create_partition_integration_test.go b/internal/cli/migrate_online_create_partition_integration_test.go new file mode 100644 index 00000000..fa2aee42 --- /dev/null +++ b/internal/cli/migrate_online_create_partition_integration_test.go @@ -0,0 +1,112 @@ +package cli + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/block/pg-sprite/internal/testutil" + "github.com/block/pg-sprite/pkg/dbconn" + "github.com/block/pg-sprite/pkg/planner" + "github.com/block/pg-sprite/pkg/router" + "github.com/block/pg-sprite/pkg/verdict" +) + +// A CREATE TABLE ... PARTITION OF plans as the online create of a +// partition: the dry run reports it executable on the partitioned parent +// with the online-create-partition execution and creates nothing, and the +// apply creates and attaches the table, which then carries the statement's +// bound. Its fingerprint differs from the same statement planned to run as +// written, so a pin cannot carry over to the blocking form. +func TestMigrateAlterCreatesAPartitionOnline(t *testing.T) { + url := testutil.StartPostgres(t) + pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url}) + require.NoError(t, err) + t.Cleanup(pool.Close) + schema := testutil.NewSchema(t, pool) + _, err = pool.Exec(t.Context(), fmt.Sprintf(` + CREATE TABLE %[1]s.orders ( + id bigint NOT NULL, + day date NOT NULL, + PRIMARY KEY (id, day) + ) PARTITION BY RANGE (day); + CREATE TABLE %[1]s.orders_2026 PARTITION OF %[1]s.orders + FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')`, schema)) + require.NoError(t, err) + exists := func(table string) bool { + t.Helper() + var found bool + require.NoError(t, pool.QueryRow(t.Context(), `SELECT to_regclass($1) IS NOT NULL`, schema+"."+table).Scan(&found)) + return found + } + create := fmt.Sprintf(`CREATE TABLE %[1]s.orders_2027 + PARTITION OF %[1]s.orders + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, schema) + + report := dryRunPlan(t, url, create) + assert.Equal(t, router.DispositionExecute, report.Disposition) + assert.Equal(t, schema, report.Schema) + assert.Equal(t, "orders", report.Table, "the plan reports on the partitioned parent") + require.Len(t, report.Statements, 1) + ps := report.Statements[0] + assert.Equal(t, planner.ExecutionOnlineCreatePartition, ps.Execution) + assert.Equal(t, []string{ps.SQL}, ps.ExecSQL) + assert.False(t, exists("orders_2027"), "the dry run creates nothing") + asWritten := report + asWritten.Statements = append(asWritten.Statements[:0:0], ps) + asWritten.Statements[0].Execution = planner.ExecutionAutocommit + assert.NotEqual(t, report.Fingerprint, asWritten.ComputeFingerprint()) + + v, err := runMigrate(t, newMigrateCmd(url, create)) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeExecuted, v.Outcome) + assert.Equal(t, schema+".orders", v.Table) + var bound string + require.NoError(t, pool.QueryRow(t.Context(), `SELECT pg_get_expr(relpartbound, oid) FROM pg_class WHERE oid = $1::regclass`, + schema+".orders_2027").Scan(&bound)) + assert.Equal(t, "FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')", bound) +} + +// The dry run refuses what the apply refuses before it reads the parent: +// an unqualified parent, which the online attach does not take, with the +// apply's verdict; and a DEFAULT bound, which the gate refuses without a +// connection. +func TestMigrateAlterDryRunRefusesAPartitionTheOnlineCreateDoesNotTake(t *testing.T) { + url := testutil.StartPostgres(t) + pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url}) + require.NoError(t, err) + t.Cleanup(pool.Close) + schema := testutil.NewSchema(t, pool) + _, err = pool.Exec(t.Context(), fmt.Sprintf(` + CREATE TABLE %[1]s.orders ( + id bigint NOT NULL, + day date NOT NULL + ) PARTITION BY RANGE (day)`, schema)) + require.NoError(t, err) + + for name, sql := range map[string]string{ + "unqualified parent": fmt.Sprintf(`CREATE TABLE %[1]s.orders_2027 + PARTITION OF orders + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, schema), + "DEFAULT bound": fmt.Sprintf(`CREATE TABLE %[1]s.orders_default + PARTITION OF %[1]s.orders + DEFAULT`, schema), + } { + t.Run(name, func(t *testing.T) { + cmd := newMigrateCmd(url, sql) + cmd.DryRun = true + v, err := runMigrate(t, cmd) + require.ErrorIs(t, err, verdict.ErrRefused) + assert.Equal(t, verdict.OutcomeRefused, v.Outcome) + assert.Equal(t, verdict.ReasonUnsupportedStatement, v.Reason) + assert.Equal(t, verdict.ClassCapabilityBoundary, v.Class) + + applied, err := runMigrate(t, newMigrateCmd(url, sql)) + require.ErrorIs(t, err, verdict.ErrRefused) + assert.Equal(t, v.Reason, applied.Reason, "the apply refuses it the same way") + assert.Equal(t, v.Class, applied.Class) + }) + } +} diff --git a/pkg/capabilities/capabilities.yaml b/pkg/capabilities/capabilities.yaml index 9386d3f0..20199b66 100644 --- a/pkg/capabilities/capabilities.yaml +++ b/pkg/capabilities/capabilities.yaml @@ -333,15 +333,16 @@ rows: - id: create-table-partition-of area: "partitioned_tables" operation: "`CREATE TABLE ... PARTITION OF`" - tier: "t2" - status_mark: "🟡" + tier: "t1" + status_mark: "✅" engine_path: "native_planned_flow" + maturity: "ga" online_safety_problem: true front_doors: - migrate: refused + migrate: supported diff: refused refusal_reason: unsupported-statement - reason_notes: "Typed refusal at both doors: the imperative door does not take `CREATE TABLE`, and the declarative create path refuses the form at plan time and re-checks it at apply — attaching a partition takes a brief `ACCESS EXCLUSIVE` on the **parent**, which the greenfield absence proof does not cover. A desired file for a partition that already exists is refused before planning builds anything, since the scratch build would attach to the live parent, and a desired file that declares several partitions, or a parent with its partitions, is refused at parse as a `capability-boundary`. The partition-aware flow is planned" + reason_notes: "Run as written, the statement takes `ACCESS EXCLUSIVE` on the **parent**, so it queues behind every reader of the tree and every query after it queues behind it. `migrate --alter` runs a bare `CREATE TABLE name PARTITION OF schema.parent FOR VALUES ...` as the online create of a partition instead: it creates the table standalone with `LIKE` the parent (its columns, defaults, generation expressions, storage, compression, and `CHECK`s; the parent's identity is taken on at the attach), which reads the parent without blocking it, then runs the online attach of that table with the statement's own bound (see the `ATTACH PARTITION` row), and reports the change on the parent. Running the same statement again resumes: an empty standalone table of that name is attached, and a partition already attached changes nothing; a table of that name holding rows is refused (`unsupported-statement`, `environmental`). A `DEFAULT` bound, an unqualified parent, and any clause beside the bound (a column list, constraints, `IF NOT EXISTS`, `UNLOGGED`, `WITH (...)`, `TABLESPACE`, `USING`, `PARTITION BY`) are refused (`unsupported-statement`, `capability-boundary`) before anything runs, as is a parent with a `DEFAULT` partition. Acknowledgements (`--force` included) are refused as usage errors. `--dry-run` plans it on the parent with the `online-create-partition` execution and refuses what the run refuses before it reads the parent; like the online attach's, it does not read the parent's `DEFAULT` partition, which only the run refuses. In a desired file, `PARTITION OF` is refused at plan time, since the scratch build would attach to the live parent, and a file that declares several partitions, or a parent with its partitions, is refused at parse as a `capability-boundary`" - id: attach-partition area: "partitioned_tables" operation: "`ATTACH PARTITION`" diff --git a/pkg/capabilities/front_door_integration_test.go b/pkg/capabilities/front_door_integration_test.go index 94f24e76..d8a17c47 100644 --- a/pkg/capabilities/front_door_integration_test.go +++ b/pkg/capabilities/front_door_integration_test.go @@ -267,6 +267,20 @@ var migrateClaims = map[string]migrateClaim{ `ALTER TABLE %[1]s.events ATTACH PARTITION %[1]s.events_low FOR VALUES FROM (0) TO (1000)`, }, }, + // The online create of a partition makes the table standalone and runs + // the online attach of it, so the parent is never locked against reads. + "create-table-partition-of": { + setup: ` + CREATE TABLE %[1]s.events ( + id bigint NOT NULL, + PRIMARY KEY (id) + ) PARTITION BY RANGE (id); + CREATE TABLE %[1]s.events_low PARTITION OF %[1]s.events + FOR VALUES FROM (0) TO (1000)`, + statements: []string{ + `CREATE TABLE %[1]s.events_high PARTITION OF %[1]s.events FOR VALUES FROM (1000) TO (2000)`, + }, + }, "index-build-on-a-partitioned-parent": { setup: ` CREATE TABLE %[1]s.events ( diff --git a/pkg/executor/attach_partition_flow.go b/pkg/executor/attach_partition_flow.go index 9ff3047e..3da334cf 100644 --- a/pkg/executor/attach_partition_flow.go +++ b/pkg/executor/attach_partition_flow.go @@ -191,7 +191,7 @@ type AttachPartitionReport struct { // A pool smaller than a concurrent index build needs is refused with // ErrPoolTooSmall before the lock is taken. func AttachPartitionOnline(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, o AttachPartitionOptions) (AttachPartitionReport, error) { - return attachPartitionAt(ctx, cfg, pool, pt, sql, o, nil, 0) + return attachPartitionWith(ctx, cfg, pool, pt, sql, false, o, nil, 0) } // AttachPartitionOnlineAsStep is AttachPartitionOnline reported to the run @@ -202,10 +202,13 @@ func AttachPartitionOnlineAsStep(ctx context.Context, cfg dbconn.Config, pool *p if err := at.validate(); err != nil { return AttachPartitionReport{}, err } - return attachPartitionAt(ctx, cfg, pool, pt, sql, o, at.Tracker, at.Step) + return attachPartitionWith(ctx, cfg, pool, pt, sql, false, o, at.Tracker, at.Step) } -func attachPartitionAt(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, o AttachPartitionOptions, tracker *progress.Tracker, runStep int) (AttachPartitionReport, error) { +// attachPartitionWith runs the online attach of the ATTACH sql, first +// creating the table it attaches when create is set (see +// CreatePartitionOnline). +func attachPartitionWith(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, create bool, o AttachPartitionOptions, tracker *progress.Tracker, runStep int) (AttachPartitionReport, error) { rep := AttachPartitionReport{ParentSchema: pt.Schema(), Parent: pt.Table()} if err := o.validate(); err != nil { return rep, err @@ -225,7 +228,7 @@ func attachPartitionAt(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Poo ran := false err = runUnderParentLock(ctx, cfg, pool, pt.Schema(), pt.Table(), "the online attach", func(lockedCtx context.Context) error { ran = true - f := attachPartitionFlow{pool: pool, st: st, attach: attach, searchPath: AttemptSearchPath(pt.Schema(), nil), opts: o, tracker: tracker, runStep: runStep, rep: &rep} + f := attachPartitionFlow{pool: pool, st: st, attach: attach, create: create, searchPath: AttemptSearchPath(pt.Schema(), nil), opts: o, tracker: tracker, runStep: runStep, rep: &rep} return f.run(lockedCtx) }) if !ran { @@ -292,9 +295,11 @@ func admitAttachPartition(sql string, pt preflight.PreflightedTable) (statement. // attachPartitionFlow is one run of the online attach under the parent's // advisory lock. type attachPartitionFlow struct { - pool *pgxpool.Pool - st statement.Statement - attach statement.AttachPartition + pool *pgxpool.Pool + st statement.Statement + attach statement.AttachPartition + // create is set when the run first creates the table it attaches. + create bool searchPath []string opts AttachPartitionOptions tracker *progress.Tracker @@ -310,6 +315,11 @@ type attachResolved struct { } func (f attachPartitionFlow) run(ctx context.Context) error { + if f.create { + if err := f.createTable(ctx); err != nil { + return err + } + } r, err := f.resolve(ctx) if err != nil { return err diff --git a/pkg/executor/create_partition_online.go b/pkg/executor/create_partition_online.go new file mode 100644 index 00000000..b9447a5b --- /dev/null +++ b/pkg/executor/create_partition_online.go @@ -0,0 +1,148 @@ +package executor + +import ( + "context" + "fmt" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/block/pg-sprite/pkg/dbconn" + "github.com/block/pg-sprite/pkg/preflight" + "github.com/block/pg-sprite/pkg/progress" + "github.com/block/pg-sprite/pkg/statement" +) + +// The online CREATE TABLE ... PARTITION OF. The plain statement takes +// ACCESS EXCLUSIVE on the parent, so it waits behind every reader and +// writer of the tree and every query queued behind it waits too. This flow +// creates the table standalone, with the parent's columns, which locks the +// parent only to read it, and then runs the online attach of that table +// with the CREATE's own bound, which locks the parent SHARE UPDATE +// EXCLUSIVE. + +// AttachPartitionStepTable is the table the online create of a partition +// creates before it attaches it. +const AttachPartitionStepTable AttachPartitionStepKind = "table" + +// The Action of the table step. +const ( + createPartitionTableCreated = "created" + createPartitionTableFound = "found" +) + +// CreatePartitionOnline runs a reviewed CREATE TABLE name PARTITION OF +// schema.parent FOR VALUES ... online, and returns once the table is a +// partition of the parent. +// +// The statement is a bare CREATE TABLE ... PARTITION OF the +// statement.CreatedPartition reads, on the preflighted partitioned table; a +// statement in another form is refused with statement.ErrCreatePartitionShape +// before anything runs. An unqualified name creates the table in the +// parent's schema, where the plain statement, run under AttemptSearchPath of +// that schema, would create it. Under the parent's advisory table lock +// (LK-1) the run: +// +// 1. creates the table, when it does not exist, as CREATE TABLE name (LIKE +// parent ...) with the parent's columns, their defaults, generation +// expressions, storage, and compression, and its CHECK constraints; the +// table holds no rows, so the CHECKs it is given are validated at once. +// Identity is not copied: a table of its own would draw on a sequence of +// its own, and the attach gives the column the parent's identity on the +// servers whose partitions carry it; +// 2. runs the online attach of that table with the CREATE's own bound (see +// AttachPartitionOnline), which gives it the parent's indexes and +// foreign keys and attaches it without a scan. +// +// A rerun resumes: a table of that name found standalone and empty, as a +// run that stopped before the attach left it, is attached; one found +// attached to the parent is reported as found. A table of that name that +// holds rows is refused with ErrAttachPartitionTable, before anything is +// changed: the plain statement creates a new, empty partition, and would +// fail on a name already taken. +// +// The report is the attach's, with the table step first. +func CreatePartitionOnline(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, o AttachPartitionOptions) (AttachPartitionReport, error) { + return createPartitionAt(ctx, cfg, pool, pt, sql, o, nil, 0) +} + +// CreatePartitionOnlineAsStep is CreatePartitionOnline reported to the run +// step at, as AttachPartitionOnlineAsStep is. +func CreatePartitionOnlineAsStep(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, o AttachPartitionOptions, at RunStep) (AttachPartitionReport, error) { + if err := at.validate(); err != nil { + return AttachPartitionReport{}, err + } + return createPartitionAt(ctx, cfg, pool, pt, sql, o, at.Tracker, at.Step) +} + +func createPartitionAt(ctx context.Context, cfg dbconn.Config, pool *pgxpool.Pool, pt preflight.PreflightedTable, sql string, o AttachPartitionOptions, tracker *progress.Tracker, runStep int) (AttachPartitionReport, error) { + created, ok, err := statement.CreatedPartition(sql) + if err != nil { + return AttachPartitionReport{ParentSchema: pt.Schema(), Parent: pt.Table()}, err + } + if !ok { + return AttachPartitionReport{ParentSchema: pt.Schema(), Parent: pt.Table()}, + fmt.Errorf("%w: not a single CREATE TABLE ... PARTITION OF", statement.ErrCreatePartitionShape) + } + return attachPartitionWith(ctx, cfg, pool, pt, created.AttachSQL, true, o, tracker, runStep) +} + +// createTable creates the table the attach takes, or finds it, and records +// which in the report. +func (f attachPartitionFlow) createTable(ctx context.Context) error { + schema := f.attach.Schema + if schema == "" { + schema = f.attach.ParentSchema + } + table := pgx.Identifier{schema, f.attach.Name}.Sanitize() + action := createPartitionTableFound + err := briefTx{pool: f.pool}.run(ctx, "create the table "+table, f.searchPath, true, func(ctx context.Context, tx pgx.Tx) error { + found, ok, err := relationByName(ctx, tx, schema, f.attach.Name) + if err != nil { + return err + } + if ok { + return refuseTableWithRows(ctx, tx, found) + } + create := createPartitionTableSQL(table, pgx.Identifier{f.attach.ParentSchema, f.attach.Parent}.Sanitize()) + f.started(progress.OperationBrief, create) + if _, err := tx.Exec(ctx, create); err != nil { + return fmt.Errorf("create the table %s: %w", table, err) + } + action = createPartitionTableCreated + return nil + }) + if err != nil { + return err + } + f.record(AttachPartitionStepTable, f.attach.Name, action) + return nil +} + +// refuseTableWithRows refuses a standalone plain table that holds rows. Any +// other relation found under the name is left to the attach, which refuses +// what is not a standalone plain table with the parent's columns and finds +// a table already attached to the parent. +func refuseTableWithRows(ctx context.Context, tx pgx.Tx, found relationFacts) error { + if found.relkind != "r" || found.isPartition { + return nil + } + table := pgx.Identifier{found.schema, found.name}.Sanitize() + var rows bool + if err := tx.QueryRow(ctx, "SELECT EXISTS (SELECT FROM ONLY "+table+")").Scan(&rows); err != nil { + return fmt.Errorf("read whether %s holds rows: %w", table, err) + } + if rows { + return fmt.Errorf("%w: %s already exists and holds rows, and the CREATE makes a new, empty partition", + ErrAttachPartitionTable, table) + } + return nil +} + +// createPartitionTableSQL creates table standalone with parent's columns: +// what CREATE TABLE ... PARTITION OF gives a partition before it attaches +// it, less the identity, which the attach gives. +func createPartitionTableSQL(table, parent string) string { + return "CREATE TABLE " + table + " (LIKE " + parent + + " INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING STORAGE INCLUDING COMPRESSION INCLUDING CONSTRAINTS)" +} diff --git a/pkg/executor/create_partition_online_integration_test.go b/pkg/executor/create_partition_online_integration_test.go new file mode 100644 index 00000000..8f628ace --- /dev/null +++ b/pkg/executor/create_partition_online_integration_test.go @@ -0,0 +1,228 @@ +package executor + +import ( + "context" + "fmt" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/block/pg-sprite/pkg/dbconn" + "github.com/block/pg-sprite/pkg/preflight" + "github.com/block/pg-sprite/pkg/statement" +) + +// These tests run the online CREATE TABLE ... PARTITION OF end to end: the +// table is created standalone and attached online, and the partition it +// leaves is the one the plain statement makes. + +// eventsCreateParent is a range-partitioned table with an identity column, a +// default, a generated column, a column with its own storage and +// compression, a CHECK, a primary key, an index, and a foreign key, and a +// DEFAULT partition holding a row outside the 2027 bound. +const eventsCreateParent = ` + CREATE TABLE %[1]s.accounts ( + id bigint PRIMARY KEY + ); + INSERT INTO %[1]s.accounts VALUES (10); + CREATE TABLE %[1]s.events ( + id bigint GENERATED BY DEFAULT AS IDENTITY, + day date NOT NULL, + note text COMPRESSION pglz DEFAULT 'none', + total int, + cents int GENERATED ALWAYS AS (total * 100) STORED, + account_id bigint, + CONSTRAINT events_pkey PRIMARY KEY (id, day), + CONSTRAINT events_total_check CHECK (total >= 0), + CONSTRAINT events_account_fkey FOREIGN KEY (account_id) REFERENCES %[1]s.accounts (id) + ) PARTITION BY RANGE (day); + ALTER TABLE %[1]s.events ALTER COLUMN note SET STORAGE EXTERNAL; + CREATE INDEX events_note_idx ON %[1]s.events (note); + CREATE TABLE %[1]s.events_2026 PARTITION OF %[1]s.events + FOR VALUES FROM ('2026-01-01') TO ('2027-01-01'); + CREATE TABLE %[1]s.events_default PARTITION OF %[1]s.events DEFAULT; + INSERT INTO %[1]s.events (day, total, account_id) VALUES ('2030-06-01', 1, 10)` + +const createEvents2027Online = `CREATE TABLE %[1]s.events_2027 + PARTITION OF %[1]s.events + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')` + +// createOnline runs the online create of the statement, with %[1]s standing +// for the fixture's schema, preflighting the events table. +func (f attachProofFixture) createOnline(t *testing.T, sql string) (AttachPartitionReport, error) { + t.Helper() + pt, err := preflight.CheckTable(t.Context(), f.pool, f.schema, "events", preflight.NoSizeLimit) + require.NoError(t, err) + return CreatePartitionOnline(t.Context(), dbconn.Config{URL: f.url}, f.pool, pt, fmt.Sprintf(sql, f.schema), attachFlowOptions) +} + +// partitionCatalog describes a partition as the catalog holds it, with every +// name the server derives from the partition's own name, an index's or a +// constraint's, replaced by the name of the parent's index or constraint it +// is attached to, so two partitions of one parent compare equal when they +// differ only in those names. +func (f attachProofFixture) partitionCatalog(t *testing.T, table string) []string { + t.Helper() + rows, err := f.pool.Query(t.Context(), ` + SELECT format('table relkind=%s persistence=%s am=%s options=%s rls=%s partition=%s', + c.relkind, c.relpersistence, c.relam, c.reloptions, c.relrowsecurity, c.relispartition) + FROM pg_class c WHERE c.oid = $1::regclass + UNION ALL + SELECT format('column %s %s collation=%s notnull=%s identity=%s generated=%s storage=%s compression=%s local=%s inherited=%s default=%s', + a.attnum || ' ' || a.attname, format_type(a.atttypid, a.atttypmod), a.attcollation, + a.attnotnull, a.attidentity, a.attgenerated, a.attstorage, a.attcompression, + a.attislocal, a.attinhcount, pg_get_expr(d.adbin, d.adrelid)) + FROM pg_attribute a + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = $1::regclass AND a.attnum > 0 AND NOT a.attisdropped + UNION ALL + SELECT format('constraint %s type=%s def=%s local=%s inherited=%s valid=%s attached=%s', + COALESCE(p.conname, k.conname), k.contype, pg_get_constraintdef(k.oid), + k.conislocal, k.coninhcount, k.convalidated, k.conparentid <> 0) + FROM pg_constraint k + LEFT JOIN pg_constraint p ON p.oid = k.conparentid + WHERE k.conrelid = $1::regclass + UNION ALL + SELECT format('index %s unique=%s primary=%s valid=%s method=%s', + pi.relname, x.indisunique, x.indisprimary, x.indisvalid, + split_part(pg_get_indexdef(x.indexrelid), ' USING ', 2)) + FROM pg_index x + JOIN pg_inherits h ON h.inhrelid = x.indexrelid + JOIN pg_class pi ON pi.oid = h.inhparent + WHERE x.indrelid = $1::regclass + UNION ALL + SELECT 'unattached index ' || x.indexrelid::regclass + FROM pg_index x + WHERE x.indrelid = $1::regclass + AND NOT EXISTS (SELECT 1 FROM pg_inherits h WHERE h.inhrelid = x.indexrelid) + ORDER BY 1`, pgx.Identifier{f.schema, table}.Sanitize()) + require.NoError(t, err) + got, err := pgx.CollectRows(rows, pgx.RowTo[string]) + require.NoError(t, err) + return got +} + +// The online create makes the partition the plain CREATE TABLE ... PARTITION +// OF makes: the same columns, with the parent's defaults, generation, +// storage, compression, and identity, the same CHECK, key, index, and +// foreign key, each attached to or inherited from the parent's, and the same +// bound. A row inserted through the parent lands in it and takes the next +// identity value. A rerun finds the partition and changes nothing. +func TestCreatePartitionOnlineMakesThePartitionThePlainStatementMakes(t *testing.T) { + withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) { + f := newFixture(t) + f.exec(t, eventsCreateParent) + + rep, err := f.createOnline(t, createEvents2027Online) + require.NoError(t, err) + require.NotEmpty(t, rep.Steps) + assert.Equal(t, AttachPartitionStep{Kind: AttachPartitionStepTable, Name: "events_2027", Action: "created"}, rep.Steps[0]) + assert.True(t, rep.Attached) + assert.Equal(t, "events_2027", rep.Table) + assert.Equal(t, "FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')", rep.Bound) + assert.Empty(t, f.proofConstraints(t, "events_2027")) + assert.Empty(t, f.proofConstraints(t, "events_default")) + + // The control: the plain statement, run on a second partition of + // the same parent, gives the partition the catalog the online + // create gave its own. + f.exec(t, `CREATE TABLE %[1]s.events_2028 PARTITION OF %[1]s.events + FOR VALUES FROM ('2028-01-01') TO ('2029-01-01')`) + assert.Equal(t, f.partitionCatalog(t, "events_2028"), f.partitionCatalog(t, "events_2027")) + assert.Equal(t, "FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')", f.partitionBound(t, "events_2027")) + + var id int64 + var landed string + require.NoError(t, f.pool.QueryRow(t.Context(), fmt.Sprintf(`INSERT INTO %s.events (day, total, account_id) + VALUES ('2027-05-01', 2, 10) RETURNING id, tableoid::regclass::text`, pgx.Identifier{f.schema}.Sanitize())).Scan(&id, &landed)) + assert.Equal(t, int64(2), id, "the partition draws on the parent's identity") + assert.Equal(t, f.schema+".events_2027", landed) + + again, err := f.createOnline(t, createEvents2027Online) + require.NoError(t, err) + assert.False(t, again.Attached) + assert.Equal(t, []AttachPartitionStep{{Kind: AttachPartitionStepTable, Name: "events_2027", Action: "found"}}, again.Steps) + }) +} + +// An unqualified name creates the table in the parent's schema, where the +// plain statement under the run's search_path would create it, even when a +// table of that name exists in public. +func TestCreatePartitionOnlineCreatesAnUnqualifiedTableInTheParentsSchema(t *testing.T) { + withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) { + f := newFixture(t) + f.exec(t, eventsCreateParent) + _, err := f.pool.Exec(t.Context(), `CREATE TABLE public.events_2027 (id bigint)`) + require.NoError(t, err) + t.Cleanup(func() { + _, err := f.pool.Exec(context.WithoutCancel(t.Context()), `DROP TABLE public.events_2027`) + assert.NoError(t, err) + }) + + rep, err := f.createOnline(t, `CREATE TABLE events_2027 + PARTITION OF %[1]s.events + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`) + require.NoError(t, err) + assert.True(t, rep.Attached) + assert.Equal(t, f.schema, rep.Schema) + assert.Equal(t, "FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')", f.partitionBound(t, "events_2027")) + }) +} + +// A table an earlier run created and stopped before attaching, standalone and +// empty, is resumed: the rerun finds it and attaches it. +func TestCreatePartitionOnlineResumesATableAStoppedRunLeft(t *testing.T) { + withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) { + f := newFixture(t) + f.exec(t, eventsCreateParent) + f.exec(t, `CREATE TABLE %[1]s.events_2027 (LIKE %[1]s.events + INCLUDING DEFAULTS INCLUDING GENERATED INCLUDING STORAGE INCLUDING COMPRESSION INCLUDING CONSTRAINTS)`) + + rep, err := f.createOnline(t, createEvents2027Online) + require.NoError(t, err) + require.NotEmpty(t, rep.Steps) + assert.Equal(t, AttachPartitionStep{Kind: AttachPartitionStepTable, Name: "events_2027", Action: "found"}, rep.Steps[0]) + assert.True(t, rep.Attached) + }) +} + +// A table of that name that holds rows is refused before anything changes: +// the statement makes a new, empty partition. +func TestCreatePartitionOnlineRefusesATableThatHoldsRows(t *testing.T) { + withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) { + f := newFixture(t) + f.exec(t, eventsCreateParent) + f.exec(t, `CREATE TABLE %[1]s.events_2027 (LIKE %[1]s.events INCLUDING DEFAULTS INCLUDING GENERATED); + INSERT INTO %[1]s.events_2027 (id, day, total) VALUES (5, '2027-02-01', 3)`) + + rep, err := f.createOnline(t, createEvents2027Online) + require.ErrorIs(t, err, ErrAttachPartitionTable) + assert.Empty(t, rep.Steps) + assert.Empty(t, f.partitionBound(t, "events_2027")) + assert.Empty(t, f.proofConstraints(t, "events_2027")) + }) +} + +// A statement that is not a bare CREATE TABLE ... PARTITION OF is refused +// before anything runs. +func TestCreatePartitionOnlineRefusesAnotherShape(t *testing.T) { + withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) { + f := newFixture(t) + f.exec(t, eventsCreateParent) + + _, err := f.createOnline(t, `CREATE TABLE %[1]s.events_default2 + PARTITION OF %[1]s.events + DEFAULT`) + require.ErrorIs(t, err, statement.ErrCreatePartitionShape) + _, err = f.createOnline(t, `ALTER TABLE %[1]s.events + ATTACH PARTITION %[1]s.events_2026 + FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')`) + require.ErrorIs(t, err, statement.ErrCreatePartitionShape) + var exists bool + require.NoError(t, f.pool.QueryRow(t.Context(), `SELECT to_regclass($1) IS NOT NULL`, + pgx.Identifier{f.schema, "events_default2"}.Sanitize()).Scan(&exists)) + assert.False(t, exists) + }) +} diff --git a/pkg/migrate/copy_swap_stopped_doors_test.go b/pkg/migrate/copy_swap_stopped_doors_test.go index 2ed2a5f5..80d92859 100644 --- a/pkg/migrate/copy_swap_stopped_doors_test.go +++ b/pkg/migrate/copy_swap_stopped_doors_test.go @@ -24,6 +24,9 @@ var stoppedRunChecks = []string{ "AdmitStoppedRun", "AdmitPlanStoppedRun", "AdmitRowSecurityStoppedRun", + // The online create of a partition's admission refuses over a run + // stopped on a table of the new partition's name. + "admitCreatePartition", } // executingPackages are the packages whose functions this package calls to diff --git a/pkg/migrate/migrate.go b/pkg/migrate/migrate.go index 4963ada5..4ca2ee28 100644 --- a/pkg/migrate/migrate.go +++ b/pkg/migrate/migrate.go @@ -351,6 +351,11 @@ func runStatement(ctx context.Context, pool *pgxpool.Pool, st statement.Statemen if st.Kind() == statement.KindCreateEnumType { return createEnumType(ctx, pool, st, opts, step, logger) } + if st.Kind() == statement.KindCreateTable { + // Past the gate, a CREATE TABLE is the PARTITION OF the online + // create of a partition takes. + return onlineCreatePartition(ctx, pool, st, opts, step, logger) + } st, err = resolveTarget(ctx, pool, st, logger) if err != nil { return verdict.Verdict{}, err diff --git a/pkg/migrate/migrate_test.go b/pkg/migrate/migrate_test.go index 5d87aa82..deb01fcf 100644 --- a/pkg/migrate/migrate_test.go +++ b/pkg/migrate/migrate_test.go @@ -70,6 +70,27 @@ func TestGate(t *testing.T) { "the library names the concept; each front door attaches its own actionable spelling") }) + // A bare CREATE TABLE ... PARTITION OF runs as the online create of a + // partition, so it passes; one with a clause the online create does not + // carry, such as a DEFAULT bound, is a capability boundary, not a pointer + // at the declarative front door, which refuses a PARTITION OF too. + t.Run("a bare create of a partition passes", func(t *testing.T) { + _, refused := Gate(parse(t, `CREATE TABLE billing.invoices_2027 + PARTITION OF billing.invoices + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`)) + assert.False(t, refused) + }) + + t.Run("a create of a DEFAULT partition is a capability boundary", func(t *testing.T) { + v, refused := Gate(parse(t, `CREATE TABLE billing.invoices_default + PARTITION OF billing.invoices + DEFAULT`)) + require.True(t, refused) + assert.Equal(t, verdict.ReasonUnsupportedStatement, v.Reason) + assert.Equal(t, verdict.ClassCapabilityBoundary, v.Class) + assert.Empty(t, v.Owner) + }) + t.Run("other kinds are unsupported", func(t *testing.T) { v, refused := Gate(parse(t, "DROP TABLE t")) require.True(t, refused) diff --git a/pkg/migrate/online_create_partition.go b/pkg/migrate/online_create_partition.go new file mode 100644 index 00000000..9e4ac1c1 --- /dev/null +++ b/pkg/migrate/online_create_partition.go @@ -0,0 +1,231 @@ +package migrate + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/block/pg-sprite/pkg/executor" + "github.com/block/pg-sprite/pkg/preflight" + "github.com/block/pg-sprite/pkg/statement" + "github.com/block/pg-sprite/pkg/verdict" +) + +// ErrCreatePartitionAcknowledgement means an acknowledgement was given for +// a CREATE TABLE ... PARTITION OF, which runs only as the online create of +// a partition: it never runs through copy-and-swap, discards nothing, and +// has no blocking form to force. Nothing has executed. +var ErrCreatePartitionAcknowledgement = errors.New("the acknowledgement does not apply to the online create of a partition") + +// gateCreatePartition is the statement-type gate for a CREATE TABLE. A bare +// CREATE TABLE name PARTITION OF parent FOR VALUES ... proceeds, to run as +// the online create of a partition. A PARTITION OF in another form is a +// capability boundary that names the clause the online create does not +// take. Any other CREATE TABLE is not a partition, and handled is false. +func gateCreatePartition(st statement.Statement) (v verdict.Verdict, refused, handled bool) { + _, ok, err := statement.CreatedPartition(st.SQL()) + if errors.Is(err, statement.ErrCreatePartitionShape) { + return verdict.Verdict{ + Statement: st.SQL(), + Detail: fmt.Sprintf("%v; pg-sprite creates a partition online only from that form, so create the table with LIKE the parent "+ + "and run ALTER TABLE ... ATTACH PARTITION, or run this statement directly against the database", err), + }.WithRefusal(verdict.CapabilityBoundary(verdict.ReasonUnsupportedStatement)), true, true + } + if err != nil { + // The statement parsed once already; a CREATE the reader cannot + // take keeps the gate's refusal of a CREATE TABLE. + return verdict.Verdict{}, false, false + } + return verdict.Verdict{}, false, ok +} + +// createPartitionRequest is a CREATE TABLE ... PARTITION OF the gate +// admitted: the partition it creates and the ATTACH that attaches it, +// which names the partitioned parent every verdict and plan reports on. +type createPartitionRequest struct { + created statement.CreatePartition + attach statement.Statement +} + +// schema is the schema the new table is created in: the parent's when the +// statement does not qualify the table. +func (r createPartitionRequest) schema() string { + if r.created.Attach.Schema != "" { + return r.created.Attach.Schema + } + return r.created.Attach.ParentSchema +} + +// AdmitCreatePartition is the dry run's forecast of the checks [Run] makes +// of a CREATE TABLE ... PARTITION OF before it reads the parent: every +// acknowledgement is a usage error (ErrCreatePartitionAcknowledgement), a +// parent the online attach does not take, such as an unqualified one, is +// refused, and so is a copy-and-swap run stopped on a table of the new +// partition's name, each with the verdict Run gives. On admission it +// returns the ATTACH the statement describes, whose table is the +// partitioned parent the plan reports on. The parent's preflight, the +// privilege checks, and every check the online attach makes under its lock +// stay the run's. +func AdmitCreatePartition(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, opts Options) (statement.Statement, verdict.Verdict, bool, error) { + req, v, refused, err := admitCreatePartition(ctx, pool, st, opts) + return req.attach, v, refused, err +} + +// admitCreatePartition makes the checks AdmitCreatePartition names. A +// refusal's verdict reports the submitted statement on the parent. +func admitCreatePartition(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, opts Options) (createPartitionRequest, verdict.Verdict, bool, error) { + if err := rejectCreatePartitionAcks(opts); err != nil { + return createPartitionRequest{}, verdict.Verdict{}, false, err + } + created, _, err := statement.CreatedPartition(st.SQL()) + if err != nil { + return createPartitionRequest{}, verdict.Verdict{}, false, err + } + attach, err := statement.ParseOne(created.AttachSQL) + if err != nil { + return createPartitionRequest{}, verdict.Verdict{}, false, err + } + req := createPartitionRequest{created: created, attach: attach} + if err := executor.AdmitAttachPartitionShape(created.AttachSQL); err != nil { + r, refused := onlineAttachRefusal(err) + if !refused { + return req, verdict.Verdict{}, false, err + } + v := admissionRefusalVerdict(attach, err, r, false) + v.Statement = st.SQL() + return req, v, true, nil + } + // A copy-and-swap run stopped on a table of the new partition's name + // would meet the table the create makes, or attaches, so the create is + // refused over it. + v, refused, err := refuseOverStoppedRun(ctx, pool, st, req.schema(), created.Attach.Name) + if err != nil { + return req, verdict.Verdict{}, false, err + } + return req, v, refused, nil +} + +// onlineCreatePartition runs a bare CREATE TABLE name PARTITION OF parent +// FOR VALUES ... as the online create of a partition and ends in one +// verdict, whose table is the partitioned parent. As written the statement +// takes ACCESS EXCLUSIVE on the parent and queues behind every reader of +// the tree; the online create makes the table standalone and runs the +// online attach of it with the statement's own bound +// (executor.CreatePartitionOnline), so the parent is never locked against +// reads or writes. +// +// The parent must be schema-qualified, as the online attach's is. The +// connected role needs the index-build tier on the parent, since the attach +// builds the parent's indexes on the new table, and the right to create in +// the new table's schema: the parent's, when the name is unqualified. A +// copy-and-swap run stopped on a table of the new partition's name refuses +// it; none can stand on the parent, since copy-and-swap refuses a +// partitioned table. +// +// The refusals are the online attach's (onlineAttachRefusal), each decided +// before anything is created or given to the table. Every other stop is a +// failed verdict: what the earlier steps made stays, and running the same +// statement again resumes. +func onlineCreatePartition(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, opts Options, step int, logger *slog.Logger) (verdict.Verdict, error) { + req, v, refused, err := admitCreatePartition(ctx, pool, st, opts) + if err != nil { + return verdict.Verdict{}, err + } + if refused { + return v, nil + } + v, err = runOnlineCreatePartition(ctx, pool, st, req, opts, step, logger) + v.Statement = st.SQL() + return v, err +} + +// runOnlineCreatePartition preflights the parent and the role and runs the +// online create of an admitted request. +func runOnlineCreatePartition(ctx context.Context, pool *pgxpool.Pool, st statement.Statement, req createPartitionRequest, + opts Options, step int, logger *slog.Logger) (verdict.Verdict, error) { + attach := req.attach + pt, err := preflight.CheckTable(ctx, pool, attach.Schema(), attach.Table(), preflight.NoSizeLimit) + if err != nil { + return verdict.Verdict{}, err + } + priv, err := preflight.CheckPrivileges(ctx, pool, attach.Schema(), attach.Table(), + preflight.Requirement{Tier: preflight.TierIndexBuild}) + if privErr, ok := errors.AsType[*preflight.PrivilegeError](err); ok { + return privilegeVerdict(attach, privErr, false), nil + } + if err != nil { + return verdict.Verdict{}, err + } + if _, err := preflight.CheckCreatePrivileges(ctx, pool, req.schema()); err != nil { + if privErr, ok := errors.AsType[*preflight.PrivilegeError](err); ok { + return privilegeVerdict(attach, privErr, false), nil + } + return verdict.Verdict{}, fmt.Errorf("verify creation access for %s.%s: %w", req.schema(), req.created.Attach.Name, err) + } + logger.Debug("privilege preflight passed", "role", priv.Role(), "owner", priv.Owner(), "tier", preflight.TierIndexBuild.String()) + if err := checkPartitionedIndexConnection(ctx, pool, opts); err != nil { + return verdict.Verdict{}, fmt.Errorf("migrate: %w", err) + } + logger.Debug("routing a CREATE TABLE ... PARTITION OF to the online create", "table", qualified(attach), "partition", req.created.Attach.Name) + start := time.Now() + rep, err := executor.CreatePartitionOnlineAsStep(ctx, opts.Connection, pool, pt, st.SQL(), executor.AttachPartitionOptions{ + Attach: opts.Budget.Brief, + Validate: opts.Budget.Validate, + Index: opts.Budget.Concurrent, + HolderWait: opts.retry().HolderWait, + }, opts.runStep(step)) + elapsed := time.Since(start) + if err != nil { + if r, refused := onlineAttachRefusal(err); refused { + v := admissionRefusalVerdict(attach, err, r, false) + logger.Debug("online create of a partition refused", "reason", string(v.Reason), "class", string(v.Class), "elapsed", elapsed) + return v, nil + } + v := onlineAttachFailureVerdict(attach, err) + logger.Debug("online create of a partition failed", "code", v.Code, "elapsed", elapsed) + return v, fmt.Errorf("run schema change on %s: %w", qualified(attach), err) + } + logger.Debug("online create of a partition committed", "table", qualified(attach), "partition", rep.Table, + "attached", rep.Attached, "steps", len(rep.Steps), "elapsed", elapsed) + return verdict.Verdict{ + Outcome: verdict.OutcomeExecuted, + Table: qualified(attach), + Detail: onlineCreatePartitionDetail(rep), + }, nil +} + +// onlineCreatePartitionDetail says what a finished online create did, in +// one sentence. +func onlineCreatePartitionDetail(rep executor.AttachPartitionReport) string { + partition := fmt.Sprintf("%s.%s", rep.Schema, rep.Table) + if !rep.Attached { + return fmt.Sprintf("%s was already a partition %s; pg-sprite dropped any proof CHECK an earlier run left and changed nothing else", partition, rep.Bound) + } + return fmt.Sprintf("pg-sprite created %s with the parent's columns without locking the parent against reads or writes, gave it what the "+ + "partitioned parent requires while writes continued (indexes built concurrently and validated foreign keys: %d steps), then attached it %s "+ + "in one brief transaction that scanned and built nothing", partition, len(rep.Steps), rep.Bound) +} + +// rejectCreatePartitionAcks refuses every acknowledgement given for the +// online create of a partition. +func rejectCreatePartitionAcks(opts Options) error { + switch { + case opts.Force != "": + return fmt.Errorf("%w: a CREATE TABLE ... PARTITION OF runs only online, so there is no blocking form to force; nothing was executed", + ErrCreatePartitionAcknowledgement) + case opts.CopySwap.Restart != "": + return fmt.Errorf("%w: creating a partition never runs through copy-and-swap; nothing was executed", + ErrCreatePartitionAcknowledgement) + case opts.CopySwap.BlockWrites != "": + return fmt.Errorf("%w: block-writes names a table to fence, and creating a partition never runs through copy-and-swap; nothing was executed", + ErrCreatePartitionAcknowledgement) + case opts.AllowDestructive != "": + return fmt.Errorf("%w: creating a partition discards nothing; nothing was executed", + ErrCreatePartitionAcknowledgement) + } + return nil +} diff --git a/pkg/migrate/online_create_partition_integration_test.go b/pkg/migrate/online_create_partition_integration_test.go new file mode 100644 index 00000000..9788b966 --- /dev/null +++ b/pkg/migrate/online_create_partition_integration_test.go @@ -0,0 +1,101 @@ +package migrate_test + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/block/pg-sprite/pkg/migrate" + "github.com/block/pg-sprite/pkg/verdict" +) + +// These tests run a CREATE TABLE ... PARTITION OF through migrate.Run: it +// runs as the online create of a partition, which creates the table +// standalone and attaches it online, instead of the plain statement's +// ACCESS EXCLUSIVE on the parent. + +// createOrders2028 creates a 2028 partition of the orders table +// ordersToAttach makes. +const createOrders2028 = ` + CREATE TABLE %[1]s.orders_2028 + PARTITION OF %[1]s.orders + FOR VALUES FROM ('2028-01-01') TO ('2029-01-01')` + +func TestRunCreatesAPartitionOnline(t *testing.T) { + withAttachServer(t, func(t *testing.T, newSchema func(t *testing.T) (*pgxpool.Pool, migrate.Options, string)) { + // While a reader holds ACCESS SHARE on orders, the plain statement + // waits for ACCESS EXCLUSIVE and fails on its lock budget. Run + // creates orders_2028 and attaches it with the parent's key and + // CHECK without waiting on the reader, and reports the change on the + // partitioned parent. The same statement again finds the partition + // and changes nothing. + t.Run("runs as the online create beside a reader of the parent", func(t *testing.T) { + pool, opts, schema := newSchema(t) + reader, err := pool.Begin(t.Context()) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, reader.Rollback(context.WithoutCancel(t.Context()))) }) + _, err = reader.Exec(t.Context(), fmt.Sprintf(`SELECT count(*) FROM %s.orders`, schema)) + require.NoError(t, err) + + plain, err := pool.Begin(t.Context()) + require.NoError(t, err) + _, err = plain.Exec(t.Context(), `SET LOCAL lock_timeout = '200ms'`) + require.NoError(t, err) + _, err = plain.Exec(t.Context(), fmt.Sprintf(` + CREATE TABLE %[1]s.orders_plain + PARTITION OF %[1]s.orders + FOR VALUES FROM ('2030-01-01') TO ('2031-01-01')`, schema)) + var pgErr *pgconn.PgError + require.True(t, errors.As(err, &pgErr), "the plain statement waits on the reader: %v", err) + assert.Equal(t, "55P03", pgErr.Code) + require.NoError(t, plain.Rollback(t.Context())) + + sql := fmt.Sprintf(createOrders2028, schema) + v, err := migrate.Run(t.Context(), pool, parseOne(t, sql), opts) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeExecuted, v.Outcome) + assert.Equal(t, schema+".orders", v.Table) + assert.Equal(t, sql, v.Statement) + assert.Equal(t, "FOR VALUES FROM ('2028-01-01') TO ('2029-01-01')", partitionBoundOf(t, pool, schema, "orders_2028")) + // The parent's key and CHECK; no proof CHECK is left. + assert.Equal(t, 2, constraintsOn(t, pool, schema, "orders_2028")) + + again, err := migrate.Run(t.Context(), pool, parseOne(t, sql), opts) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeExecuted, again.Outcome) + assert.Equal(t, 2, constraintsOn(t, pool, schema, "orders_2028")) + }) + + // The online attach takes only a schema-qualified parent, so an + // unqualified one is refused before anything is created. + t.Run("refuses an unqualified parent", func(t *testing.T) { + pool, opts, schema := newSchema(t) + + v, err := migrate.Run(t.Context(), pool, parseOne(t, fmt.Sprintf(` + CREATE TABLE %[1]s.orders_2028 + PARTITION OF orders + FOR VALUES FROM ('2028-01-01') TO ('2029-01-01')`, schema)), opts) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeRefused, v.Outcome) + assert.Equal(t, verdict.ReasonUnsupportedStatement, v.Reason) + assert.False(t, tableExists(t, pool, schema, "orders_2028")) + }) + + // The statement has no blocking form the engine would substitute, + // so --force names nothing to override and is a usage error. + t.Run("refuses an acknowledgement", func(t *testing.T) { + pool, opts, schema := newSchema(t) + opts.Force = schema + ".orders_2028" + + _, err := migrate.Run(t.Context(), pool, parseOne(t, fmt.Sprintf(createOrders2028, schema)), opts) + require.ErrorIs(t, err, migrate.ErrCreatePartitionAcknowledgement) + assert.False(t, tableExists(t, pool, schema, "orders_2028")) + }) + }) +} diff --git a/pkg/migrate/verdicts.go b/pkg/migrate/verdicts.go index 858ffdf2..9f3bb9c9 100644 --- a/pkg/migrate/verdicts.go +++ b/pkg/migrate/verdicts.go @@ -42,6 +42,11 @@ func Gate(st statement.Statement) (verdict.Verdict, bool) { "or run this statement directly against the database", }.WithRefusal(verdict.CapabilityBoundary(verdict.ReasonUnsupportedStatement)), true } + if st.Kind() == statement.KindCreateTable { + if v, refused, handled := gateCreatePartition(st); handled { + return v, refused + } + } r, refused := gateRefusal(st.Kind(), st.Concurrent(), st.IndexTarget()) if !refused { return verdict.Verdict{}, false diff --git a/pkg/plan/plan.go b/pkg/plan/plan.go index 1397c372..81d48a2e 100644 --- a/pkg/plan/plan.go +++ b/pkg/plan/plan.go @@ -110,7 +110,10 @@ import ( // Version 46 added the statement-level resumes field, which the statement // of a stopped copy-and-swap run carries with the copy-and-swap route and // backend in place of the route against the table's current shape. -const FormatVersion = 46 +// Version 47 added the online-create-partition execution contract and its +// part in the fingerprint, which a CREATE TABLE ... PARTITION OF carries in +// a migrate --dry-run plan. +const FormatVersion = 47 // Source identifies which front door derived the plan. type Source string @@ -634,6 +637,31 @@ func RouteOnlineAttach(report *Report) error { return nil } +// RouteOnlineCreatePartition routes, in an alter-source report on the +// partitioned parent, the executing CREATE TABLE ... PARTITION OF ... FOR +// VALUES the router planned to run as written to the online create of a +// partition: its one step is the statement itself, with the execution +// online-create-partition. The imperative dry run calls it for a statement +// migrate.AdmitCreatePartition admitted. A statement that is not such a +// CREATE, or does not execute, is left alone. +func RouteOnlineCreatePartition(report *Report) error { + for i := range report.Statements { + st := &report.Statements[i] + if st.Disposition != router.DispositionExecute { + continue + } + _, creates, err := statement.CreatedPartition(st.SQL) + if err != nil { + return fmt.Errorf("route the online create of a partition: %w", err) + } + if !creates { + continue + } + routeToPartitionedBuild(st, planner.ExecutionOnlineCreatePartition) + } + return nil +} + // ResumeStoppedRun marks the one statement of an alter-source report as // the statement of the copy-and-swap run stopped on the report's table, // which the run resumes in place of the route the router chose against the @@ -1002,15 +1030,15 @@ func (r Report) ComputeFingerprint() string { // hashesExecution reports whether the fingerprint covers a statement's // execution: one whose exec_sql is the statement as written and whose // execution decides how it runs — the partitioned index, key, and foreign -// key builds, the online attach, and the accepted blocking drop of a -// partitioned table's index. +// key builds, the online attach and create of a partition, and the accepted +// blocking drop of a partitioned table's index. // Every other execution is derived from exec_sql and keeps the identity it // always had. func hashesExecution(e planner.Execution) bool { switch e { case planner.ExecutionPartitionedIndexBuild, planner.ExecutionPartitionedKeyBuild, planner.ExecutionPartitionedForeignKeyBuild, planner.ExecutionBlockingIndexDrop, - planner.ExecutionOnlineAttach: + planner.ExecutionOnlineAttach, planner.ExecutionOnlineCreatePartition: return true default: return false diff --git a/pkg/plan/plan_test.go b/pkg/plan/plan_test.go index ae9f8af2..2b657bbb 100644 --- a/pkg/plan/plan_test.go +++ b/pkg/plan/plan_test.go @@ -893,7 +893,7 @@ func TestDiscloseGreenfieldExecutionRequiresAbsentTable(t *testing.T) { } // The JSON shape is the adapter-facing contract: exact keys, exact -// omissions. A consumer pins format_version 46 against this test. +// omissions. A consumer pins format_version 47 against this test. func TestReportJSONShape(t *testing.T) { exists := true r := plan.Report{ @@ -962,7 +962,7 @@ func TestReportJSONShape(t *testing.T) { raw, err := json.Marshal(r) require.NoError(t, err) assert.JSONEq(t, fmt.Sprintf(`{ - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "public", "table": "t", @@ -1033,7 +1033,7 @@ func TestReportJSONOmitsUnsetOptionalFields(t *testing.T) { raw, err := json.Marshal(r) require.NoError(t, err) assert.JSONEq(t, `{ - "format_version": 46, + "format_version": 47, "source": "alter", "disposition": "execute", "fingerprint": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", @@ -1079,7 +1079,7 @@ func TestResumeStoppedRunPlansTheResume(t *testing.T) { raw, err := json.Marshal(r) require.NoError(t, err) assert.JSONEq(t, fmt.Sprintf(`{ - "format_version": 46, + "format_version": 47, "source": "alter", "schema": "app", "table": "orders", @@ -1186,7 +1186,7 @@ func TestReportJSONAdvisoriesShape(t *testing.T) { raw, err := json.Marshal(r) require.NoError(t, err) assert.JSONEq(t, `{ - "format_version": 46, + "format_version": 47, "source": "diff", "schema": "public", "table": "t", @@ -1475,7 +1475,7 @@ func TestFingerprintCoversExtensionSchemas(t *testing.T) { } // Sources is the closed vocabulary a consumer branches on; the set is -// pinned to format_version 46. +// pinned to format_version 47. func TestSourcesVocabularyPinned(t *testing.T) { assert.Equal(t, []plan.Source{plan.SourceAlter, plan.SourceDiff}, plan.Sources()) } diff --git a/pkg/planner/planner.go b/pkg/planner/planner.go index 3e34fb0a..8f97af3b 100644 --- a/pkg/planner/planner.go +++ b/pkg/planner/planner.go @@ -321,6 +321,16 @@ const ( // earlier steps finished on the new table; running the same statement // again resumes from it. ExecutionOnlineAttach Execution = "online-attach" + // ExecutionOnlineCreatePartition: the one step is a CREATE TABLE ... + // PARTITION OF ... FOR VALUES, and it runs as the online create of a + // partition, not as the statement: the table is created standalone with + // the parent's columns, which does not lock the parent against reads or + // writes, and then attached by the online attach (ExecutionOnlineAttach) + // with the statement's own bound. The statement must not be run as + // written, which would take ACCESS EXCLUSIVE on the parent. A failed or + // interrupted run leaves the table and what the attach finished on it; + // running the same statement again resumes from it. + ExecutionOnlineCreatePartition Execution = "online-create-partition" ) // Executions returns the closed set of Execution values. It is part of the @@ -328,7 +338,7 @@ const ( // format_version bump, and a consumer that meets an unrecognized value must // treat the sequence as unknown and refuse to run it. func Executions() []Execution { - return []Execution{ExecutionAutocommit, ExecutionPartitionedIndexBuild, ExecutionBlockingIndexDrop, ExecutionPartitionedKeyBuild, ExecutionPartitionedForeignKeyBuild, ExecutionOnlineAttach} + return []Execution{ExecutionAutocommit, ExecutionPartitionedIndexBuild, ExecutionBlockingIndexDrop, ExecutionPartitionedKeyBuild, ExecutionPartitionedForeignKeyBuild, ExecutionOnlineAttach, ExecutionOnlineCreatePartition} } // Decision is the classification of one operation. diff --git a/pkg/statement/create_partition.go b/pkg/statement/create_partition.go new file mode 100644 index 00000000..22fb917a --- /dev/null +++ b/pkg/statement/create_partition.go @@ -0,0 +1,134 @@ +package statement + +import ( + "errors" + "fmt" + "slices" + + pganalyze "github.com/pganalyze/pg_query_go/v6" +) + +// ErrCreatePartitionShape is returned for a CREATE TABLE ... PARTITION OF +// whose form the online create of a partition does not take: anything but +// a bare CREATE TABLE name PARTITION OF parent FOR VALUES ..., with no +// column list, constraint, IF NOT EXISTS, persistence, storage parameter, +// tablespace, access method, or partition key of its own, and a bound that +// is not DEFAULT. +var ErrCreatePartitionShape = errors.New("the online create of a partition takes only a bare CREATE TABLE name PARTITION OF parent with a FOR VALUES bound") + +// CreatePartition is a lone CREATE TABLE ... PARTITION OF ... FOR VALUES: +// the partition it creates, as the attach of a table of that name to the +// parent describes it, and that ATTACH statement. +type CreatePartition struct { + // Attach is the parent, the new table, each as the grammar spelled it + // (an empty schema when unqualified), and the bound. + Attach AttachPartition + // AttachSQL is ALTER TABLE parent ATTACH PARTITION table with the + // statement's own bound, deparsed from the parse tree of the CREATE: + // the relation names and the bound node are the CREATE's, unchanged. + AttachSQL string +} + +// CreatedPartition returns the CREATE TABLE ... PARTITION OF a statement +// is. ok is false for every other statement. A PARTITION OF in a form the +// online create does not take returns ErrCreatePartitionShape naming the +// clause. +func CreatedPartition(sql string) (CreatePartition, bool, error) { + node, err := parseSingle(sql) + if err != nil { + return CreatePartition{}, false, err + } + create := node.GetCreateStmt() + if create == nil || create.GetPartbound() == nil { + return CreatePartition{}, false, nil + } + if err := refuseCreatePartitionShape(create); err != nil { + return CreatePartition{}, false, err + } + parent := create.GetInhRelations()[0].GetRangeVar() + attach := &pganalyze.Node{Node: &pganalyze.Node_AlterTableStmt{AlterTableStmt: &pganalyze.AlterTableStmt{ + Relation: parent, + Objtype: pganalyze.ObjectType_OBJECT_TABLE, + Cmds: []*pganalyze.Node{{Node: &pganalyze.Node_AlterTableCmd{AlterTableCmd: &pganalyze.AlterTableCmd{ + Subtype: pganalyze.AlterTableType_AT_AttachPartition, + Def: &pganalyze.Node{Node: &pganalyze.Node_PartitionCmd{PartitionCmd: &pganalyze.PartitionCmd{ + Name: create.GetRelation(), + Bound: create.GetPartbound(), + }}}, + Behavior: pganalyze.DropBehavior_DROP_RESTRICT, + }}}}, + }}} + attachSQL, err := deparseOne(attach) + if err != nil { + return CreatePartition{}, false, fmt.Errorf("deparse the attach of partition %s: %w", create.GetRelation().GetRelname(), err) + } + want, err := partitionBound(create.GetPartbound()) + if err != nil { + return CreatePartition{}, false, err + } + // The deparsed ATTACH is read back and must name the same tables and + // bound as the CREATE, or it is not the statement the CREATE described. + got, ok, err := AttachedPartition(attachSQL) + if err != nil { + return CreatePartition{}, false, fmt.Errorf("read back the attach of partition %s: %w", create.GetRelation().GetRelname(), err) + } + expected := AttachPartition{ + ParentSchema: parent.GetSchemaname(), + Parent: parent.GetRelname(), + Schema: create.GetRelation().GetSchemaname(), + Name: create.GetRelation().GetRelname(), + Bound: want, + } + if !ok || !sameAttach(got, expected) { + return CreatePartition{}, false, fmt.Errorf("%w: the attach deparsed from %q reads back as %+v, not %+v", + ErrUnexpectedPartitionBound, sql, got, expected) + } + return CreatePartition{Attach: expected, AttachSQL: attachSQL}, true, nil +} + +// refuseCreatePartitionShape returns ErrCreatePartitionShape for a clause of +// create the online create of a partition does not carry to the standalone +// table it builds. +func refuseCreatePartitionShape(create *pganalyze.CreateStmt) error { + refuse := func(clause string) error { + return fmt.Errorf("%w: the statement has %s", ErrCreatePartitionShape, clause) + } + switch { + case len(create.GetInhRelations()) != 1 || create.GetInhRelations()[0].GetRangeVar() == nil: + return refuse("no single partitioned parent") + case create.GetPartbound().GetIsDefault(): + return refuse("a DEFAULT bound") + case len(create.GetTableElts()) > 0: + return refuse("a column list or table constraint") + case len(create.GetConstraints()) > 0: + return refuse("a table constraint") + case create.GetIfNotExists(): + return refuse("IF NOT EXISTS") + case create.GetRelation().GetRelpersistence() != "p": + return refuse("TEMPORARY or UNLOGGED") + case create.GetPartspec() != nil: + return refuse("a PARTITION BY of its own") + case len(create.GetOptions()) > 0: + return refuse("storage parameters (WITH ...)") + case create.GetTablespacename() != "": + return refuse("a TABLESPACE") + case create.GetAccessMethod() != "": + return refuse("an access method (USING ...)") + case create.GetOncommit() != pganalyze.OnCommitAction_ONCOMMIT_NOOP: + return refuse("ON COMMIT") + } + return nil +} + +// sameAttach reports whether two attaches name the same tables and bound. +func sameAttach(a, b AttachPartition) bool { + return a.ParentSchema == b.ParentSchema && a.Parent == b.Parent && + a.Schema == b.Schema && a.Name == b.Name && sameBound(a.Bound, b.Bound) +} + +// sameBound reports whether two bounds have the same form and values. +func sameBound(a, b PartitionBound) bool { + return a.Default == b.Default && a.Strategy == b.Strategy && + a.Modulus == b.Modulus && a.Remainder == b.Remainder && + slices.Equal(a.List, b.List) && slices.Equal(a.Lower, b.Lower) && slices.Equal(a.Upper, b.Upper) +} diff --git a/pkg/statement/create_partition_test.go b/pkg/statement/create_partition_test.go new file mode 100644 index 00000000..19caf663 --- /dev/null +++ b/pkg/statement/create_partition_test.go @@ -0,0 +1,127 @@ +package statement_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/block/pg-sprite/pkg/statement" +) + +// A lone CREATE TABLE ... PARTITION OF reads as the attach of a table of the +// same name to the parent, with the statement's own bound: the tables as +// spelled, schema-qualified or not, and the bound's values unchanged in the +// ATTACH statement it derives. +func TestCreatedPartitionDerivesTheAttach(t *testing.T) { + for name, tc := range map[string]struct { + sql string + attach statement.AttachPartition + want string + }{ + "a range bound, qualified": { + sql: ` + CREATE TABLE app.orders_2027 + PARTITION OF app.orders + FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + attach: statement.AttachPartition{ + ParentSchema: "app", Parent: "orders", Schema: "app", Name: "orders_2027", + Bound: statement.PartitionBound{ + Strategy: statement.PartitionByRange, + Lower: []statement.BoundDatum{{Kind: statement.BoundValue, Value: "2027-01-01"}}, + Upper: []statement.BoundDatum{{Kind: statement.BoundValue, Value: "2028-01-01"}}, + }, + }, + want: `ALTER TABLE app.orders ATTACH PARTITION app.orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + }, + "a list bound with NULL, the new table unqualified": { + sql: ` + CREATE TABLE "Events EU" + PARTITION OF app.events + FOR VALUES IN ('eu', NULL)`, + attach: statement.AttachPartition{ + ParentSchema: "app", Parent: "events", Name: "Events EU", + Bound: statement.PartitionBound{ + Strategy: statement.PartitionByList, + List: []statement.BoundDatum{{Kind: statement.BoundValue, Value: "eu"}, {Kind: statement.BoundNull}}, + }, + }, + want: `ALTER TABLE app.events ATTACH PARTITION "Events EU" FOR VALUES IN ('eu', NULL)`, + }, + "a hash bound": { + sql: ` + CREATE TABLE app.accounts_p3 + PARTITION OF app.accounts + FOR VALUES WITH (MODULUS 8, REMAINDER 3)`, + attach: statement.AttachPartition{ + ParentSchema: "app", Parent: "accounts", Schema: "app", Name: "accounts_p3", + Bound: statement.PartitionBound{Strategy: statement.PartitionByHash, Modulus: 8, Remainder: 3}, + }, + want: `ALTER TABLE app.accounts ATTACH PARTITION app.accounts_p3 FOR VALUES WITH (MODULUS 8, REMAINDER 3)`, + }, + "a range bound with MINVALUE and MAXVALUE": { + sql: ` + CREATE TABLE app.events_low + PARTITION OF app.events + FOR VALUES FROM (MINVALUE, MINVALUE) TO ('2027-02-01', MAXVALUE)`, + attach: statement.AttachPartition{ + ParentSchema: "app", Parent: "events", Schema: "app", Name: "events_low", + Bound: statement.PartitionBound{ + Strategy: statement.PartitionByRange, + Lower: []statement.BoundDatum{{Kind: statement.BoundMinValue}, {Kind: statement.BoundMinValue}}, + Upper: []statement.BoundDatum{{Kind: statement.BoundValue, Value: "2027-02-01"}, {Kind: statement.BoundMaxValue}}, + }, + }, + // The deparser spells MINVALUE and MAXVALUE in lower case, which the + // grammar reads as the same bound. + want: `ALTER TABLE app.events ATTACH PARTITION app.events_low FOR VALUES FROM (minvalue, minvalue) TO ('2027-02-01', maxvalue)`, + }, + } { + t.Run(name, func(t *testing.T) { + got, ok, err := statement.CreatedPartition(tc.sql) + require.NoError(t, err) + require.True(t, ok) + assert.Equal(t, tc.attach, got.Attach) + assert.Equal(t, tc.want, got.AttachSQL) + }) + } +} + +// Every other statement is not a CREATE TABLE ... PARTITION OF, including a +// plain CREATE TABLE and the ATTACH itself. +func TestCreatedPartitionIgnoresOtherStatements(t *testing.T) { + for _, sql := range []string{ + `CREATE TABLE app.orders (id bigint)`, + `CREATE TABLE app.orders_copy (LIKE app.orders)`, + `ALTER TABLE app.orders ATTACH PARTITION app.orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + } { + _, ok, err := statement.CreatedPartition(sql) + require.NoError(t, err, sql) + assert.False(t, ok, sql) + } +} + +// A clause the online create would have to carry to the standalone table +// it builds, or a bound the online attach cannot prove, is refused with +// ErrCreatePartitionShape: the statement is a PARTITION OF, but not one this +// route runs. +func TestCreatedPartitionRefusesShapesItDoesNotCarry(t *testing.T) { + for clause, sql := range map[string]string{ + "a DEFAULT bound": `CREATE TABLE app.orders_other PARTITION OF app.orders DEFAULT`, + "a column option": `CREATE TABLE app.orders_2027 PARTITION OF app.orders (status DEFAULT 'old') FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + "a table constraint": `CREATE TABLE app.orders_2027 PARTITION OF app.orders (CONSTRAINT qty_small CHECK (qty < 10)) FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + "IF NOT EXISTS": `CREATE TABLE IF NOT EXISTS app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + "UNLOGGED": `CREATE UNLOGGED TABLE app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + "a sub-partition key": `CREATE TABLE app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01') PARTITION BY LIST (region)`, + "storage parameters": `CREATE TABLE app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01') WITH (fillfactor = 70)`, + "a tablespace": `CREATE TABLE app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01') TABLESPACE fast`, + "an access method": `CREATE TABLE app.orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01') USING heap`, + "a temporary partition": `CREATE TEMP TABLE orders_2027 PARTITION OF app.orders FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, + } { + t.Run(clause, func(t *testing.T) { + _, ok, err := statement.CreatedPartition(sql) + require.ErrorIs(t, err, statement.ErrCreatePartitionShape) + assert.False(t, ok) + }) + } +}