Skip to content

fix: drop CHECKs referencing only the dropped column in ALTER TABLE - #31010

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30956-main-81e68bac
Oct 24, 2026
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-30956-main-81e68bac

Conversation

@gouhongshen

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #30956

What this PR does / why we need it:

ALTER TABLE ... DROP COLUMN failed with error 1054 whenever a CHECK constraint referenced only the dropped column: the COPY-alter planner kept the constraint metadata, and the rebuilt table definition tried to bind the dead column reference. MySQL removes such single-column CHECKs implicitly; MatrixOne could neither do that nor drop the column, so a trivial, legal DROP COLUMN was blocked. CHECKs referencing other columns were collapsed into the same unbound path instead of being rejected with MySQL error 3959.

Root causes (three layers, each red-probed on its reviewed predecessor)

  1. Base defect (the issue): the COPY-alter planner copied every CHECK into the temporary table definition and rebound it against the post-drop schema, producing invalid input: column 'v' does not exist or cannot be referenced by a generated column for any CHECK that referenced only the dropped column.
  2. Persisted-expression replay, replacement case: on the replay path a same-statement replacement (DROP COLUMN v auto-drops ck(v>0), the same ALTER re-adds v and ck(w>0)) could inherit the old persisted expression because positional expressions compare equal; the constraint displayed CHECK (w > 0) but enforced v > 0, and COPY accepted rows violating the authored constraint.
  3. Persisted-expression replay, retained case: an OriginSql-text guard used to fix (2) misclassified retained CHECKs rewritten by a same-ALTER RENAME/CHANGE COLUMN as new declarations, so they were rebound from the temporary CREATE text under the ALTER session's div_precision_increment: a division bound at increment 10 (decimal(22,12)) came back as decimal(16,6) at the default (scale 2 at increment 0), so previously valid rows failed COPY validation and empty-table alters persisted changed constraint semantics.

Exact changes

  • pkg/sql/plan/build_alter_check.go: classify every CHECK on the source table by column dependency: a CHECK whose expression references only the dropped column(s) is dropped together with the column; a CHECK still referencing surviving columns rejects with MySQL 3959 (Check constraint '%s' uses column '%s', hence column cannot be dropped or renamed.); auto-dropped CHECK names are released so a same-statement ADD CONSTRAINT of the same name is valid.
  • pkg/common/moerr/error.go: new ErrDependentByCheckConstraint (20483) mapped to MySQL 3959, with its constructor; message text byte-identical to MySQL's.
  • pkg/sql/plan/build_alter_add_column.go: DropColumn invokes the CHECK classification before positional handling (mirrors MySQL's prepare_check_constraints_for_alter).
  • pkg/sql/plan/ddl_expression_replay.go: the persisted-expression replay distinguishes a retained CHECK from a same-name replacement by column identity: a same-name, expression-equal CHECK replays its preserved bound expression only when every referenced original column still resolves by ColId in the COPY target (RENAME/CHANGE preserve ColIds; a replacement's original columns were dropped, so its IDs cannot resolve). Retained CHECKs keep their creation-time bound semantics (division scale preserved through RENAME/CHANGE regardless of the session's div_precision_increment); replacements bind their own authored expression.
  • Tests, planner level (pkg/sql/plan/build_alter_check_test.go): dependency classification incl. plan-level atomicity (source TableDef untouched), the replacement binding proof through the real execution replay wrapper (WithAlterTableDDLReplay + replan of CreateTmpTableSql), and rename precision preservation (decimal(22,12) survives an ALTER planned under default precision; OriginSql follows the rename).
  • Tests, SQL level (test/distributed/cases/ddl/alter_table_check_constraints.sql/.result): the issue reproduction with retained rows, an unrelated-column control, multi-column 3959 rejection with full failure atomicity, same-name re-add/replace enforcement (land/reject insert pairs), rename division-scale preservation under differing div_precision_increment (row-bearing and empty-table forms), and the pre-existing explicit ADD/DROP CHECK scenarios.

Issue-to-test proof

  • TestAlterRenameRetainedCheckPreservesBoundPrecision: RED on the reviewed predecessor of layer 3 (decimal(16,6) vs required decimal(22,12)), PASS on unmodified base (layers 2/3 defects existed only inside this branch's earlier revisions), GREEN after the fix; TestAlterDropColumnReplacementCheckBindsAuthoredColumn (layer 2) likewise red-then-green.
  • Focused planner batch over the whole replay/ALTER surface: 596 PASS / 0 FAIL; full go test ./pkg/sql/plan: ok 115.817s; gofmt/go vet clean; golangci-lint --new-from-rev clean.
  • Isolated-cluster runtime over the MySQL protocol (binary built from this branch at base 5fe68a88e4): issue reproduction succeeds with the row retained; atomic 3819 rejection leaves columns/constraint/row fully intact; replacement enforcement discriminated by the (2,-5,9) reject vs (2,5,-9) accept pair; rename scenario created at div_precision_increment=10 and altered at 0 succeeds, keeps satisfying rows, and keeps rejecting violating inserts.
  • BVT comparison via mo-tester on the extended case: two consecutive runs, 316/316 SUCCESS each (299 pre-existing statements + 17 new).

Residual risks

  • A same-statement replacement whose authored SQL is byte-identical to the original still replays the original expression; the authored intent is identical by construction, so the installed expression is semantically equivalent (covered by the replacement-order BVT scenarios).
  • Retained CHECKs whose referenced columns carry ColId == 0 (synthetic LIKE skeletons) keep the previous name-resolution acceptance; their declarations are unchanged in the reconstructed skeleton.
  • Any reference the identity walk cannot resolve safely skips the replay and rebinds from the CREATE text (the conservative path), so a classification miss degrades to a rebind rather than to a wrong binding.

### Root cause

`ALTER TABLE ... DROP COLUMN` failed with 1054 when a CHECK constraint
referenced only the dropped column: the COPY-alter planner kept the
constraint metadata, and the rebuilt table bound the dead column reference.
MySQL implicitly removes such single-column CHECKs; MatrixOne could neither
do that nor drop the column. CHECKs referencing surviving columns were
collapsed into the same unbound path instead of rejecting with MySQL 3959.

Two latent defects sat on the alter-copy expression replay and were proven by
counterexamples on this branch:

- a same-statement replacement (DROP COLUMN v auto-drops ck(v>0); the same
  ALTER re-adds v and ck(w>0)) could inherit the old persisted expression
  because positional expressions compare equal, so COPY accepted rows
  violating the authored constraint;
- a retained CHECK rewritten by RENAME/CHANGE was rebound from the temporary
  CREATE text under the ALTER session's div_precision_increment, silently
  changing its division scale and rejecting previously valid rows during
  COPY.

### Exact change

- pkg/sql/plan/build_alter_check.go: classify every CHECK on the source
  table by column dependency; drop the ones referencing only the dropped
  column(s) together with the column, reject a surviving CHECK that still
  references the column with MySQL 3959, and release auto-dropped names for
  same-statement ADD admission.
- pkg/common/moerr/error.go: ErrDependentByCheckConstraint (20483) mapped to
  MySQL 3959 with MySQL's message text.
- pkg/sql/plan/build_alter_add_column.go: DropColumn invokes the CHECK
  classification (mirrors MySQL's prepare_check_constraints_for_alter).
- pkg/sql/plan/ddl_expression_replay.go: the replay distinguishes a retained
  CHECK from a same-name replacement by column identity - a same-name,
  expression-equal CHECK replays its preserved bound expression only when
  every referenced original column still resolves by ColId in the COPY
  target (RENAME/CHANGE preserve ColIds; a replacement's original columns
  were dropped). Retained CHECKs keep creation-time bound semantics;
  replacements bind their own authored expression.
- pkg/sql/plan/build_alter_check_test.go: dependency classification with
  plan-level atomicity, replacement binding through the real execution
  replay wrapper, and rename division-scale preservation.
- test/distributed/cases/ddl/alter_table_check_constraints.sql/.result:
  issue reproduction, unrelated-column control, 3959 rejection with failure
  atomicity, re-add/replace enforcement pairs, and rename scale preservation
  under differing div_precision_increment.

### Proof

- RED on assigned base 5fe68a8: the issue repro returns 1054; each later
  layer red-probed on its reviewed predecessor before fixing; the rename
  precision probe is GREEN on unmodified base (layers 2/3 exist only inside
  this branch's earlier revisions).
- GREEN: focused planner batch 596 PASS / 0 FAIL; full pkg/sql/plan
  ok 115.817s; golangci-lint --new-from-rev, gofmt and go vet clean.
- Isolated-cluster runtime over the MySQL protocol (binary built from this
  branch at base 5fe68a8): issue repro succeeds with the row retained;
  atomic 3819 rejection with full intactness; land/reject insert pairs
  discriminating replacement and rename-precision semantics.
- BVT via mo-tester on the extended case: two consecutive 316/316 runs.

Related to matrixorigin#30956.
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH

XuPeng-SH commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 327961a72a1f5d522df846aa67adb3c4beeb5657

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: 327961a72a1f5d522df846aa67adb3c4beeb5657

Assessment: approve

Reviewed the complete seven-file delta and affected callers. The design keeps CHECK dependency handling in the COPY planner and bound-expression preservation in the existing replay owner. It correctly distinguishes automatically dropped constraints, replacements and retained constraints without changing catalog formats. Boundary, failure-atomicity, compatibility and test-quality review found no actionable defects. Added work is confined to DDL planning and replay.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1

Validation:

  • Eight focused top-level planner tests passed, including all new regressions and existing replay controls: 131 PASS records, zero failures, count=1, using the supplied test-exec. Receipt: checks/1792806948255722329-3.json; retained output: focused-tests.log.

  • Isolation preflight passed. All 192 tracked native inputs matched the reused build, and the current repository provenance checker accepted it. Receipts: checks/1792806714668975604-3.json, checks/1792806759720362953-3.json and checks/1792806759944225405-30.json.

  • Reused the supplied exact-head successful build, unit-test, static-analysis and BVT results. Inspected workflow selection and confirmed the changed SQL case belongs to the included DDL group.

  • Final audit verified the exact HEAD, merge base, unchanged source, commands, exit receipts and retained logs. Audit receipt: checks/1792807053825010698-3.json. Evidence and assessment are retained under /home/xupeng/.local/state/mo-bot/jobs/b9e8772c5aea1d788e8a9d2b/attempt-1 in review-evidence-audit.json and review-record.json.

Limitations:

  • SQL BVT was not repeated locally. Broader coverage relies on the supplied frozen-head CI snapshot; per-case CI logs and author-reported execution artifacts were unavailable. Author-reported counts were not treated as independently verified executions.

  • No base/head performance benchmark was run. Source tracing found bounded DDL-only overhead and no added per-row SELECT/DML work, I/O, locks or background state.

  • The linked issue's independent body was unavailable; its behavioral contract was assessed from the supplied PR description.

@mergify mergify Bot added the queued label Oct 24, 2026
@mergify

mergify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-24 01:59 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-24 02:55 UTC · at 12a740e0d5746a7637a9d1bcd1c0c24b1f33897b · squash

This pull request spent 55 minutes 52 seconds in the queue, including 55 minutes 36 seconds running CI.

Required conditions to merge

@mergify
mergify Bot merged commit 12a740e into matrixorigin:main Oct 24, 2026
29 of 30 checks passed
@mergify mergify Bot removed the queued label Oct 24, 2026

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants