On entity save causes unnecessary update with one to many relation
Issue type:
[ ] question [ X ] bug report [ ] feature request [ ] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[ X ] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[ X ] latest
[ ] @next
[ ] 0.x.x (or put your version here)
Steps to reproduce or a small repository showing the problem:
Entities, also separate repo (https://github.com/typeorm/typeorm/compare/master...riston:issue-3603?expand=1):
@Entity()
export class Photo {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@Column()
user_id: number;
@ManyToOne(() => User, user => user.photos)
@JoinColumn({ name: 'user_id' })
user: User;
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Photo, photo => photo.user)
photos: Photo[];
}
const user = new User();
user.name = "John";
await connection.manager.save(user);
const photo2 = new Photo();
photo2.url = "me-and-bears.jpg";
photo2.user_id = user.id;
await connection.manager.save(photo2);
const photo1 = new Photo();
photo1.url = "me.jpg";
photo1.user_id = user.id;
await connection.manager.save(photo1);
// In case one of the photos is missing
const firstPhoto = await connection.manager.findOne(Photo, { id: 1 });
const firstUser = await connection.manager.findOne(User, {}, { relations: ['photos']});
if (firstUser === undefined || firstPhoto === undefined) {
throw Error('Not found entity');
}
firstPhoto.url = 'next.jpg';
firstPhoto.user_id = user.id;
firstUser.photos = [firstPhoto]; // Note one of the photos wasn't provided
await connection.manager.save(firstUser); // This would throw error
console.log(await connection.manager.find(User, { relations: ['photos'] }));
Error on save causes strange update with null user_id which is actually defined.
query: SELECT "User"."id" AS "User_id", "User"."name" AS "User_name", "User__photos"."id" AS "User__photos_id", "User__photos"."url" AS "User__photos_url", "User__photos"."user_id"
AS "User__photos_user_id" FROM "user" "User" LEFT JOIN "photo" "User__photos" ON "User__photos"."user_id"="User"."id" WHERE "User"."id" IN (1)
query: SELECT "User"."id" AS "User_id", "User"."name" AS "User_name" FROM "user" "User" WHERE "User"."id" IN ($1) -- PARAMETERS: [1]
query: SELECT "photo"."id" AS "id", "photo"."user_id" AS "user_id" FROM "photo" "photo" WHERE (("photo"."user_id" = $1)) -- PARAMETERS: [1]
query: START TRANSACTION
query: UPDATE "photo" SET "user_id" = $2 WHERE "id" = $1 -- PARAMETERS: [2,null]
query failed: UPDATE "photo" SET "user_id" = $2 WHERE "id" = $1 -- PARAMETERS: [2,null]
error: { error: null value in column "user_id" violates not-null constraint
at Connection.parseE (/Users/riston/exper/typeorm/node_modules/pg/lib/connection.js:554:11)
at Connection.parseMessage (/Users/riston/exper/typeorm/node_modules/pg/lib/connection.js:379:19)
at Socket.<anonymous> (/Users/riston/exper/typeorm/node_modules/pg/lib/connection.js:119:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:607:20)
name: 'error',
length: 187,
severity: 'ERROR',
code: '23502',
detail: 'Failing row contains (2, me.jpg, null).',
hint: undefined,
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: 'public',
table: 'photo',
column: 'user_id',
dataType: undefined,
constraint: undefined,
file: 'execMain.c',
line: '1736',
routine: 'ExecConstraints' }
query: ROLLBACK
Expected result: This save should execute without the UPDATE query.
When the @JoinColumn({ name: 'user_id' }) and user_id column is removed from Photo entity everything works as expected.
This is working as expected.
Using firstUser.photos = [firstPhoto] you are telling TypeORM to override the set of related Photos of the User. That's causing the update error (destroying the User relation with the Photo not provided in the array of photos).
What are you trying to achieve?
If your goal is to create a new relation between firstPhoto and firstUser, you can just save the changes on firstPhoto instead:
const firstPhoto = await connection.manager.findOneOrFail(Photo, { id: 1 });
const firstUser = await connection.manager.findOneOrFail(User, {}, { relations: ['photos']});
firstPhoto.url = 'next.jpg';
firstPhoto.user_id = firstUser.id;
await connection.manager.save(firstPhoto);
*Note the use of findOneOrFail
Closing as no response from the author.
you can get all entity relationships from metadata and update it like this:
const repository = manager.getRepository(Entity)
const metadata = repository.metadata
const record = repository.findOne(updateData.id)
const relTypes = metadata.ownRelations.map(col => ({ name: col.propertyName, type: col.type }))
for (const key of Object.keys(updateData)) {
if (relTypes.some(({ name }) => name === key)) {
const type = relTypes.find(val => val.name === key).type
const repo = connection.getRepository(type)
const ids = updateData[key]
record[key] = await repo.findByIds(ids)
} else {
record[key] = updateData[key]
}
}
await repository.save(record)