@strapi/core 5.36.0 → 5.36.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/migrations/database/5.0.0-discard-drafts.d.ts +21 -7
  2. package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
  3. package/dist/migrations/database/5.0.0-discard-drafts.js +1936 -59
  4. package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
  5. package/dist/migrations/database/5.0.0-discard-drafts.mjs +1937 -60
  6. package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
  7. package/dist/package.json.js +17 -13
  8. package/dist/package.json.js.map +1 -1
  9. package/dist/package.json.mjs +17 -13
  10. package/dist/package.json.mjs.map +1 -1
  11. package/dist/services/cron.d.ts.map +1 -1
  12. package/dist/services/cron.js +3 -0
  13. package/dist/services/cron.js.map +1 -1
  14. package/dist/services/cron.mjs +3 -0
  15. package/dist/services/cron.mjs.map +1 -1
  16. package/dist/services/entity-validator/validators.d.ts.map +1 -1
  17. package/dist/services/entity-validator/validators.js +22 -5
  18. package/dist/services/entity-validator/validators.js.map +1 -1
  19. package/dist/services/entity-validator/validators.mjs +22 -5
  20. package/dist/services/entity-validator/validators.mjs.map +1 -1
  21. package/dist/services/webhook-runner.js +2 -2
  22. package/dist/services/webhook-runner.js.map +1 -1
  23. package/dist/services/webhook-runner.mjs +2 -2
  24. package/dist/services/webhook-runner.mjs.map +1 -1
  25. package/dist/services/worker-queue.js +2 -2
  26. package/dist/services/worker-queue.js.map +1 -1
  27. package/dist/services/worker-queue.mjs +2 -2
  28. package/dist/services/worker-queue.mjs.map +1 -1
  29. package/package.json +17 -13
@@ -1,6 +1,44 @@
1
- import { async, contentTypes } from '@strapi/utils';
2
- import { createDocumentService } from '../../services/document-service/index.mjs';
1
+ import { createId } from '@paralleldrive/cuid2';
2
+ import { contentTypes } from '@strapi/utils';
3
+ import createDebug from 'debug';
4
+ import { getComponentJoinTableName, getComponentJoinColumnEntityName, getComponentJoinColumnInverseName, getComponentTypeColumn } from '../../utils/transform-content-types-to-models.mjs';
3
5
 
6
+ const DEFAULT_PRIMARY_KEY_COLUMN = 'id';
7
+ /**
8
+ * Determines the primary-key column name for a schema, handling the various shapes
9
+ * metadata can take (string, object, attribute flag) and defaulting to `id`.
10
+ */ const resolvePrimaryKeyColumn = (meta)=>{
11
+ const { primaryKey } = meta;
12
+ if (typeof primaryKey === 'string' && primaryKey) {
13
+ return primaryKey;
14
+ }
15
+ if (primaryKey && typeof primaryKey === 'object') {
16
+ const pkObject = primaryKey;
17
+ const columnName = pkObject.columnName;
18
+ if (typeof columnName === 'string' && columnName) {
19
+ return columnName;
20
+ }
21
+ const name = pkObject.name;
22
+ if (typeof name === 'string' && name) {
23
+ return name;
24
+ }
25
+ }
26
+ const attributes = meta.attributes ?? {};
27
+ for (const [attributeName, attribute] of Object.entries(attributes)){
28
+ const normalizedAttribute = attribute;
29
+ if (!normalizedAttribute) {
30
+ continue;
31
+ }
32
+ const { column } = normalizedAttribute;
33
+ if (column?.primary === true) {
34
+ if (typeof normalizedAttribute.columnName === 'string' && normalizedAttribute.columnName) {
35
+ return normalizedAttribute.columnName;
36
+ }
37
+ return attributeName;
38
+ }
39
+ }
40
+ return DEFAULT_PRIMARY_KEY_COLUMN;
41
+ };
4
42
  /**
5
43
  * Check if the model has draft and publish enabled.
6
44
  */ const hasDraftAndPublish = async (trx, meta)=>{
@@ -47,7 +85,9 @@ import { createDocumentService } from '../../services/document-service/index.mjs
47
85
  ])).insert((subQb)=>{
48
86
  // SELECT columnName1, columnName2, columnName3, ...
49
87
  subQb.select(...scalarAttributes.map((att)=>{
50
- // Override 'publishedAt' and 'updatedAt' attributes
88
+ // NOTE: these literals reference Strapi's built-in system columns. They never get shortened by
89
+ // the identifier migration (5.0.0-01-convert-identifiers-long-than-max-length) so we can safely
90
+ // compare/use them directly here.
51
91
  if (att === 'published_at') {
52
92
  return trx.raw('NULL as ??', 'published_at');
53
93
  }
@@ -57,100 +97,1937 @@ import { createDocumentService } from '../../services/document-service/index.mjs
57
97
  });
58
98
  }
59
99
  /**
60
- * Load a batch of versions to discard.
61
- *
62
- * Versions with only a draft version will be ignored.
63
- * Only versions with a published version (which always have a draft version) will be discarded.
64
- */ async function* getBatchToDiscard({ db, trx, uid, defaultBatchSize = 1000 }) {
65
- const client = db.config.connection.client;
100
+ * Orchestrates the relation cloning pipeline for a single content type. We duplicate
101
+ * every category of relation (self, inbound, outbound, components) using direct SQL so
102
+ * the migration can scale without calling `discardDraft` entry by entry.
103
+ */ async function copyRelationsToDrafts({ db, trx, uid }) {
104
+ const meta = db.metadata.get(uid);
105
+ if (!meta) {
106
+ return;
107
+ }
108
+ // Create mapping from published entry ID to draft entry ID
109
+ const publishedToDraftMap = await buildPublishedToDraftMap({
110
+ trx,
111
+ uid,
112
+ meta
113
+ });
114
+ if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
115
+ return;
116
+ }
117
+ // Copy relations for this content type
118
+ await copyRelationsForContentType({
119
+ trx,
120
+ uid,
121
+ publishedToDraftMap
122
+ });
123
+ // Copy relations from other content types that target this content type
124
+ await copyRelationsFromOtherContentTypes({
125
+ trx,
126
+ uid,
127
+ publishedToDraftMap
128
+ });
129
+ // Copy relations from this content type that target other content types (category 3)
130
+ await copyRelationsToOtherContentTypes({
131
+ trx,
132
+ uid,
133
+ publishedToDraftMap
134
+ });
135
+ // Copy component relations from published entries to draft entries
136
+ await copyComponentRelations({
137
+ trx,
138
+ uid,
139
+ publishedToDraftMap
140
+ });
141
+ }
142
+ /**
143
+ * Splits large input arrays into smaller batches so we can run SQL queries without
144
+ * hitting parameter limits (SQLite) or payload limits (MySQL/Postgres).
145
+ */ function chunkArray(array, chunkSize) {
146
+ const chunks = [];
147
+ for(let i = 0; i < array.length; i += chunkSize){
148
+ chunks.push(array.slice(i, i + chunkSize));
149
+ }
150
+ return chunks;
151
+ }
152
+ /**
153
+ * Bulk-load existing relation rows for (sourceId, newTargetId) pairs so we can avoid
154
+ * per-row SELECTs when deciding update vs delete.
155
+ */ async function buildExistingRelationMap({ trx, tableName, sourceColumnName, targetColumnName, updates, batchSize }) {
156
+ const existingMap = new Map();
157
+ if (updates.length === 0) {
158
+ return existingMap;
159
+ }
160
+ const queryChunks = chunkArray(updates, batchSize);
161
+ for (const chunk of queryChunks){
162
+ const rows = await trx(tableName).select([
163
+ 'id',
164
+ sourceColumnName,
165
+ targetColumnName
166
+ ]).where((qb)=>{
167
+ for (const update of chunk){
168
+ qb.orWhere((subQb)=>{
169
+ subQb.where(sourceColumnName, update.sourceId).where(targetColumnName, update.newTargetId);
170
+ });
171
+ }
172
+ });
173
+ for (const row of rows){
174
+ const key = `${row[sourceColumnName]}_${row[targetColumnName]}`;
175
+ existingMap.set(key, row.id);
176
+ }
177
+ }
178
+ return existingMap;
179
+ }
180
+ /**
181
+ * Chooses a safe batch size for bulk operations depending on the database engine,
182
+ * falling back to smaller units on engines (notably SQLite) that have low limits.
183
+ */ function getBatchSize(trx, defaultSize = 1000) {
184
+ const client = trx.client.config.client;
66
185
  const isSQLite = typeof client === 'string' && [
67
186
  'sqlite',
68
187
  'sqlite3',
69
188
  'better-sqlite3'
70
189
  ].includes(client);
71
- // The SQLite documentation states that the maximum number of terms in a
190
+ // SQLite documentation states that the maximum number of terms in a
72
191
  // compound SELECT statement is 500 by default.
73
192
  // See: https://www.sqlite.org/limits.html
74
- // To ensure a successful migration, we limit the batch size to 500 for SQLite.
75
- const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;
76
- let offset = 0;
77
- let hasMore = true;
78
- while(hasMore){
79
- // Look for the published entries to discard
80
- const batch = await db.queryBuilder(uid).select([
193
+ // We use 250 to be safe and account for other query complexity.
194
+ return isSQLite ? Math.min(defaultSize, 250) : defaultSize;
195
+ }
196
+ /**
197
+ * Applies stable ordering to join-table queries so cloning work is deterministic and
198
+ * matches the ordering logic used by the entity service (important for tests and DZ order).
199
+ */ const applyJoinTableOrdering = (qb, joinTable, sourceColumnName)=>{
200
+ const seenColumns = new Set();
201
+ const enqueueColumn = (column, direction = 'asc')=>{
202
+ if (!column || seenColumns.has(column)) {
203
+ return;
204
+ }
205
+ seenColumns.add(column);
206
+ qb.orderBy(column, direction);
207
+ };
208
+ enqueueColumn(sourceColumnName, 'asc');
209
+ if (Array.isArray(joinTable?.orderBy)) {
210
+ for (const clause of joinTable.orderBy){
211
+ if (!clause || typeof clause !== 'object') {
212
+ continue;
213
+ }
214
+ const [column, direction] = Object.entries(clause)[0] ?? [];
215
+ if (!column) {
216
+ continue;
217
+ }
218
+ const normalizedDirection = typeof direction === 'string' && direction.toLowerCase() === 'desc' ? 'desc' : 'asc';
219
+ enqueueColumn(column, normalizedDirection);
220
+ }
221
+ }
222
+ enqueueColumn(joinTable?.orderColumnName, 'asc');
223
+ enqueueColumn(joinTable?.orderColumn, 'asc');
224
+ enqueueColumn('id', 'asc');
225
+ };
226
+ /**
227
+ * Builds a stable key for join-table relations to detect duplicates.
228
+ * Key format: sourceId::targetId::field::componentType
229
+ */ const buildRelationKey = (relation, sourceColumnName, targetId)=>{
230
+ const sourceId = normalizeId(relation[sourceColumnName]) ?? relation[sourceColumnName];
231
+ const fieldValue = 'field' in relation ? relation.field ?? '' : '';
232
+ const componentTypeValue = 'component_type' in relation ? relation.component_type ?? '' : '';
233
+ return `${sourceId ?? 'null'}::${targetId ?? 'null'}::${fieldValue}::${componentTypeValue}`;
234
+ };
235
+ /**
236
+ * Queries existing relations from a join table and builds a set of keys for duplicate detection.
237
+ */ async function getExistingRelationKeys({ trx, joinTable, sourceColumnName, targetColumnName, sourceIds }) {
238
+ const existingKeys = new Set();
239
+ if (sourceIds.length === 0) {
240
+ return existingKeys;
241
+ }
242
+ const idChunks = chunkArray(sourceIds, getBatchSize(trx, 1000));
243
+ for (const chunk of idChunks){
244
+ const existingRelationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, chunk);
245
+ applyJoinTableOrdering(existingRelationsQuery, joinTable, sourceColumnName);
246
+ const existingRelations = await existingRelationsQuery;
247
+ for (const relation of existingRelations){
248
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
249
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
250
+ existingKeys.add(key);
251
+ }
252
+ }
253
+ return existingKeys;
254
+ }
255
+ /**
256
+ * Inserts relations into a join table with database-specific duplicate handling.
257
+ * Tries batch insert first, then falls back to individual inserts with conflict handling.
258
+ */ async function insertRelationsWithDuplicateHandling({ trx, tableName, relations, context = {} }) {
259
+ if (relations.length === 0) {
260
+ return;
261
+ }
262
+ try {
263
+ await trx.batchInsert(tableName, relations, getBatchSize(trx, 1000));
264
+ } catch (error) {
265
+ // If batch insert fails due to duplicates, try with conflict handling
266
+ if (!isDuplicateEntryError(error)) {
267
+ throw error;
268
+ }
269
+ const client = trx.client.config.client;
270
+ if (client === 'postgres' || client === 'pg') {
271
+ for (const relation of relations){
272
+ try {
273
+ await trx(tableName).insert(relation).onConflict().ignore();
274
+ } catch (err) {
275
+ if (err.code !== '23505' && !err.message?.includes('duplicate key')) {
276
+ throw err;
277
+ }
278
+ }
279
+ }
280
+ } else {
281
+ // MySQL and SQLite: use insertRowWithDuplicateHandling
282
+ for (const relation of relations){
283
+ await insertRowWithDuplicateHandling(trx, tableName, relation, context);
284
+ }
285
+ }
286
+ }
287
+ }
288
+ const componentParentSchemasCache = new Map();
289
+ const joinTableExistsCache = new Map();
290
+ const componentMetaCache = new Map();
291
+ const SKIPPED_RELATION_SAMPLE_LIMIT = 5;
292
+ const supportsReturning = (trx)=>{
293
+ const client = trx.client.config.client;
294
+ if (typeof client !== 'string') {
295
+ return false;
296
+ }
297
+ return [
298
+ 'postgres',
299
+ 'pg'
300
+ ].includes(client.toLowerCase());
301
+ };
302
+ const skippedRelationStats = new Map();
303
+ const DUPLICATE_ERROR_CODES = new Set([
304
+ '23505',
305
+ 'ER_DUP_ENTRY',
306
+ 'SQLITE_CONSTRAINT_UNIQUE'
307
+ ]);
308
+ const debug = createDebug('strapi::migration::discard-drafts');
309
+ /**
310
+ * Converts arbitrary id values into numbers when possible so we can safely index into
311
+ * mapping tables without worrying about string/number mismatches.
312
+ */ const normalizeId = (value)=>{
313
+ if (value == null) {
314
+ return null;
315
+ }
316
+ const num = Number(value);
317
+ if (Number.isNaN(num)) {
318
+ return null;
319
+ }
320
+ return num;
321
+ };
322
+ /**
323
+ * Wrapper around map lookups that first normalizes the provided identifier.
324
+ */ const getMappedValue = (map, key)=>{
325
+ if (!map) {
326
+ return undefined;
327
+ }
328
+ const normalized = normalizeId(key);
329
+ if (normalized == null) {
330
+ return undefined;
331
+ }
332
+ return map.get(normalized);
333
+ };
334
+ /**
335
+ * Extracts the inserted row identifier across the various shapes returned by different
336
+ * clients/drivers (numbers, objects, arrays). Falls back to `null` if nothing usable.
337
+ */ const resolveInsertedId = (insertResult)=>{
338
+ if (insertResult == null) {
339
+ return null;
340
+ }
341
+ if (typeof insertResult === 'number') {
342
+ return insertResult;
343
+ }
344
+ if (Array.isArray(insertResult)) {
345
+ if (insertResult.length === 0) {
346
+ return null;
347
+ }
348
+ const first = insertResult[0];
349
+ if (first == null) {
350
+ return null;
351
+ }
352
+ if (typeof first === 'number') {
353
+ return first;
354
+ }
355
+ if (typeof first === 'object') {
356
+ if ('id' in first) {
357
+ return Number(first.id);
358
+ }
359
+ const idKey = Object.keys(first).find((key)=>key.toLowerCase() === 'id');
360
+ if (idKey) {
361
+ return Number(first[idKey]);
362
+ }
363
+ }
364
+ }
365
+ if (typeof insertResult === 'object' && 'id' in insertResult) {
366
+ return Number(insertResult.id);
367
+ }
368
+ return null;
369
+ };
370
+ /**
371
+ * Detects vendor-specific duplicate key errors so we can safely ignore them when our
372
+ * goal is to insert-or-ignore without branching on the client everywhere.
373
+ */ const isDuplicateEntryError = (error)=>{
374
+ if (!error) {
375
+ return false;
376
+ }
377
+ if (DUPLICATE_ERROR_CODES.has(error.code)) {
378
+ return true;
379
+ }
380
+ const message = typeof error.message === 'string' ? error.message : '';
381
+ return message.includes('duplicate key') || message.includes('UNIQUE constraint failed');
382
+ };
383
+ /**
384
+ * Inserts a row while tolerating duplicates across all supported clients. Used when
385
+ * bulk operations fall back to single inserts to resolve constraint conflicts.
386
+ */ const insertRowWithDuplicateHandling = async (trx, tableName, row, context = {})=>{
387
+ try {
388
+ const client = trx.client.config.client;
389
+ if (client === 'postgres' || client === 'pg' || client === 'sqlite3' || client === 'better-sqlite3') {
390
+ await trx(tableName).insert(row).onConflict().ignore();
391
+ return;
392
+ }
393
+ if (client === 'mysql' || client === 'mysql2') {
394
+ await trx.raw(`INSERT IGNORE INTO ?? SET ?`, [
395
+ tableName,
396
+ row
397
+ ]);
398
+ return;
399
+ }
400
+ await trx(tableName).insert(row);
401
+ } catch (error) {
402
+ if (!isDuplicateEntryError(error)) {
403
+ const details = JSON.stringify(context);
404
+ const wrapped = new Error(`Failed to insert row into ${tableName}: ${error.message} | context=${details}`);
405
+ wrapped.cause = error;
406
+ throw wrapped;
407
+ }
408
+ }
409
+ };
410
+ /**
411
+ * Normalizes identifiers into a comparable string so we can dedupe target ids
412
+ * regardless of whether they come in as numbers, strings, or objects.
413
+ */ const toComparisonKey = (value)=>{
414
+ if (value === null || value === undefined) {
415
+ return 'null';
416
+ }
417
+ if (typeof value === 'object') {
418
+ try {
419
+ return JSON.stringify(value);
420
+ } catch {
421
+ return String(value);
422
+ }
423
+ }
424
+ return String(value);
425
+ };
426
+ /**
427
+ * Formats ids for log output while keeping the log lightweight and JSON-safe.
428
+ */ const toDisplayValue = (value)=>{
429
+ if (value === null || value === undefined) {
430
+ return 'null';
431
+ }
432
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
433
+ return String(value);
434
+ }
435
+ try {
436
+ return JSON.stringify(value);
437
+ } catch {
438
+ return String(value);
439
+ }
440
+ };
441
+ /**
442
+ * Tracks how many relation rows we skipped because their targets are missing, so we
443
+ * can emit a consolidated warning once the migration finishes copying relations.
444
+ */ function recordSkippedRelations(context, skippedIds) {
445
+ if (!skippedIds.length) {
446
+ return;
447
+ }
448
+ const key = `${context.sourceUid}::${context.attributeName}::${context.joinTable ?? 'NO_JOIN_TABLE'}`;
449
+ let stats = skippedRelationStats.get(key);
450
+ if (!stats) {
451
+ stats = {
452
+ ...context,
453
+ count: 0,
454
+ samples: new Set()
455
+ };
456
+ }
457
+ stats.count += skippedIds.length;
458
+ for (const id of skippedIds){
459
+ if (stats.samples.size >= SKIPPED_RELATION_SAMPLE_LIMIT) {
460
+ break;
461
+ }
462
+ stats.samples.add(toDisplayValue(id));
463
+ }
464
+ skippedRelationStats.set(key, stats);
465
+ }
466
+ /**
467
+ * Emits aggregated warnings for all skipped relations and resets the counters.
468
+ * This keeps the log readable even when millions of orphaned rows exist.
469
+ */ function flushSkippedRelationLogs() {
470
+ if (skippedRelationStats.size === 0) {
471
+ return;
472
+ }
473
+ for (const stats of skippedRelationStats.values()){
474
+ const sampleArray = Array.from(stats.samples);
475
+ const sampleText = sampleArray.length > 0 ? sampleArray.join(', ') : 'n/a';
476
+ const targetInfo = stats.targetUid ? `target=${stats.targetUid}` : 'target=unknown';
477
+ const joinTableInfo = stats.joinTable ? `joinTable=${stats.joinTable}` : 'joinTable=n/a';
478
+ const ellipsis = stats.count > sampleArray.length ? ', ...' : '';
479
+ strapi.log.warn(`[discard-drafts] Skipped ${stats.count} relation(s) for ${stats.sourceUid}.${stats.attributeName} (${targetInfo}, ${joinTableInfo}). Example target ids: ${sampleText}${ellipsis}`);
480
+ }
481
+ strapi.log.warn('[discard-drafts] Some join-table relations referenced missing targets and were skipped. Review these warnings and clean up orphaned relations before rerunning the migration if needed.');
482
+ skippedRelationStats.clear();
483
+ }
484
+ /**
485
+ * Returns every schema (content type or component) that can embed the provided component.
486
+ * Cached because we consult it repeatedly while remapping nested components.
487
+ */ function listComponentParentSchemas(componentUid) {
488
+ if (!componentParentSchemasCache.has(componentUid)) {
489
+ const schemas = [
490
+ ...Object.values(strapi.contentTypes),
491
+ ...Object.values(strapi.components)
492
+ ];
493
+ const parents = schemas.filter((schema)=>{
494
+ if (!schema?.attributes) {
495
+ return false;
496
+ }
497
+ return Object.values(schema.attributes).some((attr)=>{
498
+ if (attr.type === 'component') {
499
+ return attr.component === componentUid;
500
+ }
501
+ if (attr.type === 'dynamiczone') {
502
+ return attr.components?.includes(componentUid);
503
+ }
504
+ return false;
505
+ });
506
+ }).map((schema)=>({
507
+ uid: schema.uid,
508
+ collectionName: schema.collectionName
509
+ }));
510
+ componentParentSchemasCache.set(componentUid, parents);
511
+ }
512
+ return componentParentSchemasCache.get(componentUid);
513
+ }
514
+ /**
515
+ * Memoized helper for checking whether a table exists. Avoids repeating expensive
516
+ * information_schema queries when we touch the same join table many times.
517
+ */ async function ensureTableExists(trx, tableName) {
518
+ if (!joinTableExistsCache.has(tableName)) {
519
+ const exists = await trx.schema.hasTable(tableName);
520
+ joinTableExistsCache.set(tableName, exists);
521
+ }
522
+ return joinTableExistsCache.get(tableName);
523
+ }
524
+ /**
525
+ * Filters out relation rows whose target entity no longer exists, returning the safe
526
+ * rows along with a list of skipped ids so we can log them later.
527
+ */ async function filterRelationsWithExistingTargets({ trx, targetUid, relations, getTargetId }) {
528
+ if (!relations.length) {
529
+ return {
530
+ relations,
531
+ skippedIds: []
532
+ };
533
+ }
534
+ if (!targetUid) {
535
+ return {
536
+ relations,
537
+ skippedIds: []
538
+ };
539
+ }
540
+ const targetMeta = strapi.db.metadata.get(targetUid);
541
+ if (!targetMeta) {
542
+ return {
543
+ relations,
544
+ skippedIds: []
545
+ };
546
+ }
547
+ const tableName = targetMeta.tableName;
548
+ const primaryKeyColumn = resolvePrimaryKeyColumn(targetMeta);
549
+ if (!tableName) {
550
+ return {
551
+ relations,
552
+ skippedIds: []
553
+ };
554
+ }
555
+ const uniqueIdMap = new Map();
556
+ for (const relation of relations){
557
+ const targetId = getTargetId(relation);
558
+ if (targetId == null) {
559
+ continue;
560
+ }
561
+ const key = toComparisonKey(targetId);
562
+ if (!uniqueIdMap.has(key)) {
563
+ uniqueIdMap.set(key, targetId);
564
+ }
565
+ }
566
+ if (uniqueIdMap.size === 0) {
567
+ return {
568
+ relations,
569
+ skippedIds: []
570
+ };
571
+ }
572
+ const hasTable = await ensureTableExists(trx, tableName);
573
+ if (!hasTable) {
574
+ return {
575
+ relations: [],
576
+ skippedIds: Array.from(uniqueIdMap.values())
577
+ };
578
+ }
579
+ const existingKeys = new Set();
580
+ const uniqueIds = Array.from(uniqueIdMap.values());
581
+ const idChunks = chunkArray(uniqueIds, getBatchSize(trx, 1000));
582
+ for (const chunk of idChunks){
583
+ const rows = await trx(tableName).select(primaryKeyColumn).whereIn(primaryKeyColumn, chunk);
584
+ for (const row of rows){
585
+ const value = row[primaryKeyColumn];
586
+ existingKeys.add(toComparisonKey(value));
587
+ }
588
+ }
589
+ const filteredRelations = [];
590
+ const skippedIds = [];
591
+ for (const relation of relations){
592
+ const targetId = getTargetId(relation);
593
+ if (targetId == null) {
594
+ skippedIds.push(targetId);
595
+ continue;
596
+ }
597
+ if (existingKeys.has(toComparisonKey(targetId))) {
598
+ filteredRelations.push(relation);
599
+ } else {
600
+ skippedIds.push(targetId);
601
+ }
602
+ }
603
+ return {
604
+ relations: filteredRelations,
605
+ skippedIds
606
+ };
607
+ }
608
+ /**
609
+ * Locates the owning entity (content type or component) for a given component instance.
610
+ * This mirrors the document service logic we need in order to decide whether a relation
611
+ * should propagate to drafts, and is cached for performance.
612
+ */ async function findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches) {
613
+ const cacheKey = `${componentUid}:${componentId}:${excludeUid ?? 'ALL'}`;
614
+ if (caches.parentInstanceCache.has(cacheKey)) {
615
+ return caches.parentInstanceCache.get(cacheKey);
616
+ }
617
+ const parentComponentIdColumn = getComponentJoinColumnInverseName(identifiers);
618
+ const parentComponentTypeColumn = getComponentTypeColumn(identifiers);
619
+ const parentEntityIdColumn = getComponentJoinColumnEntityName(identifiers);
620
+ const potentialParents = listComponentParentSchemas(componentUid).filter((schema)=>schema.uid !== excludeUid);
621
+ for (const parentSchema of potentialParents){
622
+ if (!parentSchema.collectionName) {
623
+ continue;
624
+ }
625
+ const parentJoinTableName = getComponentJoinTableName(parentSchema.collectionName, identifiers);
626
+ try {
627
+ if (!await ensureTableExists(trx, parentJoinTableName)) {
628
+ continue;
629
+ }
630
+ const parentRow = await trx(parentJoinTableName).where({
631
+ [parentComponentIdColumn]: componentId,
632
+ [parentComponentTypeColumn]: componentUid
633
+ }).first(parentEntityIdColumn);
634
+ if (parentRow) {
635
+ const parentInstance = {
636
+ uid: parentSchema.uid,
637
+ parentId: parentRow[parentEntityIdColumn]
638
+ };
639
+ caches.parentInstanceCache.set(cacheKey, parentInstance);
640
+ return parentInstance;
641
+ }
642
+ } catch {
643
+ continue;
644
+ }
645
+ }
646
+ caches.parentInstanceCache.set(cacheKey, null);
647
+ return null;
648
+ }
649
+ /**
650
+ * Fetches and caches database metadata for a component uid. Saves repeated lookups while
651
+ * cloning the same component type thousands of times.
652
+ */ const getComponentMeta = (componentUid)=>{
653
+ if (!componentMetaCache.has(componentUid)) {
654
+ const meta = strapi.db.metadata.get(componentUid);
655
+ componentMetaCache.set(componentUid, meta ?? null);
656
+ }
657
+ return componentMetaCache.get(componentUid);
658
+ };
659
+ /**
660
+ * Determines whether a component's parent entity participates in draft/publish,
661
+ * short-circuiting a lot of recursion when deciding relation propagation rules.
662
+ */ async function hasDraftPublishAncestorForParent(trx, identifiers, parent, caches) {
663
+ const cacheKey = `${parent.uid}:${parent.parentId}`;
664
+ if (caches.parentDpCache.has(cacheKey)) {
665
+ return caches.parentDpCache.get(cacheKey);
666
+ }
667
+ const parentContentType = strapi.contentTypes[parent.uid];
668
+ if (parentContentType) {
669
+ const result = !!parentContentType?.options?.draftAndPublish;
670
+ caches.parentDpCache.set(cacheKey, result);
671
+ return result;
672
+ }
673
+ const parentComponent = strapi.components[parent.uid];
674
+ if (!parentComponent) {
675
+ caches.parentDpCache.set(cacheKey, false);
676
+ return false;
677
+ }
678
+ const result = await hasDraftPublishAncestorForComponent(trx, identifiers, parent.uid, parent.parentId, undefined, caches);
679
+ caches.parentDpCache.set(cacheKey, result);
680
+ return result;
681
+ }
682
+ /**
683
+ * Recursively checks whether a component lies beneath a draft/publish-enabled parent
684
+ * component or content type. We mirror discardDraft's propagation guard.
685
+ */ async function hasDraftPublishAncestorForComponent(trx, identifiers, componentUid, componentId, excludeUid, caches) {
686
+ const cacheKey = `${componentUid}:${componentId}:${'ALL'}`;
687
+ if (caches.ancestorDpCache.has(cacheKey)) {
688
+ return caches.ancestorDpCache.get(cacheKey);
689
+ }
690
+ const parent = await findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches);
691
+ if (!parent) {
692
+ caches.ancestorDpCache.set(cacheKey, false);
693
+ return false;
694
+ }
695
+ const result = await hasDraftPublishAncestorForParent(trx, identifiers, parent, caches);
696
+ caches.ancestorDpCache.set(cacheKey, result);
697
+ return result;
698
+ }
699
+ /**
700
+ * Abstracts `NOW()` handling so that timestamps stay consistent across databases—
701
+ * using Knex's native function when available and falling back to JS dates otherwise.
702
+ */ const resolveNowValue = (trx)=>{
703
+ if (typeof trx.fn?.now === 'function') {
704
+ return trx.fn.now();
705
+ }
706
+ return new Date();
707
+ };
708
+ /**
709
+ * Builds or retrieves the published→draft id map for a target content type, caching
710
+ * the result so nested relation remapping can reuse the work.
711
+ */ async function getDraftMapForTarget(trx, targetUid, draftMapCache) {
712
+ if (draftMapCache.has(targetUid)) {
713
+ return draftMapCache.get(targetUid) ?? null;
714
+ }
715
+ const targetMeta = strapi.db.metadata.get(targetUid);
716
+ if (!targetMeta) {
717
+ draftMapCache.set(targetUid, null);
718
+ return null;
719
+ }
720
+ const map = await buildPublishedToDraftMap({
721
+ trx,
722
+ uid: targetUid,
723
+ meta: targetMeta,
724
+ options: {
725
+ requireDraftAndPublish: true
726
+ }
727
+ });
728
+ draftMapCache.set(targetUid, map ?? null);
729
+ return map ?? null;
730
+ }
731
+ /**
732
+ * Builds a reverse map from draft IDs to published IDs for a target content type.
733
+ * This is needed to check if a target ID is already a draft and find its published version.
734
+ */ async function getDraftToPublishedMap(trx, targetUid, reverseMapCache) {
735
+ if (reverseMapCache.has(targetUid)) {
736
+ return reverseMapCache.get(targetUid) ?? null;
737
+ }
738
+ const targetMeta = strapi.db.metadata.get(targetUid);
739
+ if (!targetMeta) {
740
+ reverseMapCache.set(targetUid, null);
741
+ return null;
742
+ }
743
+ const draftToPublishedMap = new Map();
744
+ const draftMap = await getDraftMapForTarget(trx, targetUid, new Map());
745
+ if (draftMap) {
746
+ // Reverse the published->draft map to get draft->published
747
+ for (const [publishedId, draftId] of draftMap.entries()){
748
+ draftToPublishedMap.set(draftId, publishedId);
749
+ }
750
+ debug(`[getDraftToPublishedMap] ${targetUid}: Built reverse map with ${draftToPublishedMap.size} entries (draft->published)`);
751
+ } else {
752
+ debug(`[getDraftToPublishedMap] ${targetUid}: No draft map found, returning null`);
753
+ }
754
+ reverseMapCache.set(targetUid, draftToPublishedMap.size > 0 ? draftToPublishedMap : null);
755
+ return draftToPublishedMap.size > 0 ? draftToPublishedMap : null;
756
+ }
757
+ /**
758
+ * Checks if a target ID is published or draft by querying the database.
759
+ */ async function getTargetPublicationState(trx, targetId, targetUid) {
760
+ const targetMeta = strapi.db.metadata.get(targetUid);
761
+ if (!targetMeta) {
762
+ return null;
763
+ }
764
+ const target = await trx(targetMeta.tableName).select('published_at').where('id', targetId).first();
765
+ if (!target) {
766
+ return null;
767
+ }
768
+ return target.published_at !== null ? 'published' : 'draft';
769
+ }
770
+ /**
771
+ * Maps relation foreign keys so that draft entities reference draft targets when those
772
+ * targets exist; otherwise we preserve the original reference (matching discardDraft).
773
+ *
774
+ * When mapping for a draft component: maps published targets → draft targets
775
+ * When mapping for a published component: maps draft targets → published targets (if needed)
776
+ */ async function mapTargetId(trx, originalId, targetUid, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity = true, reverseMapCache) {
777
+ if (originalId == null || !targetUid) {
778
+ return originalId;
779
+ }
780
+ if (targetUid === parentUid) {
781
+ if (isForDraftEntity) {
782
+ return parentPublishedToDraftMap.get(Number(originalId)) ?? originalId;
783
+ }
784
+ // For published entity, if we got a draft ID, find the published version
785
+ const effectiveReverseCache = reverseMapCache ?? new Map();
786
+ const reverseMap = await getDraftToPublishedMap(trx, targetUid, effectiveReverseCache);
787
+ if (reverseMap) {
788
+ return reverseMap.get(Number(originalId)) ?? originalId;
789
+ }
790
+ return originalId;
791
+ }
792
+ const targetMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
793
+ if (!targetMap) {
794
+ return originalId;
795
+ }
796
+ // Check if the original ID is already a draft or published
797
+ const targetState = await getTargetPublicationState(trx, Number(originalId), targetUid);
798
+ if (isForDraftEntity) {
799
+ // For draft entities: map published targets to draft targets
800
+ if (targetState === 'published') {
801
+ return targetMap.get(Number(originalId)) ?? originalId;
802
+ }
803
+ if (targetState === 'draft') {
804
+ // Already a draft, keep it
805
+ return originalId;
806
+ }
807
+ // If we can't determine state, try the map lookup
808
+ return targetMap.get(Number(originalId)) ?? originalId;
809
+ }
810
+ // For published entities: map draft targets to published targets
811
+ if (targetState === 'draft') {
812
+ const effectiveReverseCache = reverseMapCache ?? new Map();
813
+ const reverseMap = await getDraftToPublishedMap(trx, targetUid, effectiveReverseCache);
814
+ if (reverseMap) {
815
+ return reverseMap.get(Number(originalId)) ?? originalId;
816
+ }
817
+ return originalId;
818
+ }
819
+ if (targetState === 'published') {
820
+ // Already published, keep it
821
+ return originalId;
822
+ }
823
+ // If we can't determine state, assume it's published
824
+ return originalId;
825
+ }
826
+ /**
827
+ * Clones a database row and strips the `id` column so it can be reinserted as a new row.
828
+ */ const ensureObjectWithoutId = (row)=>{
829
+ const cloned = {
830
+ ...row
831
+ };
832
+ if ('id' in cloned) {
833
+ delete cloned.id;
834
+ }
835
+ return cloned;
836
+ };
837
+ /**
838
+ * Duplicates join-table relations for a component instance while remapping any foreign
839
+ * keys to draft targets. Mirrors the runtime clone logic but operates entirely in SQL.
840
+ */ async function cloneComponentRelationJoinTables(trx, componentMeta, componentUid, originalComponentId, newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity = true, reverseMapCache) {
841
+ for (const [attributeName, attribute] of Object.entries(componentMeta.attributes)){
842
+ if (attribute.type !== 'relation' || !attribute.joinTable) {
843
+ continue;
844
+ }
845
+ const joinTable = attribute.joinTable;
846
+ const sourceColumnName = joinTable.joinColumn.name;
847
+ const targetColumnName = joinTable.inverseJoinColumn.name;
848
+ if (!componentMeta.relationsLogPrinted) {
849
+ debug(`[cloneComponentRelationJoinTables] Inspecting join table ${joinTable.name} for component ${componentUid}`);
850
+ componentMeta.relationsLogPrinted = true;
851
+ }
852
+ const relations = await trx(joinTable.name).select('*').where(sourceColumnName, originalComponentId);
853
+ if (relations.length === 0) {
854
+ continue;
855
+ }
856
+ const preparedRelations = [];
857
+ for (const relation of relations){
858
+ const clonedRelation = ensureObjectWithoutId(relation);
859
+ clonedRelation[sourceColumnName] = newComponentId;
860
+ if (targetColumnName in clonedRelation) {
861
+ const originalTargetId = clonedRelation[targetColumnName];
862
+ clonedRelation[targetColumnName] = await mapTargetId(trx, clonedRelation[targetColumnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
863
+ debug(`[cloneComponentRelationJoinTables] ${componentUid} join ${joinTable.name}: mapped ${targetColumnName} from ${originalTargetId} to ${clonedRelation[targetColumnName]} (target=${attribute.target})`);
864
+ }
865
+ preparedRelations.push(clonedRelation);
866
+ }
867
+ let relationsToInsert = preparedRelations;
868
+ if (preparedRelations.some((relation)=>targetColumnName in relation)) {
869
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
870
+ trx,
871
+ targetUid: attribute.target,
872
+ relations: preparedRelations,
873
+ getTargetId: (relation)=>relation[targetColumnName]
874
+ });
875
+ recordSkippedRelations({
876
+ sourceUid: componentUid,
877
+ attributeName,
878
+ targetUid: attribute.target,
879
+ joinTable: joinTable.name
880
+ }, skippedIds);
881
+ relationsToInsert = safeRelations;
882
+ }
883
+ if (relationsToInsert.length === 0) {
884
+ continue;
885
+ }
886
+ for (const relation of relationsToInsert){
887
+ // Ensure we're only creating relations for the NEW component, not the original
888
+ // The sourceColumnName must be newComponentId to ensure we don't accidentally modify
889
+ // the original published component's relations
890
+ if (relation[sourceColumnName] !== newComponentId) {
891
+ debug(`[cloneComponentRelationJoinTables] ERROR: Relation source ${relation[sourceColumnName]} does not match newComponentId ${newComponentId} - skipping to prevent modifying original component relations`);
892
+ continue;
893
+ }
894
+ debug(`[cloneComponentRelationJoinTables] inserting relation into ${joinTable.name} (component=${componentUid}, source=${relation[sourceColumnName]}, target=${relation[targetColumnName]})`);
895
+ await insertRowWithDuplicateHandling(trx, joinTable.name, relation, {
896
+ componentUid,
897
+ originalComponentId,
898
+ newComponentId,
899
+ joinTable: joinTable.name,
900
+ sourceColumnName,
901
+ targetColumnName,
902
+ targetUid: attribute.target,
903
+ parentUid
904
+ });
905
+ }
906
+ }
907
+ }
908
+ /**
909
+ * Clones a component row (including nested relations) so the newly created draft entity
910
+ * owns its own copy, matching what the document service would have produced.
911
+ */ async function cloneComponentInstance({ trx, componentUid, componentId, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity = true, reverseMapCache }) {
912
+ const componentMeta = getComponentMeta(componentUid);
913
+ if (!componentMeta) {
914
+ return componentId;
915
+ }
916
+ const componentTableName = componentMeta.tableName;
917
+ const componentPrimaryKey = Number.isNaN(Number(componentId)) ? componentId : Number(componentId);
918
+ const componentRow = await trx(componentTableName).select('*').where('id', componentPrimaryKey).first();
919
+ if (!componentRow) {
920
+ return componentId;
921
+ }
922
+ const newComponentRow = ensureObjectWithoutId(componentRow);
923
+ // `document_id`, `created_at`, `updated_at` are Strapi system columns whose names remain stable across the
924
+ // identifier-shortening migration, so it’s safe to check them directly here.
925
+ if ('document_id' in newComponentRow) {
926
+ newComponentRow.document_id = createId();
927
+ }
928
+ if ('updated_at' in newComponentRow) {
929
+ newComponentRow.updated_at = resolveNowValue(trx);
930
+ }
931
+ if ('created_at' in newComponentRow && newComponentRow.created_at == null) {
932
+ newComponentRow.created_at = resolveNowValue(trx);
933
+ }
934
+ for (const attribute of Object.values(componentMeta.attributes)){
935
+ if (attribute.type !== 'relation') {
936
+ continue;
937
+ }
938
+ const joinColumn = attribute.joinColumn;
939
+ if (!joinColumn) {
940
+ continue;
941
+ }
942
+ const columnName = joinColumn.name;
943
+ if (!columnName || !(columnName in newComponentRow)) {
944
+ continue;
945
+ }
946
+ newComponentRow[columnName] = await mapTargetId(trx, newComponentRow[columnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
947
+ }
948
+ let insertResult;
949
+ if (supportsReturning(trx)) {
950
+ try {
951
+ insertResult = await trx(componentTableName).insert(newComponentRow, [
952
+ 'id'
953
+ ]);
954
+ } catch (error) {
955
+ insertResult = await trx(componentTableName).insert(newComponentRow);
956
+ }
957
+ } else {
958
+ insertResult = await trx(componentTableName).insert(newComponentRow);
959
+ }
960
+ let newComponentId = resolveInsertedId(insertResult);
961
+ if (!newComponentId) {
962
+ if ('document_id' in newComponentRow && newComponentRow.document_id) {
963
+ const insertedRow = await trx(componentTableName).select('id').where('document_id', newComponentRow.document_id).orderBy('id', 'desc').first();
964
+ newComponentId = insertedRow?.id ?? null;
965
+ }
966
+ if (!newComponentId) {
967
+ const insertedRow = await trx(componentTableName).select('id').orderBy('id', 'desc').first();
968
+ newComponentId = insertedRow?.id ?? null;
969
+ }
970
+ }
971
+ if (!newComponentId) {
972
+ throw new Error(`Failed to clone component ${componentUid} (id: ${componentId})`);
973
+ }
974
+ newComponentId = Number(newComponentId);
975
+ if (Number.isNaN(newComponentId)) {
976
+ throw new Error(`Invalid cloned component identifier for ${componentUid} (id: ${componentId})`);
977
+ }
978
+ await cloneComponentRelationJoinTables(trx, componentMeta, componentUid, Number(componentPrimaryKey), newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache, isForDraftEntity, reverseMapCache);
979
+ return newComponentId;
980
+ }
981
+ /**
982
+ * Generates a map between published row ids and their corresponding draft ids so we can
983
+ * rewire relations in bulk. Handles localization nuances and caches the newest draft.
984
+ */ async function buildPublishedToDraftMap({ trx, uid, meta, options = {} }) {
985
+ if (!meta) {
986
+ return null;
987
+ }
988
+ const model = strapi.getModel(uid);
989
+ const hasDraftAndPublishEnabled = contentTypes.hasDraftAndPublish(model);
990
+ if (options.requireDraftAndPublish && !hasDraftAndPublishEnabled) {
991
+ return null;
992
+ }
993
+ const [publishedEntries, draftEntries] = await Promise.all([
994
+ // `document_id`, `locale`, and `published_at` are core columns that keep their exact names after the
995
+ // identifier-shortening migration, so selecting them by literal is safe.
996
+ trx(meta.tableName).select([
81
997
  'id',
82
- 'documentId',
998
+ 'document_id',
83
999
  'locale'
84
- ]).where({
85
- publishedAt: {
86
- $ne: null
1000
+ ]).whereNotNull('published_at'),
1001
+ trx(meta.tableName).select([
1002
+ 'id',
1003
+ 'document_id',
1004
+ 'locale'
1005
+ ]).whereNull('published_at')
1006
+ ]);
1007
+ if (publishedEntries.length === 0 || draftEntries.length === 0) {
1008
+ return null;
1009
+ }
1010
+ const i18nService = strapi.plugin('i18n')?.service('content-types');
1011
+ const contentType = strapi.contentTypes[uid];
1012
+ const isLocalized = i18nService?.isLocalizedContentType(contentType) ?? false;
1013
+ const draftByDocumentId = new Map();
1014
+ for (const draft of draftEntries){
1015
+ if (!draft.document_id) {
1016
+ continue;
1017
+ }
1018
+ const key = isLocalized ? `${draft.document_id}:${draft.locale || ''}` : draft.document_id;
1019
+ const existing = draftByDocumentId.get(key);
1020
+ if (!existing) {
1021
+ draftByDocumentId.set(key, draft);
1022
+ continue;
1023
+ }
1024
+ const existingId = Number(existing.id);
1025
+ const draftId = Number(draft.id);
1026
+ if (Number.isNaN(existingId) || Number.isNaN(draftId)) {
1027
+ draftByDocumentId.set(key, draft);
1028
+ continue;
1029
+ }
1030
+ if (draftId > existingId) {
1031
+ draftByDocumentId.set(key, draft);
1032
+ }
1033
+ }
1034
+ const publishedToDraftMap = new Map();
1035
+ for (const published of publishedEntries){
1036
+ if (!published.document_id) {
1037
+ continue;
1038
+ }
1039
+ const key = isLocalized ? `${published.document_id}:${published.locale || ''}` : published.document_id;
1040
+ const draft = draftByDocumentId.get(key);
1041
+ if (draft) {
1042
+ const publishedId = normalizeId(published.id);
1043
+ const draftId = normalizeId(draft.id);
1044
+ if (publishedId == null || draftId == null) {
1045
+ continue;
1046
+ }
1047
+ publishedToDraftMap.set(publishedId, draftId);
1048
+ }
1049
+ }
1050
+ return publishedToDraftMap.size > 0 ? publishedToDraftMap : null;
1051
+ }
1052
+ /**
1053
+ * Copy relations within the same content type (self-referential relations)
1054
+ */ async function copyRelationsForContentType({ trx, uid, publishedToDraftMap }) {
1055
+ const meta = strapi.db.metadata.get(uid);
1056
+ if (!meta) return;
1057
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1058
+ for (const attribute of Object.values(meta.attributes)){
1059
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
1060
+ continue;
1061
+ }
1062
+ const joinTable = attribute.joinTable;
1063
+ if (!joinTable) {
1064
+ continue;
1065
+ }
1066
+ // Skip component join tables - they are handled by copyComponentRelations
1067
+ if (joinTable.name.includes('_cmps')) {
1068
+ continue;
1069
+ }
1070
+ const { name: sourceColumnName } = joinTable.joinColumn;
1071
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1072
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1073
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1074
+ for (const publishedIdsChunk of publishedIdsChunks){
1075
+ const draftSourceIds = publishedIdsChunk.map((value)=>getMappedValue(publishedToDraftMap, value)).filter((value)=>value != null);
1076
+ // Get relations where the source is a published entry (in batches)
1077
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
1078
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1079
+ const relations = await relationsQuery;
1080
+ if (relations.length === 0) {
1081
+ continue;
1082
+ }
1083
+ // Create new relations pointing to draft entries
1084
+ // Remove the 'id' field to avoid duplicate key errors
1085
+ const newRelations = relations.map((relation)=>{
1086
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
1087
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
1088
+ if (!newSourceId || !newTargetId) {
1089
+ // Skip if no mapping found
1090
+ return null;
1091
+ }
1092
+ // Create new relation object without the 'id' field
1093
+ const { id, ...relationWithoutId } = relation;
1094
+ return {
1095
+ ...relationWithoutId,
1096
+ [sourceColumnName]: newSourceId,
1097
+ [targetColumnName]: newTargetId
1098
+ };
1099
+ }).filter(Boolean);
1100
+ if (newRelations.length === 0) {
1101
+ continue;
1102
+ }
1103
+ const existingKeys = await getExistingRelationKeys({
1104
+ trx,
1105
+ joinTable,
1106
+ sourceColumnName,
1107
+ targetColumnName,
1108
+ sourceIds: draftSourceIds
1109
+ });
1110
+ const relationsToInsert = newRelations.filter((relation)=>{
1111
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
1112
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
1113
+ return !existingKeys.has(key);
1114
+ });
1115
+ if (relationsToInsert.length === 0) {
1116
+ continue;
1117
+ }
1118
+ await insertRelationsWithDuplicateHandling({
1119
+ trx,
1120
+ tableName: joinTable.name,
1121
+ relations: relationsToInsert,
1122
+ context: {
1123
+ reason: 'duplicate-self-relation-check',
1124
+ sourceUid: uid,
1125
+ targetUid: uid
1126
+ }
1127
+ });
1128
+ }
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Copy relations from other content types that target this content type
1133
+ */ async function copyRelationsFromOtherContentTypes({ trx, uid, publishedToDraftMap }) {
1134
+ const targetMeta = strapi.db.metadata.get(uid);
1135
+ if (!targetMeta) {
1136
+ return;
1137
+ }
1138
+ const publishedTargetIds = Array.from(publishedToDraftMap.keys()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1139
+ if (publishedTargetIds.length === 0) {
1140
+ return;
1141
+ }
1142
+ const draftTargetIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1143
+ const models = [
1144
+ ...Object.values(strapi.contentTypes),
1145
+ ...Object.values(strapi.components)
1146
+ ];
1147
+ for (const model of models){
1148
+ const dbModel = strapi.db.metadata.get(model.uid);
1149
+ if (!dbModel) {
1150
+ continue;
1151
+ }
1152
+ const sourceHasDraftAndPublish = Boolean(model.options?.draftAndPublish);
1153
+ for (const attribute of Object.values(dbModel.attributes)){
1154
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
1155
+ continue;
1156
+ }
1157
+ const joinTable = attribute.joinTable;
1158
+ if (!joinTable) {
1159
+ continue;
1160
+ }
1161
+ // Component join tables are handled separately when cloning components.
1162
+ if (joinTable.name.includes('_cmps')) {
1163
+ continue;
1164
+ }
1165
+ // If the source content type also has draft/publish, its own cloning routine will recreate its relations.
1166
+ if (sourceHasDraftAndPublish) {
1167
+ continue;
1168
+ }
1169
+ const { name: sourceColumnName } = joinTable.joinColumn;
1170
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1171
+ // Query existing relations by target IDs to avoid duplicates
1172
+ const existingKeys = await getExistingRelationKeys({
1173
+ trx,
1174
+ joinTable,
1175
+ sourceColumnName,
1176
+ targetColumnName,
1177
+ sourceIds: draftTargetIds
1178
+ });
1179
+ const publishedIdChunks = chunkArray(publishedTargetIds, getBatchSize(trx, 1000));
1180
+ for (const chunk of publishedIdChunks){
1181
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(targetColumnName, chunk);
1182
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1183
+ const relations = await relationsQuery;
1184
+ if (relations.length === 0) {
1185
+ continue;
1186
+ }
1187
+ const newRelations = [];
1188
+ for (const relation of relations){
1189
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
1190
+ if (!newTargetId) {
1191
+ continue;
1192
+ }
1193
+ const key = buildRelationKey(relation, sourceColumnName, newTargetId);
1194
+ if (existingKeys.has(key)) {
1195
+ continue;
1196
+ }
1197
+ existingKeys.add(key);
1198
+ const { id, ...relationWithoutId } = relation;
1199
+ newRelations.push({
1200
+ ...relationWithoutId,
1201
+ [targetColumnName]: newTargetId
1202
+ });
1203
+ }
1204
+ if (newRelations.length === 0) {
1205
+ continue;
1206
+ }
1207
+ await insertRelationsWithDuplicateHandling({
1208
+ trx,
1209
+ tableName: joinTable.name,
1210
+ relations: newRelations,
1211
+ context: {
1212
+ reason: 'duplicate-draft-target-relation',
1213
+ sourceUid: model.uid,
1214
+ targetUid: uid
1215
+ }
1216
+ });
1217
+ }
1218
+ }
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Copy relations from this content type that target other content types (category 3)
1223
+ * Example: Article -> Categories/Tags
1224
+ */ async function copyRelationsToOtherContentTypes({ trx, uid, publishedToDraftMap }) {
1225
+ const meta = strapi.db.metadata.get(uid);
1226
+ if (!meta) return;
1227
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1228
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1229
+ const targetMapCache = new Map();
1230
+ for (const [attributeName, attribute] of Object.entries(meta.attributes)){
1231
+ if (attribute.type !== 'relation' || attribute.target === uid) {
1232
+ continue;
1233
+ }
1234
+ const joinTable = attribute.joinTable;
1235
+ if (!joinTable) {
1236
+ continue;
1237
+ }
1238
+ // Skip component join tables - they are handled by copyComponentRelations
1239
+ if (joinTable.name.includes('_cmps')) {
1240
+ continue;
1241
+ }
1242
+ const { name: sourceColumnName } = joinTable.joinColumn;
1243
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1244
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1245
+ const targetUid = attribute.target;
1246
+ if (!targetMapCache.has(targetUid)) {
1247
+ const targetMeta = strapi.db.metadata.get(targetUid);
1248
+ const targetMap = await buildPublishedToDraftMap({
1249
+ trx,
1250
+ uid: targetUid,
1251
+ meta: targetMeta,
1252
+ options: {
1253
+ requireDraftAndPublish: true
1254
+ }
1255
+ });
1256
+ targetMapCache.set(targetUid, targetMap);
1257
+ }
1258
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1259
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1260
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1261
+ for (const publishedIdsChunk of publishedIdsChunks){
1262
+ // Get relations where the source is a published entry of our content type (in batches)
1263
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
1264
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1265
+ const relations = await relationsQuery;
1266
+ if (relations.length === 0) {
1267
+ continue;
1268
+ }
1269
+ // Create new relations pointing to draft entries
1270
+ // Remove the 'id' field to avoid duplicate key errors
1271
+ const newRelations = relations.map((relation)=>{
1272
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
1273
+ if (!newSourceId) {
1274
+ return null;
1275
+ }
1276
+ // Map target ID to draft if target has draft/publish enabled
1277
+ // This matches discard() behavior: drafts relate to drafts
1278
+ let newTargetId = relation[targetColumnName];
1279
+ if (targetPublishedToDraftMap) {
1280
+ const mappedTargetId = getMappedValue(targetPublishedToDraftMap, relation[targetColumnName]);
1281
+ if (mappedTargetId !== undefined) {
1282
+ newTargetId = mappedTargetId;
1283
+ }
1284
+ // If no draft mapping, keep published target (target might not have DP or was deleted)
1285
+ // This will be fixed by fixExistingDraftRelations if needed
1286
+ }
1287
+ // Create new relation object without the 'id' field
1288
+ const { id, ...relationWithoutId } = relation;
1289
+ return {
1290
+ ...relationWithoutId,
1291
+ [sourceColumnName]: newSourceId,
1292
+ [targetColumnName]: newTargetId
1293
+ };
1294
+ }).filter(Boolean);
1295
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
1296
+ trx,
1297
+ targetUid,
1298
+ relations: newRelations,
1299
+ getTargetId: (relation)=>relation[targetColumnName]
1300
+ });
1301
+ recordSkippedRelations({
1302
+ sourceUid: uid,
1303
+ attributeName,
1304
+ targetUid,
1305
+ joinTable: joinTable.name
1306
+ }, skippedIds);
1307
+ if (safeRelations.length === 0) {
1308
+ continue;
1309
+ }
1310
+ // Check for existing relations to avoid duplicates (similar to copyRelationsFromOtherContentTypes)
1311
+ // This is important when the target doesn't have D&P, as copyRelationsFromOtherContentTypes
1312
+ // may have already created some relations
1313
+ const draftSourceIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1314
+ const existingKeys = await getExistingRelationKeys({
1315
+ trx,
1316
+ joinTable,
1317
+ sourceColumnName,
1318
+ targetColumnName,
1319
+ sourceIds: draftSourceIds
1320
+ });
1321
+ // Filter out relations that already exist
1322
+ const relationsToInsert = safeRelations.filter((relation)=>{
1323
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
1324
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
1325
+ return !existingKeys.has(key);
1326
+ });
1327
+ if (relationsToInsert.length > 0) {
1328
+ await insertRelationsWithDuplicateHandling({
1329
+ trx,
1330
+ tableName: joinTable.name,
1331
+ relations: relationsToInsert,
1332
+ context: {
1333
+ reason: 'duplicate-relation-check',
1334
+ sourceUid: uid,
1335
+ targetUid
1336
+ }
1337
+ });
1338
+ }
1339
+ }
1340
+ }
1341
+ }
1342
+ /**
1343
+ * Update JoinColumn relations (oneToOne, manyToOne foreign keys) to point to draft versions
1344
+ * This matches discard() behavior: when creating drafts, foreign keys should point to draft targets
1345
+ */ async function updateJoinColumnRelations({ db, trx, uid }) {
1346
+ const meta = db.metadata.get(uid);
1347
+ if (!meta) {
1348
+ return;
1349
+ }
1350
+ // Create mapping from published entry ID to draft entry ID
1351
+ const publishedToDraftMap = await buildPublishedToDraftMap({
1352
+ trx,
1353
+ uid,
1354
+ meta
1355
+ });
1356
+ if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
1357
+ return;
1358
+ }
1359
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1360
+ const targetMapCache = new Map();
1361
+ // Find all JoinColumn relations (oneToOne, manyToOne without joinTable)
1362
+ for (const attribute of Object.values(meta.attributes)){
1363
+ if (attribute.type !== 'relation') {
1364
+ continue;
1365
+ }
1366
+ // Skip relations with joinTable (handled by copyRelationsToOtherContentTypes)
1367
+ if (attribute.joinTable) {
1368
+ continue;
1369
+ }
1370
+ // Only handle oneToOne and manyToOne relations that use joinColumn
1371
+ const joinColumn = attribute.joinColumn;
1372
+ if (!joinColumn) {
1373
+ continue;
1374
+ }
1375
+ const targetUid = attribute.target;
1376
+ const foreignKeyColumn = joinColumn.name;
1377
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1378
+ if (!targetMapCache.has(targetUid)) {
1379
+ const targetMeta = strapi.db.metadata.get(targetUid);
1380
+ const targetMap = await buildPublishedToDraftMap({
1381
+ trx,
1382
+ uid: targetUid,
1383
+ meta: targetMeta,
1384
+ options: {
1385
+ requireDraftAndPublish: true
1386
+ }
1387
+ });
1388
+ targetMapCache.set(targetUid, targetMap);
1389
+ }
1390
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1391
+ if (!targetPublishedToDraftMap) {
1392
+ continue;
1393
+ }
1394
+ const draftIds = Array.from(publishedToDraftMap.values());
1395
+ if (draftIds.length === 0) {
1396
+ continue;
1397
+ }
1398
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1399
+ for (const draftIdsChunk of draftIdsChunks){
1400
+ // Get draft entries with their foreign key values
1401
+ const draftEntriesWithFk = await trx(meta.tableName).select([
1402
+ 'id',
1403
+ foreignKeyColumn
1404
+ ]).whereIn('id', draftIdsChunk).whereNotNull(foreignKeyColumn);
1405
+ const updates = draftEntriesWithFk.reduce((acc, draftEntry)=>{
1406
+ const publishedTargetIdRaw = draftEntry[foreignKeyColumn];
1407
+ const normalizedPublishedTargetId = normalizeId(publishedTargetIdRaw);
1408
+ const draftTargetId = normalizedPublishedTargetId == null ? undefined : targetPublishedToDraftMap.get(normalizedPublishedTargetId);
1409
+ if (draftTargetId != null && normalizeId(draftTargetId) !== normalizedPublishedTargetId) {
1410
+ acc.push({
1411
+ id: draftEntry.id,
1412
+ draftTargetId
1413
+ });
1414
+ }
1415
+ return acc;
1416
+ }, []);
1417
+ if (updates.length === 0) {
1418
+ continue;
1419
+ }
1420
+ const caseFragments = updates.map(()=>'WHEN ? THEN ?').join(' ');
1421
+ const idsPlaceholders = updates.map(()=>'?').join(', ');
1422
+ await trx.raw(`UPDATE ?? SET ?? = CASE ?? ${caseFragments} ELSE ?? END WHERE ?? IN (${idsPlaceholders})`, [
1423
+ meta.tableName,
1424
+ foreignKeyColumn,
1425
+ 'id',
1426
+ ...updates.flatMap(({ id, draftTargetId })=>[
1427
+ id,
1428
+ draftTargetId
1429
+ ]),
1430
+ foreignKeyColumn,
1431
+ 'id',
1432
+ ...updates.map(({ id })=>id)
1433
+ ]);
1434
+ }
1435
+ }
1436
+ }
1437
+ /**
1438
+ * Fixes existing v4 draft entries' join table relations by converting published targets to draft targets.
1439
+ * This ensures that draft entries point to draft targets, not published ones.
1440
+ */ async function fixExistingDraftRelations({ trx, uid }) {
1441
+ const meta = strapi.db.metadata.get(uid);
1442
+ if (!meta) {
1443
+ return;
1444
+ }
1445
+ // Get all draft entity IDs (including existing v4 drafts, not just newly created ones)
1446
+ const draftEntities = await trx(meta.tableName).select('id').whereNull('published_at');
1447
+ if (draftEntities.length === 0) {
1448
+ return;
1449
+ }
1450
+ const draftIds = draftEntities.map((e)=>Number(e.id));
1451
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1452
+ const draftMapCache = new Map();
1453
+ for (const [attributeName, attribute] of Object.entries(meta.attributes)){
1454
+ if (attribute.type !== 'relation') {
1455
+ continue;
1456
+ }
1457
+ const joinTable = attribute.joinTable;
1458
+ if (!joinTable) {
1459
+ continue;
1460
+ }
1461
+ // Skip component join tables - they are handled by fixExistingDraftComponentRelations
1462
+ if (joinTable.name.includes('_cmps')) {
1463
+ continue;
1464
+ }
1465
+ // Skip self-referential relations - they're handled by copyRelationsForContentType
1466
+ if (attribute.target === uid) {
1467
+ continue;
1468
+ }
1469
+ const targetUid = attribute.target;
1470
+ if (!targetUid) {
1471
+ continue;
1472
+ }
1473
+ const targetContentType = strapi.contentTypes[targetUid];
1474
+ const targetHasDP = targetContentType?.options?.draftAndPublish;
1475
+ if (!targetHasDP) {
1476
+ continue;
1477
+ }
1478
+ const { name: sourceColumnName } = joinTable.joinColumn;
1479
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1480
+ // Get draft map for target to convert published targets to draft targets
1481
+ const targetDraftMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
1482
+ if (!targetDraftMap || targetDraftMap.size === 0) {
1483
+ continue;
1484
+ }
1485
+ // Get target publication states
1486
+ const targetMeta = strapi.db.metadata.get(targetUid);
1487
+ if (!targetMeta) {
1488
+ continue;
1489
+ }
1490
+ for (const draftIdsChunk of draftIdsChunks){
1491
+ // Get all relations for these draft entries
1492
+ const relations = await trx(joinTable.name).whereIn(sourceColumnName, draftIdsChunk).select('id', sourceColumnName, targetColumnName);
1493
+ if (relations.length === 0) {
1494
+ continue;
1495
+ }
1496
+ const targetIds = [
1497
+ ...new Set(relations.map((r)=>r[targetColumnName]).filter(Boolean))
1498
+ ];
1499
+ if (targetIds.length === 0) {
1500
+ continue;
1501
+ }
1502
+ const targets = await trx(targetMeta.tableName).whereIn('id', targetIds).select('id', 'published_at');
1503
+ const targetPublicationState = new Map(targets.map((t)=>[
1504
+ Number(t.id),
1505
+ t.published_at !== null ? 'published' : 'draft'
1506
+ ]));
1507
+ // Find relations from draft entries to published targets and convert them
1508
+ const relationsToUpdate = [];
1509
+ for (const relation of relations){
1510
+ const targetId = Number(relation[targetColumnName]);
1511
+ const targetState = targetPublicationState.get(targetId);
1512
+ if (targetState === 'published') {
1513
+ // This is a relation from a draft entry to a published target - convert to draft target
1514
+ const draftTargetId = targetDraftMap.get(targetId);
1515
+ if (draftTargetId != null) {
1516
+ relationsToUpdate.push({
1517
+ relationId: relation.id,
1518
+ sourceId: Number(relation[sourceColumnName]),
1519
+ oldTargetId: targetId,
1520
+ newTargetId: draftTargetId
1521
+ });
1522
+ }
1523
+ }
1524
+ }
1525
+ if (relationsToUpdate.length > 0) {
1526
+ debug(`[fixExistingDraftRelations] ${uid}: Converting ${relationsToUpdate.length} relations from draft entries to published targets -> draft targets (attribute: ${attributeName}, target: ${targetUid})`);
1527
+ const updateChunks = chunkArray(relationsToUpdate, getBatchSize(trx, 1000));
1528
+ for (const updateChunk of updateChunks){
1529
+ // Preload existing relations for this chunk to avoid N+1 lookups.
1530
+ const existingRelationMap = await buildExistingRelationMap({
1531
+ trx,
1532
+ tableName: joinTable.name,
1533
+ sourceColumnName,
1534
+ targetColumnName,
1535
+ updates: updateChunk.map((update)=>({
1536
+ sourceId: update.sourceId,
1537
+ newTargetId: update.newTargetId
1538
+ })),
1539
+ batchSize: getBatchSize(trx, 100)
1540
+ });
1541
+ for (const update of updateChunk){
1542
+ try {
1543
+ // Check if relation to draft target already exists
1544
+ const key = `${update.sourceId}_${update.newTargetId}`;
1545
+ const existingRelationId = existingRelationMap.get(key);
1546
+ if (existingRelationId && existingRelationId !== update.relationId) {
1547
+ // If relation to draft target already exists, delete the published target relation
1548
+ await trx(joinTable.name).where('id', update.relationId).delete();
1549
+ debug(`[fixExistingDraftRelations] ${uid}: Deleted relation ${update.relationId} (entry ${update.sourceId} -> published target ${update.oldTargetId}), draft relation already exists (-> ${update.newTargetId})`);
1550
+ } else {
1551
+ // Update the relation to point to draft target
1552
+ const updated = await trx(joinTable.name).where('id', update.relationId).update({
1553
+ [targetColumnName]: update.newTargetId
1554
+ });
1555
+ if (updated > 0) {
1556
+ debug(`[fixExistingDraftRelations] ${uid}: Updated relation ${update.relationId} (entry ${update.sourceId} -> published target ${update.oldTargetId} -> draft target ${update.newTargetId})`);
1557
+ }
1558
+ }
1559
+ } catch (error) {
1560
+ // If update fails due to duplicate key, try deleting the published target relation instead
1561
+ if (isDuplicateEntryError(error)) {
1562
+ await trx(joinTable.name).where('id', update.relationId).delete();
1563
+ debug(`[fixExistingDraftRelations] ${uid}: Deleted relation ${update.relationId} due to duplicate key error (entry ${update.sourceId})`);
1564
+ } else {
1565
+ throw error;
1566
+ }
1567
+ }
1568
+ }
1569
+ }
1570
+ }
1571
+ }
1572
+ }
1573
+ }
1574
+ /**
1575
+ * Fixes existing v4 draft entries' component relations by converting published targets to draft targets.
1576
+ * This ensures that draft components point to draft targets, not published ones.
1577
+ */ async function fixExistingDraftComponentRelations({ trx, uid }) {
1578
+ const meta = strapi.db.metadata.get(uid);
1579
+ if (!meta) {
1580
+ return;
1581
+ }
1582
+ const contentType = strapi.contentTypes[uid];
1583
+ const collectionName = contentType?.collectionName;
1584
+ if (!collectionName) {
1585
+ return;
1586
+ }
1587
+ const identifiers = strapi.db.metadata.identifiers;
1588
+ const joinTableName = getComponentJoinTableName(collectionName, identifiers);
1589
+ const entityIdColumn = getComponentJoinColumnEntityName(identifiers);
1590
+ const componentIdColumn = getComponentJoinColumnInverseName(identifiers);
1591
+ const componentTypeColumn = getComponentTypeColumn(identifiers);
1592
+ const hasTable = await trx.schema.hasTable(joinTableName);
1593
+ if (!hasTable) {
1594
+ return;
1595
+ }
1596
+ // Get all draft entity IDs (including existing v4 drafts, not just newly created ones)
1597
+ const draftEntities = await trx(meta.tableName).select('id').whereNull('published_at');
1598
+ if (draftEntities.length === 0) {
1599
+ return;
1600
+ }
1601
+ const draftIds = draftEntities.map((e)=>Number(e.id));
1602
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1603
+ for (const draftIdsChunk of draftIdsChunks){
1604
+ // Get components that belong to draft entities
1605
+ const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, draftIdsChunk);
1606
+ if (componentRelations.length === 0) {
1607
+ continue;
1608
+ }
1609
+ const componentTypes = [
1610
+ ...new Set(componentRelations.map((r)=>r[componentTypeColumn]))
1611
+ ];
1612
+ const draftMapCache = new Map();
1613
+ for (const componentType of componentTypes){
1614
+ const componentMeta = strapi.db.metadata.get(componentType);
1615
+ if (!componentMeta) continue;
1616
+ for (const [, attr] of Object.entries(componentMeta.attributes || {})){
1617
+ if (attr.type !== 'relation' || !attr.joinTable) continue;
1618
+ const targetUid = attr.target;
1619
+ if (!targetUid) continue;
1620
+ const targetContentType = strapi.contentTypes[targetUid];
1621
+ const targetHasDP = targetContentType?.options?.draftAndPublish;
1622
+ if (!targetHasDP) continue;
1623
+ const relationJoinTable = attr.joinTable.name;
1624
+ const sourceColumn = attr.joinTable.joinColumn.name;
1625
+ const targetColumn = attr.joinTable.inverseJoinColumn.name;
1626
+ const hasRelationTable = await trx.schema.hasTable(relationJoinTable);
1627
+ if (!hasRelationTable) continue;
1628
+ // Get component IDs that belong to draft entities
1629
+ const componentIds = componentRelations.filter((r)=>r[componentTypeColumn] === componentType).map((r)=>Number(r[componentIdColumn]));
1630
+ if (componentIds.length === 0) continue;
1631
+ // Get all relations for these components
1632
+ const relations = await trx(relationJoinTable).whereIn(sourceColumn, componentIds).select('id', sourceColumn, targetColumn);
1633
+ if (relations.length === 0) continue;
1634
+ // Get target publication states
1635
+ const targetMeta = strapi.db.metadata.get(targetUid);
1636
+ if (!targetMeta) continue;
1637
+ const targetIds = [
1638
+ ...new Set(relations.map((r)=>r[targetColumn]).filter(Boolean))
1639
+ ];
1640
+ if (targetIds.length === 0) continue;
1641
+ const targets = await trx(targetMeta.tableName).whereIn('id', targetIds).select('id', 'published_at');
1642
+ const targetPublicationState = new Map(targets.map((t)=>[
1643
+ Number(t.id),
1644
+ t.published_at !== null ? 'published' : 'draft'
1645
+ ]));
1646
+ // Get draft map for target to convert published targets to draft targets
1647
+ const targetDraftMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
1648
+ if (!targetDraftMap || targetDraftMap.size === 0) continue;
1649
+ // Find relations from draft components to published targets and convert them
1650
+ const relationsToUpdate = [];
1651
+ for (const relation of relations){
1652
+ const targetId = Number(relation[targetColumn]);
1653
+ const targetState = targetPublicationState.get(targetId);
1654
+ if (targetState === 'published') {
1655
+ // This is a relation from a draft component to a published target - convert to draft target
1656
+ const draftTargetId = targetDraftMap.get(targetId);
1657
+ if (draftTargetId != null) {
1658
+ relationsToUpdate.push({
1659
+ relationId: relation.id,
1660
+ componentId: Number(relation[sourceColumn]),
1661
+ oldTargetId: targetId,
1662
+ newTargetId: draftTargetId
1663
+ });
1664
+ }
1665
+ }
1666
+ }
1667
+ if (relationsToUpdate.length > 0) {
1668
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Converting ${relationsToUpdate.length} relations from draft components to published targets -> draft targets (component type: ${componentType}, target: ${targetUid})`);
1669
+ const updateChunks = chunkArray(relationsToUpdate, getBatchSize(trx, 1000));
1670
+ for (const updateChunk of updateChunks){
1671
+ // Preload existing relations for this chunk to avoid N+1 lookups.
1672
+ const existingRelationMap = await buildExistingRelationMap({
1673
+ trx,
1674
+ tableName: relationJoinTable,
1675
+ sourceColumnName: sourceColumn,
1676
+ targetColumnName: targetColumn,
1677
+ updates: updateChunk.map((update)=>({
1678
+ sourceId: update.componentId,
1679
+ newTargetId: update.newTargetId
1680
+ })),
1681
+ batchSize: getBatchSize(trx, 100)
1682
+ });
1683
+ for (const update of updateChunk){
1684
+ try {
1685
+ // Check if relation to draft target already exists
1686
+ const key = `${update.componentId}_${update.newTargetId}`;
1687
+ const existingRelationId = existingRelationMap.get(key);
1688
+ if (existingRelationId && existingRelationId !== update.relationId) {
1689
+ // If relation to draft target already exists, delete the published target relation
1690
+ await trx(relationJoinTable).where('id', update.relationId).delete();
1691
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Deleted relation ${update.relationId} (component ${update.componentId} -> published target ${update.oldTargetId}), draft relation already exists (-> ${update.newTargetId})`);
1692
+ } else {
1693
+ // Update the relation to point to draft target
1694
+ const updated = await trx(relationJoinTable).where('id', update.relationId).update({
1695
+ [targetColumn]: update.newTargetId
1696
+ });
1697
+ if (updated > 0) {
1698
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Updated relation ${update.relationId} (component ${update.componentId} -> published target ${update.oldTargetId} -> draft target ${update.newTargetId})`);
1699
+ }
1700
+ }
1701
+ } catch (error) {
1702
+ // If update fails due to duplicate key, try deleting the published target relation instead
1703
+ if (isDuplicateEntryError(error)) {
1704
+ await trx(relationJoinTable).where('id', update.relationId).delete();
1705
+ debug(`[fixExistingDraftComponentRelations] ${uid}: Deleted relation ${update.relationId} due to duplicate key error (component ${update.componentId})`);
1706
+ } else {
1707
+ throw error;
1708
+ }
1709
+ }
1710
+ }
1711
+ }
1712
+ }
1713
+ }
1714
+ }
1715
+ }
1716
+ }
1717
+ /**
1718
+ * Copy component relations from published entries to draft entries
1719
+ */ async function copyComponentRelations({ trx, uid, publishedToDraftMap }) {
1720
+ const meta = strapi.db.metadata.get(uid);
1721
+ if (!meta) {
1722
+ return;
1723
+ }
1724
+ // Get collectionName from content type schema (Meta only has tableName which may be shortened)
1725
+ const contentType = strapi.contentTypes[uid];
1726
+ const collectionName = contentType?.collectionName;
1727
+ if (!collectionName) {
1728
+ return;
1729
+ }
1730
+ const identifiers = strapi.db.metadata.identifiers;
1731
+ const joinTableName = getComponentJoinTableName(collectionName, identifiers);
1732
+ const entityIdColumn = getComponentJoinColumnEntityName(identifiers);
1733
+ const componentIdColumn = getComponentJoinColumnInverseName(identifiers);
1734
+ const componentTypeColumn = getComponentTypeColumn(identifiers);
1735
+ const fieldColumn = identifiers.FIELD_COLUMN;
1736
+ // Check if component join table exists
1737
+ const hasTable = await trx.schema.hasTable(joinTableName);
1738
+ if (!hasTable) {
1739
+ return;
1740
+ }
1741
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1742
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1743
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1744
+ for (const publishedIdsChunk of publishedIdsChunks){
1745
+ // Get component relations for published entries
1746
+ const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, publishedIdsChunk);
1747
+ if (componentRelations.length === 0) {
1748
+ continue;
1749
+ }
1750
+ const componentCloneCache = new Map();
1751
+ const componentTargetDraftMapCache = new Map();
1752
+ const componentTargetReverseMapCache = new Map();
1753
+ const componentHierarchyCaches = {
1754
+ parentInstanceCache: new Map(),
1755
+ ancestorDpCache: new Map(),
1756
+ parentDpCache: new Map()
1757
+ };
1758
+ // Filter component relations: only propagate if component's parent in the component hierarchy doesn't have draft/publish
1759
+ // This matches discardDraft() behavior via shouldPropagateComponentRelationToNewVersion
1760
+ //
1761
+ // The logic: find what contains this component instance (could be a content type or another component).
1762
+ // If it's a component, recursively check its parents. If any parent in the chain has DP, filter out the relation.
1763
+ // Filter in batches to cap memory use and DB fan-out when relations are large.
1764
+ const filteredComponentRelations = [];
1765
+ const filterBatches = chunkArray(componentRelations, getBatchSize(trx, 100));
1766
+ for (const batch of filterBatches){
1767
+ const batchResults = await Promise.all(batch.map(async (relation)=>{
1768
+ const componentId = relation[componentIdColumn];
1769
+ const componentType = relation[componentTypeColumn];
1770
+ const entityId = relation[entityIdColumn];
1771
+ const componentSchema = strapi.components[componentType];
1772
+ if (!componentSchema) {
1773
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - unknown component type ${componentType} (entity: ${entityId}, componentId: ${componentId})`);
1774
+ return relation;
1775
+ }
1776
+ const componentParent = await findComponentParentInstance(trx, identifiers, componentSchema.uid, componentId, uid, componentHierarchyCaches);
1777
+ if (!componentParent) {
1778
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}) is directly on entity ${entityId} (no nested parent found)`);
1779
+ return relation;
1780
+ }
1781
+ debug(`[copyComponentRelations] ${uid}: Component ${componentType} (id: ${componentId}, entity: ${entityId}) has parent in hierarchy: ${componentParent.uid} (parentId: ${componentParent.parentId})`);
1782
+ const hasDPParent = await hasDraftPublishAncestorForParent(trx, identifiers, componentParent, componentHierarchyCaches);
1783
+ if (hasDPParent) {
1784
+ debug(`[copyComponentRelations] Filtering: component ${componentType} (id: ${componentId}, entity: ${entityId}) has DP parent in hierarchy (${componentParent.uid})`);
1785
+ return null;
1786
+ }
1787
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}, entity: ${entityId}) has no DP parent in hierarchy`);
1788
+ return relation;
1789
+ }));
1790
+ filteredComponentRelations.push(...batchResults);
1791
+ }
1792
+ // Filter out null values (filtered relations)
1793
+ const relationsToProcess = filteredComponentRelations.filter(Boolean);
1794
+ const filteredCount = componentRelations.length - relationsToProcess.length;
1795
+ if (filteredCount > 0) {
1796
+ debug(`[copyComponentRelations] ${uid}: Filtered ${filteredCount} of ${componentRelations.length} component relations (removed ${filteredCount} with DP parents)`);
1797
+ }
1798
+ // Create new component relations for draft entries
1799
+ // Remove the 'id' field to avoid duplicate key errors
1800
+ const mappedRelations = (await Promise.all(relationsToProcess.map(async (relation)=>{
1801
+ const newEntityId = getMappedValue(publishedToDraftMap, relation[entityIdColumn]);
1802
+ if (!newEntityId) {
1803
+ return null;
1804
+ }
1805
+ const componentId = relation[componentIdColumn];
1806
+ const componentType = relation[componentTypeColumn];
1807
+ const componentKey = `${componentId}:${newEntityId}`;
1808
+ let cloneMap = componentCloneCache.get(componentType);
1809
+ if (!cloneMap) {
1810
+ cloneMap = new Map();
1811
+ componentCloneCache.set(componentType, cloneMap);
1812
+ }
1813
+ let newComponentId = cloneMap.get(componentKey);
1814
+ if (!newComponentId) {
1815
+ newComponentId = await cloneComponentInstance({
1816
+ trx,
1817
+ componentUid: componentType,
1818
+ componentId: Number(componentId),
1819
+ parentUid: uid,
1820
+ parentPublishedToDraftMap: publishedToDraftMap,
1821
+ draftMapCache: componentTargetDraftMapCache,
1822
+ isForDraftEntity: true,
1823
+ reverseMapCache: componentTargetReverseMapCache
1824
+ });
1825
+ cloneMap.set(componentKey, newComponentId);
1826
+ }
1827
+ const { id, ...relationWithoutId } = relation;
1828
+ return {
1829
+ ...relationWithoutId,
1830
+ [entityIdColumn]: newEntityId,
1831
+ [componentIdColumn]: newComponentId
1832
+ };
1833
+ }))).filter(Boolean);
1834
+ // Deduplicate relations based on the unique constraint columns
1835
+ // This prevents duplicates within the same batch that could cause conflicts
1836
+ const uniqueKeyMap = new Map();
1837
+ for (const relation of mappedRelations){
1838
+ const uniqueKey = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
1839
+ if (!uniqueKeyMap.has(uniqueKey)) {
1840
+ uniqueKeyMap.set(uniqueKey, relation);
1841
+ }
1842
+ }
1843
+ const deduplicatedRelations = Array.from(uniqueKeyMap.values());
1844
+ if (deduplicatedRelations.length === 0) {
1845
+ continue;
1846
+ }
1847
+ // Check which relations already exist in the database to avoid conflicts
1848
+ // We need to check all unique constraint columns (entity_id, cmp_id, field, component_type)
1849
+ // Batch the check to avoid SQLite expression tree depth limits
1850
+ // Use smaller batches for OR queries (50 for SQLite, 100 for others)
1851
+ const batchSize = getBatchSize(trx, 50);
1852
+ const relationChunks = chunkArray(deduplicatedRelations, batchSize);
1853
+ const existingKeys = new Set();
1854
+ for (const relationChunk of relationChunks){
1855
+ const existingRelations = await trx(joinTableName).select([
1856
+ entityIdColumn,
1857
+ componentIdColumn,
1858
+ fieldColumn,
1859
+ componentTypeColumn
1860
+ ]).where((qb)=>{
1861
+ // Build OR conditions for each relation in this chunk
1862
+ for (const relation of relationChunk){
1863
+ qb.orWhere((subQb)=>{
1864
+ subQb.where(entityIdColumn, relation[entityIdColumn]).where(componentIdColumn, relation[componentIdColumn]).where(fieldColumn, relation[fieldColumn]).where(componentTypeColumn, relation[componentTypeColumn]);
1865
+ });
1866
+ }
1867
+ });
1868
+ // Add existing relation keys to the set
1869
+ for (const existing of existingRelations){
1870
+ const key = `${existing[entityIdColumn]}_${existing[componentIdColumn]}_${existing[fieldColumn]}_${existing[componentTypeColumn]}`;
1871
+ existingKeys.add(key);
1872
+ }
1873
+ }
1874
+ // Filter out relations that already exist
1875
+ const newComponentRelations = deduplicatedRelations.filter((relation)=>{
1876
+ const key = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
1877
+ return !existingKeys.has(key);
1878
+ });
1879
+ if (newComponentRelations.length > 0) {
1880
+ // Insert component relations with PostgreSQL-specific ON CONFLICT handling
1881
+ // Component relations use a different conflict resolution than regular relations
1882
+ const client = trx.client.config.client;
1883
+ if (client === 'postgres' || client === 'pg') {
1884
+ // PostgreSQL: Batch insert with ON CONFLICT DO NOTHING for better throughput.
1885
+ const relationChunks = chunkArray(newComponentRelations, getBatchSize(trx, 500));
1886
+ let insertedCount = 0;
1887
+ for (const relationChunk of relationChunks){
1888
+ await trx(joinTableName).insert(relationChunk).onConflict([
1889
+ entityIdColumn,
1890
+ componentIdColumn,
1891
+ fieldColumn,
1892
+ componentTypeColumn
1893
+ ]).ignore();
1894
+ insertedCount += relationChunk.length;
1895
+ }
1896
+ if (insertedCount > 0) {
1897
+ debug(`[copyComponentRelations] ${uid}: Attempted to insert ${insertedCount} component relations (duplicates ignored)`);
1898
+ }
1899
+ } else {
1900
+ // MySQL and SQLite: use standard insert with duplicate handling
1901
+ await insertRelationsWithDuplicateHandling({
1902
+ trx,
1903
+ tableName: joinTableName,
1904
+ relations: newComponentRelations,
1905
+ context: {
1906
+ reason: 'component-relation-insert',
1907
+ sourceUid: uid
1908
+ }
1909
+ });
87
1910
  }
88
- }).limit(batchSize).offset(offset).orderBy('id').transacting(trx).execute();
89
- if (batch.length < batchSize) {
90
- hasMore = false;
91
1911
  }
92
- offset += batchSize;
93
- yield batch;
94
1912
  }
95
1913
  }
96
1914
  /**
97
1915
  * 2 pass migration to create the draft entries for all the published entries.
98
- * And then discard the drafts to copy the relations.
1916
+ * And then copy relations directly using database queries.
99
1917
  */ const migrateUp = async (trx, db)=>{
1918
+ strapi.log.info('[discard-drafts] Migration started');
100
1919
  const dpModels = [];
101
- for (const meta of Array.from(db.metadata.values())){
1920
+ for (const meta of db.metadata.values()){
102
1921
  const hasDP = await hasDraftAndPublish(trx, meta);
103
1922
  if (hasDP) {
104
1923
  dpModels.push(meta);
105
1924
  }
106
1925
  }
1926
+ debug(`Found ${dpModels.length} draft/publish content types to process`);
107
1927
  /**
108
1928
  * Create plain draft entries for all the entries that were published.
109
- */ for (const model of dpModels){
1929
+ */ strapi.log.info('[discard-drafts] Stage 1/5 – cloning published entries into draft rows');
1930
+ for (const model of dpModels){
1931
+ debug(` • cloning scalars for ${model.uid}`);
110
1932
  await copyPublishedEntriesToDraft({
111
1933
  db,
112
1934
  trx,
113
1935
  uid: model.uid
114
1936
  });
115
1937
  }
1938
+ strapi.log.info('[discard-drafts] Stage 1/5 complete');
116
1939
  /**
117
- * Discard the drafts will copy the relations from the published entries to the newly created drafts.
118
- *
119
- * Load a batch of entries (batched to prevent loading millions of rows at once ),
120
- * and discard them using the document service.
121
- *
122
- * NOTE: This is using a custom document service without any validations,
123
- * to prevent the migration from failing if users already had invalid data in V4.
124
- * E.g. @see https://github.com/strapi/strapi/issues/21583
125
- */ const documentService = createDocumentService(strapi, {
126
- async validateEntityCreation (_, data) {
127
- return data;
128
- },
129
- async validateEntityUpdate (_, data) {
130
- // Data can be partially empty on partial updates
131
- // This migration doesn't trigger any update (or partial update),
132
- // so it's safe to return the data as is.
133
- return data;
134
- }
135
- });
1940
+ * Copy relations from published entries to draft entries using direct database queries.
1941
+ * This is much more efficient than calling discardDraft for each entry.
1942
+ */ strapi.log.info('[discard-drafts] Stage 2/5 copying relations and components to drafts');
136
1943
  for (const model of dpModels){
137
- const discardDraft = async (entry)=>documentService(model.uid).discardDraft({
138
- documentId: entry.documentId,
139
- locale: entry.locale
140
- });
141
- for await (const batch of getBatchToDiscard({
1944
+ debug(` copying relations for ${model.uid}`);
1945
+ await copyRelationsToDrafts({
142
1946
  db,
143
1947
  trx,
144
1948
  uid: model.uid
145
- })){
146
- // NOTE: concurrency had to be disabled to prevent a race condition with self-references
147
- // TODO: improve performance in a safe way
148
- await async.map(batch, discardDraft, {
149
- concurrency: 1
150
- });
151
- }
1949
+ });
1950
+ }
1951
+ flushSkippedRelationLogs();
1952
+ strapi.log.info('[discard-drafts] Stage 2/5 complete');
1953
+ /**
1954
+ * Fix existing v4 draft entries' join table relations to ensure they point to draft targets.
1955
+ * In v4, draft entries might have had relations pointing to published targets. These need
1956
+ * to be converted to point to the draft versions of those targets.
1957
+ */ strapi.log.info('[discard-drafts] Stage 3/5 – fixing existing draft relations');
1958
+ for (const model of dpModels){
1959
+ debug(` • fixing existing draft relations for ${model.uid}`);
1960
+ await fixExistingDraftRelations({
1961
+ trx,
1962
+ uid: model.uid
1963
+ });
1964
+ }
1965
+ strapi.log.info('[discard-drafts] Stage 3/5 complete');
1966
+ /**
1967
+ * Fix existing v4 draft entries' component relations to ensure they point to draft targets.
1968
+ * In v4, draft entries might have had components pointing to published targets. These need
1969
+ * to be converted to point to the draft versions of those targets.
1970
+ */ strapi.log.info('[discard-drafts] Stage 4/5 – fixing existing draft component relations');
1971
+ for (const model of dpModels){
1972
+ debug(` • fixing existing draft component relations for ${model.uid}`);
1973
+ await fixExistingDraftComponentRelations({
1974
+ trx,
1975
+ uid: model.uid
1976
+ });
152
1977
  }
1978
+ strapi.log.info('[discard-drafts] Stage 4/5 complete');
1979
+ /**
1980
+ * Update JoinColumn relations (foreign keys) to point to draft versions
1981
+ * This matches discard() behavior: drafts relate to drafts
1982
+ */ strapi.log.info('[discard-drafts] Stage 5/5 – updating foreign key references to draft targets');
1983
+ for (const model of dpModels){
1984
+ debug(` • updating join columns for ${model.uid}`);
1985
+ await updateJoinColumnRelations({
1986
+ db,
1987
+ trx,
1988
+ uid: model.uid
1989
+ });
1990
+ }
1991
+ strapi.log.info('[discard-drafts] Stage 5/5 complete');
1992
+ strapi.log.info('[discard-drafts] Migration completed successfully');
153
1993
  };
1994
+ /**
1995
+ * Load a batch of versions to discard.
1996
+ *
1997
+ * Versions with only a draft version will be ignored.
1998
+ * Only versions with a published version (which always have a draft version) will be discarded.
1999
+ */ async function* getBatchToDiscard({ db, trx, uid, defaultBatchSize = 1000 }) {
2000
+ const client = db.config.connection.client;
2001
+ const isSQLite = typeof client === 'string' && [
2002
+ 'sqlite',
2003
+ 'sqlite3',
2004
+ 'better-sqlite3'
2005
+ ].includes(client);
2006
+ // The SQLite documentation states that the maximum number of terms in a
2007
+ // compound SELECT statement is 500 by default.
2008
+ // See: https://www.sqlite.org/limits.html
2009
+ // To ensure a successful migration, we limit the batch size to 500 for SQLite.
2010
+ const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;
2011
+ let offset = 0;
2012
+ let hasMore = true;
2013
+ while(hasMore){
2014
+ // Look for the published entries to discard
2015
+ const batch = await db.queryBuilder(uid).select([
2016
+ 'id',
2017
+ 'documentId',
2018
+ 'locale'
2019
+ ]).where({
2020
+ publishedAt: {
2021
+ $ne: null
2022
+ }
2023
+ }).limit(batchSize).offset(offset).orderBy('id').transacting(trx).execute();
2024
+ if (batch.length < batchSize) {
2025
+ hasMore = false;
2026
+ }
2027
+ offset += batchSize;
2028
+ yield batch;
2029
+ }
2030
+ }
154
2031
  const discardDocumentDrafts = {
155
2032
  name: 'core::5.0.0-discard-drafts',
156
2033
  async up (trx, db) {