Skip to content

fix(driver): ignore a length carried by types that accept none - #12742

Open
tada5hi wants to merge 8 commits into
typeorm:masterfrom
tada5hi:fix/12741-postgres-length-on-lengthless-types
Open

tada5hi wants to merge 8 commits into
typeorm:masterfrom
tada5hi:fix/12741-postgres-length-on-lengthless-types

Conversation

@tada5hi

@tada5hi tada5hi commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #12741

What

A length on a column type that accepts none reaches validation, DDL rendering, and schema comparison. All three paths now ignore it consistently.

Every schema-backed driver consults its normalized withLengthColumnTypes allowlist before honoring a declared length. This keeps one shared entity portable across dialects: { type: "uuid", length: 36 } becomes native uuid on PostgreSQL and MariaDB, while MySQL uses varchar(36). Driver defaults such as generated UUID widths remain intact.

Schema comparison now uses getColumnLength() instead of raw metadata in PostgreSQL, CockroachDB, Aurora MySQL, SQLite, and React Native, closing the remaining perpetual-drift paths. PostgreSQL and CockroachDB also match direct TableColumn type names case-insensitively.

The public column-option docs now state that an unsupported length is ignored.

Tests

  • getColumnLength and createFullType unit matrix across PostgreSQL/Aurora, CockroachDB, MySQL/Aurora, Oracle, SQL Server, SAP, Spanner, SQLite, and React Native
  • metadata validation across every constructible driver family
  • functional synchronize-plus-schema-log coverage across the database CI drivers, including exact UUID type/length assertions for PostgreSQL, MySQL, and MariaDB

Local verification: 254 unit tests and 16 entity-metadata-validator/schema tests pass; tsc --noEmit, targeted Prettier, and ESLint complete with zero errors. Live PostgreSQL 18, MySQL 9, MariaDB 10.11, and sql.js runs all report zero follow-up schema queries.

Copilot AI review requested due to automatic review settings July 29, 2026 07:59

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@pkg-pr-new

pkg-pr-new Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12742
    

commit: 32504a7

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (4) 📜 Skill insights (0)

Grey Divider


Action required

1. Validator contains comment noise 📘 Rule violation ⚙ Maintainability
Description
The removed validation is replaced by a ten-line narrative comment that restates the PR rationale
and downstream implementation rather than clarifying non-obvious local code. This is extra AI-like
commentary prohibited by the checklist and makes the validator harder to scan.
Code

src/metadata-builder/EntityMetadataValidator.ts[R135-138]

+                    // a length carried by a type that accepts none is ignored
+                    // rather than rejected. One entity definition is expected
+                    // to run on several drivers, and whether a type takes a
+                    // length is a property of the driver, not of the entity:
Evidence
PR Compliance ID 4 prohibits extra AI-like comments. The cited block is a ten-line implementation
narrative describing portability, MySQL/Postgres normalization, DDL rendering, and schema comparison
despite having no local statement to explain.

Rule 4: Remove AI-generated noise
src/metadata-builder/EntityMetadataValidator.ts[135-144]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Remove the oversized narrative comment left where unsupported-length validation was deleted.
## Issue Context
The behavior is already documented publicly and implemented in driver methods; the validator does not need a PR-style explanation of cross-driver behavior and downstream call sites.
## Fix Focus Areas
- src/metadata-builder/EntityMetadataValidator.ts[135-144]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Length validation removed globally 🐞 Bug ≡ Correctness
Description
EntityMetadataValidator no longer rejects (or strips) ColumnMetadata.length when the current
driver’s normalized type is not in driver.withLengthColumnTypes. Several other drivers still
render any provided length in createFullType (via getColumnLength), so a now-accepted definition
like { type: "int", length: 10 } can generate invalid DDL (e.g. int(10) on SQL Server) or cause
perpetual schema diffs.
Code

src/metadata-builder/EntityMetadataValidator.ts[R135-138]

+                    // a length carried by a type that accepts none is ignored
+                    // rather than rejected. One entity definition is expected
+                    // to run on several drivers, and whether a type takes a
+                    // length is a property of the driver, not of the entity:
Evidence
The PR removes the validator’s length-support check, but multiple non-Postgres/Cockroach drivers
still treat any column.length as renderable, so unsupported lengths can now reach DDL generation
and schema comparison for those drivers.

src/metadata-builder/EntityMetadataValidator.ts[122-154]
src/driver/sqlserver/SqlServerDriver.ts[768-817]
src/driver/mysql/MysqlDriver.ts[880-934]
src/driver/oracle/OracleDriver.ts[742-799]
src/driver/spanner/SpannerDriver.ts[572-614]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`EntityMetadataValidator` no longer enforces any rule around `column.length`. Postgres/Cockroach now ignore unsupported lengths in their drivers, but other drivers (e.g. SqlServer/MySQL/Oracle/Spanner) still append a length whenever `column.length` is set.
This makes previously-invalid entity definitions newly pass validation, but they can still generate invalid DDL (or schema drift) on those other drivers.
### Issue Context
Before this PR, the validator prevented `length` from reaching drivers for types outside `driver.withLengthColumnTypes`. With the check removed, the behavior is only safe on drivers that were updated to ignore unsupported lengths.
### Fix Focus Areas
- src/metadata-builder/EntityMetadataValidator.ts[122-154]
- src/driver/sqlserver/SqlServerDriver.ts[768-817]
- src/driver/mysql/MysqlDriver.ts[880-934]
### Suggested fix
Option A (centralized, minimal):
- In `EntityMetadataValidator.validate(...)`, if `column.length` is set and `normalizedColumn` is **not** in `driver.withLengthColumnTypes`, **clear** the value (e.g. `column.length = ""` or `undefined`) instead of throwing.
- This preserves the PR’s intent (“ignore rather than reject”) while preventing unsupported lengths from reaching drivers that still render them.
Option B (distributed, broader):
- Update every driver’s `getColumnLength`/`createFullType` to consult `withLengthColumnTypes` (as Postgres/Cockroach now do), so ignoring happens consistently at the driver layer.
Add at least one regression test for a non-Postgres/Cockroach driver that currently appends arbitrary lengths (e.g. `mssql`), demonstrating that `{ type: "int", length: 10 }` does not produce `int(10)`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. Missing #12741 test comment 📘 Rule violation ⚙ Maintainability
Description
The new functional tests for this fix don’t include an issue reference comment, reducing
traceability from the tests back to the reported issue. This does not meet the guideline to include
issue references in functional tests when applicable.
Code

test/functional/entity-metadata-validator/column-length/schema-column-length.test.ts[R10-12]

+describe("schema builder > column length", () => {
+    let dataSources: DataSource[]
+
Evidence
PR Compliance ID 3 requires issue fixes to live in functional tests and include an issue reference
comment when applicable. The newly added functional tests introduce coverage for this change but do
not mention #12741 in a comment near the suite/tests.

Rule 3: Prefer functional tests over per-issue tests
test/functional/entity-metadata-validator/column-length/schema-column-length.test.ts[10-12]
test/functional/entity-metadata-validator/column-length/validator-column-length.test.ts[9-12]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New functional tests added for this fix do not reference `#12741` in a test comment, which reduces auditability/traceability.
## Issue Context
Compliance requires issue fixes to live in `test/functional` and include an issue reference comment when applicable.
## Fix Focus Areas
- test/functional/entity-metadata-validator/column-length/schema-column-length.test.ts[10-12]
- test/functional/entity-metadata-validator/column-length/validator-column-length.test.ts[9-12]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Undocumented length ignore behavior 📘 Rule violation ⚙ Maintainability
Description
The PR changes length on unsupported types from being rejected to being silently ignored, which is
a user-facing behavior change. The documentation still describes length generically without noting
driver/type-specific applicability or that it may be ignored.
Code

src/metadata-builder/EntityMetadataValidator.ts[R135-138]

+                    // a length carried by a type that accepts none is ignored
+                    // rather than rejected. One entity definition is expected
+                    // to run on several drivers, and whether a type takes a
+                    // length is a property of the driver, not of the entity:
Evidence
The validator behavior was changed to ignore a length on types that accept none (instead of
throwing), which alters how entity definitions behave at runtime. Documentation pages describing
@Column/ColumnOptions.length do not mention that length support varies by type/driver or that
unsupported lengths are ignored, so users won’t learn about this changed behavior from the docs.

Rule 2: Docs updated for user-facing changes
src/metadata-builder/EntityMetadataValidator.ts[135-144]
docs/docs/help/3-decorator-reference.md[131-139]
docs/docs/entity/1-entities.md[411-434]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
This PR changes runtime behavior: `length` values on types that don’t accept a length are now ignored (instead of throwing). Docs currently describe `length` as a general column option without clarifying that support is type/driver-dependent and that unsupported lengths are ignored.
## Issue Context
- Validator no longer throws for `length` on unsupported types, enabling cross-driver entities.
- Docs should reflect this so users understand that `length` is only applied where supported and otherwise ignored.
## Fix Focus Areas
- docs/docs/help/3-decorator-reference.md[131-139]
- docs/docs/entity/1-entities.md[411-434]
- src/metadata-builder/EntityMetadataValidator.ts[135-144]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Issue test added to test/unit 📘 Rule violation ⚙ Maintainability
Description
The PR adds coverage for #12741 only in the unit test suite (test/unit) rather than the functional
test suite (test/functional) as required. This may reduce end-to-end confidence that the fix
behaves correctly in real schema/migration flows.
Code

test/unit/driver/create-full-type.test.ts[R1-70]

+import { expect } from "chai"
+import { CockroachDriver } from "../../../src/driver/cockroachdb/CockroachDriver"
+import { PostgresDriver } from "../../../src/driver/postgres/PostgresDriver"
+import type { ColumnType } from "../../../src/driver/types/ColumnTypes"
+import type { TableColumn } from "../../../src/schema-builder/table/TableColumn"
+
+describe("driver > createFullType", () => {
+    // Minimal driver instances via Object.create to avoid constructor
+    // side effects — createFullType reads withLengthColumnTypes and
+    // spatialTypes only.
+    const build = (ctor: { prototype: object }) => {
+        const driver = Object.create(ctor.prototype)
+        driver.withLengthColumnTypes = [
+            "character varying",
+            "varchar",
+        ] as ColumnType[]
+        driver.spatialTypes = ["geometry", "geography"] as ColumnType[]
+        return driver as { createFullType(column: TableColumn): string }
+    }
+
+    const column = (options: Partial<TableColumn>) => options as TableColumn
+
+    const drivers: [string, { createFullType(column: TableColumn): string }][] =
+        [
+            ["PostgresDriver", build(PostgresDriver)],
+            ["CockroachDriver", build(CockroachDriver)],
+        ]
+
+    for (const [name, driver] of drivers) {
+        describe(name, () => {
+            it("renders a length for a type that accepts one", () => {
+                expect(
+                    driver.createFullType(
+                        column({ type: "varchar", length: "255" }),
+                    ),
+                ).to.equal("varchar(255)")
+            })
+
+            it("ignores a length carried by a type that accepts none", () => {
+                expect(
+                    driver.createFullType(
+                        column({ type: "uuid", length: "36" }),
+                    ),
+                ).to.equal("uuid")
+            })
+
+            it("renders no length when none is set", () => {
+                expect(
+                    driver.createFullType(column({ type: "uuid" })),
+                ).to.equal("uuid")
+            })
+
+            it("still renders precision and scale", () => {
+                expect(
+                    driver.createFullType(
+                        column({ type: "numeric", precision: 5, scale: 2 }),
+                    ),
+                ).to.equal("numeric(5,2)")
+            })
+
+            it("still renders precision alone", () => {
+                expect(
+                    driver.createFullType(
+                        column({ type: "numeric", precision: 5 }),
+                    ),
+                ).to.equal("numeric(5)")
+            })
+        })
+    }
+})
Evidence
PR Compliance ID 3 requires issue fixes to add or update tests in test/functional. The PR instead
introduces a new unit test file under test/unit/driver/, with no corresponding functional test
coverage.

Rule 3: Prefer functional tests over per-issue tests
test/unit/driver/create-full-type.test.ts[1-70]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The change for #12741 is tested only via a new unit test under `test/unit`, but the compliance checklist requires issue fixes to live in the functional test suite.
## Issue Context
This PR closes #12741 and introduces `test/unit/driver/create-full-type.test.ts` to validate `createFullType()` behavior for Postgres and Cockroach.
## Fix Focus Areas
- test/unit/driver/create-full-type.test.ts[1-70]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View review recommended (1)
6. Case-sensitive length lookup 🐞 Bug ≡ Correctness
Description
createFullType now appends (length) only when column.type exactly matches a lowercased entry in
withLengthColumnTypes, so a supported type provided with different casing (e.g. "VARCHAR") will drop
its length and generate incorrect DDL. This can affect migration/query-runner code paths that
construct TableColumn objects directly (no metadata normalization).
Code

src/driver/postgres/PostgresDriver.ts[R1339-1345]

+        // a length is only rendered for the types that accept one, so a
+        // length carried by a type that takes none (uuid, for instance)
+        // cannot produce an unparsable type such as "uuid(36)"
+        if (
+            column.length &&
+            this.withLengthColumnTypes.indexOf(column.type as ColumnType) !== -1
+        ) {
Evidence
The new code uses indexOf(column.type) against a lowercase allowlist, but TableColumn.type is a
free-form string and query runners feed it to createFullType as-is when generating DDL, so a
differently cased but valid SQL type name will no longer get its length appended.

src/driver/postgres/PostgresDriver.ts[1336-1347]
src/driver/cockroachdb/CockroachDriver.ts[920-931]
src/driver/postgres/PostgresDriver.ts[247-257]
src/driver/cockroachdb/CockroachDriver.ts[210-217]
src/schema-builder/table/TableColumn.ts[18-22]
src/driver/postgres/PostgresQueryRunner.ts[5164-5169]
src/driver/cockroachdb/CockroachQueryRunner.ts[4470-4490]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`createFullType` checks `withLengthColumnTypes` using an exact, case-sensitive match against `column.type`. Since `TableColumn.type` is an arbitrary string and query runners call `driver.createFullType(column)` directly, types like `"VARCHAR"` won’t match the driver’s lowercase allowlist and will incorrectly omit the `(length)`.
### Issue Context
- `withLengthColumnTypes` entries are lowercase canonical names.
- `TableColumn.type` is not constrained/normalized for user-constructed `TableColumn` objects (e.g. in migrations).
### Fix
- Compare a normalized (e.g. `toLowerCase()`) version of `column.type` against `withLengthColumnTypes`, but continue to use the original `column.type` when constructing the output string (so you don’t change emitted casing).
- Add a unit test covering an uppercase/mixed-case type like `{ type: "VARCHAR", length: "255" }` to ensure it still renders `VARCHAR(255)`.
### Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[1339-1347]
- src/driver/cockroachdb/CockroachDriver.ts[923-931]
- test/unit/driver/create-full-type.test.ts[31-37]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Grey Divider

Tip of the day
💡 Did you know, you can turn on the rule miner and Qodo learns your standards from review history

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@tada5hi
tada5hi force-pushed the fix/12741-postgres-length-on-lengthless-types branch from 4945bb2 to 826c828 Compare July 29, 2026 08:10
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

PostgresDriver and CockroachDriver appended `(length)` to any column
carrying a `length`, without checking whether the type accepts one, so
`createFullType({ type: "uuid", length: "36" })` produced `uuid(36)` -
not a valid type. Both drivers already declare the types that do accept
a length via `withLengthColumnTypes`, which the check now consults.

The other drivers are unaffected: mysql, oracle and sqlserver render
through `getColumnLength()`, and the types that take no length there
normalize to ones that do (mysql maps `uuid` to `varchar` before this
point).

Closes typeorm#12741
@tada5hi
tada5hi force-pushed the fix/12741-postgres-length-on-lengthless-types branch from 826c828 to 2515fb1 Compare July 29, 2026 08:12
@alumni alumni changed the title fix(driver): do not render a length for types that accept none fix(postgres): do not render a length for types that accept none Jul 29, 2026
@tada5hi

tada5hi commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@alumni is there a timeline, when and if you intend to release this fix?

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@tada5hi tada5hi changed the title fix(postgres): do not render a length for types that accept none fix(driver): ignore a length carried by types that accept none Aug 5, 2026
…none

Rendering was only one of three places a length reached. `uuid(36)` could no
longer be produced, but the column still could not be defined: the validator
rejected it up front, and had it passed, `getColumnLength` would have reported
the declared length while postgres reports none for such a column, so it read
as changed on every synchronization and generated a destructive `DROP COLUMN`
plus re-`ADD`.

Whether a type accepts a length is a property of the driver, not of the entity.
`uuid` normalizes to `varchar` on mysql, where a length applies, and stays
native on postgres, where it does not, and the same holds for other types
across the drivers typeorm supports. Rejecting the length made such a column
undefinable for a codebase targeting more than one driver, with no portable
alternative: a per-driver column type is not expressible, since the entity
classes are shared.

The length is now ignored consistently, so carrying one is harmless: it is not
rendered, not rejected, and not reported for comparison. `normalizeType` is
consulted rather than the raw type, so a column declared with a constructor
(`@Column({ length: 255 })` on a string property arrives as String) still
reports its length.

Verified against postgres 18 and mysql 9: one entity declaring
`{ type: "uuid", length: 36 }` yields a native `uuid` on postgres and
`varchar(36)` on mysql, with zero drift over repeated synchronizations, while
varchar, char, array and numeric columns are unaffected.
@tada5hi
tada5hi force-pushed the fix/12741-postgres-length-on-lengthless-types branch from f332338 to 8349db1 Compare August 5, 2026 13:32
@tada5hi
tada5hi marked this pull request as draft August 5, 2026 13:42
tada5hi added a commit to authup/authup that referenced this pull request Aug 5, 2026
#3409)

Pinning `length: 36` needs three changes in typeorm, not one. Postgres must
stop rendering the length (typeorm/typeorm#12742), stop rejecting it in
`EntityMetadataValidator`, and stop comparing it in `getColumnLength`.

The third is the one that decides feasibility and is unwritten: `getColumnLength`
returns the metadata length while postgres reads back none, so with only the
first two the column is seen as changed on every boot and generates a
destructive `DROP COLUMN` plus re-`ADD`. Verified by simulating each part
against postgres 18: parts 1+2 drift 2 statements per pass indefinitely, all
three converge to 0.
tada5hi added 2 commits August 5, 2026 17:38
Use each driver's normalized length allowlist consistently during type
rendering and schema comparison. Preserve driver-specific defaults,
including generated UUID widths, while native MariaDB UUID remains
lengthless.

Add cross-driver unit and schema coverage and document the ignored
option.
Align the typeorm#8832 regression with the relaxed validator contract. Physical native types remain lengthless and are covered by the schema drift test.
@tada5hi
tada5hi marked this pull request as ready for review August 5, 2026 16:16
@alumni
alumni self-requested a review August 27, 2026 08:59
mkovac-conductive added a commit to mkovac-conductive/typeorm that referenced this pull request Aug 27, 2026
…ort it in postgres

Geometry/geography (and other) column types have no precision or scale in
the Postgres catalog, so the value from entity metadata (for geometry, used
only to control ST_AsGeoJSON precision on read) never matches what is
introspected back. findChangedColumns therefore always reported such columns
as changed, causing the schema builder to drop and recreate related foreign
keys, composite indices, and composite unique constraints, and emit a no-op

    ALTER TABLE ... ALTER COLUMN ... TYPE ...

on every synchronize/migration:generate.

Only compare precision when the column type is in withPrecisionColumnTypes,
and scale when it is in withScaleColumnTypes, mirroring how length is handled
generically in typeorm#12742. The same guard is applied to the precision/scale
branch of PostgresQueryRunner.changeColumn.

Closes typeorm#12800

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@michaelbromley

Copy link
Copy Markdown
Member

This repository was recently restructured into a pnpm workspace, and the typeorm package moved from the repo root into packages/typeorm (PR #12854). Everything moved as a pure rename with no content changes, so your branch should replay across the move cleanly once git's rename detection limit is raised:

git fetch origin
git -c merge.renameLimit=999999 -c diff.renameLimit=999999 rebase origin/master

If your branch has diverged enough that a full rebase isn't worth it, scripts/migrate-pr-to-packages-layout.sh --replay (run on top of master) rewrites the paths of your net diff instead. Both approaches, plus a path-mapping table and a prompt you can hand to a coding agent, are documented in scripts/migrate-pr-to-packages-layout.md.

Sorry for the disruption, and thanks for your patience.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

linked-issue PR references an issue

Development

Successfully merging this pull request may close these issues.

PostgresDriver.createFullType appends a length to types that do not take one (uuid(36))

3 participants