Repository navigation
fix(schema): use ALTER COLUMN instead of DROP/ADD for type changes - #11620
BenraouaneSoufiane wants to merge 163 commits into
Conversation
There was a problem hiding this comment.
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.
📒 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
left a comment
There was a problem hiding this comment.
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.
…upport other drivers, move the associated test into its right path
There was a problem hiding this comment.
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” typesMinor 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 comboPlease 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 typesAs with other drivers, guard this branch with
withLengthColumnTypesto 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 ALTERsPlease 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
isColumnChangedpath.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 changesThe 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.
📒 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.
…-column test, remove the dir test/github-issues/3357
There was a problem hiding this comment.
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 ALTERsUse 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 optionsCreate 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 alterationMatch 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.
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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.
… existing pattern
sgarner
left a comment
There was a problem hiding this comment.
Sorry, still not quite there yet!
In addition to code comments:
- I noticed that
AuroraMysqlQueryRunnerhasn't been updated, but it should support this feature the same asMysqlQueryRunner. - I think
SapQueryRunnercan support this too.
…nerQueryRunner, SapQueryRunner, AuroraMysqlQueryRunner, remove PG-specific assertion, add similar length change test for reducing
There was a problem hiding this comment.
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 quotesThese 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 requiredCurrent 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 hereThe 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 isundefined. 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 commentThis 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 HANATweak 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 SpannerFix 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
📒 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/addRemoving length from the destructive path is correct; it will now flow to the in-place
ALTER (...)form.
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>
|
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 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 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 ( |
…unctional schema-builder test
|
@OSA413, improved, thks! |
|
Test |
Yes, of course, will let you know once fix it, thnks. |
OSA413
left a comment
There was a problem hiding this comment.
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).
| expect(sqlBlob).to.match( | ||
| /ALTER TABLE .* ALTER COLUMN "name" (SET DATA TYPE|TYPE) .*varchar/i, | ||
| ) |
There was a problem hiding this comment.
| 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.
|
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) |
|
Following up on OSA413's branch coverage note — I went through The current test file doesn't import Additional tests to add to
|
…nner-helper.test.ts
|
@OSA413 Qodos comments already addressed. |
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.
|
CI has been fixed (except which related with sonar scanner), should some one review this? |
|
This repository was recently restructured into a pnpm workspace, and the If your branch has diverged enough that a full rebase isn't worth it, Sorry for the disruption, and thanks for your patience. |
Summary
Some column changes currently follow the
DROP/ADDpath, which can lead to data loss (reported in #3357).This PR updates the
DROP/ADDguard 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-specificALTER COLUMNpath.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)wherem >= nNVARCHAR2widening (Oracle)VARCHAR→TEXT/NTEXT/CLOBNumerics (precision/width widening)
Integer widening:
TINYINT→SMALLINTSMALLINT→INTINT→BIGINTDECIMAL/NUMERICprecision or scale increaseUnparameterized → parameterized numeric types
DECIMAL→DECIMAL(10,2)Floating-point widening:
FLOAT→DOUBLEREAL→DOUBLEFLOAT↔REAL(treated as compatible)Temporals
Same temporal type with parameter changes
TIME(3)→TIME(6)DATE→TIMESTAMP/DATETIME/DATETIME2/DATETIMEOFFSETDatetime-family widening:
DATETIME→TIMESTAMPDATETIME→DATETIME2DATETIME→DATETIMEOFFSETDATETIME2→DATETIMEOFFSETAdditional changes