servicesToptal's picture
EC-SWE dataset
ec02279
Raw History Blame Contribute Delete
18.2 kB
diff --git a/packages/core/src/model.js b/packages/core/src/model.js
index cb25a684a..da84d6840 100644
--- a/packages/core/src/model.js
+++ b/packages/core/src/model.js
@@ -2327,6 +2327,10 @@ ${associationOwner._getAssociationDebugList()}`);
const modelDefinition = model.modelDefinition;
+ // Instances whose row the database skipped (ignoreDuplicates). They are
+ // left as the caller built them: unsaved, and carrying no other row's values.
+ const skipped = new Set();
+
options.fields = options.fields || Array.from(modelDefinition.attributes.keys());
const createdAtAttr = modelDefinition.timestampAttributeNames.createdAt;
const updatedAtAttr = modelDefinition.timestampAttributeNames.updatedAt;
@@ -2497,6 +2501,21 @@ ${associationOwner._getAssociationDebugList()}`);
);
}
+ // With ignoreDuplicates, a RETURNING dialect only hands back the rows
+ // it actually inserted, so the returned rows cannot be matched to the
+ // records by position. They are matched on the model's candidate keys
+ // instead; make sure those columns come back even when the caller
+ // restricted the returning list.
+ const identityKeys =
+ options.ignoreDuplicates &&
+ options.returning &&
+ model.sequelize.dialect.supports.returnValues
+ ? model._bulkCreateIdentityKeys()
+ : null;
+ if (identityKeys && Array.isArray(options.returning)) {
+ options.returning = uniq([...options.returning, ...identityKeys.flat()]);
+ }
+
const results = await model.queryInterface.bulkInsert(
model.table,
records,
@@ -2504,9 +2523,17 @@ ${associationOwner._getAssociationDebugList()}`);
fieldMappedAttributes,
);
if (Array.isArray(results)) {
- for (const [i, result] of results.entries()) {
+ const resultForInstance = identityKeys
+ ? model._matchReturnedRows(instances, records, results, identityKeys, skipped)
+ : results;
+
+ for (const [i, result] of resultForInstance.entries()) {
const instance = instances[i];
+ if (!result) {
+ continue;
+ }
+
for (const key in result) {
if (!Object.hasOwn(result, key)) {
continue;
@@ -2555,6 +2582,12 @@ ${associationOwner._getAssociationDebugList()}`);
const associationInstanceIndexToInstanceMap = [];
for (const instance of instances) {
+ if (skipped.has(instance)) {
+ // the parent row was not created by this call, so its key
+ // is unknown; its children must not be stored under it
+ continue;
+ }
+
let associated = instance.get(include.as);
if (!Array.isArray(associated)) {
associated = [associated];
@@ -2660,6 +2693,20 @@ ${associationOwner._getAssociationDebugList()}`);
// map fields back to attributes
for (const instance of instances) {
+ if (skipped.has(instance)) {
+ // the timestamps this call filled in were never stored for a
+ // skipped record; drop them so the instance shows only its own state
+ if (createdAtAttr && instance.dataValues[createdAtAttr] === now) {
+ delete instance.dataValues[createdAtAttr];
+ }
+
+ if (updatedAtAttr && instance.dataValues[updatedAtAttr] === now) {
+ delete instance.dataValues[updatedAtAttr];
+ }
+
+ continue;
+ }
+
const attributeDefs = modelDefinition.attributes;
for (const attribute of attributeDefs.values()) {
@@ -2692,6 +2739,165 @@ ${associationOwner._getAssociationDebugList()}`);
return await recursiveBulkCreate(instances, options);
}
+ /**
+ * The column sets a returned row can be identified by: the primary key and
+ * every non-partial unique index. Used by {@link Model.bulkCreate} to match
+ * the rows a RETURNING dialect hands back to the records that were sent
+ * when `ignoreDuplicates` may have skipped some of them.
+ *
+ * @returns {string[][]} column names, one array per candidate key
+ * @private
+ */
+ static _bulkCreateIdentityKeys() {
+ const keys = [];
+ const seen = new Set();
+ const add = columns => {
+ const normalized = columns.map(column => (typeof column === 'string' ? column : column.name));
+ const id = normalized.join('\0');
+ if (normalized.length > 0 && !seen.has(id)) {
+ seen.add(id);
+ keys.push(normalized);
+ }
+ };
+
+ add(Object.values(this.primaryKeys).map(attribute => attribute.field));
+ for (const index of this.getIndexes()) {
+ if (index.unique && !index.where && index.fields) {
+ add(index.fields);
+ }
+ }
+
+ return keys;
+ }
+
+ /**
+ * Pairs the rows returned by a bulk INSERT with the records that produced
+ * them. A row belongs to the first not-yet-paired record that agrees with
+ * it on one of the candidate keys; the row order is never relied on.
+ * Records that no row matches were skipped by the database and are added
+ * to `skipped`. Refuses to guess: if a returned row cannot be attributed
+ * to any record, an error is thrown rather than assigning it by position.
+ *
+ * @param {Model[]} instances the instances, in record order
+ * @param {object[]} records the column-keyed values sent for each instance
+ * @param {object[]} results the rows the database returned
+ * @param {string[][]} identityKeys from {@link Model._bulkCreateIdentityKeys}
+ * @param {Set<Model>} skipped receives the instances whose row was not inserted
+ * @returns {Array<object|null>} the matching row for each instance, or null
+ * @private
+ */
+ static _matchReturnedRows(instances, records, results, identityKeys, skipped) {
+ const modelDefinition = this.modelDefinition;
+
+ const normalize = value => {
+ if (value instanceof Date) {
+ return value.toISOString();
+ }
+
+ if (Buffer.isBuffer(value)) {
+ return value.toString('hex');
+ }
+
+ return String(value);
+ };
+
+ const parseRow = row => {
+ const out = pojo();
+ for (const column of Object.keys(row)) {
+ const attribute = modelDefinition.columns.get(column);
+ out[column] =
+ row[column] != null && attribute?.type instanceof AbstractDataType
+ ? attribute.type.parseDatabaseValue(row[column])
+ : row[column];
+ }
+
+ return out;
+ };
+
+ // every key signature a column-keyed value set can be identified by
+ const signaturesOf = values => {
+ const signatures = [];
+ for (const [k, key] of identityKeys.entries()) {
+ const parts = [];
+ for (const column of key) {
+ if (values[column] == null) {
+ parts.length = 0;
+ break;
+ }
+
+ parts.push(normalize(values[column]));
+ }
+
+ if (parts.length > 0) {
+ signatures.push(`${k}:${parts.join('\0')}`);
+ }
+ }
+
+ return signatures;
+ };
+
+ const rowsBySignature = new Map();
+ const unpaired = new Set(results);
+ for (const row of results) {
+ for (const signature of signaturesOf(parseRow(row))) {
+ if (!rowsBySignature.has(signature)) {
+ rowsBySignature.set(signature, []);
+ }
+
+ rowsBySignature.get(signature).push(row);
+ }
+ }
+
+ const paired = instances.map(() => null);
+ const withoutKey = [];
+ for (const [i, instance] of instances.entries()) {
+ const signatures = signaturesOf(records[i]);
+ if (signatures.length === 0) {
+ withoutKey.push(i);
+ continue;
+ }
+
+ for (const signature of signatures) {
+ const row = (rowsBySignature.get(signature) ?? []).find(candidate =>
+ unpaired.has(candidate),
+ );
+ if (row) {
+ paired[i] = row;
+ unpaired.delete(row);
+ break;
+ }
+ }
+
+ if (!paired[i]) {
+ skipped.add(instance);
+ }
+ }
+
+ // Records that carry no value for any candidate key cannot have
+ // conflicted, so the leftover rows are theirs, provided the counts agree.
+ if (withoutKey.length > 0) {
+ if (unpaired.size !== withoutKey.length) {
+ throw new Error(
+ `bulkCreate could not attribute the rows returned by the database to the records: ${unpaired.size} returned row(s) left for ${withoutKey.length} record(s) without a key value.`,
+ );
+ }
+
+ const leftovers = results.filter(row => unpaired.has(row));
+ for (const [j, i] of withoutKey.entries()) {
+ paired[i] = leftovers[j];
+ unpaired.delete(leftovers[j]);
+ }
+ }
+
+ if (unpaired.size > 0) {
+ throw new Error(
+ `bulkCreate could not attribute ${unpaired.size} row(s) returned by the database to any record. Every candidate key column must be part of the returned columns.`,
+ );
+ }
+
+ return paired;
+ }
+
/**
* Truncates the table associated with the model.
*
diff --git a/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts b/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts
new file mode 100644
index 000000000..69e8c1ab8
--- /dev/null
+++ b/packages/core/test/integration/model/bulk-create/ignore-duplicates.test.ts
@@ -0,0 +1,237 @@
+import type {
+ CreationOptional,
+ InferAttributes,
+ InferCreationAttributes,
+ NonAttribute,
+} from '@sequelize/core';
+import { DataTypes, Model } from '@sequelize/core';
+import { expect } from 'chai';
+import { beforeAll2, sequelize, setResetMode } from '../../support';
+
+const dialect = sequelize.dialect;
+
+// With ignoreDuplicates, a RETURNING dialect only returns the rows it actually
+// inserted. The instances bulkCreate returns must still line up with the
+// records that were passed in.
+describe('Model.bulkCreate with ignoreDuplicates on a RETURNING dialect', () => {
+ if (
+ !dialect.supports.returnValues ||
+ !(dialect.supports.inserts.ignoreDuplicates || dialect.supports.inserts.onConflictDoNothing)
+ ) {
+ return;
+ }
+
+ setResetMode('destroy');
+
+ const vars = beforeAll2(async () => {
+ class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
+ declare id: CreationOptional<number>;
+ declare uniqueName: string;
+ declare secretValue: string | null;
+ declare createdAt: CreationOptional<Date>;
+ declare updatedAt: CreationOptional<Date>;
+ declare tasks?: NonAttribute<Task[]>;
+ }
+
+ class Task extends Model<InferAttributes<Task>, InferCreationAttributes<Task>> {
+ declare id: CreationOptional<number>;
+ declare title: string;
+ declare userId: CreationOptional<number | null>;
+ }
+
+ class Seat extends Model<InferAttributes<Seat>, InferCreationAttributes<Seat>> {
+ declare id: CreationOptional<number>;
+ declare room: string;
+ declare number: number;
+ declare label: string | null;
+ }
+
+ class Code extends Model<InferAttributes<Code>, InferCreationAttributes<Code>> {
+ declare code: string;
+ declare label: string | null;
+ }
+
+ User.init(
+ {
+ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
+ uniqueName: { type: DataTypes.STRING, unique: true, allowNull: false },
+ secretValue: DataTypes.STRING,
+ },
+ { sequelize },
+ );
+ Task.init(
+ {
+ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
+ title: { type: DataTypes.STRING, allowNull: false },
+ },
+ { sequelize },
+ );
+ Seat.init(
+ {
+ id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
+ room: { type: DataTypes.STRING, allowNull: false },
+ number: { type: DataTypes.INTEGER, allowNull: false },
+ label: DataTypes.STRING,
+ },
+ { sequelize, indexes: [{ unique: true, fields: ['room', 'number'] }] },
+ );
+ Code.init(
+ {
+ code: { type: DataTypes.STRING, primaryKey: true },
+ label: DataTypes.STRING,
+ },
+ { sequelize },
+ );
+
+ User.hasMany(Task, { as: 'tasks', foreignKey: 'userId' });
+
+ await sequelize.sync({ force: true });
+
+ return { User, Task, Seat, Code };
+ });
+
+ it('assigns each returned row to its own record when some records are skipped', async () => {
+ const { User } = vars;
+ await User.bulkCreate([
+ { uniqueName: 'Peter', secretValue: '42' },
+ { uniqueName: 'Paul', secretValue: '23' },
+ ]);
+
+ const statements: string[] = [];
+ const result = await User.bulkCreate(
+ [
+ { uniqueName: 'Peter', secretValue: 'dup' },
+ { uniqueName: 'Michael', secretValue: '26' },
+ { uniqueName: 'Paul', secretValue: 'dup' },
+ { uniqueName: 'Anna', secretValue: '27' },
+ ],
+ { ignoreDuplicates: true, logging: sql => statements.push(sql) },
+ );
+
+ expect(statements).to.have.length(1);
+ expect(result.map(user => user.uniqueName)).to.deep.equal(['Peter', 'Michael', 'Paul', 'Anna']);
+
+ const rows = await User.findAll({ order: ['id'], raw: true });
+ expect(rows.map(row => row.uniqueName)).to.deep.equal(['Peter', 'Paul', 'Michael', 'Anna']);
+
+ const byName = new Map(rows.map(row => [row.uniqueName, row]));
+ for (const inserted of [result[1], result[3]]) {
+ expect(inserted.isNewRecord).to.equal(false);
+ expect(inserted.id).to.equal(byName.get(inserted.uniqueName)!.id);
+ expect(inserted.secretValue).to.equal(byName.get(inserted.uniqueName)!.secretValue);
+ expect(inserted.changed()).to.equal(false);
+ }
+
+ for (const skipped of [result[0], result[2]]) {
+ expect(skipped.isNewRecord).to.equal(true);
+ expect(skipped.id).to.equal(null);
+ expect(skipped.secretValue).to.equal('dup');
+ // nothing was stored for it, so it carries no generated timestamps either
+ expect(skipped.createdAt).to.equal(undefined);
+ expect(skipped.updatedAt).to.equal(undefined);
+ }
+ });
+
+ it('does not report any record as persisted when every row is skipped', async () => {
+ const { User } = vars;
+ await User.bulkCreate([{ uniqueName: 'Peter' }, { uniqueName: 'Paul' }]);
+
+ const result = await User.bulkCreate([{ uniqueName: 'Peter' }, { uniqueName: 'Paul' }], {
+ ignoreDuplicates: true,
+ });
+
+ expect(result.map(user => user.uniqueName)).to.deep.equal(['Peter', 'Paul']);
+ for (const user of result) {
+ expect(user.isNewRecord).to.equal(true);
+ expect(user.id).to.equal(null);
+ }
+
+ expect(await User.count()).to.equal(2);
+ });
+
+ it('does not store the children of a skipped record under another record', async () => {
+ const { User, Task } = vars;
+ await User.bulkCreate([{ uniqueName: 'Peter' }]);
+
+ const records = [
+ { uniqueName: 'Peter', secretValue: null, tasks: [{ title: 'peter-task' }] },
+ { uniqueName: 'Michael', secretValue: null, tasks: [{ title: 'michael-task' }] },
+ ];
+ const result = await User.bulkCreate(records, {
+ ignoreDuplicates: true,
+ include: [{ model: Task, as: 'tasks' }],
+ });
+
+ const michael = await User.findOne({ where: { uniqueName: 'Michael' }, rejectOnEmpty: true });
+ expect(result[1].id).to.equal(michael.id);
+
+ const tasks = await Task.findAll({ order: ['id'], raw: true });
+ expect(tasks).to.have.length(1);
+ expect(tasks[0].title).to.equal('michael-task');
+ expect(tasks[0].userId).to.equal(michael.id);
+
+ expect(result[0].isNewRecord).to.equal(true);
+ expect(result[0].tasks![0].isNewRecord).to.equal(true);
+ });
+
+ it('matches on a composite unique key', async () => {
+ const { Seat } = vars;
+ await Seat.bulkCreate([{ room: 'A', number: 1, label: 'taken' }]);
+
+ const result = await Seat.bulkCreate(
+ [
+ { room: 'A', number: 1, label: 'dup' },
+ { room: 'A', number: 2, label: 'new' },
+ { room: 'B', number: 1, label: 'new' },
+ ],
+ { ignoreDuplicates: true },
+ );
+
+ const rows = await Seat.findAll({ order: ['id'], raw: true });
+ expect(rows).to.have.length(3);
+ expect(result[0].isNewRecord).to.equal(true);
+ expect(result[0].label).to.equal('dup');
+ expect(result[1].id).to.equal(rows[1].id);
+ expect(result[1].room + result[1].number).to.equal('A2');
+ expect(result[2].id).to.equal(rows[2].id);
+ expect(result[2].room + result[2].number).to.equal('B1');
+ });
+
+ it('matches on a caller-supplied primary key', async () => {
+ const { Code } = vars;
+ await Code.bulkCreate([{ code: 'x', label: 'taken' }]);
+
+ const result = await Code.bulkCreate(
+ [
+ { code: 'x', label: 'dup' },
+ { code: 'y', label: 'new' },
+ ],
+ { ignoreDuplicates: true },
+ );
+
+ expect(result[0].isNewRecord).to.equal(true);
+ expect(result[0].label).to.equal('dup');
+ expect(result[1].isNewRecord).to.equal(false);
+ expect(result[1].label).to.equal('new');
+ expect((await Code.findByPk('x', { rejectOnEmpty: true })).label).to.equal('taken');
+ });
+
+ it('keeps the rows aligned when the returning list omits the key columns', async () => {
+ const { User } = vars;
+ await User.bulkCreate([{ uniqueName: 'Peter', secretValue: '42' }]);
+
+ const result = await User.bulkCreate(
+ [
+ { uniqueName: 'Peter', secretValue: 'dup' },
+ { uniqueName: 'Michael', secretValue: '26' },
+ ],
+ { ignoreDuplicates: true, returning: ['id'] },
+ );
+
+ const michael = await User.findOne({ where: { uniqueName: 'Michael' }, rejectOnEmpty: true });
+ expect(result[0].isNewRecord).to.equal(true);
+ expect(result[0].id).to.equal(null);
+ expect(result[1].id).to.equal(michael.id);
+ expect(result[1].isNewRecord).to.equal(false);
+ });
+});