Skip to content

fix: prefix relation id columns contained in embedded entities (#6977)#6981

Closed
nebkat wants to merge 3 commits intotypeorm:masterfrom
nebkat:master
Closed

fix: prefix relation id columns contained in embedded entities (#6977)#6981
nebkat wants to merge 3 commits intotypeorm:masterfrom
nebkat:master

Conversation

@nebkat
Copy link
Copy Markdown
Contributor

@nebkat nebkat commented Oct 27, 2020

Searches embedded entity columns for relation ID column if relation column is in embedded entity. If not found, creates new relation ID with embedded metadata set to match the relation column.

Fixes: #2254
Fixes: #3132
Fixes: #3226
Fixes: #6977

Description of change

See #6977.

Currently the relation column's entityMetadata is searched for columns matching the join column, rather than embeddedMetadata (when present).

let relationalColumn = relation.entityMetadata.ownColumns.find(column => column.databaseName === joinColumnName);
.

This changes that behavior to match

if (relation.embeddedMetadata) {
relation.embeddedMetadata.indices.push(index);
} else {
relation.entityMetadata.ownIndices.push(index);
}

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run lint passes with this change
  • 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
  • The new commits follow conventions explained in CONTRIBUTING.md

@imnotjames
Copy link
Copy Markdown
Contributor

imnotjames commented Oct 29, 2020

Looks like this change causes the oracle tests to fail?

Tests run in CircleCI in open PRs and you can see the failure here - https://circleci.com/gh/typeorm/typeorm/4727?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link

nebkat added a commit to nebkat/typeorm that referenced this pull request Oct 29, 2020
@nebkat
Copy link
Copy Markdown
Contributor Author

nebkat commented Oct 29, 2020

Oracle issue with max identifier length being 30 characters, looks like it never occurred in the past because the column names always excluded the embedded prefixes. Fixed by shortening a prefix in the edge cases with long identifiers.

const joinColumnName = joinColumnMetadataArg ? joinColumnMetadataArg.name : this.connection.namingStrategy.joinColumnName(relation.propertyName, referencedColumn.propertyName);

let relationalColumn = relation.entityMetadata.ownColumns.find(column => column.databaseName === joinColumnName);
const relationalColumns = relation.embeddedMetadata ? relation.embeddedMetadata.columns : relation.entityMetadata.ownColumns;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

what if there is an embedded, but we point to a relation that not in the embedded?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm not sure what you mean, I think relation.embeddedMetadata is only set if relation is a column within an embedded entity. It was somewhat confusing initially but relation refers only to the foreign key column, not the target relation entity.

This particular section is what searches for an existing relation id column, and if the relation is located inside an embedded then it only makes sense to search for the relation id column also in the embedded rather than in the base of the entity.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

okay, thank you for explanation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've had a second look at this, and in theory we could allow relation IDs to not be in the embedded entity together with the relation, but I'm not sure whether that would cause additional confusion.

@Entity()
class Other {
    @PrimaryColumn() id: number;
}
@Entity()
class User {
    @Column(() => Embed) embed: Embed;

    @Column() embedOther1Id: number;
    @ManyToOne(() => Other) embedOther2: Other;
}
class Embed {
    @ManyToOne(() => Other) other1: Other;
    @Column() other2Id: number;
}

Both relations here could match up correctly if we want, and if they are not matched up they will lead to a duplicate column error anyway. MongoDB is an exception since it maintains the embedded objects in DB, so both relation/ID have to be in the same entity.

favorites: number;

@Column(() => Subcounters)
@Column(() => Subcounters, {prefix: "sub"})
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why did you change exist test? You need to create a separate test for a new use case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The columns inside embedded entities were being incorrectly generated previously. The correct column name is countersSubcountersWatchedUserId, which is 32 characters long, and too long for Oracle DB which can only take 30 characters. Before this fix, the column name would have been watchedUserId or something, so there was no problem, but the wrong column name was going unnoticed.

This test only checks the ORM side of things anyway, so the exact name in database was irrelevant, but I can change the variable name from subcounters to sub directly if you'd prefer. I have already created a new test case for the issue #6977.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the problem is, if we merge these changes, we introduce a breaking change. Right now Oracle users have same case working (even if column name is invalid), but if we merge these changes their codebases won't be working at all. We can't tell them "hey guys just monkey patch it using "prefix" like we did it on our tests". Proper solution is to fix related Oracle issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For this test anyway there is no solution for Oracle unless we plan to truncate column names automatically? Could potentially introduce a more informative error during column generation if target DB is Oracle since the DB error is very vague.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

we already do truncate in some other places for Oracle

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Might be something worth looking at with naming strategies for the future, gives the user the option for more meaningful change than simple truncation.

@pleerock
Copy link
Copy Markdown
Member

@imnotjames it looks like this will introduce a serious breaking change for the users who have same use case. Right now what we have is a bug, this is true. If we merge these changes bug will be fixed, but it will also lead to schema re-creation and data loss for users. We need to decide how much acceptable it is to merge these changes not into the next.

@nebkat
Copy link
Copy Markdown
Contributor Author

nebkat commented Oct 31, 2020

I see the difficulty of maintaining the project now 🙂 Would it be worth introducing a temporary option property to relations that applies this fix until next major release? Definitely shouldn't break existing setups, but unless the next release is coming soon it might be frustrating for users and will also lead to more broken columns being initiated in new projects. In my case I have multiple userId references and it fails because of duplicate column so I can't even keep the ORM side correct.

@ManyToOne(() => UserEntity, {fixEmbeddedRelationColumn: true})?

@pleerock
Copy link
Copy Markdown
Member

if we go this way, but better to make same a connection-level option

@nebkat
Copy link
Copy Markdown
Contributor Author

nebkat commented Oct 31, 2020

Sounds good, if you think this is best I can implement it. I propose maybe a field in BaseConnectionOptions e.g. targetVersion: "0.3.0" which defaults to the current release, string comparison as a condition for the breaking changes, along with a strong warning for users that things are likely to break if they target future versions. Once that version is released the old code gets removed, but hopefully additional feedback can be gained from users willing to test new features.

@pleerock
Copy link
Copy Markdown
Member

pleerock commented Nov 2, 2020

I think it's better just to call them "enableNextFeatures", don't think we'll really try to support more than one next breaking version.

nebkat added a commit to nebkat/typeorm that referenced this pull request Nov 2, 2020
Adds a new flag to connection options to allow user to enabled planned future
breaking changes before next release.

See typeorm#6981.
nebkat added a commit to nebkat/typeorm that referenced this pull request Nov 2, 2020
nebkat added a commit to nebkat/typeorm that referenced this pull request Nov 3, 2020
Adds a new flag to connection options to allow user to enabled planned future
breaking changes before next release.

See typeorm#6981.
nebkat added a commit to nebkat/typeorm that referenced this pull request Nov 3, 2020
nebkat added a commit to nebkat/typeorm that referenced this pull request Dec 16, 2020
Adds a new flag to connection options to allow user to enabled planned future
breaking changes before next release.

See typeorm#6981.
nebkat added a commit to nebkat/typeorm that referenced this pull request Dec 16, 2020
Adds a new flag to connection options to allow user to enabled planned future
breaking changes before next release.

See typeorm#6981.
…rm#6977)

Searches embedded entity columns for relation ID column if relation column
is in embedded entity. If not found, creates new relation ID with embedded
metadata set to match the relation column.

fixes: typeorm#6977, typeorm#3226, typeorm#3132 and typeorm#2254
@nebkat
Copy link
Copy Markdown
Contributor Author

nebkat commented Feb 26, 2021

Since latest TypeScript is merged the next release should be considered breaking, can the enableNextFeatures flag be removed and have the fix applied by default?

nebkat added a commit to nebkat/typeorm that referenced this pull request Feb 26, 2021
@nebkat nebkat closed this Feb 26, 2021
nebkat added a commit to nebkat/typeorm that referenced this pull request Feb 26, 2021
nebkat added a commit to nebkat/typeorm that referenced this pull request Feb 27, 2021
holm pushed a commit to PlatiaTeam/typeorm that referenced this pull request Dec 16, 2021
cwikla pushed a commit to puzzlefin/typeorm that referenced this pull request Dec 22, 2021
pleerock pushed a commit that referenced this pull request Feb 16, 2022
#7432)

* fix: prefix relation id columns contained in embedded entities (#6977)

Searches embedded entity columns for relation ID column if relation column
is in embedded entity. If not found, creates new relation ID with embedded
metadata set to match the relation column.

fixes: #2254
fixes: #3132
fixes: #3226
fixes: #6977

* test: prefix subcounters sub-entity with "sub" to fit in 30 character identifier for oracle

Problem introduced with #6981
pleerock added a commit that referenced this pull request Mar 17, 2022
* added find options and new option relationLoadStrategy

* find now returns null instead of undefined; removed primary relations support; bugfixing; added some changes and tests from next branch;

* added typename to connection options; added data loader types, lot of deprecations; new es2020 emit by tsc; new custom repositories syntax

* applied lint fixing

* replaced some instanceof checks

* reverting docker compose image versions

* optimizing imports

* reverting back some instanceof checks to prevent compiler errors

* downgrading es compilation version

* docs: remove "primary" from relation options (#8619)

remove ex-line 26 for being deprecated in 0.3.0:
"* `primary: boolean` - Indicates whether this relation's column will be a primary column or not."

* Revert "reverting back some instanceof checks to prevent compiler errors"

This reverts commit 7bf12a3.

* Revert "optimizing imports"

This reverts commit 7588ac1.

* Revert "replaced some instanceof checks"

This reverts commit bfa5a2d.

* fixing few comments

* removing transaction decorators

* this test is invalid - it's not clear why the hell getTreeRepository will throw an error and it's not clear what kind of error its going to throw

* addded mixed list support in connection options

* trying to fix oracle length issue

* lintfix

* removed shorten usages

* added named entity target support to the connection

* fixing entity target support in relation options via entity schema

* debugging oracle issue

* fixed issue with alias not being shortened in many to many alias cases

* some day we'll have a prettier.

* fixing oracle tests

* fixing oracle failing test

* removed "null" support in where expressions; fixed softDelete and restore incorrect usages

* renamed FindConditions to FindOptionsWhere

* version bump

* docs: update loading relation in find method (v 0.3.0) (#8621)

* docs: update relation definition method

Update the method that allows loading a specific relation inside the find method.
This method is found on the one-to-one-relations page.
Change `const users = await userRepository.find({ relations: ["profile"] });` to `const users = await userRepository.find({ relations: {profile: true});`.

* fix formatting

Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com>

* docs: change relations option definition (#8620)

* docs: change relations option definition

change line 139 from 
`const users = await connection.getRepository(User).find({ relations: ["profile", "photos", "videos"] });`
to
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });`
to reflect version 0.3.0 changes

* docs: change relations option definition

Rectified a type on line 139
from:
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true] });`
to
`const users = await connection.getRepository(User).find({ relations: { profile: true, photos: true, videos: true} });`

* formatting

Co-authored-by: Umed Khudoiberdiev <pleerock.me@gmail.com>

* lint

* improved find options types

* fixed types and removed nonnever because it causes circual issue for some reason

* docs: update entitymanager definition (#8623)

* docs: update entitymanager definition

change the "What is EntityManager?" page to be up-to-date with v 0.3.0

1. line 6 changes from
`You can access the entity manager via 'getManager()' or from 'Connection'.`
to 
`You can access the entity manager via DataSource's manager.`

2. the import on `getManager` in line 10 becomes `Manager` that the user have configured beforehand:
`import {getManager} from "typeorm";`
becomes 
`import {Manager} from "./config/DataSource";`

3.change entityManager definition in line 13:
from
`const entityManager = getManager(); // you can also get it via getConnection().manager`
to
`const entityManager = Manager;`

* docs: update entitymanager definition

changed line 10 from: 
`import {Manager} from "./config/DataSource";`
to
`import {DataSource} from "typeorm";`

and changed line 13 and 14 from: 
`const entityManager = Manager;`
`const user = await entityManager.findOne(User, 1);`
to 
`const myDataSource = new DataSource({ /*...*/ });`
`const user = await myDataSource.manager.findOne(User, 1);`

for a simpler way of describing the origin of DataSource and how it works.

* In return type doesn't seem to work in all cases

* feat: mssql v7 support (#8592)

Adds support for v7 of the mssql library as v6 is EOL. This also makes use of the new toReadableStream method on requests to return a native stream where required.

* fix: prefix relation id columns contained in embedded entities (#6977) (#7432)

* fix: prefix relation id columns contained in embedded entities (#6977)

Searches embedded entity columns for relation ID column if relation column
is in embedded entity. If not found, creates new relation ID with embedded
metadata set to match the relation column.

fixes: #2254
fixes: #3132
fixes: #3226
fixes: #6977

* test: prefix subcounters sub-entity with "sub" to fit in 30 character identifier for oracle

Problem introduced with #6981

* fix: find by Date object in sqlite driver (#7538)

* fix: find by Date object in sqlite driver

In sqlite, Date objects are persisted as UtcDatetimeString.
But a Date object parameter was escaped with .toISOString(), making such queries impossible.
This commit aligns both transforms.
This bug does *not* apply to better-sql where you can only bind numbers, strings, bigints, buffers,
and null.
This is breaking for when the user inserted their dates manually as ISO and relied on this old
maltransformation, after this their find()s by Date won't work anymore.

BREAKING CHANGE: Change Date serialization in selects
Closes: #2286

* add failing test

* fix: find by Date object in sqlite driver (with query builder)

Also consider query builder parameter escaping

* test: add test for 3426

Co-authored-by: James Ward <james@notjam.es>

* manually ported changes from #7796

* updated changelog

* fixes after merge

* new findOne syntax

* new find* syntax

* new find* syntax

* lint

* tsc version bump

* tsc version bump and fixed mongodb issues

* moved date fns into non dev deps

* returned oracledb dep into place

* removed lock files

* returned lock files back

* eslint upgrade

* fixing mongodb issue

* fixing mongodb issue

* test: keep junction aliases short (#8637)

Tests a fix for an issue where junction aliases (e.g. in many-to-many relations)
are not unique because they are too long and thus truncated by the driver.

Closes: #8627
Related to: 76cee41

* fixing mongodb issues

* fixing sqlite test

* fixing sqlite test

* fixing sqlite test

* fixing mongodb test

* fixing entity schema tests

* fixing entity schema tests

* merged latest master

* removed driver instanceof checks

* removed function instanceof checks

* removed Object instanceof checks

* removing instanceof checks...

* fixing instanceof checks

* added InstanceChecker to remove remaining instanceof checks

* fixed failing test

* linting

* fixing failing test

* version bump

* compiler fixes

* Connection type usages replace to DataSource

* updated dev deps

* updated deps, add prettier, removed oracledb due to m1 issue

* chalk downgrade

* fixing failing test

* applied prettier formatting

* replaced eslint to prettier

* okay I think we can call it lint

* fixing linting

* fixed prettier introduced compiler bug

* fixed failing test

* prettier;

* fixed failing test

* alias shortening only for junction tables;
fixed failing tests;

* changed aurora db names and reverted change of junction table name shorten algorithm

* format

* removed platform from docker compose

* made numeric parameters to not use parameters to prevent parameters number limit issue. Also enabled shorten only for junction tables

* fixing test

* fixing returning columns bugs

* fixing test

* fixed returning issue

* fixing merge conflicts

* updating documentation

* working on docs / improving api

* working on docs

* fixed isConnected issue

* re-worked commands

* commenting cli command tests for now

* commenting cli command tests for now

* removed platform

* returned Connection back

* refactor: export tree repository helper methods (#8753)

* Migrated protected tree methods to util class

* Added tree repository extend override

* Ran prettier format

* merge master into 0.3.0

Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de>

* working on documentation

Co-authored-by: Bilel Taktak <47742269+Parsath@users.noreply.github.com>
Co-authored-by: Salah Azzouz <52634440+Salah-Azzouz@users.noreply.github.com>
Co-authored-by: Daniel Hensby <dhensby@users.noreply.github.com>
Co-authored-by: Nebojša Cvetković <nebkat@gmail.com>
Co-authored-by: Philip Waritschlager <philip+github@waritschlager.de>
Co-authored-by: James Ward <james@notjam.es>
Co-authored-by: Felix Gohla <37421906+felix-gohla@users.noreply.github.com>
Co-authored-by: Dmitry Zotov <dmzt08@gmail.com>
Co-authored-by: Jimmy Chen <50786287+Q16solver@users.noreply.github.com>
Co-authored-by: Bitcollage <serkan.sipahi@yahoo.de>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants