Repository navigation
fix(postgres): keep USING clause out of COMMENT ON COLUMN when altering ENUM - #18254
xianjianlf2 wants to merge 10 commits into
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 Walkthrough
🚥 Pre-merge checks | ✅ 5
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Comments in this are unnecessarily verbose, and in the age of AI, can be misleading . In addition this does not conform to our coding style and can be confusing to users. We should use the same if statement styles used on line 70, so at least its consistent. Second, Although I am aware comments are done similarly for table comments, I don't particularly like just doing normal generation and then using regex to find and replace it? Sure it doesn't run very often, but this is just a bad practice we want to avoid for the future. Ideally, It would be better to have it handled in a way which is more programmatic in nature and extensible to other databases. |
fd5eb0b to
da87c13
Compare
|
Thanks for the review — good points, reworked it. Instead of splicing the I agree the broader |
da87c13 to
f391101
Compare
4a4c21a to
29c8d6e
Compare
|
Synced with the latest upstream/main at Local validation:
The focused core test runner could not start locally because the interrupted optional |
There was a problem hiding this comment.
Thanks for tackling #17894. The approach works for the simple case, but the split happens after the string has already been mangled, so the target scenario is still broken for many real comments. Requesting changes for the three points below; the rest are suggestions.
Note: this review was written with Claude Code Every point is open to discussion, as long as the argument is grounded in test cases: if you can show a test that passes where I claim it fails (or the other way round), that settles it.
Blocking
1. Move the ; COMMENT ON COLUMN split before dataTypeMapping() (line 146)
dataTypeMapping() runs first and applies /^ENUM\(.+\)/ greedily to the whole string, comment included. As soon as the comment contains a ), the regex consumes through the comment, the sentinel is gone, and we get the wrong output:
queryInterface.changeColumn('t', 'c', {
type: DataTypes.ENUM('a', 'b'),
allowNull: false,
comment: 'Amount (in cents)',
});produces DROP NOT NULL instead of SET NOT NULL, no COMMENT ON COLUMN statement at all, and TYPE "public"."enum_t_c"' with a stray quote, which is a syntax error. The same ordering bites non-ENUM columns too: an INTEGER column with comment 'legacy SERIAL id' hits the includes('SERIAL') branch and emits TYPE ;.
The split needs to happen on the raw attributes[attributeName] before calling dataTypeMapping(), which is what createTableQuery already does at lines 68-75.
2. pgEnum() still receives the unsplit string (line 172)
Even with (1) fixed, this.pgEnum(tableName, attributeName, attributes[attributeName]) passes the original string, and pgEnum has its own greedy match(/^ENUM\(.+\)/). With a comment containing ) the COMMENT ON COLUMN text ends up inside the DO 'BEGIN CREATE TYPE ... ' body, which is invalid PL/pgSQL, so the enum type is never created and the whole changeColumn fails. Pass the comment-stripped string here.
Something like:
for (const attributeName in attributes) {
let rawDefinition = attributes[attributeName];
let columnComment = '';
const i = rawDefinition.indexOf('; COMMENT ON COLUMN ');
if (i !== -1) {
// Move comment to a separate query
columnComment = `${rawDefinition.slice(i + 1)};`;
rawDefinition = rawDefinition.slice(0, i);
}
let definition = this.dataTypeMapping(tableName, attributeName, rawDefinition);
let attrSql = '';
// ...
if (rawDefinition.startsWith('ENUM(')) {
attrSql += this.pgEnum(tableName, attributeName, rawDefinition);
definition += ` USING (${this.quoteIdentifier(attributeName)}::${this.pgEnumName(tableName, attributeName)})`;
}3. Test coverage doesn't exercise the failing case
The new fixture uses 'my comment'. Changing it to 'my comment (v2)' reproduces both bugs above on this branch without any assertion failing. Please:
- change the unit fixture (or add a second one) so the comment contains parentheses;
- add an integration test in
packages/core/test/integration/query-interface/changeColumn.test.jsthat changes a column to an ENUM with a comment and checks the result viadescribeTable. The existing ENUM cases there have no comment and the comment case there is anINTEGER, so #17894 currently never runs against a real Postgres.
Non-blocking
- Dead code (lines 173-176).
definition.replace(/^ENUM\(.+\)/, this.pgEnumName(...))can never match here, becausedataTypeMapping()already did the identical replace on the same string. It can go, leaving only theUSING (...)append (as in the snippet above). - Anchor the sentinel more tightly.
indexOf('; COMMENT ON COLUMN')finds the first occurrence anywhere, so an ENUM value or DEFAULT literal containing that text would be split mid-literal. Contrived, but it's a new failure path. Matching on the full; COMMENT ON COLUMN ${quoteTable(table)}.${quoteIdentifier(key)} ISprefix avoids it. - Sentinel is a hand-written copy of the template. The string emitted at
attributeToSQLline 327 and the one parsed here have nothing tying them together; a reformat of either silently reintroduces #17894. A small private helper that builds theCOMMENT ON COLUMNstatement, used by bothattributeToSQLand this method, would close that gap. Fine to leave for a follow-up.
Longer term the cleaner fix is to stop smuggling a second statement through the definition string and have changeColumnQuery receive the attribute object (as addColumnQuery does), but that's out of scope for this PR.
|
Based on what your review just brought up. I think that we really should just not support comments or make them a first-class property that is handled correctly rather than just riding along the define like you said. Comments in general are pretty scary while we still have regex running the show, as your enum/array cases show. While the actual surface area of a vunerablity is super low since its really something in migrations, trying to handle everything that could possibly be thrown into a comment seems like a fools errand. |
|
Addressed the blocking review points on the latest upstream/main:
The first CI run exposed only an incorrect test expectation: PostgreSQL |
628fe16 to
ecbf191
Compare
WikiRik
left a comment
There was a problem hiding this comment.
Thanks both. I re-tested this branch and main against a real PostgreSQL 17, and I think the answer to @SippieCup's point is: this should go in as-is, and the first-class-comment work belongs in a separate issue.
Why this is more than a one-symptom patch
@SippieCup is right that chasing every string a user might put in a comment would be a fools errand. But this branch does not do that. It splits the comment off the definition before any type parsing runs, so comment text never reaches the regexes at all. That closes the whole class rather than one case, which is why comments that have nothing to do with enums start working too.
changeColumn on PostgreSQL, comparing main against this branch:
| Column change | main |
this branch |
|---|---|---|
ENUM, comment Amount (in cents) |
unterminated quoted string |
pass |
INTEGER, comment legacy SERIAL id |
syntax error at or near ";" |
pass |
INTEGER, comment was PRIMARY KEY once |
comment silently stored as was once |
pass |
STRING, comment do NOT NULL this |
comment stored as do this, column silently set NOT NULL |
pass |
STRING, comment the DEFAULT value |
syntax error at or near "the" |
pass |
STRING, comment must be UNIQUE |
pass | pass |
STRING, comment REFERENCES other table |
syntax error at or near "table" |
pass |
The two silent rows are the ones that worried me most. On main a comment containing the words NOT NULL rewrites the user's comment text and makes the column non-nullable when they never asked for it.
What I pushed
I pushed one commit to your branch:
- Regression tests for the rest of that table, so the class is pinned rather than the single parenthesis case. Six of the seven fail on
main. - The same comment split applied to
addColumnQuery, which had the identical bug and was already reported as #17118. Before the fix,addColumnwith an enum and a comment ending in)producedALTER TABLE "addc" ADD COLUMN "col" "public"."enum_addc_col"';and failed withunterminated quoted string. The commit closes that issue too.
Everything else here is your work, and the approach is yours.
The refactor
Agreed that comments riding along on the definition string is the real problem. I have opened #18362 to collect options rather than settle it here, and it is explicit that no direction is decided. Worth saying plainly: dropping comment support is not on the table, since comment is a documented attribute option and createTable/addColumn carry it through the same mechanism.
Two unrelated changeColumn bugs turned up while testing, both pre-existing and both fixed separately in #18361: the USING cast for ARRAY(ENUM) targeted the scalar enum type, and changing a column to an ENUM with a defaultValue failed on statement ordering. That PR also touches changeColumnQuery, so whichever of the two lands second will need a small rebase.
Clearing my change request now.
Review by Claude Code (Claude Opus 5).
|
For anyone reviewing this later: a few follow-ups came out of this PR, listed here so the relationship is visible.
#18361 edits the same #18362 tracks the underlying structural problem these all work around: the PostgreSQL generators reconstruct column definitions by parsing generated SQL strings rather than reading the attribute object. No direction is decided there. |
…ng ENUM
When changing an ENUM column that also has a comment, `changeColumnQuery`
appended the `USING (...)` cast to the end of the generated definition. The
comment is emitted as a trailing `; COMMENT ON COLUMN ... IS '...'` statement,
so the cast ended up after it, producing invalid SQL:
COMMENT ON COLUMN "t"."c" IS 'comment' USING ("c"::"public"."enum_t_c")
PostgreSQL does not support a USING clause on COMMENT ON COLUMN, causing a
syntax error during `sync({ alter: true })`. Insert the USING clause before the
comment statement so it stays attached to the ALTER COLUMN ... TYPE statement.
Closes sequelize#17894
Co-Authored-By: Claude Fable 5 <[email protected]>
Apply the same comment split to addColumnQuery that changeColumnQuery already does, so the comment statement is removed before dataTypeMapping runs. Fixes the enum-with-parenthesised-comment failure and the case where a comment contains SERIAL. Closes sequelize#17118 Co-Authored-By: Claude Opus 5 <[email protected]>
…n test `special` is not declared on `ColumnDescription`, so asserting it broke the TS Typings job. Assert on `type` instead, which is part of the type. Co-Authored-By: Claude Opus 5 <[email protected]>
Co-authored-by: Rik Smale <[email protected]>
53d3886 to
d6b124c
Compare
Resolve conflicts with sequelize#18361 by retaining enum array casts, deferred defaults and uniqueness handling alongside the existing comment separation. Add integration coverage combining comments with enum arrays and defaults. Assisted-by: OpenAI Codex Signed-off-by: MarkXian <[email protected]>
Head branch was pushed to by a user without write access
|
Synced with main in 6c724a3 and moved the add-column regression test to the new TypeScript file, preserving the existing fixes. All 13 packages build; 119 focused unit tests and 25 PostgreSQL 17 integration tests pass, along with lint and formatting checks. |
Pull Request Checklist
Description of Changes
PostgreSQL column comments were processed as part of the SQL type definition during
changeColumnandaddColumn. Parentheses in ENUM comments could corrupt type parsing, and SQL keywords inside comments could alter the generated column definition. The ENUMUSINGcast could also end up attached toCOMMENT ON COLUMN, producing invalid SQL.Separate the generated trailing comment statement before mapping the type or processing constraints, then append it after the column alteration. Comment text therefore stays out of type, default, nullability, and reference parsing.
The branch is synchronized with main through b856a0f, preserving #18361's ENUM array casts, unique handling, and deferred default assignment. Two integration regressions combine comment handling with ENUM array conversion and changing an existing default. Both fail against main's query generator and pass with this fix.
Closes #17894.
Validation after synchronization:
yarn build: all 13 packages passed.changeColumnandadd-columnintegration tests on an isolated PostgreSQL 18.4 instance: 25 passed, including both new regressions.git diff --checkpassed for the follow-up changes.AI assistance: OpenAI Codex assisted with conflict resolution, regression tests, review, and validation.
List of Breaking Changes
None.
Validation update (2026-09-22)
Merged upstream main (53359f9), retaining attributeToSql/column normalization and the comment separation fix. Validation: all 13 packages built; PostgreSQL SQL unit tests 115 passed; addColumn/changeColumn integration tests against PostgreSQL 17: 25 passed; core/postgres type checks and changed-file Prettier/ESLint passed. Head ce42476.