Skip to content

fix: handle schema and table name correctly in generated columns in metadata table - #12423

Merged
alumni merged 17 commits into
typeorm:masterfrom
Cprakhar:fix/generated-columns
Sep 30, 2026
Merged

alumni merged 17 commits into
typeorm:masterfrom
Cprakhar:fix/generated-columns

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Apr 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #11589

Description of change

  • For some user-defined schema (not public), the generated columns metadata was stored incorrectly in the metadata table. It was storing public in schema column of metadata table even when a user-defined schema was provided during @Entity({ schema: ... }) or in DataSourceOptions.
  • Table path database.schema.tablename was being stored in table column of metadata table, and during loadTables, querying with table: tablename was causing a mismatch and false schema migrations.
  • For table rename and column rename, the metadata table was made to be in sync by updating the table or name column of the metadata table.
  • Removed (postgres version < 12) check in tests.
  • Updated columnsSql in SqlServerQueryRunner.loadTables to load correct is_persisted and definition for @Entity({ database: '...', schema: '...' }).

Users upgrading with this fix might generate migrations, as it now attempts to query against a plain table name rather than a schema- and database-qualified one.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11589
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) (N/A)

@pkg-pr-new

pkg-pr-new Bot commented Apr 30, 2026 •

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

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

commit: 7e9f3d4

@Cprakhar
Cprakhar force-pushed the fix/generated-columns branch from 5f0a655 to bebea45 Compare May 1, 2026 11:48
@Cprakhar Cprakhar changed the title fix: handle schema, database and table name correctly in generated columns in metadata table fix: handle schema and table name correctly in generated columns in metadata table May 1, 2026
@Cprakhar
Cprakhar force-pushed the fix/generated-columns branch 2 times, most recently from e7ceca4 to bc3001b Compare May 2, 2026 17:30
@Cprakhar Cprakhar self-assigned this May 3, 2026
@BenraouaneSoufiane

Copy link
Copy Markdown

I already worked on this #11620

@Cprakhar

Cprakhar commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

I already worked on this #11620

@BenraouaneSoufiane, I looked at your PR, you are working around the ALTER instead of DROP+ADD.
This PR is just to keep the metadata table in sync if the table or column is renamed. Also, correctly store schema, database, and table names to query from the metadata table. See the PR description.

@Cprakhar
Cprakhar marked this pull request as ready for review May 8, 2026 17:42
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented May 8, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Two unused clones fail test compilation ✓ Resolved
Description
The new PostgreSQL and CockroachDB rename tests each create a changedName clone but pass the
string "nameChanged" to renameColumn instead. Neither clone is read afterward, so both tests
encounter unused-local errors when compiled with the package’s noUnusedLocals setting.
Code

packages/typeorm/test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[R231-232]

+                const changedName = name.clone()
+                changedName.name = "nameChanged"
Evidence
Both added tests assign to changedName without using it, while the package TypeScript
configuration enables noUnusedLocals. The unused code also violates the checklist’s requirement to
avoid extra noise.

Rule 4: Remove AI-generated noise
packages/typeorm/test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[230-234]
packages/typeorm/test/functional/database-schema/generated-columns/cockroachdb/generated-columns-cockroachdb.test.ts[262-266]
packages/typeorm/tsconfig.json[13-13]

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

## Issue description
Two new rename tests create column clones that they never use, causing unused-local compilation errors.
## Fix Focus Areas
- packages/typeorm/test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[230-234]
- packages/typeorm/test/functional/database-schema/generated-columns/cockroachdb/generated-columns-cockroachdb.test.ts[262-266]
## Recommended Fix
Remove each unused `changedName` clone and its name assignment. Keep the existing string argument to `renameColumn`.

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


2. Default DB not dropped ⊘ Outdated
Description
With the new entities that set an explicit database, dropSchema:true/synchronize(true) will
call DataSource.dropDatabase(), which clears only the explicit metadata.database list and can
skip clearing the DataSource’s default driver.database, leaving tables/metadata behind between
tests (and for multi-db users). This is triggered in the generated-columns MySQL/MSSQL suites
because they mix default-db entities (e.g. Post) with custom-db entities (e.g. OrganizationUnit
/ Human).
Code

test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[3]

Evidence
The new test entity sets an explicit database, and the suite uses dropSchema:true +
synchronize(true). In the current core implementation, synchronize(true) calls dropDatabase(),
and dropDatabase() only clears the explicit metadata.database list when it is non-empty, which
omits clearing driver.database (where entities without metadata.database live).

test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[1-4]
test/functional/database-schema/generated-columns/mysql/entity/Post.ts[1-5]
test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[14-23]
test/utils/test-utils.ts[509-513]
src/data-source/DataSource.ts[304-310]
src/data-source/DataSource.ts[319-346]
src/data-source/DataSource.ts[262-264]

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

## Issue description
`DataSource.dropDatabase()` only clears the set of databases explicitly found in `EntityMetadata.database` when that set is non-empty. After this PR, some test suites include a mix of entities with `database` set and entities without it, so `dropSchema:true` / `synchronize(true)` does not actually clear the default `driver.database` where the non-explicit entities live, leaving tables and `typeorm_metadata` rows behind.
## Issue Context
- The PR adds entities with explicit databases (e.g. MySQL `OrganizationUnit` uses `database: "avocaty"`, MSSQL `Human` uses `database: "test_database"`).
- These suites also use `dropSchema: true` and `reloadTestingDatabases()` which runs `connection.synchronize(true)`.
- `synchronize(true)` calls `dropDatabase()`, and `dropDatabase()` currently only clears the explicit database list, which omits `driver.database` if *any* explicit database exists.
## Fix Focus Areas
- src/data-source/DataSource.ts[304-310]
- src/data-source/DataSource.ts[319-346]
### Suggested fix
In `dropDatabase()`, build the set of databases to clear as:
- all distinct `metadata.database` values **plus**
- `this.driver.database` (if set)
Then clear each (deduped) database.
That ensures `dropSchema:true` / `synchronize(true)` fully resets state even when only some entities specify a database.
(Alternative: treat `metadata.database ?? this.driver.database` as the effective database per entity, then dedupe.)

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


3. MSSQL test DB not created ⊘ Outdated
Description
The MSSQL generated-columns suite now expects a table in the hard-coded database/schema
test_database.test_schema, but the standard test harness expects users to copy
ormconfig.sample.json (which configures MSSQL to use tempdb) and the repo’s docker-compose.yml
does not initialize/create test_database. This makes
synchronize()/getTable("test_database.test_schema.human") fail unless the environment
pre-creates that database/schema.
Code

test/functional/database-schema/generated-columns/mssql/generated-columns-mssql.test.ts[R68-79]

Evidence
The new test asserts a table exists under test_database.test_schema, while the repo’s documented
test setup expects ormconfig.json to be copied from ormconfig.sample.json (which sets MSSQL
database to tempdb) and docker-compose does not create any additional user database. Since schema
sync builds tables but does not provision databases, the required test_database is not guaranteed
to exist and the test is environment-dependent.

test/functional/database-schema/generated-columns/mssql/entity/Human.ts[1-4]
test/functional/database-schema/generated-columns/mssql/generated-columns-mssql.test.ts[56-88]
test/utils/test-utils.ts[193-212]
ormconfig.sample.json[61-73]
docker-compose.yml[74-84]
src/schema-builder/RdbmsSchemaBuilder.ts[69-129]

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

## Issue description
The MSSQL generated-columns tests introduce an entity/table targeting `test_database.test_schema`, but the test harness (ormconfig-driven) does not create databases automatically, and the default local setup uses `tempdb`. As a result, `synchronize()` / `getTable("test_database.test_schema.human")` can fail in typical setups.
### Issue Context
- The test harness explicitly instructs copying `ormconfig.sample.json` to `ormconfig.json`.
- `ormconfig.sample.json` configures MSSQL with `database: "tempdb"`.
- `docker-compose.yml` starts SQL Server but does not create `test_database`.
### Fix Focus Areas
- test/functional/database-schema/generated-columns/mssql/generated-columns-mssql.test.ts[12-90]
- test/functional/database-schema/generated-columns/mssql/entity/Human.ts[1-19]
### Suggested fix
Option A (preferred for portability):
1. In the MSSQL suite `before()` (after connections are created), for each datasource:
- `await using qr = dataSource.createQueryRunner()`
- `await qr.createDatabase("test_database", true)`
- `await qr.createSchema("test_database.test_schema", true)`
2. Optionally drop `test_database` in `after()` to avoid leaving state behind.
Option B (simpler):
- Remove hard-coded `database: "test_database"` from `Human` and use only a schema under the configured database (e.g. just `schema: "test_schema"`), updating assertions accordingly.

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


View action required (4)
4. MSSQL column rows duplicated ✓ Resolved
Description
SqlServerQueryRunner.loadTables joins INFORMATION_SCHEMA.COLUMNS to sys.tables only by table name,
so if the same table name exists in multiple schemas the join can return duplicate rows for a single
INFORMATION_SCHEMA column and create duplicate TableColumn entries (and inconsistent
generatedType/asExpression). This can break schema introspection and produce incorrect
diffs/migrations.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R3208-3214]

Evidence
columnsSql joins sys.tables using only st.name = TABLE_NAME, allowing multiple matches when
different schemas share the same table name; dbColumns is then filtered only by
TABLE_NAME/TABLE_SCHEMA/TABLE_CATALOG and mapped into table.columns without any uniqueness
constraint, so duplicate result rows become duplicate TableColumn objects. Generated column
detection depends on joined cc.definition, so duplicates can also lead to inconsistent
generatedType/asExpression for the same column.

src/driver/sqlserver/SqlServerQueryRunner.ts[3196-3216]
src/driver/sqlserver/SqlServerQueryRunner.ts[3318-3378]
src/driver/sqlserver/SqlServerQueryRunner.ts[3630-3658]

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

## Issue description
`loadTables()` builds `columnsSql` that LEFT JOINs `sys.tables` on table name only. When two schemas have tables with the same name, each `INFORMATION_SCHEMA.COLUMNS` row can match multiple `sys.tables` rows, producing duplicate result rows; later code maps `dbColumns` directly to `table.columns` without de-duplication.
### Issue Context
The join chain currently applies the schema filter only in the `sys.schemas` join, which does **not** prevent duplicate rows from the earlier `sys.tables` join.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3196-3215]
### Suggested fix
Restructure joins so `sys.tables` is schema-qualified, e.g.:
- `LEFT JOIN sys.schemas ss ON ss.name = TABLE_SCHEMA`
- `LEFT JOIN sys.tables st ON st.name = TABLE_NAME AND st.schema_id = ss.schema_id`
(and then join `sys.columns` / `sys.computed_columns` via `st.object_id`).
Alternatively, join `sys.tables` via `OBJECT_ID(QUOTENAME(TABLE_SCHEMA)+'.'+QUOTENAME(TABLE_NAME))` to guarantee a single match per schema-qualified table.

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


5. Docs missing for behavior change ⊘ Outdated
Description
This PR changes how generated-column metadata rows are stored/queried (schema/table handling), which
can cause users upgrading to generate new migrations. No corresponding documentation update is
included to inform users of this behavior change.
Code

src/driver/postgres/PostgresQueryRunner.ts[R608-632]

Evidence
The checklist requires docs updates for user-facing usage/behavior changes. The updated logic now
uses parseTableName() + getCurrentSchema() to persist/query generated column metadata by plain
tableName + resolved schema, which changes upgrade/migration behavior, yet no docs changes are
present in the PR diff.

Rule 2: Docs updated for user-facing changes
src/driver/postgres/PostgresQueryRunner.ts[608-632]

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

## Issue description
The PR changes generated-column metadata storage/querying semantics (schema/table name handling), which can cause new migrations on upgrade, but the docs were not updated.
## Issue Context
Users upgrading may see migrations generated due to metadata rows being matched differently (plain table name vs qualified path; schema resolution).
## Fix Focus Areas
- docs/docs/**.md[1-1]

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


6. Oracle schema not keyed ✓ Resolved
Description
OracleQueryRunner stores and looks up generated-column metadata without the table schema/OWNER, so
typeorm_metadata rows for same-named tables in different schemas can be read/updated incorrectly.
This can load the wrong asExpression (or update the wrong rows) and trigger incorrect schema
diffs/migrations in multi-schema Oracle setups.
Code

src/driver/oracle/OracleQueryRunner.ts[R569-587]

Evidence
Oracle generated-column metadata writes use database + tableName but omit schema entirely,
while Oracle tables are scoped by schema/OWNER; metadata lookups in loadTables likewise do not
include schema. Since BaseQueryRunner only adds schema predicates when a schema value is provided,
these operations can match across schemas when table/name overlap.

src/driver/oracle/OracleQueryRunner.ts[564-592]
src/driver/oracle/OracleQueryRunner.ts[2857-2867]
src/driver/oracle/OracleDriver.ts[487-547]
src/query-runner/BaseQueryRunner.ts[435-471]

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

## Issue description
Oracle generated-column metadata is currently inserted/queried/updated without the table schema (OWNER). In multi-schema scenarios, this can cause collisions (wrong `asExpression` loaded or wrong rows updated).
### Issue Context
OracleDriver.parseTableName provides both `schema` and `database`, but the generated-column metadata paths only use `database` and `tableName`. BaseQueryRunner only constrains by `schema` when a non-empty schema is provided.
### Fix Focus Areas
- src/driver/oracle/OracleQueryRunner.ts[564-592]
- src/driver/oracle/OracleQueryRunner.ts[2857-2867]
### Expected fix
- When writing generated-column metadata (createTable/addColumn/changeColumn/dropColumn/renameColumn/renameTable paths), include `schema: parsedTableName.schema ?? await this.getCurrentSchema()`.
- When reading generated-column metadata during table loading, include the schema/owner from the DB row (e.g., `schema: dbTable["OWNER"]` if available) so lookups are schema-scoped.
- Keep `database` usage only if it is truly needed for Oracle in your metadata semantics; otherwise prefer schema-scoping as the primary discriminator.

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


7. MySQL metadata column swap ✓ Resolved
Description
MysqlQueryRunner now stores/loads generated-column metadata using the database column instead of
the schema column, which will not match existing typeorm_metadata rows created by prior versions
(and still used for view metadata). This can make generated-column expressions load as empty and
cause false-positive schema migrations after upgrading.
Code

src/driver/mysql/MysqlQueryRunner.ts[R525-541]

Evidence
Generated-column metadata is now written and read using the database field, while MySQL view
metadata in the same driver is still written using the schema field to store the current database
name. BaseQueryRunner applies predicates only for the provided column, so previously stored rows
(schema-populated/database-null) will no longer be found by the new database-filtered selects.

src/driver/mysql/MysqlQueryRunner.ts[519-546]
src/driver/mysql/MysqlQueryRunner.ts[2955-2970]
src/driver/mysql/MysqlQueryRunner.ts[3372-3384]
src/query-runner/BaseQueryRunner.ts[435-474]

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

## Issue description
MySQL generated-column metadata was historically keyed via the `schema` column (matching MySQL's `TABLE_SCHEMA` usage), but this PR moves it to the `database` column. Without a compatibility path, upgrades will not find existing metadata rows, so `asExpression` may become empty and produce incorrect diffs/migrations.
### Issue Context
Within MysqlQueryRunner, view metadata still uses `schema: currentDatabase`, indicating existing semantics of storing the DB name in the `schema` column. BaseQueryRunner only filters on the provided discriminator columns, so old rows won't be returned.
### Fix Focus Areas
- src/driver/mysql/MysqlQueryRunner.ts[519-546]
- src/driver/mysql/MysqlQueryRunner.ts[2955-2970]
- src/driver/mysql/MysqlQueryRunner.ts[3372-3384]
### Expected fix (choose one approach)
1) **Keep MySQL semantics**: continue using `schema` for MySQL generated-column metadata (revert to `schema: currentDatabase` / `schema: dbTable["TABLE_SCHEMA"]`) for consistency with existing data.
OR
2) **Provide compatibility**:
- When selecting generated-column metadata, try `database` first, then fallback to `schema` when no rows are found.
- When inserting/updating, consider writing both columns (or migrating old rows once) e.g. an UPDATE that backfills `database = schema` for GENERATED_COLUMN rows where `database IS NULL`.
The key requirement is that users upgrading do not get spurious diffs solely due to metadata key changes.

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



Remediation recommended

8. Rename tests misdescribe metadata moves ✓ Resolved
Description
The new comment in the MySQL table-rename test says generated-column records are removed, although
the assertions check that the records move to the renamed table. The Oracle and CockroachDB tests
repeat the same comment, so a later reader could mistake a metadata update for a deletion.
Code

packages/typeorm/test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[350]

+                // check if generated column records removed from typeorm_metadata table
Evidence
Rule 4 excludes extra comments and inconsistent noise. Each cited new comment describes removal,
while the adjacent assertions verify records under the renamed table name.

Rule 4: Remove AI-generated noise
packages/typeorm/test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[350-359]
packages/typeorm/test/functional/database-schema/generated-columns/oracle/generated-columns-oracle.test.ts[269-278]
packages/typeorm/test/functional/database-schema/generated-columns/cockroachdb/generated-columns-cockroachdb.test.ts[317-326]

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

## Issue description
New table-rename test comments describe metadata records as removed, while the tests verify that the records move to the new table name.
## Fix Focus Areas
- packages/typeorm/test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[350-350]
- packages/typeorm/test/functional/database-schema/generated-columns/oracle/generated-columns-oracle.test.ts[269-269]
- packages/typeorm/test/functional/database-schema/generated-columns/cockroachdb/generated-columns-cockroachdb.test.ts[317-317]
## Recommended Fix
Remove the redundant comments, or replace them with wording that accurately describes the rename.

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


9. SQL Server tests leave a database behind ✓ Resolved
Description
The new Human entity declares test_database, which the test connection helper creates, but the
SQL Server suite's after hook only closes connections. After the suite runs, test_database and
its test schema objects remain on the shared server, so later runs inherit state from this suite.
Code

packages/typeorm/test/functional/database-schema/generated-columns/mssql/entity/Human.ts[3]

+@Entity({ schema: "test_schema", database: "test_database" })
Evidence
The new entity selects a separate database; createTestingConnections creates databases named by
entity metadata, while this suite's teardown only calls closeTestingConnections. Its beforeEach
synchronizes tables rather than removing the database.

packages/typeorm/test/functional/database-schema/generated-columns/mssql/entity/Human.ts[3-3]
packages/typeorm/test/utils/test-utils.ts[386-402]
packages/typeorm/test/functional/database-schema/generated-columns/mssql/generated-columns-mssql.test.ts[14-23]

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

## Issue description
The new SQL Server test entity causes the test helper to create `test_database`, but the suite leaves that database and its schema objects behind.
## Fix Focus Areas
- packages/typeorm/test/functional/database-schema/generated-columns/mssql/entity/Human.ts[3-3]
- packages/typeorm/test/functional/database-schema/generated-columns/mssql/generated-columns-mssql.test.ts[14-23]
## Recommended Fix
Add teardown that removes the suite's custom table and schema, and remove the database if the suite created it. Run cleanup before closing the connections, without dropping a pre-existing shared database.

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


10. Cross-database table renames can fail ✓ Resolved
Description
In renameTable and renameColumn, the new metadata updateTypeormMetadataSql queries are pushed
after USE "${dbName}". getTypeormMetadataTableName() omits the database prefix when
options.database is unset, so the unqualified typeorm_metadata resolves in the entity's
database. When an entity sets database different from the connection's current database, the
UPDATE hits a missing or wrong metadata table. The migration then errors, or the metadata row keeps
the old table or column name.
Code

packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[R941-944]

+        if (hasGeneratedColumns) {
+            const updateQuery = this.updateTypeormMetadataSql({
+                database: dbName,
+                schema: schemaName,
Evidence
renameTable pushes USE dbName at line 918 and only switches back at line 1121, so the new metadata
update at line 958 runs in between. getTypeormMetadataTableName builds the name from
options.database only, so with no configured database the name is unqualified and resolves in the
entity's database. createTable never issues USE, so the metadata row lives in the connection's
default database.

packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[914-920]
packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[1119-1123]
packages/typeorm/src/query-runner/BaseQueryRunner.ts[414-423]
packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[1418-1460]

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

## Issue description
SQL Server renameTable/renameColumn push metadata UPDATE queries after `USE "dbName"`, so an unqualified typeorm_metadata table resolves in the wrong database.
## Fix Focus Areas
- packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[938-960]
- packages/typeorm/src/driver/sqlserver/SqlServerQueryRunner.ts[1441-1460]
## Recommended Fix
Collect the metadata update and revert queries separately and append them after the `USE "currentDB"` switch-back (or before the initial USE). Alternatively, build the metadata table path with a database name that falls back to `await this.getCurrentDatabase()`, captured before the switch.

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


View review recommended (8)
11. newTableName variable shadowed ✓ Resolved
Description
In renameTable(), newTableName is re-declared inside the generated-columns block, shadowing the
method parameter. This is inconsistent naming that can confuse future changes and increase the risk
of using the wrong value in metadata updates.
Code

src/driver/mysql/MysqlQueryRunner.ts[R707-724]

Evidence
PR Compliance ID 1 requires consistent naming conventions. The code reuses the identifier
newTableName for two different meanings (function parameter vs parsed tableName), which is a
naming inconsistency and reduces clarity.

Rule 1: Consistent Naming Conventions
src/driver/mysql/MysqlQueryRunner.ts[674-724]

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

## Issue description
`renameTable()` re-declares `newTableName` inside the `hasGeneratedColumns` block (`const { tableName: newTableName } = ...`), which shadows the method parameter `newTableName`.
## Issue Context
Shadowing obscures intent (parameter vs parsed table name) and makes the metadata update logic harder to reason about.
## Fix Focus Areas
- src/driver/mysql/MysqlQueryRunner.ts[707-724]

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


12. Blank generated metadata persisted ✓ Resolved
Description
MysqlQueryRunner.dropTable now generates down-migration inserts for all generated columns even when
asExpression is an empty string (which happens when metadata lookup fails during upgrades). This
can persist empty/NULL typeorm_metadata.value rows that will never hydrate back into
asExpression, causing repeated diffs and non-reversible generated-column metadata on rollback.
Code

src/driver/mysql/MysqlQueryRunner.ts[R589-611]

Evidence
MySQL table loading explicitly assigns asExpression = "" when the metadata lookup returns no
row/value, and the metadata insert helper accepts an optional value. With the new
generatedType-only filter in dropTable, down migrations can insert value: "", but future loads
will keep treating it as missing because they check results[0]?.value truthiness.

src/driver/mysql/MysqlQueryRunner.ts[589-616]
src/driver/mysql/MysqlQueryRunner.ts[2968-2991]
src/query-runner/BaseQueryRunner.ts[487-517]

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

## Issue description
`dropTable` now includes all `generatedType` columns when building metadata up/down queries, and unconditionally builds a down insert using `value: column.asExpression`. When `asExpression` is `""` (which the loader uses as a sentinel for “metadata not found”), the down migration will insert a metadata row with an empty value. Later, `loadTables` checks `results[0]?.value` truthiness and treats empty string as missing, so the inserted row will not restore the expression and can cause recurring diffs.
## Issue Context
- `loadTables` sets `asExpression = ""` when the metadata row is not found.
- `insertTypeormMetadataSql` allows `value` to be omitted/undefined.
## Fix Focus Areas
- When building **down insert** queries for generated-column metadata, only insert if `column.asExpression != null && column.asExpression !== ""`.
- Keep the **up delete** query unconditional for generated columns.
- (Optional) Consider updating loader checks to use `value != null` instead of truthiness if empty-string expressions are ever valid.
### Fix Focus Areas (code refs)
- src/driver/mysql/MysqlQueryRunner.ts[589-616]
- src/driver/mysql/MysqlQueryRunner.ts[2968-2991]
- src/query-runner/BaseQueryRunner.ts[487-517]

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


13. MSSQL clearDatabase leaves metadata ⊘ Outdated
Description
SqlServerQueryRunner.clearDatabase now deletes from typeorm_metadata using WHERE "database" = @0,
but when clearDatabase() is invoked without an argument the parameter is undefined and the delete
won’t match normal (non-null) metadata rows. This leaves orphaned metadata rows after a
dropDatabase/clearDatabase call, causing future schema loads/diffs to see stale
generated-column/view metadata.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R3009-3017]

Evidence
DataSource.dropDatabase() may call clearDatabase() with no argument when no databases are
resolved; clearDatabase() then executes a delete filtered by "database" = @0 with the passed
(possibly undefined) value, which won’t remove rows whose database column contains an actual
database name.

src/driver/sqlserver/SqlServerQueryRunner.ts[3009-3018]
src/data-source/DataSource.ts[318-349]

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

## Issue description
`clearDatabase(database?)` performs `DELETE FROM typeorm_metadata WHERE database = @0` even when `database` is not provided. In that case the delete won’t remove rows for the current database (which are typically stored with a concrete database name), leaving stale metadata.
### Issue Context
`DataSource.dropDatabase()` can call `queryRunner.clearDatabase()` with no argument when it cannot resolve any database names.
### Fix Focus Areas
- src/driver/sqlserver/SqlServerQueryRunner.ts[3009-3018]
- src/data-source/DataSource.ts[318-349]
### Suggested fix
In `SqlServerQueryRunner.clearDatabase`:
- Resolve an effective database name for metadata cleanup:
- `const effectiveDb = database ?? (await this.getCurrentDatabase())`
- Use `effectiveDb` in the delete predicate.
Optionally also delete legacy rows with NULL database if needed:
- `WHERE ("database" = @0 OR "database" IS NULL)` when `database` is not explicitly provided.

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


14. SQL Server schema omitted misparsed ⊘ Outdated
Description
SqlServerQueryRunner.renameTable/renameColumn now uses SqlServerDriver.parseTableName, which
converts a 3-part name with an empty schema segment (e.g. db..table) into schema=driverSchema,
so the subsequent schemaName ??= await getCurrentSchema() fallback never runs and operations can
target the wrong schema.
Code

src/driver/sqlserver/SqlServerQueryRunner.ts[R899-905]

Evidence
The query runner now depends on parseTableName output to decide whether to fallback to
getCurrentSchema(). For 3-part names, parseTableName uses parts[1] || driverSchema, which
turns an explicitly omitted schema segment into a concrete schema value, preventing the fallback.
Additionally, buildTableName intentionally inserts an empty schema segment when a database is
specified without a schema, making db..table a valid/expected representation that should
round-trip correctly.

src/driver/sqlserver/SqlServerQueryRunner.ts[888-911]
src/driver/sqlserver/SqlServerQueryRunner.ts[1406-1415]
src/driver/sqlserver/SqlServerDriver.ts[471-490]
src/driver/sqlserver/SqlServerDriver.ts[538-545]

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

## Issue description
`SqlServerQueryRunner.renameTable` / `renameColumn` now call `SqlServerDriver.parseTableName(...)` and then only fallback to `getCurrentSchema()` when the parsed schema is `undefined`. But `parseTableName` currently collapses an explicitly empty schema segment in a 3-part name (`db..table`) into `schema=driverSchema` via `schema: parts[1] || driverSchema`, which makes the schema non-`undefined` and prevents the intended fallback.
This is a behavior regression compared to the previous manual parsing logic, which treated an empty schema segment as “schema omitted”, enabling use of the current/default schema.
## Issue Context
SQL Server supports three-part identifiers where the schema can be omitted by using a double-dot (`database..table`). The driver’s `buildTableName` can emit this representation when a database is provided but schema is not.
## Fix Focus Areas
- src/driver/sqlserver/SqlServerDriver.ts[471-559]
- src/driver/sqlserver/SqlServerQueryRunner.ts[888-959]
- src/driver/sqlserver/SqlServerQueryRunner.ts[1406-1415]
## Suggested fix
Option A (preferred): Update `SqlServerDriver.parseTableName` to preserve an omitted schema for 3-part names:
- If `parts.length === 3` and `parts[1] === ""`, return `schema: undefined` (instead of `driverSchema`).
Option B: In `SqlServerQueryRunner.renameTable` and `renameColumn`, detect the explicit omitted schema pattern from the original string/name (e.g. `oldTable.name.split(".")` yielding length 3 with middle part empty) and force `schemaName = undefined` before applying `schemaName ??= await this.getCurrentSchema()`.
Add/adjust a test for renaming a table/column whose path is represented as `db..table` to ensure schema fallback uses `getCurrentSchema()` and generated-column metadata updates target the correct schema.

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


15. Extra DB created by tests ✓ Resolved
Description
The new MySQL OrganizationUnit entity hard-codes database: "avocaty", and the MySQL
generated-columns suite loads all entities in the directory, causing the test harness to create that
database automatically. This adds a CREATE DATABASE permission requirement and there is no
corresponding cleanup (databases are not dropped on teardown).
Code

test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[3]

Evidence
The MySQL test suite loads all entities under __dirname + "/entity/*", which includes
OrganizationUnit with database: "avocaty". The shared createTestingConnections() helper scans
entity metadata for metadata.database and calls queryRunner.createDatabase(...); teardown only
destroys connections and does not drop created databases.

test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[1-4]
test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[13-22]
test/utils/test-utils.ts[377-405]
test/utils/test-utils.ts[492-503]

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

## Issue description
The MySQL generated-columns tests now introduce an entity with `database: "avocaty"`, which triggers the shared test harness to create an additional database. This can fail in environments without CREATE DATABASE privileges and can leave extra databases behind after tests.
### Issue Context
`createTestingConnections()` automatically creates databases discovered in `connection.entityMetadatas` (via `queryRunner.createDatabase(database, true)`). `closeTestingConnections()` does not drop these databases.
### Fix Focus Areas
- test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[1-4]
- test/functional/database-schema/generated-columns/mysql/generated-columns-mysql.test.ts[13-22]
- test/utils/test-utils.ts[377-405]
- test/utils/test-utils.ts[492-503]
### Proposed fix options
1) **Cleanup in suite teardown**: in `after()` of `generated-columns-mysql.test.ts`, create a query runner and call `dropDatabase("avocaty", true)` for each datasource.
2) **Avoid hard-coded extra DB**: remove the `database: "avocaty"` from the entity if the test coverage goal can be achieved without requiring an extra database.
3) **Make DB name derived/configurable**: choose a DB name derived from the configured test database (to reduce collisions) and ensure it is dropped afterwards.

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


16. Oracle DB match breaks legacy rows ✓ Resolved
Description
OracleQueryRunner now looks up generated-column expressions with a strict `database =
currentDatabase` predicate; any existing typeorm_metadata rows with NULL/legacy database values
won’t match and will degrade to asExpression="", triggering schema diffs/false migrations after
upgrade.
Code

src/driver/oracle/OracleQueryRunner.ts[R2859-2865]

Evidence
The typeorm_metadata table schema allows NULL in the database column, and BaseQueryRunner’s select
helper adds an equality filter when a database value is provided. Oracle loadTables now always
provides database: currentDatabase for generated columns and falls back to asExpression = ""
when no row is returned, so NULL/legacy database values will be treated as missing metadata.

src/driver/oracle/OracleQueryRunner.ts[2857-2876]
src/schema-builder/RdbmsSchemaBuilder.ts[1370-1443]
src/query-runner/BaseQueryRunner.ts[435-474]

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

## Issue description
Oracle generated-column metadata lookups now require `database = currentDatabase`. Because `typeorm_metadata.database` is nullable, existing rows with NULL/legacy database values will not match, and code falls back to `asExpression = ""`.
### Issue Context
This is primarily an upgrade/backward-compatibility concern for existing databases.
### Fix Focus Areas
Implement a compatibility fallback when loading generated-column expressions, e.g.:
1) Query with `database = currentDatabase`.
2) If no rows returned, re-query without `database` (or with `database IS NULL`) to pick up legacy rows.
Alternative: one-time backfill/update of legacy rows (scoped to `type = GENERATED_COLUMN`) to set `database = currentDatabase` where `database IS NULL`.
- src/driver/oracle/OracleQueryRunner.ts[2857-2876]
- src/query-runner/BaseQueryRunner.ts[435-474]

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


17. metadata uses any ⊘ Outdated
Description
The new OrganizationUnit test entity declares metadata: any, weakening type safety and
conflicting with the requirement to avoid any usage introduced to bypass type constraints. This
can hide real typing issues and reduce maintainability of the test suite.
Code

test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[R8-10]

Evidence
PR Compliance ID 4 disallows introducing any usage to bypass type safety; the added entity
property metadata: any introduces such a type escape hatch.

Rule 4: Remove AI-generated noise
test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[8-10]

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

## Issue description
A new test entity property is typed as `any` (`metadata: any`), which weakens type safety and violates the project guideline to avoid `any` introduced to bypass type issues.
## Issue Context
This was introduced in a new MySQL functional test entity under `test/functional/...`.
## Fix Focus Areas
- test/functional/database-schema/generated-columns/mysql/entity/OrganizationUnit.ts[8-10]

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


18. Postgres tests ignore version ⊘ Outdated
Description
generated-columns-postgres.test.ts no longer skips when generated columns are unsupported, despite
PostgresDriver only enabling generated columns for Postgres >= 12. Running this suite against
Postgres < 12 will attempt DDL that the server doesn’t support and can fail CI.
Code

test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[L22-30]

Evidence
The driver explicitly gates generated-column support by server version, but the functional test now
runs unconditionally, so environments using Postgres < 12 will execute unsupported generated-column
operations.

src/driver/postgres/PostgresDriver.ts[456-459]
test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[11-23]

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

## Issue description
The Postgres generated-columns functional test suite runs unconditionally, even though generated columns are only supported on Postgres >= 12 per `PostgresDriver.isGeneratedColumnsSupported`.
### Issue Context
On Postgres < 12, running these tests can fail because the underlying DDL is not supported.
### Fix Focus Areas
- test/functional/database-schema/generated-columns/postgres/generated-columns-postgres.test.ts[11-23]
### Suggested fix
Re-introduce a version gate in the `before()` hook (or equivalent) to `this.skip()` when `(dataSources[0].driver as PostgresDriver).isGeneratedColumnsSupported` is false, or otherwise conditionally exclude the suite when the server version is < 12.

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


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

Grey Divider

Tip of the day
💡 Did you know, you can route each severity your way: inline, summary, both, or drop

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@smith-xyz smith-xyz 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.

Nice fix just one concern with the tests. The PR description mentions users upgrading may see false migrations. Would it be worth adding a note in the changelog or migration docs so users know this is expected and one-time?

Comment thread src/driver/mysql/MysqlQueryRunner.ts Resolved

@smith-xyz smith-xyz 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 think this lgmt! sorry meant to swap this to approve

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

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

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

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@Cprakhar
Cprakhar force-pushed the fix/generated-columns branch from beb7ede to bb9ad77 Compare September 29, 2026 18:31

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

Thanks @Cprakhar

@alumni
alumni merged commit 4a6a44b into typeorm:master Sep 30, 2026
46 checks passed
@github-actions github-actions Bot added this to the 2.0.next milestone Sep 30, 2026
@Cprakhar
Cprakhar deleted the fix/generated-columns branch September 30, 2026 13:15
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.

TypeORM continuously generates redundant migrations for Virtual Generated Columns with JSON expressions

6 participants