Skip to content

meta: convert attributeToSql and attributesToSql to TypeScript - #18368

Closed
wikirik-agent wants to merge 8 commits into
sequelize:mainfrom
wikirik-agent:attributes-to-sql-typescript
Closed

wikirik-agent wants to merge 8 commits into
sequelize:mainfrom
wikirik-agent:attributes-to-sql-typescript

Conversation

@wikirik-agent

Copy link
Copy Markdown
Contributor

Description of Changes

Last of the stack re-implementing #17121. Depends on #18366 and #18367 — their commits are the first five of the six here, since GitHub cannot base a cross-fork PR on a branch that only exists on the fork. Only the last commit belongs to this PR.

Moves attributeToSQL / attributesToSQL out of every dialect's query-generator.js into its query-generator-typescript.internal.ts, renames them to attributeToSql / attributesToSql, and types them.

Closes the last unchecked item of #15533.

No SQL changes. The suites from #18366 produce byte-identical output for all nine dialects (2,296–2,906 tests each), with clean eslint and clean tsc on both --noEmit and test/tsconfig.json.

What the types say

The old declaration claimed attributesToSQL(attributes: ColumnsDescription, ...), which described none of the real callers — ColumnsDescription has no references, unique, field or onDelete, all of which every dialect reads. That is why the tests needed @ts-expect-error and a hand-written cast.

The new AttributeToSqlColumn documents what the dialects actually read. It is deliberately wider than NormalizedAttributeOptions, because these methods are also called with describeTable output (where type is a raw SQL string) and with hand-written migration definitions. AttributeToSqlInput additionally allows a bare type, which every dialect already normalised to { type }.

Both methods are now declared on the core query generator as a contract each dialect implements, so a dialect drifting from the shared signature is a compile error.

isBinaryStringType joins attributeTypeToDataTypeId (added in #18367) in the core data type utilities, replacing the attribute.type.options?.binary reach-through into a property the base class does not declare.

What typing found

Typing the test file caught two things it was getting wrong:

  • deferrable: 'INITIALLY_IMMEDIATE' as a raw string rather than the Deferrable enum.
  • A leftover pre-rename option name in the quoteIdentifiers: false block.

Three sets of arguments went away because the compiler proved they could not do anything:

  • AttributeToSqlOptions and EscapeOptions share no properties, so mssql and snowflake were handing escape an object it could never read. TypeScript's weak-type check is what surfaced this.
  • Several toSql({ dialect }) calls passed an argument no implementation accepts — toSql() takes none in core and in every dialect override.
  • db2 called escape(value, undefined, { replacements }) where escape takes two parameters.

All three are removals of dead arguments, confirmed no-ops by the pinned expectations.

Notes for review

  • attributesToSql result maps are now consistently null-prototype. mssql and ibmi already used pojo(); the rest built {}. Only the prototype differs and every consumer uses for...in / Object.keys.
  • A few non-null assertions on attribute.field remain (mssql, db2, ibmi ENUM branches). These preserve the existing throw rather than papering over it — the "an ENUM without a column name throws" TODO in the test file still describes real behaviour.
  • postgres deliberately keeps ! on options.tableOrModel in the comment branch rather than adding a guard: a guard would flip the if/else and emit COMMENT ... instead of throwing, which would be a real SQL change.
  • Integration tests have not been run locally — same caveat as fix: correct attributeToSQL across all dialects #18367.

Latent bugs found while converting, deliberately left alone

  • oracle: the attribute.type === 'DOUBLE' branch compares against a raw string then calls .toSql() on it, so reaching it throws. Its self-reference check compares references.tableName, but v7 references use references.table, so it is always undefined.
  • mariadb: does not wrap BaseSqlExpression defaults in parentheses while mysql does. MariaDB 10.2+ requires the same parenthesisation, so expression defaults likely emit invalid SQL.
  • ibmi: attributeString is now dead — both branches overwrite template immediately.
  • sqlite3: ignores attribute.comment entirely, so comments are dropped when a table is rebuilt.

Each is a separate fix with its own test expectations; none are TypeScript-conversion concerns.

List of Breaking Changes

attributeToSQL / attributesToSQL are renamed to attributeToSql / attributesToSql. Both are internal query generator methods, exported only under _non-semver-use-at-your-own-risk_.

🤖 Generated with Claude Code

wikirik-agent and others added 5 commits September 11, 2026 22:54
Replaces the per-dialect `attributesToSQL` suites with two dialect-agnostic
suites that cover all nine dialects, including ibmi and mssql which had no
coverage at all.

The expectations pin current behaviour exactly, so this commit changes no SQL.
Behaviour that is wrong today is pinned as-is and marked with a TODO.

`sqlite3` gains an `attributeToSQL` method, extracted from `attributesToSQL`
without changing its output, so the shared suite can cover it like every other
dialect.

`inlineErrorCause` now inspects non-error values instead of stringifying them:
mssql and ibmi return null-prototype maps from `attributesToSQL`, which threw
when the assertion message was built.

Closes sequelize#15533

Co-Authored-By: Claude Opus 5 <[email protected]>
Every dialect that refuses a DEFAULT for certain column types was checking
conditions that can never be true on v7 data types:

- `attribute.type._binary` was a v6 property of STRING/CHAR set by `.BINARY`.
  It does not exist in v7, so the check was always a no-op. It is now
  `attribute.type.options?.binary`, which is where that flag lives today.
- db2, mssql and oracle compared `attribute.type !== 'TEXT'`, comparing a
  DataType instance against a string, so it never matched.
- mariadb, mysql, snowflake and ibmi looked up the rendered SQL string in a set
  of type names. That only matched the default length variant, and never
  matched at all on ibmi, whose BLOB renders as `BLOB(1M)`.

The lookups now use `attributeTypeToDataTypeId`, added to the core data type
utilities, which returns the dialect-independent identity of a type. Each
dialect keeps exactly the list of types it already named.

As a result db2, mssql and oracle stop emitting a DEFAULT for BLOB and TEXT
columns, and ibmi stops emitting one for BLOB. A raw `'BLOB'` string type with
a default no longer throws while trying to escape the value.

Co-Authored-By: Claude Opus 5 <[email protected]>
`attributeToSQL` received the table under two different names and the column
under three, and no caller passed all of them:

- Core passed `table`, while mysql, mariadb, snowflake, db2 and ibmi read
  `tableName`. Passing the name declared in `AttributeToSqlOptions` therefore
  threw on mariadb and mysql, and named the constraint `undefined_..._foreign_idx`
  on snowflake, db2 and ibmi.
- The column arrived as `key` on postgres, `attributeName` on oracle and
  `foreignKey` everywhere else, duplicating `attribute.field`.

There is now a single `tableOrModel` option, accepting anything `quoteTable`
does, and the column name is always read from `attribute.field`, which
`attributesToSQL` and every `addColumnQuery` now set. `schema` is gone: core
already stamps the multi-tenancy schema onto the table it passes, so an
explicitly qualified reference target keeps its own schema instead of being
overridden.

Fixed along the way:

- snowflake and ibmi built foreign key constraint names out of an
  already-quoted column, producing `"myTable_""myColumn""_foreign_idx"`, and db2
  left the constraint name unquoted entirely.
- sqlite3, snowflake and ibmi ignored `withoutForeignKeyConstraints`.
- postgres dereferenced `options.schema`, `options.table` and
  `options.withoutForeignKeyConstraints` without guarding, so `attributeToSQL`
  threw for any attribute with `references` and no options. Deferrable
  references were unreachable as a result.
- mssql and ibmi threw on plain string attributes such as `{ id: 'INTEGER' }`,
  which the other seven dialects accept.
- snowflake and sqlite3 did not normalize the data type in `addColumnQuery`.
- `columnName` is now honoured by every dialect, not only sqlite3.

Co-Authored-By: Claude Opus 5 <[email protected]>
…ause

Neither dialect can change a column's type and its nullability in a single
ALTER COLUMN clause, and both got it wrong in a different way.

db2's `attributeToSQL` returned an array of fragments in the changeColumn
context so that `changeColumnQuery` could split them into separate clauses,
which meant one method returned a string or an array depending on its options.
Worse, the COMMENT branch that follows appended to that array, coercing it into
`DATA TYPE INTEGER,DROP NOT NULL COMMENT Test` and collapsing the two clauses
back into one invalid fragment.

ibmi produced `ALTER COLUMN "c" SET DATA TYPE INTEGER DROP NOT NULL`, a single
clause the server rejects, and joined multiple columns with a comma rather than
repeating ALTER COLUMN.

`attributeToSQL` now always returns a string. `changeColumnQuery` receives the
attribute definitions alongside the generated SQL and emits the nullability as
its own clause, so both dialects produce the form db2 already produced for
`allowNull: false`.

ibmi also quotes the column through `quoteIdentifier` instead of interpolating
double quotes directly.

Co-Authored-By: Claude Opus 5 <[email protected]>
Removes the notes describing behaviour this branch fixed, and corrects two that
were wrong: db2 and mssql drop the referential actions of repeated references
to the same table on purpose, because both servers reject more than one
cascading constraint to a table. Only db2's extra rule for unique attributes
has no known justification, so that one keeps a TODO.

Co-Authored-By: Claude Opus 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true

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.

Follow-up to the previous commit, which restored guards that turned out to be
describing restrictions that do not exist. Verified against db2 12.1.4, SQL
Server 2025, Oracle 23.26, MySQL 8.4 and MariaDB 11.6:

- db2, mssql and oracle accept a DEFAULT on their LOB types. `CLOB DEFAULT
  'abc'`, `NVARCHAR(MAX) DEFAULT N'abc'` and `BLOB DEFAULT BLOB('abc')` all
  work. The SQL Server folklore appears to come from CREATE TABLE's rule that
  CHECK constraints cannot be defined on text/ntext/image, which is a different
  clause. Those three lists are removed.
- `.BINARY` on a string type is a collation, not a storage class, and every
  server tested accepts a default on such a column. That guard is removed
  everywhere rather than repaired.

mariadb, mysql, snowflake and ibmi keep the lists they already had, now matched
by data type identity rather than by rendered SQL string.

Without this, a `defaultValue` the user asked for would silently vanish.

Co-Authored-By: Claude Opus 5 <[email protected]>
Giving `attributeToSQL` a single column option made db2's `addColumn` foreign
key branch reachable for the first time: it used to require `options.foreignKey`,
which db2's `addColumnQuery` never passed, and now reads `attribute.field`,
which it does set.

The branch separated the two clauses with a comma, which db2 rejects — ALTER
TABLE actions are not comma separated. It now uses ` ADD CONSTRAINT`, the same
form ibmi uses, which db2 accepts.

Caught by the removeColumn integration test against db2 12.1.4.

Co-Authored-By: Claude Opus 5 <[email protected]>
@wikirik-agent
wikirik-agent force-pushed the attributes-to-sql-typescript branch from 443f785 to 49d43c3 Compare September 12, 2026 00:55
Moves both methods out of every dialect's `query-generator.js` and into its
`query-generator-typescript.internal.ts`, and renames them from `attributeToSQL`
/ `attributesToSQL` to `attributeToSql` / `attributesToSql`.

Closes the last item of sequelize#15533.

The core declaration is now a typed contract every dialect implements, rather
than a `ColumnsDescription` signature that described none of them. The new
`AttributeToSqlColumn` interface documents what the dialects actually read, and
is deliberately wider than `NormalizedAttributeOptions` because these methods
are also called with `describeTable` output, where the type is a raw SQL string.

`isBinaryStringType` joins `attributeTypeToDataTypeId` in the core data type
utilities, replacing the `attribute.type.options?.binary` reach-through.

No SQL changes. The pinned suites produce byte-identical output for all nine
dialects. Typing the tests did surface two things they were getting wrong:
a `deferrable` passed as a raw string rather than the `Deferrable` enum, and a
leftover pre-rename option name.

Three no-op arguments went away because the compiler proved they could not do
anything: `AttributeToSqlOptions` and `EscapeOptions` share no properties, so
mssql and snowflake were handing `escape` an object it could never read, and
several `toSql({ dialect })` calls passed an argument no implementation accepts.

Co-Authored-By: Claude Opus 5 <[email protected]>
@wikirik-agent

Copy link
Copy Markdown
Contributor Author

Superseded by #18401. Now that the agent account can push to this repo, the same commits have been reopened from sequelize/sequelize as part of stack #18403, so each PR only shows its own changes.

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