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
{{ message }}
Repository navigation
bulkCreate can't do "upsert" logic with postgres, even though normal "upsert" is supported by postgres? #4324
dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: featureDEPRECATED: replace with the "feature" issue type
How come bulkCreate can't use "upsert" logic with postgres? The normal "upsert" command supports Postgres.
Reacted by Jason Kraus, Leonid Beschasny, Johnny Nguyen, Charlie Deuter, Ihor Halchevskyi, Tylor Stewart, Gábor Soós, Dustin Blackman, Crisoforo Gaspar Hernández, Aaron Schaef and 40 more
Do you mean upsert as in ON DUPLICATE KEY UPDATE? That feature only exists in postgres 9.5, which isn't officially released yet.
Right now single row upsert is handled using a function which catches the unique constraint error. It's not pretty :-). We're definitely going to switch to the new syntax once it's released officially, but not before we can test it on Travis
// True if the model has a non-autogenerated primary keyconsthas_actual_primary_key=(model)=>{constattrs=Object.keys(model.attributes)constpk_fields=attrs.filter((x)=>{returnmodel.attributes[x].primaryKey&&!model.attributes[x]._autoGenerated})returnpk_fields.length>0}// Uses true "upsert" if the model has a primary key, otherwise findOrCreate().constbulk_upsert=(model,rows)=>{returnPromise.all(rows.map((row)=>{if(has_actual_primary_key(model)){returnmodel.upsert(row)}else{returnmodel.findOrCreate({where: row,defaults: row})}}))}module.exports=bulk_upsert
Reacted by Mari Kennedy, Oleksii , Umair Ghazi, Flashpoint Srl and Pegah Ahmadvand
Reacted by Charlie Deuter, Dustin Blackman, Guilherme Munhoz, Mari Kennedy, Brandon Cook, Noah Prince, Daniel Qiu, Muhammad Sadiq, Ryan Harmuth, Aymeric Beaumet and 3 more
I hacked the bulk insert query generated by Sequelize and added ON CONFLICT at the end.
constupsertCompiled=template(`<%= bulkQuery %>ON CONFLICT (<%= constraint %>) DO UPDATESET<%= sets %>;`);/** * Postgres bulk Upsert * Hacked from the insert query generated by Sequelize * https://www.postgresql.org/docs/10/static/sql-insert.html * * @param {Sequelize.Model} Model - Model to do bulk upsert on * @param {any[]} values - bulk values for model * @param {string} constraint - constraint name or primary key to check * @param {string[]} fieldsToSet - fields to set on conflict * */exportasyncfunctionbulkUpsert(Model: Sequelize.Model<any,any>,values: any[],constraint: string,fieldsToSet: string[]){constmodel: any=Model;// Map attributes to fields for serial identificationconstfieldMappedAttributes: any={};for(constattrofkeys(model.tableAttributes)){fieldMappedAttributes[model.rawAttributes[attr].field||attr]=model.rawAttributes[attr];}constqueryGererator=sequelize.getQueryInterface().QueryGenerator;letbulkQuery=queryGererator.bulkInsertQuery(Model.getTableName(),values,{},fieldMappedAttributes,);bulkQuery=bulkQuery.replace(/;\s*$/,'');constsets=fieldsToSet.map(f=>` ${f} = EXCLUDED.${f} `).join(',');constbulkUpsertQuery=upsertCompiled({bulkQuery, constraint, sets});awaitsequelize.query(bulkUpsertQuery);}
you probably should be careful with this!
Reacted by test, jeromemalot, Kellen Hawley, Felipe Forbeck, konstantinbarkalov, Phạm Huy Hoàng, Corey Pauley and Anton Petrov
// True if the model has a non-autogenerated primary keyconsthas_actual_primary_key=(model)=>{constattrs=Object.keys(model.attributes)constpk_fields=attrs.filter((x)=>{returnmodel.attributes[x].primaryKey&&!model.attributes[x]._autoGenerated})returnpk_fields.length>0}// Uses true "upsert" if the model has a primary key, otherwise findOrCreate().constbulk_upsert=(model,rows)=>{returnPromise.all(rows.map((row)=>{if(has_actual_primary_key(model)){returnmodel.upsert(row)}else{returnmodel.findOrCreate({where: row,defaults: row})}}))}module.exports=bulk_upsert
If I use an array of upsert's instead of a single bulkCreate, I get a
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
My table has 113 thousand rows.
Another problem is that I need to insert/update in bulk because some rows have foreign keys to other rows that are to be inserted but are not in the DB yet. If I use upsert, I get a SequelizeForeignKeyConstraintError.
dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).type: featureDEPRECATED: replace with the "feature" issue type
Activity
janmeier commentedon Aug 14, 2015
Do you mean upsert as in
ON DUPLICATE KEY UPDATE? That feature only exists in postgres 9.5, which isn't officially released yet.Right now single row upsert is handled using a function which catches the unique constraint error. It's not pretty :-). We're definitely going to switch to the new syntax once it's released officially, but not before we can test it on Travis
GeoffreyPlitt commentedon Aug 14, 2015
Here's what I'm currently doing:
janmeier commentedon Aug 14, 2015
Yeah, something along those lines is probably your best bet for now
janmeier commentedon Aug 17, 2015
Closing, works as intended until postgres 9.5 is out
diosney commentedon Feb 29, 2016
It seems that Postgres 9.5.1 is already out, maybe you can reopen the issue now?
mickhansen commentedon Feb 29, 2016
@diosney Is it on travis yet?
diosney commentedon Feb 29, 2016
It seems that not yet (latest version they have in the docs are 9.4.1) :(
I will leave here the links for future reference:
https://docs.travis-ci.com/user/using-postgresql/
travis-ci/travis-ci#4264
prasadbhosale commentedon May 2, 2016
Postgres 9.5 is already out . You can reopen this issue now ?
janmeier commentedon May 2, 2016
but its not yet easily available on travis travis-ci/travis-ci#4264
benbonnet commentedon Aug 13, 2016
It is now available; isn't it ?
andrewgbliss commentedon Aug 16, 2016
+1
charlesdeuter commentedon Dec 22, 2016
+1
trjstewart commentedon Jan 16, 2017
+1
14 remaining items
jameskennethrobinson commentedon Dec 19, 2017
Would love to see this feature!
a7ul commentedon Feb 4, 2018
👍 Need it !
petersg83 commentedon Mar 7, 2018
Almost 3 years now it is open ?...
breakpointninja commentedon Mar 16, 2018
I
hackedthe bulk insert query generated by Sequelize and addedON CONFLICTat the end.you probably should be careful with this!
flashpointsrl commentedon Nov 17, 2018
If the model has an autogenerated primary key is still possible to do something to update the existent items?
thank you
cld
metaman commentedon Jan 7, 2019
Would love to see this implemented too!
EdoardoPaluan commentedon Jan 12, 2019
Any updates on this? Would love to get an affectedRows output on bulkCreate :)
imShara commentedon Jan 17, 2019
ON CONFLICT UPDATEis supported in postgres long time ago. Why not to support in sequelize?UPD. Self-answer, because
ON CONFLICT UPDATE SETin Postgres is made.. strange.mickhansen commentedon Jan 17, 2019
@imShara The reason, as for most things, is time. Maintainers have limited time and no one has taken the time to contribute.
lpedromachado commentedon Apr 5, 2019
If I use an array of
upsert's instead of a singlebulkCreate, I get aMy table has 113 thousand rows.
Another problem is that I need to insert/update in bulk because some rows have foreign keys to other rows that are to be inserted but are not in the DB yet. If I use
upsert, I get aSequelizeForeignKeyConstraintError.I don't know what to do. :(
gabrielmsdiniz commentedon Jun 19, 2019
+1
sushantdhiman commentedon Jul 27, 2019
Fixed #11163