You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)
Steps to reproduce or a small repository showing the problem:
Hi,
I am trying to do an upsert to a large object and I am having trouble.
I saw #1090 but this solution is not very good for me.
to upsert I need to build my query with createQueryBuilder but onConflict only excepts string queries, which makes it very difficult with large objects since I have to write my query manually.
I did it, but the parameters are not ordered the same in both queries..
also, you need to start the onConflict with '("violation_column") DO' and remove the table name from the update query...
EDIT The below solution still has problems. Namely, the update query and the insert query sort column names differently and therefore, values passed through end up not lining up properly for the update query.
Original Comment:
I got this working, but it ended up requiring some string replace to be done on the resulting update query.
See this example to understand what I did to make it work. It's dirty, and would be nice if supported directly in typeorm.
// Wherever you're doing your queryconstnewUser={id: uuidv4(),// let's assume this was passed// in from client and might be dupefirstName: 'bob',lastName: 'bobberson',age: 38,}constnewUserSansId={firstName: 'bob',lastName: 'bobberson',age: 38,}constupdateQb=connection.createQueryBuilder().update(User,newUserSansId)awaitconnection.createQueryBuilder().insert().into(User).values(newUser).onConflict(`(id) DO ${updateQb.getQuery()// Update the beginning of the statement. Normal updates start slightly// differently than ON CONFLICT DO UPDATE.replace(/^UPDATE"users"/i,'UPDATE')// Update the parameter numbers. (increment by one to skip the id param).replace(/\$(\d{1,2})/g,(wholeMatch,numberMatch)=>`$${Number.parseInt(numberMatch,10)+1}`,)}`,).setParameters(updateQb.getParameters()).execute()
Additional Information:
The syntax for update after ON CONFLICT is slightly different than a normal update. Also, it gives you a bit more power than a normal update by letting you reference EXCLUDED (similar to NEW in update triggers).
So, for instance, version columns are busted in on conflict updates because the reference is ambigious:
SET "version" = "version" +1
vs:
SET "version" = "table_name"."version" + 1
Also, no where clause exists in my above example because the update only looks at the conflicting row. You can put a where clause if needed, but in my above example it is not needed.
Seems like a lot of unnecessary workarounds when a simple upsert method would solve everything.
Reacted by Ryan Bright, Daniel Sousa, feelthewind, Aleksi Pekkala, AnastasiusVivaldus, Park Hee Chan, Bagas Nugroho, Stepan Hilbert, Marvin Countryman, AnthonyMouallem and 19 more
The @pleerock suggestion would be very useful. Unfortunately I cannot do it with mysql. Upsert is much faster for massive inserts. It's avoid to run multiples queries to do one atomic operation. For my scenario I have to run a native query as follow bellow, the results of entire process were 3 times faster than using typeorm multiples queries:
const query = INSERT INTO product ( field1, filed2 ) VALUES('field1Value', field2Value) ON DUPLICATE KEY UPDATE field1='field1Value', field2='field2Value';|
await repoProduct.query(query);
However we know that get into native queries aren't so good when the entities have to update. So any news on upsert with query builder for mysql in typeorm?
For everyone that can't upgrade anytime soon. I found this function to work pretty well for my needs.
export class CustomRepository<Entity> extends Repository<Entity> {
async upsert(
connect: FindConditions<Entity> | FindConditions<Entity>[],
newFields: DeepPartial<Entity>,
): Promise<Entity> {
// Use find conditions and search for a pre-existing entity.
for (const findCondition of _.castArray(connect)) {
const entity = await this.findOne(findCondition);
if (entity) {
// Combine entity with new fields and update DB.
return this.save(await this.merge(entity, newFields));
}
}
// No entity found. Create and save new entity.
return this.save(newFields);
}
}
Activity
pleerock commentedon Jun 19, 2018
does it work for you?
tomer-amir-vonage commentedon Jun 19, 2018
Hi @pleerock
it does not... 😞
I'm having issues with parameters
Currently trying to work around it
pleerock commentedon Jun 19, 2018
Try this:
not sure, maybe you'll need to set native parameters as well.
tomer-amir-vonage commentedon Jun 19, 2018
I did it, but the parameters are not ordered the same in both queries..
also, you need to start the
onConflictwith'("violation_column") DO'and remove the table name from the update query...tomer-amir-vonage commentedon Jun 24, 2018
any news?
pleerock commentedon Jun 24, 2018
What is your proposal?
tomer-amir-vonage commentedon Jul 1, 2018
something like
onConflict(...conflictFields: string[]).doUpdate()would be nice 😄Devang142 commentedon Oct 1, 2018
Seems like onConflict method not working for mysql. Can you please add support for mysql as well?
pthrasher commentedon Feb 22, 2019
EDIT The below solution still has problems. Namely, the update query and the insert query sort column names differently and therefore, values passed through end up not lining up properly for the update query.
Original Comment:
I got this working, but it ended up requiring some string replace to be done on the resulting update query.
See this example to understand what I did to make it work. It's dirty, and would be nice if supported directly in typeorm.
Additional Information:
The syntax for update after ON CONFLICT is slightly different than a normal update. Also, it gives you a bit more power than a normal update by letting you reference EXCLUDED (similar to NEW in update triggers).
So, for instance, version columns are busted in on conflict updates because the reference is ambigious:
SET "version" = "version" +1vs:
SET "version" = "table_name"."version" + 1Also, no where clause exists in my above example because the update only looks at the conflicting row. You can put a where clause if needed, but in my above example it is not needed.
pbirsinger commentedon Jul 26, 2019
Seems like a lot of unnecessary workarounds when a simple upsert method would solve everything.
JeremyBernier commentedon Feb 5, 2020
Yes TypeORM needs an upsert function.
For anyone in need of an upsert() function for PostgreSQL, here's the one I wrote
https://gist.github.com/JeremyBernier/5683ebc8e83990a4d4e3d0abd1a9549d
feat: add upsert methods for the drivers that support it
feat: add upsert methods for the drivers that support it
feat: add upsert methods for the drivers that support it
feat: add upsert methods for the drivers that support it
cassioseffrin commentedon Sep 5, 2021
Hello.
The @pleerock suggestion would be very useful. Unfortunately I cannot do it with mysql. Upsert is much faster for massive inserts. It's avoid to run multiples queries to do one atomic operation. For my scenario I have to run a native query as follow bellow, the results of entire process were 3 times faster than using typeorm multiples queries:
const query =
INSERT INTO product ( field1, filed2 ) VALUES('field1Value', field2Value) ON DUPLICATE KEY UPDATE field1='field1Value', field2='field2Value';|await repoProduct.query(query);
However we know that get into native queries aren't so good when the entities have to update. So any news on upsert with query builder for mysql in typeorm?
feat: add upsert methods for the drivers that support onUpdate (#8104)
yestheboxer commentedon Nov 10, 2021
For everyone that can't upgrade anytime soon. I found this function to work pretty well for my needs.
feat: add upsert methods for the drivers that support onUpdate (typeo…