Repository navigation
Closed
Labels
dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).status: understoodFor issues. Applied when the issue is understood / reproducible.type: bugDEPRECATED: replace with the "bug" issue type
Description
Issue Description
What are you doing?
I am trying to use bulkCreate to updateOnDuplicate when a duplicate is detected. Duplicate should be detected by a "multi column unique index".
"use strict";
const Sequelize = require("./index");
const sequelize = require("./test/support").createSequelizeInstance();
const chai = require("chai"),
expect = chai.expect;
class Bar extends Sequelize.Model {}
Bar.init(
{
value: Sequelize.DataTypes.STRING,
timestamp: {
type: Sequelize.DataTypes.DATE,
allowNull: false
}
},
{
indexes: [
{
name: "unique_timestamp_per_foo",
unique: true,
fields: ["timestamp", "FooId"]
}
],
sequelize
}
);
class Foo extends Sequelize.Model {}
Foo.init({}, { sequelize });
Bar.belongsTo(Foo, {
foreignKey: { allowNull: false },
onDelete: "CASCADE"
});
Foo.hasMany(Bar, { foreignKey: { allowNull: false }, onDelete: "CASCADE" });
(async () => {
await sequelize.sync({ force: true });
// Create a _parent_ `Foo` model
const foo = await Foo.create();
// Create a `Bar` object
const originalBar = await Bar.create({
value: "original",
timestamp: new Date(Date.UTC(2016, 0, 1)),
FooId: foo.id
});
// We obviously expect a `Bar` object to exist with the unique constraints of `timestamp` and `FooId`
expect(
await Bar.count({
where: { FooId: foo.id, timestamp: new Date(Date.UTC(2016, 0, 1)) }
})
).to.equal(1);
// We create a modified `Bar` object that has an overlapping `timestamp` and `FooId`
// This should be detected as duplicate by the `uniqueTimestampPerFoo` unique constraint/index,
// during the next `bulkCreate` operation with `updateOnDuplicate` set.
const modifiedBar = Bar.build({
value: "modified",
timestamp: new Date(Date.UTC(2016, 0, 1)),
FooId: foo.id
});
// "Bulk" create to "upsert" a modified `existingBar` when conflict detected.
// We only want `value` and `updatedAt` to be updated on conflict.
await expect(
Bar.bulkCreate([modifiedBar.toJSON()], {
updateOnDuplicate: ["value", "updatedAt"],
logging: console.log
})
).not.to.be.rejectedWith(Sequelize.SequelizeUniqueConstraintError);
// *** The above function should not have been rejected with a `SequelizeUniqueConstraintError` ***
// *** The below is what should have been expected ***
// Reload the modified original `Bar` object by `id`
const refreshedOriginalBar = await Bar.findByPk(originalBar.id);
// The value should have been updated
expect(refreshedOriginalBar.value).to.equal("modified");
// The refreshed updatedAt should be greater than the original updatedAt
expect(refreshedOriginalBar.updatedAt > originalBar.updatedAt).be.true;
})();What do you expect to happen?
See the expected assertions from my SSCCE:
// *** The below is what should have been expected ***
// Reload the modified original `Bar` object by `id`
const refreshedOriginalBar = await Bar.findByPk(originalBar.id);
// The value should have been updated
expect(refreshedOriginalBar.value).to.equal("modified");
// The refreshed updatedAt should be greater than the original updatedAt
expect(refreshedOriginalBar.updatedAt > originalBar.updatedAt).be.true;I wanted a duplicate to be detected by the unique_timestamp_per_foo unique key when calling the bulkCreate method with updateOnDuplicate array set.
Furthermore, I wanted the insert SQL to be ON CONFLICT ("timestamp", "FooId") instead of ON CONFLICT ("id")
What is actually happening?
A SequelizeUniqueConstraintError is thrown because the expected multi-field index does not get added to upsertKeys here (
Line 2705 in 3517eb7
| options.upsertKeys = _.chain(model.uniqueKeys).values().filter(c => c.fields.length === 1).map('column').value(); |
Environment
- Sequelize version: [email protected]
- Node.js v10.16.3
- Operating System: Windows 10
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
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.
Reacted by Evan, Wilk, Alejandro Corredor, Charles and Gray
Metadata
Metadata
Assignees
Labels
dialect: postgresFor issues and PRs. Things that involve PostgreSQL (and do not involve all dialects).status: understoodFor issues. Applied when the issue is understood / reproducible.type: bugDEPRECATED: replace with the "bug" issue type
Activity
cjancsar commentedon Oct 18, 2019
It is not clear why line
sequelize/lib/model.js
Line 2705 in 3517eb7
length === 1.I have locally added a patch to allow an explicit option to be set called
upsertOnwhen callingModel.bulkCreate.upsertOncan either be:fieldNamesthat are either primary keys or composite members of a unique key.unique: 'some_string'Can be called like:
Let me know if you agree, and want me to make a PR with this enhancement.
This has solved the gap of not allowing composite unique keys with
onDuplicateUpdate.Replacing these existing lines:
sequelize/lib/model.js
Lines 2701 to 2708 in 2b9baa2
With:
cjancsar commentedon Oct 18, 2019
Code in fork here: cjancsar@45f6792
cjancsar commentedon Oct 22, 2019
@papb is this a useful feature? Should I make a PR?
fnimick commentedon Oct 23, 2019
Note: this doesn't work for composite keys with a partial index, where you need to specify ON CONFLICT ("a","b") WHERE "deleted_at" IS NULL, for example.
fnimick commentedon Oct 23, 2019
@papb I have a fix working for my use case where I allow the user to specify
upsertKeysexplicitly, which can either be an array of columns or an object{ fields: <columns>, where: ... }with the where expression mapping to a partial index. Should I make a PR?Rochet2 commentedon Oct 24, 2019
I have same issue. Seems this issue is duplicate of #11534
fnimick commentedon Oct 25, 2019
@Rochet2 I've created a patch for my fix: https://gist.github.com/fnimick/5dd3c6855cea6e000c86d1bc38876958
PR coming shortly.
feat(postgres): Add `upsertIndex` and `upsertKeys` options to `BulkCr…
feat(postgres): Add `upsertIndex` and `upsertKeys` options to `BulkCr…
papb commentedon Nov 4, 2019
Hi everyone, sorry for taking long, I will take a look at the PR by @fnimick now. Is it the same as the work by @cjancsar?
cjancsar commentedon Nov 4, 2019
@papb no it is not, but I have not had time to create a PR with my work. @fnimick work is a subfeature of the feature that my patch would add (his add ability for partial index as well). I prefer my approach as it only introduces one option
upsertOninstead of twoupsertKeysandupsertIndex. There is currently no tests on the PR so I don't really see it moving. I am using my patch at the moment, and will try to get a PR at some point next week.papb commentedon Nov 4, 2019
@cjancsar Thanks for the reply, I've been very busy so no time to look at your implementation and @fnimick implementation yet... Thanks for the patience :)
fnimick commentedon Nov 4, 2019
@cjancsar @papb I can also remove
upsertKeysfrom the PR entirely - the only use case for it was to specify an index that is defined on the table but not in the model itself, for flexibility. I am actually only usingupsertIndexin my code.feat(postgres): Add `upsertIndex` and `upsertKeys` options to `BulkCr…
papb commentedon Jan 15, 2020
@fnimick If
upsertKeysis well documented, you can keep it, flexibility is good :)vbhakta8 commentedon Mar 12, 2020
Do we have an ETA on when this PR might get looked at? Or how we can get it merged in? Is there any work required on contributors end to get this pushed through?
sushantdhiman commentedon Mar 16, 2020
Fixed by #11984
feat(postgres): add composite key options to `BulkCreateOptions`
feat(postgres): add composite key options to `BulkCreateOptions`
feat(postgres): add composite key options to `BulkCreateOptions`
feat(postgres): add composite key options to `BulkCreateOptions`
feat(postgres): add composite key options to `BulkCreateOptions`
feat(postgres): add composite key options to `BulkCreateOptions`