Skip to content

fix: virtual property handling in schema builder - #11000

Merged
gioboa merged 6 commits into
typeorm:masterfrom
skyran1278:fix-migration-drop-wih-virtual-column
Jan 5, 2026
Merged

gioboa merged 6 commits into
typeorm:masterfrom
skyran1278:fix-migration-drop-wih-virtual-column

Conversation

@skyran1278

@skyran1278 skyran1278 commented Jul 23, 2024 •

Copy link
Copy Markdown
Contributor

Description of change

Fixes #10999

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 N/A
  • The new commits follow conventions explained in CONTRIBUTING.md

Summary by CodeRabbit

  • Bug Fixes

    • Prevents accidental dropping of virtual columns during schema sync/migrations; only real columns are treated as removed.
  • Tests

    • Added regression tests validating drop/add column migration steps for the virtual-column scenario.
    • Added a test entity with a virtual column and a supporting migration to reproduce and verify behavior.

@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch from a95a772 to 0f0cba3 Compare July 23, 2024 15:03
@skyran1278 skyran1278 changed the title fix(schema-builder): fix virtual property handling in schema builder fix: virtual property handling in schema builder Jul 23, 2024
@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch from 0f0cba3 to 04c5bc9 Compare July 24, 2024 05:06
@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch 2 times, most recently from 359c3dd to 04c5bc9 Compare December 4, 2024 06:11
@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch from 04c5bc9 to d3e913b Compare December 16, 2024 06:38
Copilot AI review requested due to automatic review settings September 20, 2025 01:44

Copilot AI 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.

Pull Request Overview

Fixes virtual property handling in schema builder to prevent incorrect SQL generation when dropping columns. The issue occurred when virtual columns were being incorrectly included in drop column operations.

  • Fixed virtual property filtering logic in RdbmsSchemaBuilder to properly exclude virtual columns from drop operations
  • Added comprehensive test coverage reproducing the issue with migration SQL generation
  • Created test entity with virtual column to validate the fix

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
src/schema-builder/RdbmsSchemaBuilder.ts Fixed boolean logic for filtering virtual properties when dropping columns
test/github-issues/10999/entity/entity-with-virtual-column.ts Added test entity with virtual column to reproduce the issue
test/github-issues/10999/issue-10999.ts Added test case validating correct DROP/ADD column SQL generation
test/github-issues/10999/migration/1721739455264-init.ts Added migration file for test setup

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch 2 times, most recently from acb7bc2 to cb9247f Compare September 24, 2025 04:16
@coderabbitai

coderabbitai Bot commented Sep 24, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Tightens dropRemovedColumns logic in RdbmsSchemaBuilder to stop treating virtual properties as dropped. Adds tests for issue #10999: a new entity with a virtual column, an initial migration creating a real column foo, and a test asserting migration diff drops foo and reverses it.

Changes

Cohort / File(s) Summary of changes
Schema diff logic
src/schema-builder/RdbmsSchemaBuilder.ts
Changes the detection condition so a column is marked removed only when it is non-virtual and its databaseName matches the table column name; virtual properties are no longer considered removals.
Issue 10999 tests
test/github-issues/10999/entity/entity-with-virtual-column.ts, test/github-issues/10999/migration/1721739455264-init.ts, test/github-issues/10999/issue-10999.ts
Adds EntityWithVirtualColumn with a virtual column bar, an initial migration creating table with real foo column, and a test that verifies generated migration drops foo (and can reverse it).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant SB as SchemaBuilder
  participant MD as EntityMetadata
  participant DB as ExistingTable

  SB->>MD: Load entity columns (virtual + physical)
  SB->>DB: Load table columns
  note right of SB: Compare table columns to metadata by databaseName
  SB->>SB: Exclude virtual columns from "removed" candidates
  alt physical column missing in MD
    SB->>DB: Emit DROP COLUMN for that physical column
  else only virtual column missing in MD
    SB--xDB: Do not emit DROP (virtuals ignored)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

need review help, size-m

Suggested reviewers

  • alumni
  • sgarner
  • gioboa

Poem

I nibble diffs where columns hide,
Virtual ones kept safe inside.
Real foo falls soft, with proper hop,
Rollbacks ready — then I stop.
A rabbit cheers the migration stride. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly describes the primary change of the pull request, which is fixing the handling of virtual properties in the schema builder’s column drop logic. It is clear, concise, and directly corresponds to the modifications in dropRemovedColumns without extraneous or vague wording.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb9247f and e4deb18.

📒 Files selected for processing (4)
  • src/schema-builder/RdbmsSchemaBuilder.ts (1 hunks)
  • test/github-issues/10999/entity/entity-with-virtual-column.ts (1 hunks)
  • test/github-issues/10999/issue-10999.ts (1 hunks)
  • test/github-issues/10999/migration/1721739455264-init.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/schema-builder/RdbmsSchemaBuilder.ts
  • test/github-issues/10999/entity/entity-with-virtual-column.ts
  • test/github-issues/10999/issue-10999.ts

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/schema-builder/RdbmsSchemaBuilder.ts (2)

322-357: renameColumns length check should ignore virtual properties

The early length check counts virtual properties and can incorrectly skip rename detection when a table has virtual columns. Compare only real (non‑virtual) columns and reuse the filtered list below.

Apply this diff:

-            if (metadata.columns.length !== table.columns.length) continue
+            const metadataNonVirtualColumns = metadata.columns.filter(
+                (c) => !c.isVirtualProperty,
+            )
+            if (metadataNonVirtualColumns.length !== table.columns.length)
+                continue
@@
-            const renamedMetadataColumns = metadata.columns
-                .filter((c) => !c.isVirtualProperty)
-                .filter((column) => {
+            const renamedMetadataColumns = metadataNonVirtualColumns.filter(
+                (column) => {
                     return !table.columns.find((tableColumn) => {
                         return (
                             tableColumn.name === column.databaseName &&
                             tableColumn.type ===
                                 this.connection.driver.normalizeType(column) &&
                             tableColumn.isNullable === column.isNullable &&
                             tableColumn.isUnique ===
                                 this.connection.driver.normalizeIsUnique(column)
                         )
                     })
-                })
+                },
+            )
@@
-            const renamedTableColumns = table.columns.filter((tableColumn) => {
-                return !metadata.columns.find((column) => {
+            const renamedTableColumns = table.columns.filter((tableColumn) => {
+                return !metadataNonVirtualColumns.find((column) => {
                     return (
-                        !column.isVirtualProperty &&
                         column.databaseName === tableColumn.name &&
                         this.connection.driver.normalizeType(column) ===
                             tableColumn.type &&
                         column.isNullable === tableColumn.isNullable &&
                         this.connection.driver.normalizeIsUnique(column) ===
                             tableColumn.isUnique
                     )
                 })
             })

783-791: Minor perf/readability: precompute real column names Set

Avoid N×M scans by building a Set of non‑virtual metadata column names once per table.

Apply this diff:

-            const droppedTableColumns = table.columns.filter((tableColumn) => {
-                return !metadata.columns.find(
-                    (columnMetadata) =>
-                        !columnMetadata.isVirtualProperty &&
-                        columnMetadata.databaseName === tableColumn.name,
-                )
-            })
+            const realColumnNames = new Set(
+                metadata.columns
+                    .filter((c) => !c.isVirtualProperty)
+                    .map((c) => c.databaseName),
+            )
+            const droppedTableColumns = table.columns.filter(
+                (tableColumn) => !realColumnNames.has(tableColumn.name),
+            )
test/github-issues/10999/issue-10999.ts (1)

33-38: Make assertions resilient to query ordering

Relying on index 0 is brittle. Search for the expected SQL instead.

Apply this diff:

-                expect(sqlInMemory.upQueries[0].query).to.eql(
-                    `ALTER TABLE "entity_with_virtual_column" DROP COLUMN "foo"`,
-                )
-                expect(sqlInMemory.downQueries[0].query).to.eql(
-                    `ALTER TABLE "entity_with_virtual_column" ADD "foo" integer NOT NULL`,
-                )
+                const dropFoo = sqlInMemory.upQueries.find(
+                    (q) =>
+                        q.query ===
+                        `ALTER TABLE "entity_with_virtual_column" DROP COLUMN "foo"`,
+                )
+                expect(dropFoo, "expected DROP COLUMN foo").to.not.be.undefined
+
+                const addFoo = sqlInMemory.downQueries.find(
+                    (q) =>
+                        q.query ===
+                        `ALTER TABLE "entity_with_virtual_column" ADD "foo" integer NOT NULL`,
+                )
+                expect(addFoo, "expected ADD COLUMN foo").to.not.be.undefined
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4f7b44 and cb9247f.

📒 Files selected for processing (4)
  • src/schema-builder/RdbmsSchemaBuilder.ts (1 hunks)
  • test/github-issues/10999/entity/entity-with-virtual-column.ts (1 hunks)
  • test/github-issues/10999/issue-10999.ts (1 hunks)
  • test/github-issues/10999/migration/1721739455264-init.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
test/github-issues/10999/entity/entity-with-virtual-column.ts (2)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/VirtualColumn.ts (1)
  • VirtualColumn (22-74)
test/github-issues/10999/issue-10999.ts (1)
test/utils/test-utils.ts (2)
  • createTestingConnections (388-482)
  • closeTestingConnections (487-499)
🔇 Additional comments (3)
src/schema-builder/RdbmsSchemaBuilder.ts (1)

784-790: Correctly excluding virtual properties from drop detection — LGTM

This fixes the bug where any virtual column could mask a real DB column from being dropped. Matches the pattern already used in addNewColumns.

test/github-issues/10999/migration/1721739455264-init.ts (1)

6-14: Migration looks correct

Creates the initial table with a real column “foo” for the test setup; down drops the table. No issues.

test/github-issues/10999/entity/entity-with-virtual-column.ts (1)

12-24: VirtualColumn usage is appropriate

Good use of alias in the query; no persistence mapping leakage. All good.

- correctly filter out virtual properties when dropping columns
- add tests reproducing issue typeorm#10999 related to column drop SQL generation
- ensure migration generates appropriate SQL for creating and dropping columns
@skyran1278
skyran1278 force-pushed the fix-migration-drop-wih-virtual-column branch from cb9247f to e4deb18 Compare September 28, 2025 10:26
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

@pkg-pr-new

pkg-pr-new Bot commented Jan 5, 2026 •

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

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

commit: 05408b1

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

No code suggestions found for the PR.

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

@gioboa
gioboa merged commit 1127789 into typeorm:master Jan 5, 2026
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.

Migration: migration:generate Can't Generate a Drop SQL Command

5 participants