@strapi/core 5.36.0 → 5.37.0

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