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6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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);
+  });
+});