typeorm icon indicating copy to clipboard operation
typeorm copied to clipboard

fix: Multiple relations with same columns cause invalid SQL to be generated

Open yevhen-komarov opened this issue 8 months ago β€’ 15 comments

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 master branch
  • [x] npm run format to apply prettier formatting
  • [x] npm run test passes 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.

yevhen-komarov avatar Apr 10 '25 05:04 yevhen-komarov

Coverage Status

coverage: 76.349% (+0.002%) from 76.347% when pulling a6ebb2d20c8a4308a61c40fd9c29d853d00161fb on yevhen-komarov:fix-multiple-relations-same-column into 930eefd758eb6954f29dc8b8c4f189eb02491ffd on typeorm:master.

coveralls avatar Apr 10 '25 05:04 coveralls

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?

yevhen-komarov avatar Apr 12 '25 04:04 yevhen-komarov

what else is needed to merge this PR?

yevhen-komarov avatar Apr 23 '25 08:04 yevhen-komarov

typeorm-sql-js-example

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

commit: 19f027c

pkg-pr-new[bot] avatar May 04 '25 06:05 pkg-pr-new[bot]

What's wrong with this PR? Why isn't it being merged? I've already successfully used this build in some production projects.

yevhen-komarov avatar May 14 '25 07:05 yevhen-komarov

I found a few more issues that could possibly be resolved with this PR - #1668, #9788, #9814

yevhen-komarov avatar May 15 '25 04:05 yevhen-komarov

I found a few more PR that could possibly be resolved with this PR - #4800

yevhen-komarov avatar May 16 '25 10:05 yevhen-komarov

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.

❀️ 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.
    • 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 @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 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 pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

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.

coderabbitai[bot] avatar Jun 05 '25 14:06 coderabbitai[bot]

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.

mburmeister82 avatar Jun 10 '25 12:06 mburmeister82

Referring to my predecessor, it would therefore be very useful if the PR were integrated into the main project.

sbogeFS avatar Jun 10 '25 12:06 sbogeFS

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 πŸ˜‰

alumni avatar Jun 15 '25 21:06 alumni

@coderabbitai full review

alumni avatar Jun 15 '25 22:06 alumni

βœ… Actions performed

Full review triggered.

coderabbitai[bot] avatar Jun 15 '25 22:06 coderabbitai[bot]

@alumni please restart the check or tell me how to do it

yevhen-komarov avatar Jun 16 '25 14:06 yevhen-komarov

@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 ;)

alumni avatar Jun 16 '25 15:06 alumni

@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 :)

alumni avatar Jun 17 '25 16:06 alumni