Skip to content

feat(postgres): use ADD VALUE when changing enum values if possible - #10956

Merged
gioboa merged 17 commits into
typeorm:masterfrom
janzipek:feature/add-value-for-enums
Jan 5, 2026
Merged

gioboa merged 17 commits into
typeorm:masterfrom
janzipek:feature/add-value-for-enums

Conversation

@janzipek

@janzipek janzipek commented Jul 2, 2024 •

Copy link
Copy Markdown
Contributor

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:

  • rename the current enum type
  • create new enum type with new values
  • change the type of column to the new enum type casting values to string then to the target enum type
  • drop the now old enum type

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:

ALTER TYPE name ADD VALUE 'value'

This will add the value without any locking or updates.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • New Features

    • PostgreSQL enum migrations now use ADD VALUE when only values are appended on supported versions, simplifying migrations, preserving defaults, and ensuring correct up/down rename/revert sequences.
  • Tests

    • Added comprehensive tests covering enum additions, removals, renames, and special-character values, asserting generated migration SQL and rollback behavior.

@janzipek
janzipek force-pushed the feature/add-value-for-enums branch 2 times, most recently from 8445cc2 to c167fc4 Compare July 2, 2024 14:05
Use ADD VALUE syntax for adding new enum values in PostgreSQL instead of complicated 4-step migration

Closes: typeorm#10955
@janzipek
janzipek force-pushed the feature/add-value-for-enums branch from c167fc4 to 8101f37 Compare July 3, 2024 05:54
@dancrew32

Copy link
Copy Markdown

Hey thanks for adding this improvement! It looks like it was approved several months ago. What's the next step to get this merged?

@janzipek

Copy link
Copy Markdown
Contributor Author

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.

@maxtuzz

maxtuzz commented Nov 7, 2024 •

Copy link
Copy Markdown

+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.

@bmbferreira

Copy link
Copy Markdown

any news on this? this is a recurring issue when using typeorm...

@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 @janzipek 💜

sgarner
sgarner previously requested changes Jun 8, 2025
@sgarner
sgarner requested review from alumni, gioboa and naorpeled June 8, 2025 23:52

@gioboa gioboa 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.

Is this PR still valid? may I ask you to address the feedback please?

@janzipek

Copy link
Copy Markdown
Contributor Author

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 gioboa 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.

Yep, looking forward to seeing it
Thanks 🙏

@coderabbitai

coderabbitai Bot commented Sep 30, 2025 •

Copy link
Copy Markdown
Contributor

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📥 Commits

Reviewing files that changed from the base of the PR and between c3f4de9 and 664ce1a.

📒 Files selected for processing (2)
  • test/github-issues/10955/entity/FooWithSpecialChars.ts (1 hunks)
  • test/github-issues/10955/migration/1719925118383-create-table-with-special-chars-missing-values.ts (1 hunks)

Walkthrough

Adds 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

Cohort / File(s) Summary
Postgres enum upgrade path
src/driver/postgres/PostgresQueryRunner.ts
Adds version-aware branching for enum changes: computes diffs with OrmUtils.getArraysDiff, queries DB version via VersionUtils, uses ALTER TYPE ... ADD VALUE when only new values are added on >= 12.0, otherwise runs the full rename/recreate flow. Adjusts generated up/down SQL and default/casting handling for both paths.
Utility: array diff
src/util/OrmUtils.ts
Adds public static getArraysDiff<T>(arr1: T[], arr2: T[]): { extraItems: T[]; missingItems: T[] }.
Issue 10955 entities
test/github-issues/10955/entity/Foo.ts, test/github-issues/10955/entity/FooWithSpecialChars.ts
Adds Foo and FooWithSpecialChars entities and enums (including values with quotes) used by tests to exercise enum-change SQL generation and escaping.
Issue 10955 tests
test/github-issues/10955/issue-10955.ts
New tests exercising additive enum changes (ADD VALUE path), removals (full recreate path), type-rename scenarios, and proper SQL escaping; asserts exact up/down SQL sequences via createSchemaBuilder().log().
Issue 10955 migrations
test/github-issues/10955/migration/1719925118381-create-table-with-missing-values.ts, .../1719925118382-create-table-with-different-name.ts, .../1719925118382-create-table-with-extra-values.ts, .../1719925118383-create-table-with-special-chars-missing-values.ts
Adds migration classes that create enum types and tables for scenarios: missing-values, renamed-type, extra-values, and special-chars (to validate quoting and revert flows).
Unit tests: OrmUtils
test/unit/util/orm-utils.ts
Adds tests for getArraysDiff, verifying extraItems and missingItems for sample arrays.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Points to review closely:

  • src/driver/postgres/PostgresQueryRunner.ts — branching correctness, SQL ordering, quoting and schema qualification, handling of defaults and casting, and correctness of down-migration that reverts ADD VALUE.
  • VersionUtils.getVersion() usage and semantic comparison to "12.0".
  • OrmUtils.getArraysDiff — behavior with duplicates and consistent ordering for generated SQL.
  • Tests in test/github-issues/10955/issue-10955.ts — exact-string SQL assertions and DB-version assumptions.

Possibly related PRs

Suggested reviewers

  • naorpeled
  • mguida22
  • michaelbromley
  • sgarner

Poem

Thump-thump, I hop where enums grow,
I sniff new values soft and slow.
If Postgres twelve nods, I simply say "ADD",
Else I rebuild with a careful, clever pad.
Hooray — migrations safe, I bound away! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "feat: Use ADD VALUE for new enum values" directly and clearly summarizes the primary change in this pull request. The core modifications to PostgresQueryRunner.ts implement version-based logic to use PostgreSQL's ADD VALUE command for adding new enum values (when version >= 12.0 with new values but no removed values) instead of the previous multi-step rename/recreate approach. The title is specific and descriptive, identifying both the feature (ADD VALUE) and its context (new enum values), making it meaningful for developers scanning the commit history. The supporting changes—the utility method in OrmUtils.ts for array diffing, the comprehensive test suite, and the test migrations—all directly validate and enable this ADD VALUE functionality, confirming the title accurately reflects the changeset.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Sep 30, 2025 •

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

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

commit: 28e5322

@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: 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([], []) and getArraysDiff([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

📥 Commits

Reviewing files that changed from the base of the PR and between 925dee0 and cd2c731.

📒 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 + includes is 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.

@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

♻️ 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 useAddValueForUp is true, the up migration (lines 1604-1612) only adds values to the existing enum and never creates oldEnumNameWithSchema_old. However, the down migration attempts to:

  1. Rename oldEnumNameWithSchema_old to oldEnumNameWithoutSchema (line 1618) — fails because the type doesn't exist
  2. Use oldEnumNameWithSchema_old in the ALTER COLUMN statement (line 1626)
  3. Create oldEnumNameWithSchema_old only later (lines 1638-1644)

The down migration needs to recreate the original enum state using the correct sequence:

  1. Rename the current enum (with new values added) to a temporary name
  2. Create the old enum type with the original values (before ADD VALUE)
  3. ALTER COLUMN to cast back to the old enum
  4. 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

📥 Commits

Reviewing files that changed from the base of the PR and between cd2c731 and f3f6db1.

📒 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 VersionUtils import 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 VALUE syntax:

  • Computes differences between old and new enum values
  • Checks PostgreSQL version >= 12.0
  • Only uses ADD VALUE when there are new values and no removed values (additive-only changes)

This approach avoids unnecessary table locking for simple enum additions.

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f3f6db1 and 35be514.

📒 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.

@coveralls

coveralls commented Oct 30, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.88% (+0.02%) from 80.865%
when pulling 28e5322 on janzipek:feature/add-value-for-enums
into bfc293f on typeorm:master.

@gioboa gioboa 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.

Can I ask you to solve the conflicts please?

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 28e5322

CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix down query execution order

Correct the order of down queries for enum changes. The old enum type must be
created before it is used to alter the column, and renaming should happen last.

src/driver/postgres/PostgresQueryRunner.ts [1616-1644]

 downQueries.push(
-    new Query(
-        `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`,
+    this.createEnumTypeSql(
+        table,
+        oldColumn,
+        oldEnumNameWithSchema_old,
     ),
-)
-
-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(
-    this.createEnumTypeSql(
-        table,
-        oldColumn,
-        oldEnumNameWithSchema_old,
+    this.dropEnumTypeSql(table, newColumn, newEnumName),
+)
+
+downQueries.push(
+    new Query(
+        `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`,
     ),
 )
  • Apply / Chat
Suggestion importance[1-10]: 10

__

Why: This suggestion identifies a critical bug in the logic for the down migration queries. The queries are generated in the wrong order, which would cause the down migration to fail with a "type does not exist" error, breaking the migration rollback functionality.

High
Handle transaction limitation for ADD VALUE

The ALTER TYPE ... ADD VALUE command cannot be used within a transaction block
in PostgreSQL, which will cause migrations to fail. This should be handled, for
example by running these queries outside a transaction.

src/driver/postgres/PostgresQueryRunner.ts [1604-1612]

 for (const item of extraItems) {
     const escapedValue = item.replaceAll("'", "''")
 
+    // Note: ADD VALUE cannot run inside a transaction block
     upQueries.push(
         new Query(
             `ALTER TYPE ${oldEnumName} ADD VALUE '${escapedValue}'`,
         ),
     )
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical limitation of PostgreSQL's ALTER TYPE ... ADD VALUE command, which cannot run inside a transaction. Since migrations often run in transactions, this would cause failures, making the new feature unusable in many common scenarios.

High
Add null check for version

Add a null check for the version variable before it is used in a comparison to
prevent potential errors.

src/driver/postgres/PostgresQueryRunner.ts [1565-1568]

 const useAddValueForUp =
+    version &&
     VersionUtils.isGreaterOrEqual(version, "12.0") &&
     missingItems.length === 0 &&
     extraItems.length > 0
  • Apply / Chat
Suggestion importance[1-10]: 4

__

Why: The suggestion adds a defensive check for the version variable. While the version is expected to be defined at this point in the code flow, adding this check improves robustness against unexpected edge cases.

Low
  • More

Previous suggestions

Suggestions up to commit bc56e35
CategorySuggestion                                                                                                                                    Impact
General
Document transaction limitation for ADD VALUE

Add a comment to note that PostgreSQL's ADD VALUE command cannot be used inside
a transaction block. This warns users about potential migration issues.

src/driver/postgres/PostgresQueryRunner.ts [1602-1613]

 if (useAddValueForUp) {
     // Add values for up - that's all we need
+    // Note: ALTER TYPE ADD VALUE cannot run inside a transaction block
     for (const item of extraItems) {
         const escapedValue = item.replaceAll("'", "''")
 
         upQueries.push(
             new Query(
                 `ALTER TYPE ${oldEnumName} ADD VALUE '${escapedValue}'`,
             ),
         )
     }
 
-    // For down query, we're be doing the doing the same as normal enum change
+    // For down query, we're doing the same as normal enum change
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a significant PostgreSQL limitation regarding ALTER TYPE ... ADD VALUE within transactions. Adding a comment to warn developers is a valuable improvement for maintainability and preventing runtime migration failures.

Medium
Possible issue
Add null check for version

Add a check to ensure the version variable is defined before using it in a
comparison. This prevents potential runtime errors if the driver version is
unavailable.

src/driver/postgres/PostgresQueryRunner.ts [1565-1568]

 const useAddValueForUp =
+    version &&
     VersionUtils.isGreaterOrEqual(version, "12.0") &&
     missingItems.length === 0 &&
     extraItems.length > 0
Suggestion importance[1-10]: 6

__

Why: This is a good defensive coding practice that prevents a potential runtime error if this.driver.version is undefined, ensuring the code gracefully falls back to the old method.

Low
Suggestions up to commit 3065b1d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Incorrect PostgreSQL version check

Change the PostgreSQL version check for ALTER TYPE ... ADD VALUE from "12.0" to
"9.1" to correctly reflect when the feature was introduced.

src/driver/postgres/PostgresQueryRunner.ts [1565-1568]

 const useAddValueForUp =
-    VersionUtils.isGreaterOrEqual(version, "12.0") &&
+    VersionUtils.isGreaterOrEqual(version, "9.1") &&
     missingItems.length === 0 &&
     extraItems.length > 0
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the ALTER TYPE ... ADD VALUE feature was introduced in PostgreSQL 9.1, not 12.0, thus making the optimization available to a wider range of supported database versions.

Medium
Suggestions up to commit b25c5c2
CategorySuggestion                                                                                                                                    Impact
Possible issue
Incorrect query execution order

Correct the order of operations in the down queries. The old enum type must be
created before it is used to alter the column, and the new enum type dropped
before the old one is renamed.

src/driver/postgres/PostgresQueryRunner.ts [1616-1644]

 downQueries.push(
-    new Query(
-        `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`,
+    this.createEnumTypeSql(
+        table,
+        oldColumn,
+        oldEnumNameWithSchema_old,
     ),
-)
-
-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(
-    this.createEnumTypeSql(
-        table,
-        oldColumn,
-        oldEnumNameWithSchema_old,
+    this.dropEnumTypeSql(table, newColumn, newEnumName),
+)
+
+downQueries.push(
+    new Query(
+        `ALTER TYPE ${oldEnumNameWithSchema_old} RENAME TO ${oldEnumNameWithoutSchema}`,
     ),
 )
Suggestion importance[1-10]: 9

__

Why: This suggestion identifies a critical bug in the down migration logic. The current order of queries would fail because it tries to rename a non-existent type. The proposed reordering fixes the logical flow, ensuring the down migration can execute successfully.

High
Incorrect PostgreSQL version check

Update the PostgreSQL version check from "12.0" to "9.1" for using ALTER TYPE
... ADD VALUE, as the feature was introduced in version 9.1.

src/driver/postgres/PostgresQueryRunner.ts [1565-1568]

 const useAddValueForUp =
-    VersionUtils.isGreaterOrEqual(version, "12.0") &&
+    VersionUtils.isGreaterOrEqual(version, "9.1") &&
     missingItems.length === 0 &&
     extraItems.length > 0
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that ALTER TYPE ... ADD VALUE was introduced in PostgreSQL 9.1, not 12.0. Applying this change expands the optimization to a wider range of PostgreSQL versions, improving the feature's utility.

Medium
General
Missing IF NOT EXISTS clause

Add the IF NOT EXISTS clause to the ALTER TYPE ... ADD VALUE statement to
improve migration idempotency and prevent errors on re-runs.

src/driver/postgres/PostgresQueryRunner.ts [1604-1612]

 for (const item of extraItems) {
     const escapedValue = item.replaceAll("'", "''")
 
     upQueries.push(
         new Query(
-            `ALTER TYPE ${oldEnumName} ADD VALUE '${escapedValue}'`,
+            `ALTER TYPE ${oldEnumName} ADD VALUE IF NOT EXISTS '${escapedValue}'`,
         ),
     )
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that using ADD VALUE IF NOT EXISTS would make the generated migrations more robust and idempotent. This is a valuable improvement, although it would require an additional version check since IF NOT EXISTS was added in PostgreSQL 10.

Low
Suggestions up to commit 109d2b3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Incorrect PostgreSQL version check

Change the PostgreSQL version check for using ALTER TYPE ... ADD VALUE from
"12.0" to "9.1", as the feature was introduced in version 9.1.

src/driver/postgres/PostgresQueryRunner.ts [1565-1568]

 const useAddValueForUp =
-    VersionUtils.isGreaterOrEqual(version, "12.0") &&
+    VersionUtils.isGreaterOrEqual(version, "9.1") &&
     missingItems.length === 0 &&
     extraItems.length > 0
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that ALTER TYPE ... ADD VALUE was introduced in PostgreSQL 9.1, not 12.0, which makes the new optimization available to a wider range of users.

Medium

@gioboa
gioboa requested a review from sgarner January 5, 2026 12:55
),
)
// 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) {

@gioboa gioboa Jan 5, 2026 •

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.

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.

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.

Indentation change. You can toggle whitespace from the display settings:

Image

Also: sometimes it's easier to check the PR in VSCode/Webstorm (you'd have to configure something similar depending on your IDE).

@gioboa gioboa 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.

LGTM 👏
Thanks @janzipek

),
)
// 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) {

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.

Indentation change. You can toggle whitespace from the display settings:

Image

Also: sometimes it's easier to check the PR in VSCode/Webstorm (you'd have to configure something similar depending on your IDE).

@alumni alumni changed the title feat: Use ADD VALUE for new enum values feat(postgres): use ADD VALUE when changing enum values if possible Jan 5, 2026
@janzipek

janzipek commented Jan 5, 2026 •

Copy link
Copy Markdown
Contributor Author

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 ADD VALUE can't be called inside transaction

See:
https://www.postgresql.org/docs/11/sql-altertype.html#id-1.9.3.42.7
https://www.postgresql.org/docs/12/sql-altertype.html#id-1.9.3.42.7

  • For 11: ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) cannot be executed inside a transaction block.
  • For 12: If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed.

@alumni

alumni commented Jan 5, 2026

Copy link
Copy Markdown
Collaborator

We have to keep the minimum version at 12

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.

@alumni
alumni dismissed sgarner’s stale review January 5, 2026 15:47

requested change was implemented

@gioboa
gioboa merged commit f1be21e into typeorm:master Jan 5, 2026
33 checks passed
Cprakhar pushed a commit to Cprakhar/typeorm that referenced this pull request Jan 7, 2026
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Use alternative ADD VALUE syntax when adding a new value to enum