Skip to content

fix(schema): use ALTER COLUMN instead of DROP/ADD for type changes - #11620

Open
BenraouaneSoufiane wants to merge 163 commits into
typeorm:masterfrom
BenraouaneSoufiane:fix-migration
Open

BenraouaneSoufiane wants to merge 163 commits into
typeorm:masterfrom
BenraouaneSoufiane:fix-migration

Conversation

@BenraouaneSoufiane

@BenraouaneSoufiane BenraouaneSoufiane commented Aug 23, 2025 •

Copy link
Copy Markdown

Summary

Some column changes currently follow the DROP/ADD path, which can lead to data loss (reported in #3357).

This PR updates the DROP/ADD guard so that columns are recreated only when the change is not safely alterable (for example, cross-family type changes). Otherwise, the change proceeds through the driver-specific ALTER COLUMN path.

Examples of changes that should not require DROP/ADD:

Strings (widening only)

  • CHAR → VARCHAR (same or larger length)
  • NCHAR → NVARCHAR (same or larger length)
  • VARCHAR(n) → VARCHAR(m) where m >= n
  • NVARCHAR2 widening (Oracle)
  • VARCHAR → TEXT / NTEXT / CLOB

Numerics (precision/width widening)

  • Integer widening:

    • TINYINT → SMALLINT
    • SMALLINT → INT
    • INT → BIGINT
  • DECIMAL / NUMERIC precision or scale increase

  • Unparameterized → parameterized numeric types

    • e.g. DECIMAL → DECIMAL(10,2)
  • Floating-point widening:

    • FLOAT → DOUBLE
    • REAL → DOUBLE
    • FLOAT ↔ REAL (treated as compatible)

Temporals

  • Same temporal type with parameter changes

    • e.g. TIME(3) → TIME(6)
  • DATE → TIMESTAMP / DATETIME / DATETIME2 / DATETIMEOFFSET

  • Datetime-family widening:

    • DATETIME → TIMESTAMP
    • DATETIME → DATETIME2
    • DATETIME → DATETIMEOFFSET
    • DATETIME2 → DATETIMEOFFSET

Additional changes

  • Refactors duplicated alter-column logic across multiple drivers
  • Extends alter-path support for length-only changes
  • Adds schema-builder tests covering widening and reducing varchar length changes
  • Preserves existing rebuild behavior for drivers that require table recreation (e.g. SQLite family)

@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: 0

🧹 Nitpick comments (5)
src/driver/postgres/PostgresQueryRunner.ts (1)

1544-1560: Normalize length and guard by length-capable types to avoid spurious ALTERs; also short-circuit when type strings are equal.

In some paths oldColumn.length may be "" (default) while newColumn.length is undefined, which would trigger an ALTER even when the effective type is unchanged. Also, we should restrict this branch to types in driver.withLengthColumnTypes and skip if createFullType(old) === createFullType(new) to prevent redundant alters.

Apply this diff in the length-handling block:

-            // Handle length changes without recreating the column (e.g., varchar(n) -> varchar(m))
-            if (newColumn.length !== oldColumn.length) {
-                upQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(newColumn)}`,
-                    ),
-                )
-                downQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" TYPE ${this.driver.createFullType(oldColumn)}`,
-                    ),
-                )
-            }
+            // Handle length changes without recreating the column (e.g., varchar(n) -> varchar(m))
+            const oldLen =
+                oldColumn.length === "" || oldColumn.length == null
+                    ? undefined
+                    : oldColumn.length
+            const newLen =
+                newColumn.length === "" || newColumn.length == null
+                    ? undefined
+                    : newColumn.length
+
+            const newType = this.driver.createFullType(newColumn)
+            const oldType = this.driver.createFullType(oldColumn)
+
+            if (
+                oldLen !== newLen &&
+                this.driver.withLengthColumnTypes.indexOf(
+                    newColumn.type as ColumnType,
+                ) !== -1 &&
+                newType !== oldType
+            ) {
+                upQueries.push(
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN "${newColumn.name}" TYPE ${newType}`,
+                    ),
+                )
+                downQueries.push(
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN "${newColumn.name}" TYPE ${oldType}`,
+                    ),
+                )
+            }
test/github-issues/3357/issue-3357.ts (4)

71-77: Tighten negative assertion to avoid false positives from unrelated “ADD …” statements.

For robustness, forbid only “ADD COLUMN”, not any “ADD” (which could match “ADD CONSTRAINT” in unrelated diffs).

-        expect(upSql).to.not.match(/\bADD\b/i)
+        expect(upSql).to.not.match(/\bADD\s+COLUMN\b/i)

64-75: Also assert the down-migration reverts the length.

This ensures the generated down SQL mirrors the change (51 -> 50) and protects against regressions.

         const upSql = sqlInMemory.upQueries.map((q) => q.query).join("\n")
+        const downSql = sqlInMemory.downQueries.map((q) => q.query).join("\n")

         // Helpful for debugging
         console.log(
             "\n--- generated SQL ---\n" + upSql + "\n---------------------\n",
         )

         // Expect ALTER TYPE and forbid DROP/ADD
         expect(upSql).to.match(
             /ALTER TABLE .* ALTER COLUMN .* TYPE .*character varying\(51\)/i,
         )
         expect(upSql).to.not.match(/DROP COLUMN/i)
-        expect(upSql).to.not.match(/\bADD\b/i)
+        expect(upSql).to.not.match(/\bADD\s+COLUMN\b/i)
+
+        // And the down SQL should revert back to length 50
+        expect(downSql).to.match(
+            /ALTER TABLE .* ALTER COLUMN .* TYPE .*character varying\(50\)/i,
+        )

66-69: Reduce noisy test output.

Wrap the debugging log behind an env flag to keep CI logs clean.

-        console.log(
-            "\n--- generated SQL ---\n" + upSql + "\n---------------------\n",
-        )
+        if (process.env.DEBUG_SQL) {
+            // eslint-disable-next-line no-console
+            console.log(
+                "\n--- generated SQL ---\n" + upSql + "\n---------------------\n",
+            )
+        }

11-23: Optional: add coverage for varchar unlimited ↔ length and array of varchar.

Consider adding follow-up tests for:

  • varchar → varchar(51) and varchar(51) → varchar (unlimited)
  • varchar(50)[] → varchar(51)[] (array)
    These exercise the same code path and guard against regressions in length parsing for arrays.

If you want, I can draft the additional entity and test blocks.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 22b26d1 and d5acde1.

📒 Files selected for processing (4)
  • src/driver/postgres/PostgresQueryRunner.ts (1 hunks)
  • test/github-issues/3357/entity/BugInitial.ts (1 hunks)
  • test/github-issues/3357/entity/BugUpdated.ts (1 hunks)
  • test/github-issues/3357/issue-3357.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
test/github-issues/3357/issue-3357.ts (1)
test/utils/test-utils.ts (2)
  • createTestingConnections (388-482)
  • closeTestingConnections (487-495)
src/driver/postgres/PostgresQueryRunner.ts (1)
src/driver/Query.ts (1)
  • Query (4-8)
test/github-issues/3357/entity/BugUpdated.ts (3)
test/github-issues/3357/entity/BugInitial.ts (1)
  • Entity (3-10)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
test/github-issues/3357/entity/BugInitial.ts (3)
test/github-issues/3357/entity/BugUpdated.ts (1)
  • Entity (3-10)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
🔇 Additional comments (3)
src/driver/postgres/PostgresQueryRunner.ts (1)

1544-1560: Great fix: ALTER TYPE for varchar length changes avoids data loss from DROP/ADD.

This change correctly keeps data intact by issuing ALTER COLUMN ... TYPE when only the length changes. Placement and symmetry of up/down queries look good.

test/github-issues/3357/entity/BugUpdated.ts (1)

1-10: LGTM: updated entity reflects the target varchar(51).

test/github-issues/3357/entity/BugInitial.ts (1)

1-10: LGTM: initial entity correctly sets varchar(50) for the test baseline.

@sgarner sgarner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for your contribution @BenraouaneSoufiane

Can you implement this for all the drivers (at least those which support it)? We won't want to merge this feature just for PostgreSQL.

Comment thread test/github-issues/3357/issue-3357.ts Resolved
…upport other drivers, move the associated test into its right path

@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: 4

🧹 Nitpick comments (8)
src/driver/sqlserver/SqlServerQueryRunner.ts (2)

1258-1284: Length-only path can duplicate ALTERs; gate it and scope to length-capable types.

Right now this pushes an ALTER and later the generic isColumnChanged path can push a second ALTER for the same column. Also, restrict to types that actually support length.

Apply:

-        // BEGIN: handle varchar length-only changes without recreating (SQL Server)
-        if (
-            oldColumn.type === newColumn.type &&
-            oldColumn.length !== newColumn.length
-        ) {
+        // BEGIN: handle varchar length-only changes without recreating (SQL Server)
+        let handledLengthOnly = false
+        const supportsLength =
+            this.driver.withLengthColumnTypes.indexOf(
+                newColumn.type as ColumnType,
+            ) !== -1
+        if (
+            supportsLength &&
+            oldColumn.type === newColumn.type &&
+            oldColumn.length !== newColumn.length
+        ) {
             const upType = this.driver.createFullType(newColumn)
             const downType = this.driver.createFullType(oldColumn)
             const upNull = newColumn.isNullable ? "NULL" : "NOT NULL"
             const downNull = oldColumn.isNullable ? "NULL" : "NOT NULL"
 
             upQueries.push(
                 new Query(
                     `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" ${upType} ${upNull}`,
                 ),
             )
             downQueries.push(
                 new Query(
                     `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${newColumn.name}" ${downType} ${downNull}`,
                 ),
             )
+            handledLengthOnly = true
         }
         // END

1623-1652: Skip generic ALTER when length-only branch already handled it.

Prevents emitting two ALTER COLUMN statements for the same change.

Apply:

-            if (
-                this.isColumnChanged(oldColumn, newColumn, false, false, false)
-            ) {
+            if (
+                !handledLengthOnly &&
+                this.isColumnChanged(oldColumn, newColumn, false, false, false)
+            ) {
src/driver/cockroachdb/CockroachQueryRunner.ts (2)

1308-1329: Optional: guard to true “length-capable” types

Minor safety: only emit this path for types listed in driver.withLengthColumnTypes.

Proposed change:

-        if (
-            oldColumn.type === newColumn.type &&
-            oldColumn.length !== newColumn.length
-        ) {
+        if (
+            oldColumn.type === newColumn.type &&
+            oldColumn.length !== newColumn.length &&
+            this.driver.withLengthColumnTypes.includes(
+                newColumn.type as ColumnType,
+            )
+        ) {

1290-1329: Add test: length change + rename combo

Please add a Cockroach test where a varchar length change is combined with a column rename in one diff to ensure the sequence and down migration work.

I can draft a focused test under test/functional or github-issues if you’d like.

src/driver/mysql/MysqlQueryRunner.ts (2)

1049-1075: Optional: limit to true length-capable types

As with other drivers, guard this branch with withLengthColumnTypes to avoid generating no-op ALTERs.

-        if (
+        if (
             oldColumn.type === newColumn.type &&
-            oldColumn.length !== newColumn.length
+            oldColumn.length !== newColumn.length &&
+            this.driver.withLengthColumnTypes.includes(
+                newColumn.type as ColumnType,
+            )
         ) {

1049-1075: Add tests for rename + length change and ensure no duplicate ALTERs

Please extend MySQL functional tests to cover:

  • length-only change (no rename)
  • combined rename + length change
  • verify single CHANGE is emitted for length-only and no duplicate CHANGE alongside the later isColumnChanged path.

Happy to draft the test cases mirroring the Postgres ones.

src/driver/oracle/OracleQueryRunner.ts (2)

1078-1094: Duplicate DDL: emits two MODIFY statements for length-only changes

The general isColumnChanged branch already emits ALTER TABLE ... MODIFY with createFullType(newColumn), so this block causes an unnecessary second MODIFY. Remove it to avoid redundant DDL.


1078-1094: If you decide to keep a targeted path, constrain and reorder it

  • Gate to length-capable types only (e.g., withLengthColumnTypes and string-like types).
  • Execute after rename bookkeeping so the column name is valid, or target the pre-rename name.
  • Use else-if/early-return to avoid double-emitting MODIFY.
  • For consistency, prefer this.connection.driver.createFullType.

I can provide a corrected patch if you choose this route.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d5acde1 and b060329.

📒 Files selected for processing (6)
  • src/driver/cockroachdb/CockroachQueryRunner.ts (1 hunks)
  • src/driver/mysql/MysqlQueryRunner.ts (1 hunks)
  • src/driver/oracle/OracleQueryRunner.ts (1 hunks)
  • src/driver/postgres/PostgresQueryRunner.ts (1 hunks)
  • src/driver/sqlserver/SqlServerQueryRunner.ts (1 hunks)
  • test/functional/schema-builder/change-column.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/driver/postgres/PostgresQueryRunner.ts
🧰 Additional context used
🧬 Code graph analysis (5)
test/functional/schema-builder/change-column.ts (2)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
src/driver/oracle/OracleQueryRunner.ts (1)
src/driver/Query.ts (1)
  • Query (4-8)
src/driver/mysql/MysqlQueryRunner.ts (2)
src/schema-builder/table/TableColumn.ts (1)
  • TableColumn (6-228)
src/driver/Query.ts (1)
  • Query (4-8)
src/driver/cockroachdb/CockroachQueryRunner.ts (1)
src/driver/Query.ts (1)
  • Query (4-8)
src/driver/sqlserver/SqlServerQueryRunner.ts (1)
src/driver/Query.ts (1)
  • Query (4-8)
🔇 Additional comments (3)
test/functional/schema-builder/change-column.ts (2)

12-21: Entities for the repro look good.

Minimal, correct mappings to a shared table make sense for the diff test.


23-30: Updated entity is correct.

Only the varchar length changes; that’s exactly what we want to exercise.

src/driver/oracle/OracleQueryRunner.ts (1)

1078-1094: PR scope drift: Oracle changes contradict PR summary (Postgres-only change)

PR summary states only Postgres behavior is modified; this file alters Oracle. Confirm intent; if scope is Postgres-only, drop this Oracle change from the PR.

Comment thread src/driver/mysql/MysqlQueryRunner.ts Resolved
Comment thread src/driver/oracle/OracleQueryRunner.ts Resolved
Comment thread test/github-issues/3357/issue-3357.ts Resolved
…-column test, remove the dir test/github-issues/3357

@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: 1

♻️ Duplicate comments (2)
src/driver/mysql/MysqlQueryRunner.ts (1)

1233-1269: Avoid accidental rename in CHANGE; fix down target; prevent duplicate ALTERs

Use safe clones with old name for the column definition and target the current name in both up/down. Also sync oldColumn.length to avoid an extra CHANGE later.

Apply:

-            if (
-                this.isColumnChanged(oldColumn, newColumn, true, true) ||
-                oldColumn.length !== newColumn.length
-            ) {
-                upQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} CHANGE \`${
-                            oldColumn.name
-                        }\` ${this.buildCreateColumnSql(newColumn, true)}`,
-                    ),
-                )
-                downQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} CHANGE \`${
-                            newColumn.name
-                        }\` ${this.buildCreateColumnSql(oldColumn, true)}`,
-                    ),
-                )
+            if (
+                this.isColumnChanged(oldColumn, newColumn, true, true) ||
+                oldColumn.length !== newColumn.length
+            ) {
+                // make safe copies to avoid implicit rename via definition
+                const newColDef = new TableColumn({
+                    ...newColumn,
+                    name: oldColumn.name,
+                    asExpression: undefined,
+                    generatedType: undefined,
+                })
+                const oldColDef = new TableColumn({
+                    ...oldColumn,
+                    name: oldColumn.name,
+                    asExpression: undefined,
+                    generatedType: undefined,
+                })
+
+                const up = `ALTER TABLE ${this.escapePath(table)} CHANGE \`${oldColumn.name}\` ${this.buildCreateColumnSql(newColDef, true)}`
+                const down = `ALTER TABLE ${this.escapePath(table)} CHANGE \`${oldColumn.name}\` ${this.buildCreateColumnSql(oldColDef, true)}`
+
+                upQueries.push(new Query(up))
+                downQueries.push(new Query(down))
+
+                // prevent subsequent logic from emitting a duplicate CHANGE
+                oldColumn.length = newColumn.length
             }
test/functional/schema-builder/change-column.ts (1)

44-85: Refactor: use ephemeral testing connections; avoid manual DS reuse of base options

Create isolated connections for this scenario to run safely in CI and not depend on base connections’ DB. This also removes the need for ad-hoc cleanup.

Apply:

-    it("emits ALTER, not DROP/ADD when increasing varchar length", async () => {
-        for (const base of connections) {
-            // We choose postgres
-            if (base.options.type !== "postgres") continue
-
-            // 1) initial schema (varchar(50)) + seed
-            const ds1 = new DataSource({
-                ...(base.options as any),
-                entities: [BugInitial],
-                synchronize: true,
-                dropSchema: false, // ensure we keep the table
-            } as any)
-            await ds1.initialize()
-            await ds1.query(`INSERT INTO "bug" ("example") VALUES ('hello')`)
-
-            // 2) updated metadata (varchar(51)) to compute diff — DO NOT DROP SCHEMA
-            const ds2 = new DataSource({
-                ...(base.options as any),
-                entities: [BugUpdated],
-                synchronize: false, // we’re only logging the diff
-                dropSchema: false, // don’t wipe the tables we just created
-                migrationsRun: false,
-            } as any)
-            await ds2.initialize()
-
-            const { upQueries } = await ds2.driver.createSchemaBuilder().log()
-            const up = upQueries
-                .map((q) => q.query)
-                .join("\n")
-                .toUpperCase()
-
-            expect(up).to.match(/ALTER TABLE .* (ALTER COLUMN|CHANGE|MODIFY)/)
-            expect(up).to.not.match(/\bDROP COLUMN\b/)
-            expect(up).to.not.match(/\bADD COLUMN\b/)
-
-            await ds2.destroy()
-            try {
-                await ds1.dropDatabase()
-            } catch {}
-            await ds1.destroy()
-        }
-    })
+    it("emits ALTER, not DROP/ADD when increasing varchar length", async () => {
+        const bases = await createTestingConnections({
+            entities: [BugInitial],
+            schemaCreate: true,
+            dropSchema: true,
+            enabledDrivers: ["postgres"],
+        })
+        try {
+            for (const ds1 of bases) {
+                await ds1.synchronize()
+                await ds1.query(`INSERT INTO "bug" ("example") VALUES ('hello')`)
+                const ds2 = new DataSource({
+                    ...(ds1.options as any),
+                    entities: [BugUpdated],
+                    synchronize: false,
+                    migrationsRun: false,
+                } as any)
+                await ds2.initialize()
+                const { upQueries } = await ds2.driver.createSchemaBuilder().log()
+                const up = upQueries.map((q) => q.query).join("\n")
+                expect(up).to.match(/ALTER TABLE .* ALTER COLUMN .* TYPE .*VARYING\(51\)/i)
+                expect(up).to.not.match(/\bDROP COLUMN\b/i)
+                expect(up).to.not.match(/\bADD COLUMN\b/i)
+                await ds2.destroy()
+            }
+        } finally {
+            await closeTestingConnections(bases)
+        }
+    })
🧹 Nitpick comments (1)
test/functional/schema-builder/change-column.ts (1)

75-77: Tighten assertion to Postgres-specific TYPE alteration

Match ALTER COLUMN ... TYPE varying(51) to prove length-change path is used.

Apply:

-            expect(up).to.match(/ALTER TABLE .* (ALTER COLUMN|CHANGE|MODIFY)/)
-            expect(up).to.not.match(/\bDROP COLUMN\b/)
-            expect(up).to.not.match(/\bADD COLUMN\b/)
+            expect(up).to.match(/ALTER TABLE .* ALTER COLUMN .* TYPE .*VARYING\(51\)/i)
+            expect(up).to.not.match(/\bDROP COLUMN\b/i)
+            expect(up).to.not.match(/\bADD COLUMN\b/i)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b060329 and 087ae72.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • package.json (1 hunks)
  • src/driver/cockroachdb/CockroachQueryRunner.ts (1 hunks)
  • src/driver/mysql/MysqlQueryRunner.ts (1 hunks)
  • src/driver/oracle/OracleQueryRunner.ts (1 hunks)
  • src/driver/postgres/PostgresQueryRunner.ts (1 hunks)
  • src/driver/sqlserver/SqlServerQueryRunner.ts (1 hunks)
  • test/functional/schema-builder/change-column.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/driver/oracle/OracleQueryRunner.ts
  • src/driver/postgres/PostgresQueryRunner.ts
  • src/driver/sqlserver/SqlServerQueryRunner.ts
  • src/driver/cockroachdb/CockroachQueryRunner.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-27T17:29:18.547Z
Learnt from: alumni
PR: typeorm/typeorm#11581
File: docs/docs/drivers/mongodb.md:9-13
Timestamp: 2025-07-27T17:29:18.547Z
Learning: TypeORM is compatible only with mongodb@^6, not v4 as previously suggested. The package.json file contains the authoritative peer dependency information for the MongoDB driver version compatibility.

Applied to files:

  • package.json
🧬 Code graph analysis (1)
test/functional/schema-builder/change-column.ts (3)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/Column.ts (1)
  • Column (134-220)
src/index.ts (1)
  • DataSource (145-145)
🔇 Additional comments (1)
package.json (1)

144-144: Confirm mysql2 bump compatibility and CI test matrix
^3.14.3 satisfies peerDependencies (^2.2.5 || ^3.0.1) and the Node engine (>= 8.0); update the lockfile and verify CI tests for both MySQL and MariaDB pass.

Comment thread package.json Resolved

@sgarner sgarner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sorry, still not quite there yet!

In addition to code comments:

  • I noticed that AuroraMysqlQueryRunner hasn't been updated, but it should support this feature the same as MysqlQueryRunner.
  • I think SapQueryRunner can support this too.

Comment thread src/driver/mysql/MysqlQueryRunner.ts Resolved
BenraouaneSoufiane and others added 2 commits September 13, 2025 11:15
…nerQueryRunner, SapQueryRunner, AuroraMysqlQueryRunner, remove PG-specific assertion, add similar length change test for reducing

@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: 4

Caution

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

⚠️ Outside diff range comments (3)
src/driver/sap/SapQueryRunner.ts (1)

3392-3395: Typo in thrown error message ("spa driver")

This message is user-facing; fix the typo and clarify the driver name.

Apply:

-            `spa driver does not support change table comment.`,
+            `SAP HANA driver does not support changing table comments.`,
src/driver/spanner/SpannerQueryRunner.ts (2)

857-888: Spanner identifier quoting should use driver escape, not double quotes

These statements should also use this.driver.escape(oldColumn.name).

Apply:

-                    new Query(
-                        `ALTER TABLE ${this.escapePath(
-                            table,
-                        )} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`,
-                    )
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN ${this.driver.escape(oldColumn.name)} DROP NOT NULL`,
+                    )
                 )
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(
-                            table,
-                        )} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`,
-                    )
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN ${this.driver.escape(oldColumn.name)} SET NOT NULL`,
+                    )
                 )
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(
-                            table,
-                        )} ALTER COLUMN "${oldColumn.name}" SET NOT NULL`,
-                    )
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN ${this.driver.escape(oldColumn.name)} SET NOT NULL`,
+                    )
                 )
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(
-                            table,
-                        )} ALTER COLUMN "${oldColumn.name}" DROP NOT NULL`,
-                    )
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(
+                            table,
+                        )} ALTER COLUMN ${this.driver.escape(oldColumn.name)} DROP NOT NULL`,
+                    )

836-855: Spanner DDL: use SET DATA TYPE and driver.escape() for column identifiers — fix required

Current code emits Postgres-style ALTER ... TYPE with double quotes; Spanner requires ALTER TABLE ... ALTER COLUMN SET DATA TYPE ... and driver-specific escaping (this.driver.escape()). Fix the two Query constructions in src/driver/spanner/SpannerQueryRunner.ts (≈ lines 836–855) as shown:

-                upQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${
-                            newColumn.name
-                        }" TYPE ${this.driver.createFullType(newColumn)}`,
-                    ),
-                )
-                downQueries.push(
-                    new Query(
-                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN "${
-                            newColumn.name
-                        }" TYPE ${this.driver.createFullType(oldColumn)}`,
-                    ),
-                )
+                upQueries.push(
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN ${this.driver.escape(
+                            newColumn.name,
+                        )} SET DATA TYPE ${this.driver.createFullType(newColumn)}`,
+                    ),
+                )
+                downQueries.push(
+                    new Query(
+                        `ALTER TABLE ${this.escapePath(table)} ALTER COLUMN ${this.driver.escape(
+                            newColumn.name,
+                        )} SET DATA TYPE ${this.driver.createFullType(oldColumn)}`,
+                    ),
+                )

Run a Spanner integration or generate the DDL via log() to confirm the produced SQL matches Spanner docs.

🧹 Nitpick comments (5)
src/query-runner/BaseQueryRunner.ts (2)

489-491: Update the doc comment: length is now considered here

The comment says length is checked separately, but the code now compares oldColumn.length !== newColumn.length. Please update the comment to avoid confusion.

Apply:

-     * Checks if at least one of column properties was changed.
-     * Does not checks column type, length and autoincrement, because these properties changes separately.
+     * Checks if at least one of column properties was changed.
+     * Does not check column type and autoincrement (handled elsewhere).
+     * Note: length differences are considered here to trigger in-place alterations.

539-541: Normalize length comparison to avoid false positives ("" vs undefined).

Comparing raw strings can mark changes when one side is "" and the other is undefined. Normalize before comparing.

Apply:

-            (checkEnum && this.isEnumChanged(oldColumn, newColumn)) ||
-            oldColumn.length !== newColumn.length
+            (checkEnum && this.isEnumChanged(oldColumn, newColumn)) ||
+            (oldColumn.length ?? "") !== (newColumn.length ?? "")

Please run the schema diff tests across drivers to ensure this does not introduce spurious ALTERs when a column is at default length.

src/driver/sap/SapQueryRunner.ts (2)

1177-1181: Incorrect vendor reference in comment

This is the SAP HANA runner, but the comment mentions SQL Server.

Apply:

-            // SQL Server does not support changing of IDENTITY column, so we must drop column and recreate it again.
+            // SAP HANA does not support changing of IDENTITY column, so we must drop the column and recreate it.

32-35: Class summary mentions SQL Server instead of SAP HANA

Tweak wording to avoid confusion.

Apply:

- * Runs queries on a single SQL Server database connection.
+ * Runs queries on a single SAP HANA database connection.
src/driver/spanner/SpannerQueryRunner.ts (1)

29-32: Class summary mentions Postgres instead of Spanner

Fix the header to match the driver.

Apply:

- * Runs queries on a single postgres database connection.
+ * Runs queries on a single Cloud Spanner database connection.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ad3609 and 401bd73.

📒 Files selected for processing (8)
  • src/driver/aurora-mysql/AuroraMysqlQueryRunner.ts (0 hunks)
  • src/driver/mysql/MysqlQueryRunner.ts (0 hunks)
  • src/driver/oracle/OracleQueryRunner.ts (0 hunks)
  • src/driver/sap/SapQueryRunner.ts (1 hunks)
  • src/driver/spanner/SpannerQueryRunner.ts (1 hunks)
  • src/driver/sqlserver/SqlServerQueryRunner.ts (0 hunks)
  • src/query-runner/BaseQueryRunner.ts (1 hunks)
  • test/functional/schema-builder/change-column.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • src/driver/aurora-mysql/AuroraMysqlQueryRunner.ts
  • src/driver/oracle/OracleQueryRunner.ts
  • src/driver/sqlserver/SqlServerQueryRunner.ts
  • src/driver/mysql/MysqlQueryRunner.ts
🧰 Additional context used
🧬 Code graph analysis (1)
test/functional/schema-builder/change-column.ts (1)
src/driver/DriverUtils.ts (1)
  • DriverUtils (8-297)
🔇 Additional comments (1)
src/driver/sap/SapQueryRunner.ts (1)

1172-1176: LGTM: length change no longer forces drop/add

Removing length from the destructive path is correct; it will now flow to the in-place ALTER (...) form.

BenraouaneSoufiane and others added 9 commits September 13, 2025 14:17
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@alumni

alumni commented Sep 20, 2025 •

Copy link
Copy Markdown
Collaborator

Reducing the length is not possible in SAP HANA on purpose since it's a lossy operation (SAP software tend to prevent lossy operations, it's part of the company culture).

We usually do it like this (for text columns):

RENAME COLUMN "schema"."table"."column" TO "column_OLD";
ALTER TABLE "schema"."table" ADD "column" NVARCHAR(100) DEFAULT '' NOT NULL;
UPDATE "schema"."table" SET "column" = LEFT("column_OLD", 100);
ALTER TABLE "schema"."table" DROP "column_OLD";

The LEFT/SUBARRAY functions won't work for all data types (binary, vectors). In that case, DROP + ADD should be fine.

For SAP and MariaDB (possibly for Postgres too based on my understanding), vector columns with specified length are fixed-length, i.e. they must have data of that exact length, so increasing the length is also not possible with ALTER COLUMN.

I wonder what edge cases can be for other databases.

I would add a test (for all drivers) in which the column that is reduced contains data that is longer than the new size. We might find some more edge cases (not sure if databases trim the values).

I think we should keep the old behavior (DROP + ADD) for quite a lot of situations, for both increasing and decreasing the length :) Maybe we can use it where we know it works.

@BenraouaneSoufiane

Copy link
Copy Markdown
Author

@OSA413, improved, thks!

@OSA413

OSA413 commented May 24, 2026

Copy link
Copy Markdown
Collaborator

Test test\unit\base-query-runner-helper.ts is not run because it's extension is .ts, not .test.ts. Can you please fix this?

@BenraouaneSoufiane

BenraouaneSoufiane commented May 24, 2026 •

Copy link
Copy Markdown
Author

Test test\unit\base-query-runner-helper.ts is not run because it's extension is .ts, not .test.ts. Can you please fix this?

Yes, of course, will let you know once fix it, thnks.

@OSA413 OSA413 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'll review the tests of the PR.

You also should consider the Qodo's comments, some of them may be easy to fix. I would also not just truncate the strings when narrowing them (I will discuss this with alumni).

Meanwhile you can improve the tests by hard-coding the expected schema change against the actual result to see that we are doing it right (as I said, to see exactly what and how much is changed).

Comment on lines +180 to +182
expect(sqlBlob).to.match(
/ALTER TABLE .* ALTER COLUMN "name" (SET DATA TYPE|TYPE) .*varchar/i,
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
expect(sqlBlob).to.match(
/ALTER TABLE .* ALTER COLUMN "name" (SET DATA TYPE|TYPE) .*varchar/i,
)
//THIS IS AN EXAMPLE, DO NOT APPLY THIS CHANGE
expect(sqlBlob.split("\n")[10]).to.eq("ALTER TABLE \"post\" ALTER COLUMN \"name\" TYPE character varying(80)");

I would prefer this type of assertion everywhere where the SQL changes the schema so that we know exactly what and how much is changed, I will discuss with alumni the points of improvements.

@OSA413

OSA413 commented May 24, 2026

Copy link
Copy Markdown
Collaborator

I also see that not all branches are covered in the coverage report, 100% coverage would be ideal (but better than a 100% code coverage is 100% case coverage, which I will discuss with alumni)

@marchantdev

Copy link
Copy Markdown

Following up on OSA413's branch coverage note — I went through BaseQueryRunnerHelper.ts and mapped every uncovered branch. Here are the additions that should bring isSafeAlter and normalizeColumnLength to full branch coverage.

The current test file doesn't import normalizeColumnLength at all, so that exported function has 0% coverage. I've included tests for it at the bottom.

Additional tests to add to test/unit/base-query-runner-helper.ts
import { isSafeAlter, normalizeColumnLength } from "../../src/query-runner/BaseQueryRunnerHelper"

describe("BaseQueryRunnerHelper.isSafeAlter – branch coverage", () => {
    // Lines 184-187: special families always block within-family alters
    describe("special families block same-family alters", () => {
        it("blocks BOOLEAN -> BOOLEAN", () => {
            expect(isSafeAlter(col({ type: "boolean" }), col({ type: "boolean" }))).to.equal(false)
        })
        it("blocks BIT -> BOOL", () => {
            expect(isSafeAlter(col({ type: "bit" }), col({ type: "bool" }))).to.equal(false)
        })
        it("blocks ENUM -> ENUM", () => {
            expect(isSafeAlter(col({ type: "enum" }), col({ type: "enum" }))).to.equal(false)
        })
        it("blocks SET -> SET", () => {
            expect(isSafeAlter(col({ type: "set" }), col({ type: "set" }))).to.equal(false)
        })
        it("blocks UUID -> UUID", () => {
            expect(isSafeAlter(col({ type: "uuid" }), col({ type: "uuid" }))).to.equal(false)
        })
        it("blocks BINARY -> BINARY", () => {
            expect(isSafeAlter(col({ type: "binary" }), col({ type: "binary" }))).to.equal(false)
        })
        it("blocks BYTEA -> BYTEA", () => {
            expect(isSafeAlter(col({ type: "bytea" }), col({ type: "bytea" }))).to.equal(false)
        })
    })

    // Lines 205, 213, 221: unicode encoding mismatch blocks within-family alters
    describe("unicode encoding mismatch blocks string alter", () => {
        it("blocks NCHAR(N) -> VARCHAR(M): unicode mismatch in char->varchar path", () => {
            expect(isSafeAlter(col({ type: "nchar(10)" }), col({ type: "varchar(20)" }))).to.equal(false)
        })
        it("blocks CHAR(N) -> NVARCHAR(M): unicode mismatch in char->varchar path", () => {
            expect(isSafeAlter(col({ type: "char(10)" }), col({ type: "nvarchar(20)" }))).to.equal(false)
        })
        it("blocks NCHAR(N) -> CHAR(M): unicode mismatch in char->char path", () => {
            expect(isSafeAlter(col({ type: "nchar(10)" }), col({ type: "char(20)" }))).to.equal(false)
        })
        it("blocks VARCHAR(N) -> NVARCHAR(M): unicode mismatch in varchar->varchar path", () => {
            expect(isSafeAlter(col({ type: "varchar(100)" }), col({ type: "nvarchar(100)" }))).to.equal(false)
        })
    })

    // Lines 206, 222: unknown lengths assume widening (early return true)
    describe("unknown string lengths assume widening", () => {
        it("allows CHAR -> VARCHAR when both lengths unknown", () => {
            expect(isSafeAlter(col({ type: "char" }), col({ type: "varchar" }))).to.equal(true)
        })
        it("allows NCHAR -> NVARCHAR when new length unknown", () => {
            expect(isSafeAlter(col({ type: "nchar", length: 10 }), col({ type: "nvarchar" }))).to.equal(true)
        })
        it("allows CHAR(N) -> VARCHAR when new length unknown", () => {
            expect(isSafeAlter(col({ type: "char(10)" }), col({ type: "varchar" }))).to.equal(true)
        })
    })

    // Line 229: STR family fallthrough (non-char/varchar transitions)
    describe("string family fallthrough blocks unsupported transitions", () => {
        it("blocks JSON -> XML (both STR family, no handler matched)", () => {
            expect(isSafeAlter(col({ type: "json" }), col({ type: "xml" }))).to.equal(false)
        })
        it("blocks NTEXT -> CLOB (text-likes but not varchar->textLike direction)", () => {
            expect(isSafeAlter(col({ type: "ntext" }), col({ type: "clob" }))).to.equal(false)
        })
        it("blocks TEXT -> VARCHAR(N) (reverse of allowed varchar->text)", () => {
            expect(isSafeAlter(col({ type: "text" }), col({ type: "varchar(255)" }))).to.equal(false)
        })
    })

    // Lines 260-261: decimal precision/scale widening
    describe("decimal precision and scale widening", () => {
        it("allows strictly larger precision: DECIMAL(8,2) -> DECIMAL(12,4)", () => {
            expect(isSafeAlter(
                col({ type: "decimal(8,2)", precision: 8, scale: 2 }),
                col({ type: "decimal(12,4)", precision: 12, scale: 4 }),
            )).to.equal(true)
        })
        it("allows same precision with more scale: DECIMAL(10,2) -> DECIMAL(10,4)", () => {
            expect(isSafeAlter(
                col({ type: "decimal(10,2)", precision: 10, scale: 2 }),
                col({ type: "decimal(10,4)", precision: 10, scale: 4 }),
            )).to.equal(true)
        })
        it("blocks same precision with less scale: DECIMAL(10,4) -> DECIMAL(10,2)", () => {
            expect(isSafeAlter(
                col({ type: "decimal(10,4)", precision: 10, scale: 4 }),
                col({ type: "decimal(10,2)", precision: 10, scale: 2 }),
            )).to.equal(false)
        })
    })

    // Line 282: numeric family fallthrough (mixed int/float/decimal)
    describe("numeric cross-type fallthrough", () => {
        it("blocks FLOAT -> DECIMAL: no widening path between float and decimal families", () => {
            expect(isSafeAlter(col({ type: "float" }), col({ type: "decimal(10,2)" }))).to.equal(false)
        })
        it("blocks INT -> FLOAT: no widening path between integer and float families", () => {
            expect(isSafeAlter(col({ type: "int" }), col({ type: "float" }))).to.equal(false)
        })
    })

    // Line 300: datetime* -> timestamp widening (untested direction)
    describe("datetime* -> timestamp widening", () => {
        it("allows DATETIME -> TIMESTAMP", () => {
            expect(isSafeAlter(col({ type: "datetime" }), col({ type: "timestamp" }))).to.equal(true)
        })
        it("allows DATE -> DATETIME2", () => {
            expect(isSafeAlter(col({ type: "date" }), col({ type: "datetime2" }))).to.equal(true)
        })
        it("allows DATE -> DATETIMEOFFSET", () => {
            expect(isSafeAlter(col({ type: "date" }), col({ type: "datetimeoffset" }))).to.equal(true)
        })
    })

    // Line 306: temporal fallthrough (narrowing / unsupported)
    describe("temporal narrowing blocks alter", () => {
        it("blocks TIMESTAMP -> DATE (narrowing)", () => {
            expect(isSafeAlter(col({ type: "timestamp" }), col({ type: "date" }))).to.equal(false)
        })
        it("blocks TIMESTAMP -> TIME (narrowing)", () => {
            expect(isSafeAlter(col({ type: "timestamp" }), col({ type: "time" }))).to.equal(false)
        })
        it("blocks TIMESTAMPTZ -> TIMESTAMP (neither date nor datetime* path)", () => {
            expect(isSafeAlter(col({ type: "timestamptz" }), col({ type: "timestamp" }))).to.equal(false)
        })
        it("blocks DATETIME -> DATE (narrowing)", () => {
            expect(isSafeAlter(col({ type: "datetime" }), col({ type: "date" }))).to.equal(false)
        })
    })
})

// normalizeColumnLength has 0% coverage — it is exported but not imported in the test file
describe("BaseQueryRunnerHelper.normalizeColumnLength", () => {
    it("returns undefined for null", () => {
        expect(normalizeColumnLength(null)).to.equal(undefined)
    })
    it("returns undefined for undefined", () => {
        expect(normalizeColumnLength(undefined)).to.equal(undefined)
    })
    it("returns undefined for empty string", () => {
        expect(normalizeColumnLength("")).to.equal(undefined)
    })
    it("returns the number for a numeric input", () => {
        expect(normalizeColumnLength(42)).to.equal(42)
    })
    it("parses a numeric string", () => {
        expect(normalizeColumnLength("100")).to.equal(100)
    })
    it("returns undefined for a non-numeric string", () => {
        expect(normalizeColumnLength("abc")).to.equal(undefined)
    })
    it("returns 0 for '0' (falsy but finite)", () => {
        expect(normalizeColumnLength("0")).to.equal(0)
    })
    it("truncates a float string to integer (parseInt behaviour)", () => {
        expect(normalizeColumnLength("10.9")).to.equal(10)
    })
    it("returns undefined for Infinity (not finite)", () => {
        expect(normalizeColumnLength(Infinity)).to.equal(undefined)
    })
})

Summary of gaps covered above:

  • Lines 184–187: BOOL/ENUM/UUID/BIN same-family guards (7 tests)
  • Lines 205/213/221: unicode encoding mismatch in all three char/varchar sub-paths (4 tests)
  • Lines 206/222: undefined-length early returns (3 tests)
  • Line 229: STR family fallthrough when no char/varchar handler matches (3 tests)
  • Lines 260–261: decimal precision-only widening and scale widening (3 tests)
  • Line 282: numeric cross-family fallthrough (2 tests)
  • Line 300: datetime* → timestamp direction (3 tests)
  • Line 306: temporal narrowing fallthrough (4 tests)
  • normalizeColumnLength: 0% → full branch coverage (9 tests)

@BenraouaneSoufiane

Copy link
Copy Markdown
Author

@OSA413 Qodos comments already addressed.

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

qodo-free-for-open-source-projects Bot commented Aug 14, 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

Track whether alterColumnType already ran so the generic isColumnChanged
fast path doesn't issue a second ALTER COLUMN that SQL Server rejects
when a unique constraint or index is present. Also quote identifiers
with the driver's escape so schema/table names are handled correctly.
…AMP test

The Oracle driver emits type names as-is from column metadata, so the
MODIFY statements use lowercase `timestamp(6)`, matching the repo's other
Oracle SQL expectations. The test previously expected uppercase
TIMESTAMP(6), causing the recorded SQL comparison to fail on Oracle.
…ertions

The exact-SQL assertions added for mssql used bracket quoting and
varchar, but the SqlServer driver escapes identifiers with double
quotes and defaults string columns to nvarchar (with a byte-based
DATALENGTH truncation threshold). Align the expectations with the
driver's actual output.
… tests

Postgres normalizeType maps the default String column to
character varying, so the length-change SQL is emitted as
character varying(N) rather than varchar(N). Align the postgres
expectations in the increasing/reducing length tests with the
driver's actual output; cockroachdb keeps varchar.
@BenraouaneSoufiane

Copy link
Copy Markdown
Author

CI has been fixed (except which related with sonar scanner), should some one review this?

@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

Development

Successfully merging this pull request may close these issues.

10 participants