Skip to content

Conversation

@wszgrcy
Copy link
Contributor

@wszgrcy wszgrcy commented Aug 13, 2025

Description of change

Implement VirtualColumn using EntitySchema

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change

Summary by CodeRabbit

  • New Features

    • Added a virtualProperty option to mark columns as virtual properties.
    • Added a query option (alias => string) to supply SQL used to populate virtual column data.
    • Schema transformation now recognizes virtual-property mode while remaining backwards compatible.
  • Tests

    • Added functional tests validating virtual column behavior and query-driven value mapping.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 13, 2025

Walkthrough

Adds two new column options — virtualProperty?: boolean and query?: (alias: string) => string — exposes query through metadata args, and updates the EntitySchema transformer to set a column's mode to "virtual-property" when virtualProperty is truthy. Tests for virtual columns were added.

Changes

Cohort / File(s) Summary
Entity schema options & transformer
src/entity-schema/EntitySchemaColumnOptions.ts, src/entity-schema/EntitySchemaTransformer.ts
Added virtualProperty?: boolean and propagated query?: (alias: string) => string. Transformer now assigns column mode "virtual-property" when virtualProperty is truthy (checked after other mode checks).
Decorator options & metadata types
src/decorator/options/ColumnOptions.ts, src/metadata-args/types/ColumnMode.ts, src/metadata-args/ColumnMetadataArgs.ts
Added query?: (alias: string) => string to ColumnOptions and ColumnMetadataArgs.options; extended ColumnMode union with "virtual-property".
Functional tests (new)
test/functional/entity-schema/columns/virtual-columns/entity/Activity.ts, test/functional/entity-schema/columns/virtual-columns/virtual-columns.ts
Added Activity EntitySchema with a virtual column vK1 (uses virtualProperty: true and a query function) and tests validating virtual column behavior on read.

Sequence Diagram(s)

sequenceDiagram
  participant Dev as Entity Schema (definition)
  participant Transformer as EntitySchemaTransformer
  participant Meta as ColumnMetadataArgs
  participant DB as Runtime / Tests

  Dev->>Transformer: Provide column with virtualProperty + query
  Transformer->>Transformer: Evaluate mode checks (createDate/.../objectId/virtualProperty)
  Transformer->>Meta: Emit ColumnMetadataArgs with mode="virtual-property" and options.query
  Meta->>DB: Later used to generate mapping/SQL for virtual column in tests
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • alumni
  • naorpeled
  • gioboa

Poem

I nibble keys and whisper near,
A virtual leaf appears — so clear.
Query twinkles, modes align,
Bits of carrot, code, and time.
Hop, merge, and let the schema cheer! 🐇🥕

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 6e9f20d and 8413121.

📒 Files selected for processing (2)
  • src/entity-schema/EntitySchemaColumnOptions.ts (1 hunks)
  • src/entity-schema/EntitySchemaTransformer.ts (1 hunks)
🔇 Additional comments (1)
src/entity-schema/EntitySchemaTransformer.ts (1)

101-101: Mode assignment integration verified
All checks confirm that "virtual-property" is a valid ColumnMode and is consistently handled alongside "virtual":

  • ColumnMode union (src/metadata-args/types/ColumnMode.ts) includes both "virtual" and "virtual-property".
  • Consumer logic (src/metadata/ColumnMetadata.ts) correctly sets isVirtual for "virtual" and isVirtualProperty for "virtual-property". No other code branches directly on these raw mode strings.
  • EntitySchemaTransformer (src/entity-schema/EntitySchemaTransformer.ts:101) follows the same independent-if pattern as existing overrides, so there’s no unintended collision.

(Optional) You may extract mode resolution into a helper and add unit tests to cover:

  • { virtualProperty: true }"virtual-property"
  • { virtual: true }"virtual"

@wszgrcy wszgrcy force-pushed the entity-virtual-property branch from 8413121 to 0b7ee17 Compare August 13, 2025 14:07
@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 15, 2025

typeorm-sql-js-example

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

commit: a10184a

@alumni
Copy link
Collaborator

alumni commented Aug 15, 2025

Hi @wszgrcy, thanks for the contribution :) do you think you can add a functional test for this somewhere in test/functional/entity-schema/columns?

@coveralls
Copy link

coveralls commented Aug 15, 2025

Coverage Status

coverage: 76.355% (+0.002%) from 76.353%
when pulling a10184a on piying-org:entity-virtual-property
into 6e9f20d on typeorm:master.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (4)
src/decorator/options/ColumnOptions.ts (1)

191-196: Clarify JSDoc, fix grammar/casing, and scope the option to virtual columns

  • “entities alias” → “entity alias”
  • Use the standard “@see
  • This is evaluated at SELECT time (not “generating the relational db script”)
  • Note it only applies to mode "virtual" or "virtual-property" and add a short security note

Apply this diff to tighten up the docs:

-    /**
-     * Query to be used to populate the column data. This query is used when generating the relational db script.
-     * The query function is called with the current entities alias either defined by the Entity Decorator or automatically
-     * @See https://typeorm.io/decorator-reference#virtualcolumn for more details.
-     */
+    /**
+     * SQL fragment used to populate the value of a virtual column when reading data (SELECT).
+     * Only applies to columns with mode "virtual" or "virtual-property".
+     * The function receives the current entity alias (from QueryBuilder) to reference other columns.
+     * @see https://typeorm.io/decorator-reference#virtualcolumn
+     *
+     * Security note: never concatenate untrusted input here; this string is interpolated into the SQL.
+     */
     query?: (alias: string) => string
test/functional/entity-schema/columns/virtual-columns/virtual-columns.ts (1)

24-34: Make the test resilient to driver differences by not hard-coding id=0

Some drivers or configurations may not accept an explicit 0 for an auto-increment primary key. Capture the generated id from save() and read back by that id to avoid flakiness and improve portability.

-                await repo.save({ id: 0, k1: 1 })
-                const result = (await repo.findOne({ where: { id: 0 } }))!
+                const created = await repo.save({ k1: 1 })
+                const result = await repo.findOneByOrFail({ id: created.id })
                 expect(result.vK1).eq(result.k1)
                 expect(result.vK1).eq(1)
test/functional/entity-schema/columns/virtual-columns/entity/Activity.ts (1)

18-20: Avoid hard-coded identifier quoting to improve cross-driver portability

Double-quoted identifiers work for SQLite/Postgres but not MySQL. Since the test runs on better-sqlite3 today but the feature is cross-driver, prefer an unquoted expression to reduce driver-specific syntax. The alias is provided by TypeORM and should be used as-is.

-            query: (alias) =>
-                `SELECT k1 FROM "activities" WHERE "k1" = ${alias}."k1"`,
+            query: (alias) =>
+                `SELECT k1 FROM activities WHERE k1 = ${alias}.k1`,
src/entity-schema/EntitySchemaTransformer.ts (1)

101-101: Clarify precedence or enforce exclusivity when multiple special modes are set

virtualProperty is evaluated last, overriding other modes like createDate, updateDate, etc. If a column mistakenly sets multiple flags, the last one “wins”, which can hide configuration errors. Consider throwing or logging when virtualProperty is combined with other special modes, or document the intended precedence.

If you want, I can add a guard to error on conflicting modes (virtualProperty + any of createDate/updateDate/deleteDate/version/treeChildrenCount/treeLevel/objectId) and a small test asserting the error.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0b7ee17 and a10184a.

📒 Files selected for processing (5)
  • src/decorator/options/ColumnOptions.ts (1 hunks)
  • src/entity-schema/EntitySchemaColumnOptions.ts (2 hunks)
  • src/entity-schema/EntitySchemaTransformer.ts (2 hunks)
  • test/functional/entity-schema/columns/virtual-columns/entity/Activity.ts (1 hunks)
  • test/functional/entity-schema/columns/virtual-columns/virtual-columns.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/entity-schema/EntitySchemaColumnOptions.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/decorator/options/ColumnOptions.ts (1)
src/query-builder/QueryBuilder.ts (1)
  • alias (140-145)
test/functional/entity-schema/columns/virtual-columns/virtual-columns.ts (3)
src/connection/ConnectionManager.ts (1)
  • connections (16-18)
test/utils/test-utils.ts (3)
  • createTestingConnections (388-482)
  • reloadTestingDatabases (500-505)
  • closeTestingConnections (487-495)
test/functional/entity-schema/columns/virtual-columns/entity/Activity.ts (1)
  • Activity (3-22)
test/functional/entity-schema/columns/virtual-columns/entity/Activity.ts (2)
src/index.ts (1)
  • EntitySchema (182-182)
src/query-builder/QueryBuilder.ts (1)
  • alias (140-145)
🔇 Additional comments (1)
src/entity-schema/EntitySchemaTransformer.ts (1)

139-140: Propagating query into ColumnMetadataArgs looks correct

Passing query: regularColumn.query ensures the metadata contains the virtual-column SQL. This aligns with the new ColumnOptions.query addition and matches how the VirtualColumn decorator behaves.

@wszgrcy
Copy link
Contributor Author

wszgrcy commented Aug 16, 2025

Hi @wszgrcy, thanks for the contribution :) do you think you can add a functional test for this somewhere in test/functional/entity-schema/columns?

test case has added

Copy link
Collaborator

@gioboa gioboa left a comment

Choose a reason for hiding this comment

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

Thanks for your help @wszgrcy 🎉👏

@alumni alumni merged commit d1e3950 into typeorm:master Aug 16, 2025
58 checks passed
ThbltLmr pushed a commit to ThbltLmr/typeorm that referenced this pull request Dec 2, 2025
* feat: add entity mode virtual-property

* test: virtual columns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants