fix: Multiple relations with same columns cause invalid SQL to be generated
Closes: #1668 Closes: #4800 Closes: #9788 Closes: #9814 Closes: #10121 Closes: #10148 Closes: #11109 Closes: #11132 Closes: #11180
Description of change
In RelationJoinColumnBuilder.collectColumns, relationalColumn is used by reference and referencedColumn is overwritten.
Solution: Create a copy of the found relationalColumn.
Pull-Request Checklist
- [x] Code is up-to-date with the
masterbranch - [x]
npm run formatto apply prettier formatting - [x]
npm run testpasses with this change - [x] This pull request links relevant issues as
Fixes #0000 - [x] There are new or updated unit tests validating the change
- [x] Documentation has been updated to reflect this change
- [x] The new commits follow conventions explained in CONTRIBUTING.md
Summary by CodeRabbit
- New Features
- Added support for composite foreign key relations with shared columns, ensuring correct loading of related entities.
- Bug Fixes
- Improved handling of relational columns to prevent unintended side effects when multiple relations reference the same column.
- Tests
- Introduced new unit and functional tests to verify object cloning and composite relation loading.
- Added new entity definitions for comprehensive testing scenarios.
coverage: 76.349% (+0.002%) from 76.347% when pulling a6ebb2d20c8a4308a61c40fd9c29d853d00161fb on yevhen-komarov:fix-multiple-relations-same-column into 930eefd758eb6954f29dc8b8c4f189eb02491ffd on typeorm:master.
I don't understand why the test passes on nodes 16 and 20, but not on 18.
Should I rewrite test github issues > #7283 ... to ignore the order of array elements?
what else is needed to merge this PR?
What's wrong with this PR? Why isn't it being merged? I've already successfully used this build in some production projects.
I found a few more issues that could possibly be resolved with this PR - #1668, #9788, #9814
I found a few more PR that could possibly be resolved with this PR - #4800
Walkthrough
A new utility method for shallow object cloning was added to OrmUtils, and logic in RelationJoinColumnBuilder was updated to use it for cloning relational columns when needed. Comprehensive tests were introduced to verify the cloning behavior and to ensure correct handling of composite foreign keys with shared columns in entity relations.
Changes
| File(s) | Change Summary |
|---|---|
| src/util/OrmUtils.ts | Added static method cloneObject for shallow cloning of objects without invoking constructors. |
| src/metadata-builder/RelationJoinColumnBuilder.ts | Updated logic to clone relational columns when referencedColumn is set, using the new utility. |
| test/unit/util/orm-utils.ts | Added unit test suite for cloneObject, verifying shallow copy behavior and constructor avoidance. |
| test/functional/metadata-builder/relation-join-column-builder/entity/City.ts | Added new City entity with composite primary key and population column. |
| test/functional/metadata-builder/relation-join-column-builder/entity/Country.ts | Added new Country entity with primary key and region column. |
| test/functional/metadata-builder/relation-join-column-builder/entity/Company.ts | Added new Company entity with relations to Country and City using composite and shared keys. |
| test/functional/metadata-builder/relation-join-column-builder/relation-join-column-builder.ts | Added functional test verifying composite foreign key loading and relation correctness. |
Sequence Diagram(s)
sequenceDiagram
participant TestSuite
participant OrmUtils
participant RelationJoinColumnBuilder
TestSuite->>OrmUtils: cloneObject(originalObject)
OrmUtils-->>TestSuite: Returns shallow clone (no constructor call)
TestSuite->>RelationJoinColumnBuilder: collectColumns()
RelationJoinColumnBuilder->>OrmUtils: cloneObject(relationalColumn)
OrmUtils-->>RelationJoinColumnBuilder: Returns cloned column
RelationJoinColumnBuilder-->>TestSuite: Uses cloned column for relation setup
Poem
In the warren of code, a new clone appears,
Shallow and swift, it calms our fears.
No constructor thumps, no side effects bloom,
Relations now dance in their own little room.
With cities and countries, the tests all agreeβ
The join columns are hopping in harmony!
πβ¨
[!WARNING] There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.
π§ ESLint
If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.
npm error Exit handler never called! npm error This is an error with npm itself. Please report this error at: npm error https://github.com/npm/cli/issues npm error A complete log of this run can be found in: /.npm/_logs/2025-06-17T15_07_44_599Z-debug-0.log
β¨ Finishing Touches
- [ ] π Generate Docstrings
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.
πͺ§ 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.Explain this complex logic.Open a follow-up GitHub issue for this discussion.
- Files and specific lines of code (under the "Files changed" tab): Tag
@coderabbitaiin a new review comment at the desired location with your query. Examples:@coderabbitai explain this code block.@coderabbitai modularize this function.
- PR comments: Tag
@coderabbitaiin 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 src/utils.ts and explain its main purpose.@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.@coderabbitai help me debug CodeRabbit configuration file.
Support
Need help? Create a ticket on our support page for assistance with any issues or questions.
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.
CodeRabbit Commands (Invoked using PR comments)
@coderabbitai pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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
Documentation and Community
- 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.
I tested this pullrequest with "npm i https://pkg.pr.new/typeorm/typeorm@11400" in my project. It fixed the bug for me. No new bugs found.
Referring to my predecessor, it would therefore be very useful if the PR were integrated into the main project.
I think the PR would be merged, but we need to fix some code quality issues.
First of all, there are 9 tests that do the same thing. One would have been enough. We would like to keep the codebase maintainable. There will come a time when we will have to upgrade mocha+chai (or switch to something else, who knows?), so some tests will need to be adjusted - and it would easier to handle one test instead of 9 of them. We should think about quality not quantity π
Later edit: I extract the objectClone util, wrote some tests for it, and removed 8 of the duplicate tests. The PR should now be easier to review for the maintainers as well π
@coderabbitai full review
β Actions performed
Full review triggered.
@alumni please restart the check or tell me how to do it
@alumni please restart the check or tell me how to do it
@yevhen-komarov you don't have the permission, I'll be able to do it after all actions complete.
Seems the coverage collecting service has some random 500 errors, so nothing to worry about ;)
@yevhen-komarov Many thanks for the contribution, this was a long-standing issue (I also encountered it in my project at some point), I think many people will be pleased to see it's fixed :)