Repository navigation
feat(postgres): use ADD VALUE when changing enum values if possible - #10956
Conversation
8445cc2 to
c167fc4
Compare
Use ADD VALUE syntax for adding new enum values in PostgreSQL instead of complicated 4-step migration Closes: typeorm#10955
c167fc4 to
8101f37
Compare
|
Hey thanks for adding this improvement! It looks like it was approved several months ago. What's the next step to get this merged? |
|
Not sure if I can do anything from my side. Seems like the only approval is from non-maintainer and there wasn't any merge in past 7 months. |
|
+1 for this feature. @jhcpeixoto What are the chances of getting this out there? It's a constant thing my team and I have to be aware of and manually fix up every time we touch an enum. |
|
any news on this? this is a recurring issue when using typeorm... |
gioboa
left a comment
There was a problem hiding this comment.
Is this PR still valid? may I ask you to address the feedback please?
|
Sorry, I didn't notice the development is active again. I could take a look if I can resolve the conflict and address the comment, I just need a few days to allocate some time to this. |
gioboa
left a comment
There was a problem hiding this comment.
Yep, looking forward to seeing it
Thanks 🙏
|
Warning Rate limit exceeded@janzipek has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 18 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (2)
WalkthroughAdds PostgreSQL enum upgrade logic that chooses between ALTER TYPE ... ADD VALUE for strictly additive changes on PostgreSQL >= 12.0 and a full enum-recreate flow otherwise; adds OrmUtils.getArraysDiff; updates PostgresQueryRunner branching and up/down SQL generation; and adds tests, entities, and migrations for issue 10955 plus unit tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant MR as Migration Runner
participant PQR as PostgresQueryRunner
participant DB as PostgreSQL
MR->>PQR: Request enum-change migration SQL
PQR->>PQR: diffs = OrmUtils.getArraysDiff(newValues, oldValues)
PQR->>DB: SELECT version() -- via VersionUtils.getVersion()
DB-->>PQR: version string
alt only additive values AND version >= 12.0
rect rgba(200,255,200,0.12)
note right of PQR: ADD VALUE path (up)
loop for each v in diffs.extraItems
PQR->>DB: ALTER TYPE schema.enum ADD VALUE 'v'
end
note right of PQR: Down: recreate prior enum, rename types and revert column to remove added values
end
else
rect rgba(255,240,200,0.12)
note right of PQR: Full type-change path (up)
PQR->>DB: ALTER TYPE ... RENAME TO old_temp
PQR->>DB: CREATE TYPE ... AS ENUM(...)
PQR->>DB: ALTER TABLE ... ALTER COLUMN ... TYPE new_enum USING ...
PQR->>DB: DROP TYPE old_temp
note right of PQR: Down mirrors above in reverse
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Points to review closely:
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
commit: |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
test/unit/util/orm-utils.ts (1)
206-220: Consider additional edge case tests.The current test validates the core functionality well with overlapping arrays. For more thorough coverage, consider adding tests for:
- Empty arrays:
getArraysDiff([], [])andgetArraysDiff([1], [])- Identical arrays:
getArraysDiff([1,2,3], [1,2,3])- Completely disjoint arrays:
getArraysDiff([1,2], [3,4])These edge cases may be encountered in enum migration scenarios (e.g., empty enum, no changes, complete replacement).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/driver/postgres/PostgresQueryRunner.ts(3 hunks)src/util/OrmUtils.ts(1 hunks)test/github-issues/10955/entity/Foo.ts(1 hunks)test/github-issues/10955/issue-10955.ts(1 hunks)test/github-issues/10955/migration/1719925118381-create-table-with-missing-values.ts(1 hunks)test/github-issues/10955/migration/1719925118382-create-table-with-different-name.ts(1 hunks)test/github-issues/10955/migration/1719925118382-create-table-with-extra-values.ts(1 hunks)test/unit/util/orm-utils.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
test/unit/util/orm-utils.ts (1)
src/util/OrmUtils.ts (1)
OrmUtils(8-604)
src/driver/postgres/PostgresQueryRunner.ts (3)
src/util/OrmUtils.ts (1)
OrmUtils(8-604)src/util/VersionUtils.ts (1)
VersionUtils(1-23)src/driver/Query.ts (1)
Query(4-8)
test/github-issues/10955/issue-10955.ts (4)
test/utils/test-utils.ts (2)
closeTestingConnections(487-499)createTestingConnections(388-482)test/github-issues/10955/migration/1719925118381-create-table-with-missing-values.ts (1)
CreateTableWithMissingValues1719925118381(3-21)test/github-issues/10955/migration/1719925118382-create-table-with-extra-values.ts (1)
CreateTableWithExtraValues1719925118382(3-21)test/github-issues/10955/migration/1719925118382-create-table-with-different-name.ts (1)
CreateTableWithDifferentName1719925118382(3-21)
test/github-issues/10955/entity/Foo.ts (2)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
PrimaryGeneratedColumn(55-119)src/decorator/columns/Column.ts (1)
Column(134-220)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: tests-linux (18) / sqlite
- GitHub Check: tests-linux (20) / postgres (14)
- GitHub Check: tests-linux (20) / sap
- GitHub Check: tests-linux (20) / postgres (17)
- GitHub Check: tests-linux (20) / oracle
- GitHub Check: tests-linux (18) / mongodb
- GitHub Check: tests-linux (18) / mssql
- GitHub Check: tests-linux (20) / sqljs
- GitHub Check: tests-linux (20) / mysql_mariadb
- GitHub Check: tests-linux (20) / sqlite
- GitHub Check: tests-linux (20) / mongodb
- GitHub Check: tests-linux (20) / mysql_mariadb_latest
- GitHub Check: tests-linux (20) / mssql
- GitHub Check: tests-linux (20) / better-sqlite3
- GitHub Check: tests-linux (20) / cockroachdb
- GitHub Check: tests-windows / sqlite
- GitHub Check: tests-windows / sqljs
- GitHub Check: tests-windows / better-sqlite3
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
src/util/OrmUtils.ts (1)
250-264: LGTM! Clean array diff utility.The implementation correctly computes set differences. The O(n×m) complexity via
filter+includesis acceptable for typical enum value sets (small arrays). The generic signature makes it reusable across the codebase.test/github-issues/10955/migration/1719925118382-create-table-with-extra-values.ts (1)
17-20: Verify drop order for PostgreSQL enum and table.The
down()migration drops the enum type before dropping the table that references it. PostgreSQL typically requires dropping dependent objects (the table) before dropping the type they reference. Verify this order doesn't cause errors during rollback.Expected PostgreSQL behavior: dropping an enum type that's still referenced by a table column should fail with a "cannot drop type because other objects depend on it" error. The correct order should be:
public async down(queryRunner: QueryRunner): Promise<void> { + await queryRunner.query(`DROP TABLE "foo"`) await queryRunner.query(`DROP TYPE "public"."foo_bar_enum"`) - await queryRunner.query(`DROP TABLE "foo"`) }Test this migration's rollback path to confirm the current order works, or apply the fix above.
test/github-issues/10955/entity/Foo.ts (1)
14-17: No action required: “simple-enum” is a valid TypeORM column type.src/driver/postgres/PostgresQueryRunner.ts (1)
23-23: LGTM!The VersionUtils import is correctly added to support PostgreSQL version checking for the ADD VALUE feature.
test/github-issues/10955/issue-10955.ts (1)
1-1: No action needed: reflect-metadata@^0.2.2 is compatible with TypeORM
The installed version (^0.2.2) falls within TypeORM’s allowed peerDependency range (^0.1.14 || ^0.2.0), so there are no breaking changes.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/driver/postgres/PostgresQueryRunner.ts (2)
1604-1612: Critical: Incomplete quote escaping enables SQL injection.Line 1605 uses
.replace("'", "''")which only replaces the first occurrence of a single quote. If an enum value contains multiple single quotes, subsequent ones won't be escaped, enabling SQL injection.Apply this diff to fix the escaping:
- const escapedValue = item.replace("'", "''") + const escapedValue = item.replaceAll("'", "''")Note: This matches the existing pattern used elsewhere in the codebase (e.g., line 4397 uses
replaceAll).
1616-1644: Critical: Down migration references non-existent enum type.When
useAddValueForUpis true, the up migration (lines 1604-1612) only adds values to the existing enum and never createsoldEnumNameWithSchema_old. However, the down migration attempts to:
- Rename
oldEnumNameWithSchema_oldtooldEnumNameWithoutSchema(line 1618) — fails because the type doesn't exist- Use
oldEnumNameWithSchema_oldin the ALTER COLUMN statement (line 1626)- Create
oldEnumNameWithSchema_oldonly later (lines 1638-1644)The down migration needs to recreate the original enum state using the correct sequence:
- Rename the current enum (with new values added) to a temporary name
- Create the old enum type with the original values (before ADD VALUE)
- ALTER COLUMN to cast back to the old enum
- Drop the temporary enum
Apply this diff to fix the down migration sequence:
- downQueries.push( - new Query( - `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`, - ), - ) - - downQueries.push( - this.dropEnumTypeSql(table, newColumn, newEnumName), - ) - - const downType = `${oldEnumNameWithSchema_old}${arraySuffix} USING "${newColumn.name}"::"text"::${oldEnumNameWithSchema_old}${arraySuffix}` - - downQueries.push( - new Query( - `ALTER TABLE ${this.escapePath( - table, - )} ALTER COLUMN "${ - newColumn.name - }" TYPE ${downType}`, - ), - ) - - downQueries.push( + // First create the old enum type with original values + downQueries.push( this.createEnumTypeSql( table, oldColumn, oldEnumNameWithSchema_old, ), ) + + // Rename current enum (with new values) to temporary name + const tempEnumName = `${oldEnumName}_temp` + downQueries.push( + new Query( + `ALTER TYPE ${oldEnumName} RENAME TO ${tempEnumName.split('.').pop()}`, + ), + ) + + // Alter column to use the recreated old enum + const downType = `${oldEnumNameWithSchema_old}${arraySuffix} USING "${newColumn.name}"::"text"::${oldEnumNameWithSchema_old}${arraySuffix}` + downQueries.push( + new Query( + `ALTER TABLE ${this.escapePath( + table, + )} ALTER COLUMN "${ + newColumn.name + }" TYPE ${downType}`, + ), + ) + + // Drop the temporary enum + downQueries.push( + new Query(`DROP TYPE ${tempEnumName}`), + ) + + // Rename old enum to its original name + downQueries.push( + new Query( + `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`, + ), + )Based on past review comments
🧹 Nitpick comments (1)
src/driver/postgres/PostgresQueryRunner.ts (1)
1602-1755: Consider extracting code paths into separate methods for better maintainability.The ADD VALUE path (lines 1602-1644) and the full enum recreation path (lines 1645-1755) are currently interleaved within a single conditional block. This makes it difficult to verify the correctness of each approach independently and increases cognitive load.
As noted in past review comments, separating these code paths at a higher level would improve maintainability and make it easier to ensure both up and down migrations are correct for each approach.
Consider refactoring to:
if (useAddValueForUp) { this.generateAddValueEnumMigration( table, newColumn, oldColumn, extraItems, upQueries, downQueries, /* ... other params ... */ ) } else { this.generateEnumRecreationMigration( table, newColumn, oldColumn, upQueries, downQueries, /* ... other params ... */ ) }Where each method encapsulates:
- The complete up migration logic for that approach
- The complete down migration logic for that approach
- Default value handling specific to that approach
This would make it easier to verify that each migration path is internally consistent and correctly handles all edge cases.
Based on past review comments
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/driver/postgres/PostgresQueryRunner.ts(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/driver/postgres/PostgresQueryRunner.ts (3)
src/util/OrmUtils.ts (1)
OrmUtils(8-604)src/util/VersionUtils.ts (1)
VersionUtils(1-23)src/driver/Query.ts (1)
Query(4-8)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: tests-linux (20) / postgres (17)
- GitHub Check: tests-linux (20) / sap
- GitHub Check: tests-linux (20) / sqlite
- GitHub Check: tests-linux (20) / mysql_mariadb_latest
- GitHub Check: tests-linux (18) / oracle
- GitHub Check: tests-linux (18) / postgres (17)
- GitHub Check: tests-linux (18) / postgres (14)
- GitHub Check: tests-linux (20) / mongodb
- GitHub Check: tests-linux (18) / mongodb
- GitHub Check: tests-linux (20) / cockroachdb
- GitHub Check: tests-linux (18) / sqlite
- GitHub Check: tests-linux (18) / mysql_mariadb_latest
- GitHub Check: tests-windows / sqljs
- GitHub Check: tests-linux (18) / mssql
- GitHub Check: tests-linux (18) / sqljs
- GitHub Check: tests-linux (18) / mysql_mariadb
- GitHub Check: tests-linux (18) / better-sqlite3
- GitHub Check: tests-windows / better-sqlite3
- GitHub Check: tests-windows / sqlite
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
src/driver/postgres/PostgresQueryRunner.ts (2)
23-23: LGTM! Import is necessary for version checking.The
VersionUtilsimport is correctly added to support the PostgreSQL version check at line 1566.
1557-1569: LGTM! Version check and diff logic are correct.The implementation correctly determines when to use
ADD VALUEsyntax:
- Computes differences between old and new enum values
- Checks PostgreSQL version >= 12.0
- Only uses
ADD VALUEwhen there are new values and no removed values (additive-only changes)This approach avoids unnecessary table locking for simple enum additions.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
test/github-issues/10955/migration/1719925118382-create-table-with-different-name.ts(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: tests-linux (20) / sqlite
- GitHub Check: tests-linux (20) / better-sqlite3
- GitHub Check: tests-linux (20) / mysql_mariadb_latest
- GitHub Check: tests-linux (20) / mssql
- GitHub Check: tests-linux (20) / mongodb
- GitHub Check: tests-linux (18) / oracle
- GitHub Check: tests-linux (18) / postgres (17)
- GitHub Check: tests-linux (18) / postgres (14)
- GitHub Check: tests-linux (20) / cockroachdb
- GitHub Check: tests-linux (18) / sqljs
- GitHub Check: tests-linux (18) / sqlite
- GitHub Check: tests-linux (18) / better-sqlite3
- GitHub Check: tests-linux (18) / mongodb
- GitHub Check: tests-linux (18) / mysql_mariadb
- GitHub Check: tests-linux (18) / sap
- GitHub Check: tests-windows / better-sqlite3
- GitHub Check: tests-windows / sqlite
- GitHub Check: tests-windows / sqljs
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (2)
test/github-issues/10955/migration/1719925118382-create-table-with-different-name.ts (2)
3-6: LGTM!The migration class structure follows TypeORM conventions correctly.
8-15: LGTM!The up() migration correctly creates the enum type before the table that depends on it.
gioboa
left a comment
There was a problem hiding this comment.
Can I ask you to solve the conflicts please?
PR Code Suggestions ✨Latest suggestions up to 28e5322
Previous suggestionsSuggestions up to commit bc56e35
Suggestions up to commit 3065b1d
Suggestions up to commit b25c5c2
Suggestions up to commit 109d2b3
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ), | ||
| ) | ||
| // ADD VALUE allows us to just add new enum values without any type changes, but can of course only be used when only new values were added | ||
| if (useAddValueForUp) { |
There was a problem hiding this comment.
Note
The GH diff is not clear but the code inside this branch is the new change and in the else branch there is the old behaviour with a bit of formatting.
| ), | ||
| ) | ||
| // ADD VALUE allows us to just add new enum values without any type changes, but can of course only be used when only new values were added | ||
| if (useAddValueForUp) { |
ADD VALUE when changing enum values if possible
|
I'll verify that the syntax works with 9.1 and update the code to use the cached property EDIT: We have to keep the minimum version at 12 since before that See:
|
Postgres 13 and earlier have already reached their end of life, see https://www.postgresql.org/support/versioning/. At some point we should remove all version checks for an unsupported version. But let's keep this one for now. |
…typeorm#10956) --- Co-authored-by: Jan <[email protected]>
…typeorm#10956) --- Co-authored-by: Jan <[email protected]>
…typeorm#10956) --- Co-authored-by: Jan <[email protected]>

Use ADD VALUE syntax for adding new enum values in PostgreSQL instead of complicated 4-step migration
Closes: #10955
Description of change
When adding a new enum value, TypeORM currently generates 4 step migration:
This is a correct migration, but it's problematic for bigger tables. The type change will lock all rows of the table and the type cast basically causes update on the whole table, which can take minutes for bigger tables.
PostgreSQL actually has a solution for this since version 12:
ADD VALUE. To add a new value to enum, you can simply do this:This will add the value without any locking or updates.
Pull-Request Checklist
masterbranchnpm run formatto apply prettier formattingnpm run testpasses with this changeFixes #0000Summary by CodeRabbit
New Features
Tests