Skip to content

Postgres - bulkCreate with updateOnDuplicate fails when one of the model's primary key fields' name is different from its column name #11432

Closed

Description

@PeledYuval

Issue Description

bulkCreate with updateOnDuplicate throws error when one of the model's primary key fields has a different name from its DB column name.

bulkCreate generates the field names in the: ON CONFLICT (column1...) part of the query by looking at: this.primaryKeys.fieldName which is the model's field name, instead of looking at this.primaryKeys.field which is the DB's column name.

The error received by Postgres and thrown by Sequelize is, expectedly: Unhandled rejection SequelizeDatabaseError: column "fieldName" does not exist

What are you doing?

Minimal self contained reproducible example:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('postgres://postgres:postgres@localhost:5432/postgres');

class User extends Sequelize.Model {
}
User.init({
        userName: {
            type: Sequelize.STRING,
            primaryKey: true,
            field: 'user_name',
        },
        email: {
            type: Sequelize.STRING,
        }
    },
    { sequelize }
);

const user1 = {
    userName: 'John Smith',
};

User.sync({ force: true }).then(() =>
    User.bulkCreate([user1], {updateOnDuplicate: ['email']})
    // throws: Unhandled rejection SequelizeDatabaseError: column "userName" does not exist
);

What do you expect to happen?

The code above should run without errors.

bulkCreate with updateOnDuplicate should work even when primary key fields are named differently in the DB.

What is actually happening?

Sequelize throws: Unhandled rejection SequelizeDatabaseError: column "userName" does not exist

Additional context

The code above works if the field name is changed to user_name.

The bug is in this line:

options.upsertKeys = _.chain(model.primaryKeys).values().map('fieldName').value();

fieldName should be field.

A PR to fix this: #11434

Environment

  • Sequelize version: 5.8.14
  • Node.js version: 8.15.0
  • Operating System: macOS Mojave 10.14.6

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s): Postgres
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. papb commented on Sep 15, 2019

    @papb
    Member

    Hello! Thank you very much!!

  2. added
    dialect: postgres
    dialect: sqlite
    Great SSCCE
    status: understood
    type: bug
    on Sep 15, 2019
  3. papb commented on Sep 15, 2019

    @papb
    Member

    I noticed this problem also exists for SQLite.

  4. PeledYuval commented on Sep 15, 2019

    @PeledYuval
    ContributorAuthor

    Thanks, I didn't notice that!

    You're right, AbstractQueryGenerator contains the following code that looks at options.upsertKeys which this PR fixes:

    if (this._dialect.supports.inserts.updateOnDuplicate == ' ON CONFLICT DO UPDATE SET') { // postgres / sqlite
            // If no conflict target columns were specified, use the primary key names from options.upsertKeys
            const conflictKeys = options.upsertKeys.map(attr => this.quoteIdentifier(attr));
            ....
          }
  5. sushantdhiman commented on Sep 19, 2019

    @sushantdhiman
    Contributor
  6. jpvanoosten commented on Sep 19, 2019

    @jpvanoosten

    The bulkCreate also fails if the model contains a composite key and doesn't explicitly define a primary key.

    The upsertKeys array is emptied when the model contains a composite key since the length of the fields array of the compositeKey object will be of size > 1 (which causes this filter to skip it):

    options.upsertKeys = _.chain(model.uniqueKeys).values().filter(c => c.fields.length === 1).map('column').value();

    My model looks like this:

    "use strict";
    module.exports = (sequelize, DataTypes) => {
      const User = sequelize.define(
        "User",
        {
          username: { type: DataTypes.STRING, unique: "compositeKey" },
          discordId: { type: DataTypes.STRING, unique: "compositeKey" }
        },
        {}
      );
      User.associate = function(models) {
        // associations can be defined here
      };
      return User;
    };

    In this case, the model.uniqueKeys object only contains a single compositeKey object.
    Shouldn't the model.uniqueKeys object also contain the automatically generated id primary key for this model?

    Changing the model to this works:

    "use strict";
    module.exports = (sequelize, DataTypes) => {
      const User = sequelize.define(
        "User",
        {
          username: { type: DataTypes.STRING, unique: true },
          discordId: { type: DataTypes.STRING, unique: true }
        },
        {}
      );
      User.associate = function(models) {
        // associations can be defined here
      };
      return User;
    };
  7. papb commented on Sep 25, 2019

    @papb
    Member

    @jpvanoosten Thanks for the detailed report, can you please open a new issue, and link to this one? Thanks

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

    Great SSCCEdialect: postgresdialect: sqlitestatus: understoodtype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions