Repository navigation
fix(plan): reject FK ON DELETE/UPDATE SET NULL over NOT NULL child columns (#30282) - #30925
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
All CI legs are green at head |
|
mo-bot review · Commit: "interrupted" |
…lumns (matrixorigin#30282) MySQL error 1830 (ER_FK_COLUMN_NOT_NULL): a foreign key declared with an ON DELETE or ON UPDATE SET NULL action must not name a NOT NULL child column, because the action could never write NULL at runtime. MatrixOne accepted the definition at CREATE TABLE and ALTER TABLE ADD CONSTRAINT time; the DELETE action then silently kept the old child value (leaving an orphan) and the UPDATE action failed only at first parent update. - new moerr.ErrFkColumnNotNull (20483) mapped to ER_FK_COLUMN_NOT_NULL with MySQL's exact message text - shared checkFkSetNullColumnsRequireNullable validator consulted by CREATE TABLE, INPLACE ALTER ... ADD CONSTRAINT, and COPY ALTER ... ADD CONSTRAINT; primary-key implied NOT NULL columns are covered - recovery replay keeps historical layouts buildable (replay guard) - planner tests + BVT fk_issue_30282.sql/.result Co-authored-by: daviszhen <[email protected]>
…xorigin#30282) mo-tester renders errors carrying a mapped MySQL code without the "internal error:" prefix; the CI compose+proxy run expects the bare message.
91c33b6 to
e3cdf29
Compare
|
Rebased onto |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 91f26777ee71efa73c86ccd23e2be49739488b9d
Assessment: request_changes
Reviewed the complete six-file delta and affected callers. Shared DDL validation is the appropriate design, and the earlier forward-binding and simple ALTER cases now pass. However, name-based comparison of old nullability permits an ALTER bypass that still produces silent orphans.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
- P1
pkg/sql/plan/build_ddl.go:8187: Create child(pid INT, other INT NOT NULL) with a SET NULL foreign key on pid, then execute ALTER TABLE child DROP COLUMN other, CHANGE pid other INT NOT NULL.
Impact: The ALTER succeeds and installs an impossible SET NULL constraint. A subsequent parent DELETE succeeds, removes the parent, and leaves the child referencing its deleted value.
Evidence: oldNotNull is keyed by name, so the renamed FK column incorrectly inherits the exemption belonging to the removed column. CHANGE preserves ColId; compare old and final nullability using that identity. Current-head SQL probes reproduced both DROP-plus-rename and rename-away-plus-rename variants: SHOW CREATE retained NOT NULL with ON DELETE SET NULL; parent count became 0 while child other remained 1. tests.log lines 1715–1735 and 1842–1861 retain the results. Add regression coverage for name reuse.
Validation:
-
Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/741bb347650b2d5ab23413b2/attempt-1; review-evidence.json and final-audit-index.json correlate commands, source fingerprints, receipts and log hashes.
-
Isolation preflight passed. All 192 native inputs matched; repository provenance verification passed after restoring the retained compiler profile. The initial profile mismatch is retained separately.
-
run-tests.sh used the supplied test-exec and a test-only overlay. All six PR planner tests and seven SQL control groups passed; two name-reuse cases failed with demonstrated orphans. Receipt 1792836464526862427-4.json records exit 1.
-
Supplied exact-head CI reports successful build, UT, SCA and PROXY/PESSIMISTIC BVT checks.
-
Final evidence audit passed: clean frozen source, complete patch match, unique error code and reconciled results; receipt 1792836564434959760-4.json.
Limitations:
-
No separate linked-issue body or raw CI case logs were supplied.
-
Historical restore compatibility and performance were assessed from source, without local restore or benchmark runs. Added work is bounded DDL-only map construction; SELECT/DML execution paths are unchanged.
…matrixorigin#30282) Review round 3: CHANGE/RENAME preserve a column's ColId, while its name can be reused by a different physical column inside one ALTER (DROP COLUMN other, CHANGE pid other ... NOT NULL, or renaming the old column away first). A name-keyed comparison inherited the dropped column's NOT NULL exemption and reinstalled an impossible SET NULL constraint, orphaning child rows on the next parent DELETE. The surviving-constraint guard now compares pre- and post-ALTER nullability by ColId. UT: helper-level name-reuse scenarios plus end-to-end mock ALTER coverage for both review variants; BVT records both 1830 rejections and the legal rename-and-tighten once the constraint is dropped.
|
Review round-3 finding addressed at head Root cause confirmed. The surviving-constraint guard keyed the pre-ALTER NOT NULL set by column name, so a column renamed onto the name of a column dropped (or renamed away) by the same ALTER inherited the dropped column's exemption and reinstalled an impossible SET NULL constraint. Fix. Tests
Live verification on a single-node instance running a binary built at this head (sha256
|
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 1d3e13e8ea63765981e04bbc517cacf484a210e0
Assessment: request_changes
Reviewed the complete six-file delta and affected callers. Shared nullability validation and identity-based ALTER comparison are sound, and the earlier bypasses are addressed. However, the new CREATE validation breaks maintenance of legacy layouts that the PR explicitly preserves.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
- P2
pkg/sql/plan/build_ddl.go:4598: An existing or restored table has a NOT NULL child column with an historically accepted SET NULL foreign key. Execute TRUNCATE TABLE child or an unfiltered DELETE FROM child.
Impact: Both operations now fail with error 1830. Scope.TruncateTable recreates the unchanged table through internal CREATE without this replay marker, so the new guard treats physical reconstruction as new constraint admission. Extend the trusted reconstruction contract to these paths while retaining validation for newly authored constraints and nullability tightening.
Evidence: TestReviewLegacyRecreate seeds the legacy layout through the existing replay owner, then uses ordinary frontend SQL. At HEAD, COPY ADD COLUMN succeeds, but TRUNCATE and unfiltered DELETE fail with 1830 (legacy-head.log, lines 1283 and 1308; receipt 1792843139854506560-4.json, exit 1). The identical test passes with all three changed production files replaced by their exact merge-base blobs (legacy-base.log; receipt 1792843167801026006-3.json, exit 0). Add regression coverage for these unchanged-schema reconstruction paths.
Validation:
-
Evidence is retained under /home/xupeng/.local/state/mo-bot/jobs/c206b86b994bd6f96bf977ad/attempt-1. review-evidence.json and final-audit-index.json correlate commands, source fingerprints, receipts, logs and artifact hashes.
-
Isolation preflight and repository native-provenance verification passed; all 192 native inputs matched the frozen source. Tests used the supplied test-exec.
-
Production SQL probes confirmed rejection after fresh FK installation, including within one transaction, and successful nullable SET NULL actions and unrelated composite-primary-key changes.
-
Combined INPLACE ADD FK/MODIFY probes failed on both HEAD and merge-base; the preexisting duplicate-constraint failure was excluded from findings. Explicit COPY controls passed.
-
Supplied exact-head CI reports successful build, UT, SCA and BVT checks. Final audit passed with clean source, matching complete patch and reconciled terminal receipts: 1792843245799614473-4.json.
Limitations:
-
No separate linked-issue body or raw CI case logs were supplied.
-
Legacy metadata was seeded through the existing replay context; this was not a full upgrade or snapshot-restore run.
-
Performance was assessed from source without benchmarks: added work is bounded DDL metadata processing, with no new per-row SELECT/DML work.
…ble (matrixorigin#30282) Review round 4: TRUNCATE and the truncate-optimized unfiltered DELETE physically reconstruct the table through the internal executor, which re-plans SHOW CREATE output as an ordinary CREATE TABLE. The 1830 guard for newly authored SET NULL constraints fired on that trusted reconstruction, so a pre-validation layout (NOT NULL child column with a historically accepted SET NULL foreign key) could no longer be truncated or bulk-deleted. Extend the trusted-reconstruction contract: StatementOption gains WithTrustedForeignKeyLayout, bridged through defines.TrustedForeignKeyLayout by the internal SQL executor, and the CREATE-side 1830 gate skips only when that marker is present. TRUNCATE/unfiltered-DELETE recreate sets it, mirroring the sibling ALTER ... COPY replica. User-authored CREATE TABLE keeps failing with 1830.
|
Round-4 P2 addressed at head Root cause confirmed. TRUNCATE and the truncate-optimized unfiltered DELETE recreate the table via the internal SQL executor, which re-plans Fix. The trusted-reconstruction contract now covers these paths end to end:
Tests
Live verification (single-node instance): the legacy layout was seeded by the pristine pre-validation binary into a persistent volume — an exact old-version-upgrade scenario — then the instance was restarted on a binary built at this head (sha256 No new BVT case: the legacy layout cannot be authored at this head by user SQL (that is the point of 1830), so coverage lives in the planner UT plus this live two-version verification. |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 4af80f2dc500e3b7e353ded6e0f6c1ffe9367f9b
Assessment: approve
Reviewed the complete 11-file delta, affected callers and prior review concerns. Shared schema validation, column-identity comparison and statement-scoped reconstruction trust form a coherent fix. Earlier findings are addressed; no actionable defects remain. Added work is bounded DDL metadata processing.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
Validation:
-
Reused supplied exact-head successful build, UT, SCA and PROXY/PESSIMISTIC BVT results.
-
Isolation preflight and repository native-provenance verification passed; all 192 native inputs matched the frozen source.
-
Six focused probe groups passed using test-exec: legacy child/parent COPY ALTER, TRUNCATE, unfiltered DELETE with affected-row checks, subsequent ordinary CREATE rejection, self-reference reconstruction and internal-executor trust isolation. Receipt: 1792873070082719664-4.json; log: legacy-current.log.
-
Final audit verified clean source, complete patch correspondence, formatting, unique error code and command/source/exit/log consistency. Receipt: 1792873176941549856-5.json.
-
Evidence retained under /home/xupeng/.local/state/mo-bot/jobs/9233fac4cd9e1c95a00de601/attempt-1 in review-evidence.json and final-audit-index.json.
Limitations:
-
No separate linked-issue body or raw CI case logs were supplied.
-
Local legacy layouts were seeded through the existing replay owner; no full upgrade or snapshot-restore run was performed.
-
Performance was assessed from source without benchmarks; no new per-row SELECT/DML work was identified.
Merge Queue Status
This pull request spent 4 minutes 6 seconds in the queue, with no time running CI. ReasonPull request #30925 has been dequeued Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.
HintYou should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it. Waiting for any of
All conditions
Tick the box to put this pull request back in the merge queue (same as
|
What type of PR is this?
Which issue(s) this PR fixes:
issue #30282
What this PR does / why we need it:
Rejects at DDL time a foreign key declared
ON DELETE SET NULLorON UPDATE SET NULLover aNOT NULLchild column — MySQL error 1830(
ER_FK_COLUMN_NOT_NULL, "Column 'x' cannot be NOT NULL: needed in a foreignkey constraint 'fk' SET NULL"). Such an action could never write
NULLatruntime; MatrixOne accepted the definition, and the observed consequences
were:
ON DELETE SET NULL: deleting the parent "succeeded" but kept the childrow unchanged → silent orphan
ON UPDATE SET NULL: the parent update failed at runtime with error 3819,far away from the DDL that created the trap
ALTER TABLE ADD CONSTRAINT(issue comments)Changes
pkg/common/moerr/error.go: new internal errorErrFkColumnNotNull(20483) mapped to
ER_FK_COLUMN_NOT_NULL(MySQL 1830) with MySQL's exactmessage text; constructor
NewErrFkColumnNotNull.pkg/sql/plan/build_ddl.go:checkFkSetNullColumnsRequireNullable— consulted byboth CREATE TABLE (after the primary-key pass, so PK-implied NOT NULL
is caught) and INPLACE
ALTER ... ADD CONSTRAINTDefault.NullAbility(authoritative), withNotNull/Typ.NotNullablefallbacks for catalog-loaded definitionsreplay != nil) skips the check so layouts accepted onolder versions stay buildable during restore
pkg/sql/plan/build_alter_table.go: same validation in the COPY-ALTERadd-FK path, against the final schema view (a
NOT NULLcolumnintroduced by an earlier action of the same ALTER is caught)
pkg/sql/plan/issue_30282_test.go(SQL-driven planner tests fordelete/update/PK-implied/self-reference + direct helper coverage) and BVT
test/distributed/cases/foreign_key/fk_issue_30282.sql/.result(coversCREATE TABLE, ALTER ADD CONSTRAINT, COPY-mode ALTER, plus nullable
positive controls)
Verification
go test ./pkg/sql/planFK/DDL suite green;pkg/common/moerrgreenthe issue reproduction (and both comment variants, incl.
ALTER TABLE / COPY ALTER / self-reference) now fails with
ERROR 1830 (HY000): Column 'parent_id' cannot be NOT NULL: needed in a foreign key constraint 'fk_...' SET NULL, byte-identical to the checked-ingolden; nullable positive controls still succeed and install the constraint