Skip to content

fix: overhaul test suite of attribute(s)ToSQL - #17121

Closed
WikiRik wants to merge 30 commits into
mainfrom
WikiRik/attributes-to-sql-2
Closed

WikiRik wants to merge 30 commits into
mainfrom
WikiRik/attributes-to-sql-2

Conversation

@WikiRik

@WikiRik WikiRik commented Feb 25, 2024 •

Copy link
Copy Markdown
Member

Description of Changes

Attempt 2 on overhauling the test suite for attributesToSQL and attributeToSQL. I also did some minor improvements to the functions.

Closes #15533

TODOs

  • Confirm what is desired behaviour
  • Type attributeToSQL
  • Type attributesToSQL

Future PRs

  • Rename to attributesToSql and attributeToSql respectively
  • Clean up createTableQuery unit tests
  • Move usages of attributesToSQL to queryGenerator so both can become internal functions
  • Throw if invalid options/column keys are used (like comment for sqlite)
  • Remove weird behaviour surrounding schema's that are used in functions that call attribute(s)ToSQL (breaking change)

List of Breaking Changes

Summary by CodeRabbit

  • Bug Fixes
    • Correctly escape and display column comments across dialects (notably MSSQL).
    • More reliable default value handling for binary types.
    • Consistent foreign key constraint naming during add/change column.
    • More robust behavior when optional options are missing.
  • Refactor
    • Standardized attribute-to-SQL generation across dialects for improved consistency.
    • Internal null-safe option access and safer result object initialization.
  • Tests
    • Added comprehensive unit tests for attributeToSQL and attributesToSQL.
    • Updated integration tests for describeTable/changeColumn; removed redundant dialect-specific suites.

@WikiRik

WikiRik commented Mar 22, 2024

Copy link
Copy Markdown
Member Author

@ephys even though it's in draft; could you take a look at the test cases that we do? As mentioned in the TODOs above, there is still work to be done but I want to confirm that this is how people can use these functions before cleaning up test suites and add typings.

@WikiRik

WikiRik commented Mar 30, 2024

Copy link
Copy Markdown
Member Author

I'll mark it as ready for review since the bulk of the work is done. It's not ready for merging yet, since I want to know if there's any tests that have unwanted behaviour before I work on typing the functions.

@WikiRik
WikiRik marked this pull request as ready for review March 30, 2024 15:57
@WikiRik
WikiRik requested a review from a team as a code owner March 30, 2024 15:57
@WikiRik
WikiRik requested a review from ephys March 30, 2024 15:57
@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 Apr 10, 2024
@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 Apr 12, 2024
@WikiRik
WikiRik marked this pull request as draft April 12, 2024 06:04
@WikiRik WikiRik self-assigned this Apr 12, 2024
@coderabbitai

coderabbitai Bot commented Oct 4, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Updates attribute-to-SQL typing and usage, refactors dialect query generators to drop explicit dialect passing and improve option handling, adjusts MSSQL comment expectations, consolidates unit tests into dialect-agnostic suites, adds/change-column comment tests, and introduces SQLite-specific attributeToSQL method. Minor support and describe/return-values adjustments included.

Changes

Cohort / File(s) Summary
Core types and generator
packages/core/src/abstract-dialect/query-generator.internal-types.ts, packages/core/src/abstract-dialect/query-generator.js
Adds TableOrModel import; AttributeToSqlOptions.table becomes optional and accepts TableOrModel; adds optional foreignKey; stops passing dialect to attributeTypeToSql in return-values path.
Dialect QueryGenerator refactors (shared patterns)
packages/db2/src/query-generator.js, packages/ibmi/src/query-generator.js, packages/mariadb/src/query-generator.js, packages/mssql/src/query-generator.js, packages/mysql/src/query-generator.js, packages/postgres/src/query-generator.js, packages/snowflake/src/query-generator.js
Replace attributeTypeToSql(..., { dialect }) with attributeTypeToSql(...); use optional chaining for options/context; switch _binary checks to type.options?.binary; escape comments via this.escape; compute FK names via extractTableDetails(options.table).tableName; initialize maps with Object.create(null); assorted null-safety/flow tweaks.
SQLite attribute SQL refactor
packages/sqlite3/src/query-generator.js
Adds attributeToSQL(attribute, options); attributesToSQL delegates to it; normalizes types; handles defaults/nullability/PK/unique/refs; updates imports (adds utilities, uses isPlainObject).
MSSQL describe/query tweaks
packages/mssql/src/query.js
Adds TODO about unescaping comment in describe results; behavior unchanged.
Integration tests: MSSQL comment expectations
packages/core/test/integration/query-interface/changeColumn.test.js, packages/core/test/integration/query-interface/describeTable.test.js
Adjust expected comments for MSSQL (escaped forms like N'...'); separates MSSQL assertions from other dialects.
Unified unit tests for attribute SQL
packages/core/test/unit/query-generator/attribute-to-sql.test.ts, packages/core/test/unit/query-generator/attributes-to-sql.test.ts
New cross-dialect test suites covering attributeToSQL and attributesToSQL, including types, defaults, comments, refs, and context-sensitive cases with per-dialect expectations.
Removed dialect-specific attributesToSQL tests
packages/core/test/unit/dialects/db2/query-generator.test.js, .../mariadb/..., .../mysql/..., .../postgres/..., .../snowflake/..., .../sqlite/...
Deletes per-dialect attributesToSQL suites; retains other query generator tests; reduces duplicated coverage in favor of unified suites.
SQL change-column tests
packages/core/test/unit/sql/change-column.test.js
Adds test asserting dialect-specific SQL for changeColumn with comment across ibmi, mssql, db2, mariadb/mysql, postgres, snowflake.
Test support utility
packages/core/test/support.ts
inlineErrorCause now stringifies non-Error values using inspect instead of String.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Test
  participant QG as QueryGenerator (dialect-specific)
  participant DT as DataType utils
  participant SQL as SQL Builder

  Test->>QG: addColumn/changeColumn({ attribute, options })
  QG->>QG: attributeToSQL(attribute, { table, context, foreignKey? })
  QG->>DT: attributeTypeToSql(attribute.type)
  DT-->>QG: SQL type string
  alt has references
    QG->>QG: build REFERENCES clause (uses extractTableDetails(options.table))
  end
  QG->>QG: assemble column SQL (NULL/DEFAULT/COMMENT escaped)
  QG-->>SQL: column definition string
  SQL-->>Test: final statement
  note over QG,DT: Dialect param no longer passed to attributeTypeToSql
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • ephys
  • sdepold

Poem

I thump my paw on dialects old,
Unify the scripts—so bold!
Columns whisper, “COMMENT me,”
FK names hop table-ly.
Tests now dance in one wide field—
Carrots of green coverage yield.
Bun-approved SQL, well-tilled. 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The PR removes the numerous dialect-specific attributesToSQL tests and adds two comprehensive cross-dialect test suites, satisfying the unification and consolidation objectives, but it has not yet added TypeScript type definitions for the attributeToSQL and attributesToSQL functions as called out in issue #15533. Please include the missing TypeScript declarations for attributeToSQL and attributesToSQL in this PR or a follow-on to fully satisfy the linked issue’s typing requirements.
Out of Scope Changes Check ⚠️ Warning In addition to test suite and minor function updates scoped to attributesToSQL, this PR also alters integration tests for describeTable and changeColumn, adjusts generateReturnValues behavior, and modifies the inlineErrorCause helper—none of which are mentioned in issue #15533’s objectives and thus appear out of scope. Please remove or relocate the unrelated integration test adjustments and core helper changes into separate PRs so this review can focus solely on the attributeToSQL test suite overhaul.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly summarizes the primary change, which is an overhaul of the test suite for the attributeToSQL and attributesToSQL functions, without extraneous file lists or vague wording.

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 and usage tips.

@WikiRik

WikiRik commented Oct 4, 2025

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 4, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/snowflake/src/query-generator.js (1)

134-143: Pass table to attributeToSQL in addColumn.

attributeToSQL now expects options.table, but addColumnQuery still passes tableName. When adding a referenced column, options.table ends up undefined, so this.extractTableDetails(options.table) throws at runtime. Please switch to the new option to keep foreign-key columns working.

       this.quoteIdentifier(key),
       this.attributeToSQL(dataType, {
         context: 'addColumn',
-        tableName: table,
+        table,
         foreignKey: key,
       }),
packages/ibmi/src/query-generator.js (1)

131-137: Update addColumn to pass table into attributeToSQL.

Here we’re still providing tableName, so options.table is undefined when attribute.references is defined. this.extractTableDetails(options.table) will then throw, breaking FK column additions. Please pass the table value under the new key.

-    const definition = this.attributeToSQL(dataType, {
-      context: 'addColumn',
-      tableName: table,
-      foreignKey: key,
-    });
+    const definition = this.attributeToSQL(dataType, {
+      context: 'addColumn',
+      table,
+      foreignKey: key,
+    });
🧹 Nitpick comments (4)
packages/sqlite3/src/query-generator.js (1)

259-264: Use a null‑prototype map for safety and consistency

Prefer Object.create(null) to avoid prototype pollution and accidental key collisions.

-    const result = {};
+    const result = Object.create(null);
packages/core/test/unit/query-generator/attribute-to-sql.test.ts (2)

444-501: Add a PG addColumn(comment) test to guard regression

Please add a case that calls queryGenerator.addColumn (or attributeToSQL with { context: 'addColumn', table, key } when a comment is present) for Postgres to ensure comment DDL targets the correct column.

I can draft the test snippet if desired.


57-76: Error expectation robustness

Using new Error('quoteIdentifier received a non-string identifier:') may be brittle across implementations. Prefer asserting on error type with substring/regex match.

packages/mssql/src/query.js (1)

229-229: TODO tracked: Implement comment unescaping.

This is the correct location to unescape MSSQL comments. The format N'Users City' requires removing the N prefix and outer quotes, plus handling any escaped internal quotes ('' → ').

Would you like me to generate the unescaping logic? A basic implementation would be:

comment: _result.Comment ? _result.Comment.replace(/^N'(.*)'$/, '$1').replace(/''/g, "'") : _result.Comment,

However, verify edge cases (null comments, comments with embedded quotes) before applying.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 344fdd2 and 5d6e215.

📒 Files selected for processing (23)
  • packages/core/src/abstract-dialect/query-generator.internal-types.ts (2 hunks)
  • packages/core/src/abstract-dialect/query-generator.js (1 hunks)
  • packages/core/test/integration/query-interface/changeColumn.test.js (1 hunks)
  • packages/core/test/integration/query-interface/describeTable.test.js (1 hunks)
  • packages/core/test/support.ts (1 hunks)
  • packages/core/test/unit/dialects/db2/query-generator.test.js (0 hunks)
  • packages/core/test/unit/dialects/mariadb/query-generator.test.js (0 hunks)
  • packages/core/test/unit/dialects/mysql/query-generator.test.js (0 hunks)
  • packages/core/test/unit/dialects/postgres/query-generator.test.js (0 hunks)
  • packages/core/test/unit/dialects/snowflake/query-generator.test.js (0 hunks)
  • packages/core/test/unit/dialects/sqlite/query-generator.test.js (0 hunks)
  • packages/core/test/unit/query-generator/attribute-to-sql.test.ts (1 hunks)
  • packages/core/test/unit/query-generator/attributes-to-sql.test.ts (1 hunks)
  • packages/core/test/unit/sql/change-column.test.js (1 hunks)
  • packages/db2/src/query-generator.js (6 hunks)
  • packages/ibmi/src/query-generator.js (4 hunks)
  • packages/mariadb/src/query-generator.js (5 hunks)
  • packages/mssql/src/query-generator.js (3 hunks)
  • packages/mssql/src/query.js (1 hunks)
  • packages/mysql/src/query-generator.js (5 hunks)
  • packages/postgres/src/query-generator.js (6 hunks)
  • packages/snowflake/src/query-generator.js (3 hunks)
  • packages/sqlite3/src/query-generator.js (4 hunks)
💤 Files with no reviewable changes (6)
  • packages/core/test/unit/dialects/mysql/query-generator.test.js
  • packages/core/test/unit/dialects/snowflake/query-generator.test.js
  • packages/core/test/unit/dialects/db2/query-generator.test.js
  • packages/core/test/unit/dialects/postgres/query-generator.test.js
  • packages/core/test/unit/dialects/sqlite/query-generator.test.js
  • packages/core/test/unit/dialects/mariadb/query-generator.test.js
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
PR: sequelize/sequelize#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-generator.{js,ts} : Implement dialect feature SQL in query-generator.ts (preferred) or legacy query-generator.js

Applied to files:

  • packages/core/test/unit/query-generator/attributes-to-sql.test.ts
  • packages/core/test/unit/query-generator/attribute-to-sql.test.ts
  • packages/mariadb/src/query-generator.js
  • packages/db2/src/query-generator.js
  • packages/mssql/src/query-generator.js
  • packages/core/src/abstract-dialect/query-generator.js
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
PR: sequelize/sequelize#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/**/src/**/query-generator.{js,ts} : When modifying query generation, update both the base query generator and all dialect-specific implementations

Applied to files:

  • packages/ibmi/src/query-generator.js
  • packages/mariadb/src/query-generator.js
  • packages/db2/src/query-generator.js
  • packages/mssql/src/query-generator.js
  • packages/core/src/abstract-dialect/query-generator.js
📚 Learning: 2025-09-29T19:49:24.715Z
Learnt from: CR
PR: sequelize/sequelize#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-29T19:49:24.715Z
Learning: Applies to packages/*/src/query-interface.{js,ts} : Add schema operations for new features in query-interface.ts (preferred) or legacy query-interface.js

Applied to files:

  • packages/ibmi/src/query-generator.js
🪛 Biome (2.1.2)
packages/sqlite3/src/query-generator.js

[error] 3-7: Illegal use of an import declaration outside of a module

not allowed inside scripts

(parse)


[error] 18-19: Illegal use of an import declaration outside of a module

not allowed inside scripts

(parse)


[error] 19-20: Illegal use of an import declaration outside of a module

not allowed inside scripts

(parse)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Lint code
🔇 Additional comments (9)
packages/db2/src/query-generator.js (3)

101-112: Unique keys optional chaining looks good

Safer access to options.uniqueKeys without altering behavior. LGTM.

Also applies to: 128-136


604-606: FK constraint naming and comment escaping

  • FK name built from extractTableDetails(options.table).tableName + quoted column matches test expectations (e.g., otherTable_"bar"_fidx). Ensure options.table is provided when options.foreignKey is used.
  • Escaping column comments is a solid hardening.

LGTM, with the above caution.

Also applies to: 642-643


563-564: Confirm no two-argument attributeTypeToSql usages remain
Ripgrep across JS files returned zero instances of attributeTypeToSql with more than one argument.

packages/sqlite3/src/query-generator.js (2)

119-128: addColumn normalization + delegation: LGTM

Normalizing the type and delegating rendering to attributeToSQL improves consistency. Looks good.


204-256: attributeToSQL implementation is consistent and correct

Covers NULLability, defaults, uniqueness, PK + AUTOINCREMENT, and REFERENCES for SQLite. Matches test expectations.

packages/core/test/unit/query-generator/attribute-to-sql.test.ts (1)

13-30: Test harness and scope: solid

Well-structured per-dialect tester with wide coverage. This will meaningfully reduce dialect-specific duplication.

packages/postgres/src/query-generator.js (1)

226-236: ENUM[] handling, FK schema resolution, and attributesToSQL map: LGTM

  • Correctly renders ENUM arrays.
  • Optional chaining for schema and FK constraints is safer.
  • attributesToSQL uses null-prototype map and injects key for downstream needs.

Looks good.

Also applies to: 272-279, 285-306, 324-329

packages/core/test/integration/query-interface/changeColumn.test.js (1)

268-273: MSSQL comment expectation adjustment: LGTM

Dialect-specific escaping acknowledged with a TODO to unescape later. Fine for now.

packages/core/test/integration/query-interface/describeTable.test.js (1)

173-180: Test correctly documents current MSSQL behavior.

The separate MSSQL branch with escaped comment expectations aligns with the TODO in packages/mssql/src/query.js:229. This approach appropriately documents the current behavior while tracking the known issue.

Before finalizing the PR, ensure both TODOs are resolved together:

  1. Implement unescaping in packages/mssql/src/query.js line 229
  2. Update this test to expect 'Users City' for MSSQL (matching postgres/mysql)

The test will fail if only one side is fixed.

Comment on lines 424 to 432
if (attribute.references) {
if (options && options.context === 'addColumn' && options.foreignKey) {
if (options?.context === 'addColumn' && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);

template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}

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.

⚠️ Potential issue | 🔴 Critical

Build FK names from the unquoted column identifier.

The current code concatenates the already-quoted column name into the constraint identifier, yielding strings with embedded quotes that become invalid once wrapped by quoteIdentifier. Use the raw column for the name, and reserve quoting for the FOREIGN KEY clause itself.

-        const attrName = this.quoteIdentifier(options.foreignKey);
+        const attrName = options.foreignKey;
         const fkName = this.quoteIdentifier(
-          `${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
+          `${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
         );
 
-        template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
+        template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${this.quoteIdentifier(attrName)})`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (attribute.references) {
if (options && options.context === 'addColumn' && options.foreignKey) {
if (options?.context === 'addColumn' && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);
template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}
if (attribute.references) {
if (options?.context === 'addColumn' && options.foreignKey) {
// use the raw column name when building the FK name
const attrName = options.foreignKey;
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);
// quote only in the FOREIGN KEY clause itself
template += ` ADD CONSTRAINT ${fkName} FOREIGN KEY (${this.quoteIdentifier(attrName)})`;
}
🤖 Prompt for AI Agents
packages/ibmi/src/query-generator.js around lines 424-432: the code builds the
FK constraint identifier using the already-quoted column name (attrName), which
embeds quotes into the constraint name and breaks identifier quoting; change it
to use the raw column identifier (options.foreignKey) when composing the fkName
(e.g. `${tableName}_${rawColumn}_foreign_idx`) and only apply quoteIdentifier
when emitting the constraint identifier itself, while keeping the FOREIGN KEY
clause column wrapped in quoteIdentifier; ensure you still call
extractTableDetails(options.table).tableName for the table part and sanitize or
normalize the raw column name if necessary before concatenation.

Comment on lines 503 to 507
if (
attribute.type !== 'TEXT' &&
attribute.type._binary !== true &&
attribute.type.options?.binary !== true &&
defaultValueSchemable(attribute.defaultValue, this.dialect)
) {

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.

⚠️ Potential issue | 🟠 Major

Restore TEXT/BLOB default guard

attribute.type is typically a DataType instance (e.g. DataTypes.TEXT), not the literal string 'TEXT', so this check now always passes. As soon as a defaultValue is defined on a TEXT/BLOB column we will emit ... DEFAULT ..., which MSSQL rejects (these types cannot have defaults). Please restore the guard by keying off the DataType metadata instead of comparing the object to a string.

-      attribute.type !== 'TEXT' &&
-      attribute.type.options?.binary !== true &&
+      attribute.type.key !== 'TEXT' &&
+      attribute.type.key !== 'BLOB' &&
+      attribute.type.options?.binary !== true &&
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (
attribute.type !== 'TEXT' &&
attribute.type._binary !== true &&
attribute.type.options?.binary !== true &&
defaultValueSchemable(attribute.defaultValue, this.dialect)
) {
if (
attribute.type.key !== 'TEXT' &&
attribute.type.key !== 'BLOB' &&
attribute.type.options?.binary !== true &&
defaultValueSchemable(attribute.defaultValue, this.dialect)
) {
🤖 Prompt for AI Agents
In packages/mssql/src/query-generator.js around lines 503 to 507, the guard
currently compares attribute.type to the string 'TEXT' which always fails
because attribute.type is a DataType object; restore the guard by checking the
DataType metadata (e.g. attribute.type.key) instead of a string so TEXT/BLOB
columns are excluded from having defaults. Update the condition to skip default
generation when attribute.type.key is 'TEXT' or 'BLOB' (and preserve the
existing binary check), i.e. test attribute.type?.key !== 'TEXT' &&
attribute.type?.key !== 'BLOB' (or the inverse to early-return), keeping
defaultValueSchemable(attribute.defaultValue, this.dialect) as before.

Comment on lines 309 to 313
if (options && ['addColumn', 'changeColumn'].includes(options.context)) {
const quotedAttr = this.quoteIdentifier(options.key);
const quotedAttr = this.quoteIdentifier(attribute.key);
const escapedCommentText = this.escape(attribute.comment);
sql += `; COMMENT ON COLUMN ${this.quoteTable(options.table)}.${quotedAttr} IS ${escapedCommentText}`;
} else {

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.

⚠️ Potential issue | 🔴 Critical

Fix: addColumn(comment) uses undefined attribute.key; fallback to options.key

attributeToSQL now uses attribute.key to build COMMENT ON COLUMN, but addColumnQuery calls attributeToSQL(attribute, { context: 'addColumn', table, key }) without injecting key into the attribute. This can break comments on addColumn.

Use attribute.key ?? options.key to resolve the column name.

-      if (options && ['addColumn', 'changeColumn'].includes(options.context)) {
-        const quotedAttr = this.quoteIdentifier(attribute.key);
+      if (options && ['addColumn', 'changeColumn'].includes(options.context)) {
+        const attrKey = attribute.key ?? options.key;
+        const quotedAttr = this.quoteIdentifier(attrKey);
         const escapedCommentText = this.escape(attribute.comment);
         sql += `; COMMENT ON COLUMN ${this.quoteTable(options.table)}.${quotedAttr} IS ${escapedCommentText}`;
       } else {

Add a unit test to cover this path (see test suggestion in attribute-to-sql.test.ts comment).

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (options && ['addColumn', 'changeColumn'].includes(options.context)) {
const quotedAttr = this.quoteIdentifier(options.key);
const quotedAttr = this.quoteIdentifier(attribute.key);
const escapedCommentText = this.escape(attribute.comment);
sql += `; COMMENT ON COLUMN ${this.quoteTable(options.table)}.${quotedAttr} IS ${escapedCommentText}`;
} else {
if (options && ['addColumn', 'changeColumn'].includes(options.context)) {
const attrKey = attribute.key ?? options.key;
const quotedAttr = this.quoteIdentifier(attrKey);
const escapedCommentText = this.escape(attribute.comment);
sql += `; COMMENT ON COLUMN ${this.quoteTable(options.table)}.${quotedAttr} IS ${escapedCommentText}`;
} else {
🤖 Prompt for AI Agents
In packages/postgres/src/query-generator.js around lines 309 to 313,
attributeToSQL uses attribute.key when building the COMMENT ON COLUMN for
addColumn/changeColumn but addColumnQuery passes the column name via
options.key, so attribute.key can be undefined; change the column resolution to
use the attribute key fallback to options.key (e.g., const colName =
attribute.key ?? options.key) before quoting and escaping, and update the
COMMENT ON COLUMN call to use that resolved name; also add a unit test
exercising addColumn with comment where attribute.key is missing to ensure
comments are applied correctly.

Comment on lines +276 to 283
if (options?.context === 'addColumn' && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);

template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}

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.

⚠️ Potential issue | 🔴 Critical

Use the raw column name when constructing the FK constraint identifier.

attrName is already quoted; embedding it in the identifier string produces something like users_"userId"_foreign_idx, and quoting that yields invalid SQL. Build the constraint name from the unquoted column instead and only quote when emitting the FOREIGN KEY clause.

-        const attrName = this.quoteIdentifier(options.foreignKey);
+        const attrName = options.foreignKey;
         const fkName = this.quoteIdentifier(
-          `${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
+          `${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
         );
 
-        template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
+        template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${this.quoteIdentifier(attrName)})`;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (options?.context === 'addColumn' && options.foreignKey) {
const attrName = this.quoteIdentifier(options.foreignKey);
const fkName = this.quoteIdentifier(`${options.tableName}_${attrName}_foreign_idx`);
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);
template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${attrName})`;
}
if (options?.context === 'addColumn' && options.foreignKey) {
const attrName = options.foreignKey;
const fkName = this.quoteIdentifier(
`${this.extractTableDetails(options.table).tableName}_${attrName}_foreign_idx`,
);
template += `, ADD CONSTRAINT ${fkName} FOREIGN KEY (${this.quoteIdentifier(attrName)})`;
}
🤖 Prompt for AI Agents
In packages/snowflake/src/query-generator.js around lines 276 to 283, the FK
constraint identifier is being built using the already-quoted column name
(attrName), which results in invalid SQL like users_"userId"_foreign_idx;
instead, use the raw column name (options.foreignKey) to construct the
constraint name and then quote only the final constraint name with
quoteIdentifier. When emitting the FOREIGN KEY clause, quote the column
reference separately (e.g., quoteIdentifier(options.foreignKey)). Ensure you
replace uses of attrName in the identifier construction with the unquoted column
and keep quoting only where the SQL clause requires it.

Comment on lines +4 to +7
import {
attributeTypeToSql,
normalizeDataType,
} from '@sequelize/core/_non-semver-use-at-your-own-risk_/abstract-dialect/data-types-utils.js';

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify ESM module configuration to satisfy static analysis

Biome reports “import outside of a module”. Ensure packages/sqlite3 declares "type": "module" (or appropriate tooling/transpile settings).

Also applies to: 19-20


🏁 Script executed:

#!/bin/bash
# Check package type for sqlite3 package and root (fallback)
if fd -a 'packages/sqlite3/package.json' >/dev/null; then
  echo "packages/sqlite3/package.json type:"
  cat packages/sqlite3/package.json | jq -r '.type // "(missing)"'
fi
echo "root package.json type (if any):"
if [ -f package.json ]; then cat package.json | jq -r '.type // "(missing)"'; fi
# Spot-check other dialect packages for consistency
fd -a 'packages/*/package.json' | xargs -I{} sh -c 'printf "%s: " "{}"; cat "{}" | jq -r ".type // \"(missing)\""' | sed 's/\n/\n/g'

Length of output: 87


Enable ESM for sqlite3 package
packages/sqlite3/package.json declares "type": "commonjs" but query-generator.js uses ESM imports (lines 4-7, 19-20); update to "type": "module" or adjust build/transpiler settings to satisfy static analysis.

🧰 Tools
🪛 Biome (2.1.2)

[error] 3-7: Illegal use of an import declaration outside of a module

not allowed inside scripts

(parse)

🤖 Prompt for AI Agents
In packages/sqlite3/src/query-generator.js around lines 4 to 7 and 19 to 20, the
file uses ESM import syntax while packages/sqlite3/package.json currently
declares "type": "commonjs"; either change the package.json "type" to "module"
so Node treats the files as ESM, or convert the imports in this file to CommonJS
(require) to match the existing package type; after choosing one approach,
update any other files in the package for consistent module format and adjust
build/transpiler settings or exports as needed to ensure static analysis and
runtime resolution succeed.

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.

1 participant