Skip to content

fix(postgres): keep USING clause out of COMMENT ON COLUMN when altering ENUM - #18254

Open
xianjianlf2 wants to merge 10 commits into
sequelize:mainfrom
xianjianlf2:fix/postgres-enum-comment-using-17894
Open

xianjianlf2 wants to merge 10 commits into
sequelize:mainfrom
xianjianlf2:fix/postgres-enum-comment-using-17894

Conversation

@xianjianlf2

@xianjianlf2 xianjianlf2 commented Jul 13, 2026 •

Copy link
Copy Markdown

Pull Request Checklist

  • Have you added new tests to prevent regressions?
  • If a documentation update is necessary, have you opened a PR to the documentation repository? (Not needed for this bug fix.)
  • Did you update the typescript typings accordingly (if applicable)? (No public type changes.)
  • Does the description below contain a link to an existing issue or a description of the issue you are solving?
  • Does the name of your PR follow our conventions?

Description of Changes

PostgreSQL column comments were processed as part of the SQL type definition during changeColumn and addColumn. Parentheses in ENUM comments could corrupt type parsing, and SQL keywords inside comments could alter the generated column definition. The ENUM USING cast could also end up attached to COMMENT 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.
  • PostgreSQL query-generator and change-column SQL unit tests: 137 passed.
  • changeColumn and add-column integration tests on an isolated PostgreSQL 18.4 instance: 25 passed, including both new regressions.
  • Core and Postgres type checks passed.
  • ESLint, Prettier, and git diff --check passed 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.

@xianjianlf2
xianjianlf2 requested a review from a team as a code owner July 13, 2026 12:03
@xianjianlf2
xianjianlf2 requested review from ephys and sdepold July 13, 2026 12:03
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

PostgreSQL ENUM column alteration now separates embedded column comments from type definitions. The USING clause remains on the ALTER COLUMN ... TYPE statement. A unit test verifies the separate COMMENT ON COLUMN statement.

Changes: PostgreSQL ENUM column alteration

Layer / File(s) Summary
Separate type conversion and comment SQL
packages/postgres/src/query-generator.js, packages/core/test/unit/dialects/postgres/query-generator.test.js
The generator extracts column comments before ENUM rewrites, appends them after the alteration SQL, and tests the resulting separate statements.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: sdepold, ephys

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The implementation and regression test ensure USING remains with ALTER COLUMN TYPE and is excluded from COMMENT ON COLUMN SQL [#17894].
Out of Scope Changes check ✅ Passed The changes are limited to the PostgreSQL query generator and its regression test, with no unrelated code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main PostgreSQL fix: keeping the USING clause separate from COMMENT ON COLUMN during ENUM alterations.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@SippieCup

Copy link
Copy Markdown
Contributor

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.

@xianjianlf2
xianjianlf2 force-pushed the fix/postgres-enum-comment-using-17894 branch from fd5eb0b to da87c13 Compare July 14, 2026 02:05
@xianjianlf2

Copy link
Copy Markdown
Author

Thanks for the review — good points, reworked it.

Instead of splicing the USING clause into the middle of the definition string, the trailing ; COMMENT ON COLUMN statement is now split off once at the top of the loop (the same handling already used in attributesToSQL) and re-appended after the per-attribute SQL is built. The ENUM branch goes back to a plain definition += ' USING (...)', and every column-type rewrite in the loop now operates on the type portion only — so this is more robust than just the ENUM+comment case, and consistent with the existing style. Also trimmed the comment down.

I agree the broader changeColumnQuery string-assembly would be better handled programmatically and shared across dialects, but that's a larger refactor beyond this bug — happy to open a follow-up PR for it separately if you'd like.

@xianjianlf2
xianjianlf2 force-pushed the fix/postgres-enum-comment-using-17894 branch from da87c13 to f391101 Compare July 14, 2026 02:19
@xianjianlf2
xianjianlf2 force-pushed the fix/postgres-enum-comment-using-17894 branch from 4a4c21a to 29c8d6e Compare August 3, 2026 04:20
@xianjianlf2

Copy link
Copy Markdown
Author

Synced with the latest upstream/main at 9a8369fe; both PR files merged cleanly and the approval remains in place.

Local validation:

  • yarn workspace @sequelize/postgres build
  • ESLint on the two PR files
  • git diff --check upstream/main...HEAD

The focused core test runner could not start locally because the interrupted optional ibm_db install left its native binding unavailable; it failed during all-dialect test bootstrap before loading this test. Fresh GitHub CI is running the full matrix.

@WikiRik
WikiRik self-requested a review September 7, 2026 13:01

@WikiRik WikiRik left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.js that changes a column to an ENUM with a comment and checks the result via describeTable. The existing ENUM cases there have no comment and the comment case there is an INTEGER, 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, because dataTypeMapping() already did the identical replace on the same string. It can go, leaving only the USING (...) 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)} IS prefix avoids it.
  • Sentinel is a hand-written copy of the template. The string emitted at attributeToSQL line 327 and the one parsed here have nothing tying them together; a reformat of either silently reintroduces #17894. A small private helper that builds the COMMENT ON COLUMN statement, used by both attributeToSQL and 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.

@SippieCup

Copy link
Copy Markdown
Contributor

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.

@SippieCup
SippieCup self-requested a review September 7, 2026 14:05
@xianjianlf2

Copy link
Copy Markdown
Author

Addressed the blocking review points on the latest upstream/main:

  • split the exact column-comment statement from the raw definition before dataTypeMapping()
  • pass the stripped definition to pgEnum() and remove the now-dead second ENUM replacement
  • cover a parenthesized comment in the unit fixture and a real PostgreSQL changeColumn integration test

The first CI run exposed only an incorrect test expectation: PostgreSQL describeTable() reports enums as type: USER-DEFINED with values in special. That assertion is corrected in 628fe165; the SQL operation itself completed successfully in both postgres and postgres-native jobs. Fresh CI is running.

@WikiRik WikiRik left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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, addColumn with an enum and a comment ending in ) produced ALTER TABLE "addc" ADD COLUMN "col" "public"."enum_addc_col"'; and failed with unterminated 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).

@WikiRik
WikiRik enabled auto-merge (squash) September 11, 2026 14:22
@wikirik-agent

Copy link
Copy Markdown
Contributor

For anyone reviewing this later: a few follow-ups came out of this PR, listed here so the relationship is visible.

PR What it does Issues
#18361 Three other changeColumn bugs on PostgreSQL: the ARRAY(ENUM) USING cast, SET DEFAULT ordering, and a stray UNIQUE in the TYPE clause no linked issue
#18364 Missing DataType usage context in createTable and changeColumn, which broke ARRAY(ENUM) columns with a defaultValue closes #11285
#18363 Tooling only: a .coderabbit.yaml disabling the two CodeRabbit tools that cannot run on this repo no linked issue

#18361 edits the same changeColumnQuery function this PR does. They do not conflict semantically, but whichever merges second will need a small rebase.

#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
xianjianlf2 and others added 6 commits September 11, 2026 15:14
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]>
@SippieCup
SippieCup force-pushed the fix/postgres-enum-comment-using-17894 branch from 53d3886 to d6b124c Compare September 11, 2026 19:14
@sequelize-bot sequelize-bot Bot added the conflicted This PR has merge conflicts and will not be present in the list of PRs to review label Sep 12, 2026
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]>
auto-merge was automatically disabled September 15, 2026 02:27

Head branch was pushed to by a user without write access

@sequelize-bot sequelize-bot Bot added conflicted This PR has merge conflicts and will not be present in the list of PRs to review and removed conflicted This PR has merge conflicts and will not be present in the list of PRs to review labels Sep 15, 2026
@sequelize-bot sequelize-bot Bot removed the conflicted This PR has merge conflicts and will not be present in the list of PRs to review label Sep 22, 2026
@sequelize-bot sequelize-bot Bot added the conflicted This PR has merge conflicts and will not be present in the list of PRs to review label Oct 20, 2026
@xianjianlf2

Copy link
Copy Markdown
Author

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.

@sequelize-bot sequelize-bot Bot removed the conflicted This PR has merge conflicts and will not be present in the list of PRs to review label Oct 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sequelize sync alters ENUM column comment with invalid USING clause causing PostgreSQL syntax error

4 participants