Skip to content

bulkCreate can't do "upsert" logic with postgres, even though normal "upsert" is supported by postgres? #4324

Closed

Description

@GeoffreyPlitt

How come bulkCreate can't use "upsert" logic with postgres? The normal "upsert" command supports Postgres.

Activity

  1. janmeier commented on Aug 14, 2015

    @janmeier
    Member

    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

  2. GeoffreyPlitt commented on Aug 14, 2015

    @GeoffreyPlitt
    ContributorAuthor

    Here's what I'm currently doing:

    // True if the model has a non-autogenerated primary key
    const has_actual_primary_key = (model) => {
      const attrs = Object.keys(model.attributes)
      const pk_fields = attrs.filter( (x) => {
        return model.attributes[x].primaryKey && !model.attributes[x]._autoGenerated
      })
      return pk_fields.length>0
    }
    
    // Uses true "upsert" if the model has a primary key, otherwise findOrCreate().
    const bulk_upsert = (model, rows) => {
      return Promise.all(rows.map( (row) => {
        if(has_actual_primary_key(model)) {
          return model.upsert(row)
        } else {
          return model.findOrCreate({
            where: row,
            defaults: row
          })
        }
      }))
    }
    
    module.exports = bulk_upsert
  3. janmeier commented on Aug 14, 2015

    @janmeier
    Member

    Yeah, something along those lines is probably your best bet for now

  4. added
    dialect: postgres
    on Aug 17, 2015
  5. janmeier commented on Aug 17, 2015

    @janmeier
    Member

    Closing, works as intended until postgres 9.5 is out

  6. diosney commented on Feb 29, 2016

    @diosney
    Contributor

    It seems that Postgres 9.5.1 is already out, maybe you can reopen the issue now?

  7. mickhansen commented on Feb 29, 2016

    @mickhansen
    Contributor

    @diosney Is it on travis yet?

  8. diosney commented on Feb 29, 2016

    @diosney
    Contributor

    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

  9. prasadbhosale commented on May 2, 2016

    @prasadbhosale

    Postgres 9.5 is already out . You can reopen this issue now ?

  10. janmeier commented on May 2, 2016

    @janmeier
    Member

    but its not yet easily available on travis travis-ci/travis-ci#4264

  11. benbonnet commented on Aug 13, 2016

    @benbonnet

    It is now available; isn't it ?

  12. andrewgbliss commented on Aug 16, 2016

    @andrewgbliss

    +1

  13. charlesdeuter commented on Dec 22, 2016

    @charlesdeuter

    +1

  14. trjstewart commented on Jan 16, 2017

    @trjstewart

    +1

  15. 14 remaining items

  16. added
    type: feature
    on Dec 11, 2017
  17. jameskennethrobinson commented on Dec 19, 2017

    @jameskennethrobinson

    Would love to see this feature!

  18. a7ul commented on Feb 4, 2018

    @a7ul

    👍 Need it !

  19. petersg83 commented on Mar 7, 2018

    @petersg83

    Almost 3 years now it is open ?...

  20. breakpointninja commented on Mar 16, 2018

    @breakpointninja

    I hacked the bulk insert query generated by Sequelize and added ON CONFLICT at the end.

    const upsertCompiled = template(`
    <%= bulkQuery %>
    ON CONFLICT (<%= constraint %>) DO UPDATE
    SET
    <%= 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
     *
     */
    export async function bulkUpsert (Model: Sequelize.Model<any, any>,
                                values: any[],
                                constraint: string,
                                fieldsToSet: string[]) {
      const model: any = Model;
    
      // Map attributes to fields for serial identification
      const fieldMappedAttributes: any = {};
      for (const attr of keys(model.tableAttributes)) {
        fieldMappedAttributes[model.rawAttributes[attr].field || attr] = model.rawAttributes[attr];
      }
    
      const queryGererator = sequelize.getQueryInterface().QueryGenerator;
      let bulkQuery = queryGererator.bulkInsertQuery(
        Model.getTableName(),
        values,
        {},
        fieldMappedAttributes,
      );
    
      bulkQuery = bulkQuery.replace(/;\s*$/, '');
    
      const sets = fieldsToSet.map(f => ` ${f} = EXCLUDED.${f} `).join(',');
      const bulkUpsertQuery = upsertCompiled({bulkQuery, constraint, sets});
      await sequelize.query(bulkUpsertQuery);
    }

    you probably should be careful with this!

  21. flashpointsrl commented on Nov 17, 2018

    @flashpointsrl

    // True if the model has a non-autogenerated primary key const has_actual_primary_key = (model) =>

    If the model has an autogenerated primary key is still possible to do something to update the existent items?

    thank you

    cld

  22. metaman commented on Jan 7, 2019

    @metaman

    Would love to see this implemented too!

  23. EdoardoPaluan commented on Jan 12, 2019

    @EdoardoPaluan

    Any updates on this? Would love to get an affectedRows output on bulkCreate :)

  24. imShara commented on Jan 17, 2019

    @imShara

    ON CONFLICT UPDATE is supported in postgres long time ago. Why not to support in sequelize?

    UPD. Self-answer, because ON CONFLICT UPDATE SET in Postgres is made.. strange.

  25. mickhansen commented on Jan 17, 2019

    @mickhansen
    Contributor

    @imShara The reason, as for most things, is time. Maintainers have limited time and no one has taken the time to contribute.

  26. lpedromachado commented on Apr 5, 2019

    @lpedromachado
    Contributor

    Here's what I'm currently doing:

    // True if the model has a non-autogenerated primary key
    const has_actual_primary_key = (model) => {
      const attrs = Object.keys(model.attributes)
      const pk_fields = attrs.filter( (x) => {
        return model.attributes[x].primaryKey && !model.attributes[x]._autoGenerated
      })
      return pk_fields.length>0
    }
    
    // Uses true "upsert" if the model has a primary key, otherwise findOrCreate().
    const bulk_upsert = (model, rows) => {
      return Promise.all(rows.map( (row) => {
        if(has_actual_primary_key(model)) {
          return model.upsert(row)
        } else {
          return model.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.

    I don't know what to do. :(

  27. gabrielmsdiniz commented on Jun 19, 2019

    @gabrielmsdiniz

    +1

  28. sushantdhiman commented on Jul 27, 2019

    @sushantdhiman
    Contributor

    Fixed #11163

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    dialect: postgrestype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions