@strapi/core 5.31.0 → 5.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,46 +99,1417 @@ 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
+ * Chooses a safe batch size for bulk operations depending on the database engine,
156
+ * falling back to smaller units on engines (notably SQLite) that have low limits.
157
+ */ function getBatchSize(trx, defaultSize = 1000) {
158
+ const client = trx.client.config.client;
68
159
  const isSQLite = typeof client === 'string' && [
69
160
  'sqlite',
70
161
  'sqlite3',
71
162
  'better-sqlite3'
72
163
  ].includes(client);
73
- // The SQLite documentation states that the maximum number of terms in a
164
+ // SQLite documentation states that the maximum number of terms in a
74
165
  // compound SELECT statement is 500 by default.
75
166
  // 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([
167
+ // We use 250 to be safe and account for other query complexity.
168
+ return isSQLite ? Math.min(defaultSize, 250) : defaultSize;
169
+ }
170
+ /**
171
+ * Applies stable ordering to join-table queries so cloning work is deterministic and
172
+ * matches the ordering logic used by the entity service (important for tests and DZ order).
173
+ */ const applyJoinTableOrdering = (qb, joinTable, sourceColumnName)=>{
174
+ const seenColumns = new Set();
175
+ const enqueueColumn = (column, direction = 'asc')=>{
176
+ if (!column || seenColumns.has(column)) {
177
+ return;
178
+ }
179
+ seenColumns.add(column);
180
+ qb.orderBy(column, direction);
181
+ };
182
+ enqueueColumn(sourceColumnName, 'asc');
183
+ if (Array.isArray(joinTable?.orderBy)) {
184
+ for (const clause of joinTable.orderBy){
185
+ if (!clause || typeof clause !== 'object') {
186
+ continue;
187
+ }
188
+ const [column, direction] = Object.entries(clause)[0] ?? [];
189
+ if (!column) {
190
+ continue;
191
+ }
192
+ const normalizedDirection = typeof direction === 'string' && direction.toLowerCase() === 'desc' ? 'desc' : 'asc';
193
+ enqueueColumn(column, normalizedDirection);
194
+ }
195
+ }
196
+ enqueueColumn(joinTable?.orderColumnName, 'asc');
197
+ enqueueColumn(joinTable?.orderColumn, 'asc');
198
+ enqueueColumn('id', 'asc');
199
+ };
200
+ /**
201
+ * Builds a stable key for join-table relations to detect duplicates.
202
+ * Key format: sourceId::targetId::field::componentType
203
+ */ const buildRelationKey = (relation, sourceColumnName, targetId)=>{
204
+ const sourceId = normalizeId(relation[sourceColumnName]) ?? relation[sourceColumnName];
205
+ const fieldValue = 'field' in relation ? relation.field ?? '' : '';
206
+ const componentTypeValue = 'component_type' in relation ? relation.component_type ?? '' : '';
207
+ return `${sourceId ?? 'null'}::${targetId ?? 'null'}::${fieldValue}::${componentTypeValue}`;
208
+ };
209
+ /**
210
+ * Queries existing relations from a join table and builds a set of keys for duplicate detection.
211
+ */ async function getExistingRelationKeys({ trx, joinTable, sourceColumnName, targetColumnName, sourceIds }) {
212
+ const existingKeys = new Set();
213
+ if (sourceIds.length === 0) {
214
+ return existingKeys;
215
+ }
216
+ const idChunks = chunkArray(sourceIds, getBatchSize(trx, 1000));
217
+ for (const chunk of idChunks){
218
+ const existingRelationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, chunk);
219
+ applyJoinTableOrdering(existingRelationsQuery, joinTable, sourceColumnName);
220
+ const existingRelations = await existingRelationsQuery;
221
+ for (const relation of existingRelations){
222
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
223
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
224
+ existingKeys.add(key);
225
+ }
226
+ }
227
+ return existingKeys;
228
+ }
229
+ /**
230
+ * Inserts relations into a join table with database-specific duplicate handling.
231
+ * Tries batch insert first, then falls back to individual inserts with conflict handling.
232
+ */ async function insertRelationsWithDuplicateHandling({ trx, tableName, relations, context = {} }) {
233
+ if (relations.length === 0) {
234
+ return;
235
+ }
236
+ try {
237
+ await trx.batchInsert(tableName, relations, getBatchSize(trx, 1000));
238
+ } catch (error) {
239
+ // If batch insert fails due to duplicates, try with conflict handling
240
+ if (!isDuplicateEntryError(error)) {
241
+ throw error;
242
+ }
243
+ const client = trx.client.config.client;
244
+ if (client === 'postgres' || client === 'pg') {
245
+ for (const relation of relations){
246
+ try {
247
+ await trx(tableName).insert(relation).onConflict().ignore();
248
+ } catch (err) {
249
+ if (err.code !== '23505' && !err.message?.includes('duplicate key')) {
250
+ throw err;
251
+ }
252
+ }
253
+ }
254
+ } else {
255
+ // MySQL and SQLite: use insertRowWithDuplicateHandling
256
+ for (const relation of relations){
257
+ await insertRowWithDuplicateHandling(trx, tableName, relation, context);
258
+ }
259
+ }
260
+ }
261
+ }
262
+ const componentParentSchemasCache = new Map();
263
+ const joinTableExistsCache = new Map();
264
+ const componentMetaCache = new Map();
265
+ const SKIPPED_RELATION_SAMPLE_LIMIT = 5;
266
+ const supportsReturning = (trx)=>{
267
+ const client = trx.client.config.client;
268
+ if (typeof client !== 'string') {
269
+ return false;
270
+ }
271
+ return [
272
+ 'postgres',
273
+ 'pg'
274
+ ].includes(client.toLowerCase());
275
+ };
276
+ const skippedRelationStats = new Map();
277
+ const DUPLICATE_ERROR_CODES = new Set([
278
+ '23505',
279
+ 'ER_DUP_ENTRY',
280
+ 'SQLITE_CONSTRAINT_UNIQUE'
281
+ ]);
282
+ const debug = createDebug('strapi::migration::discard-drafts');
283
+ /**
284
+ * Converts arbitrary id values into numbers when possible so we can safely index into
285
+ * mapping tables without worrying about string/number mismatches.
286
+ */ const normalizeId = (value)=>{
287
+ if (value == null) {
288
+ return null;
289
+ }
290
+ const num = Number(value);
291
+ if (Number.isNaN(num)) {
292
+ return null;
293
+ }
294
+ return num;
295
+ };
296
+ /**
297
+ * Wrapper around map lookups that first normalizes the provided identifier.
298
+ */ const getMappedValue = (map, key)=>{
299
+ if (!map) {
300
+ return undefined;
301
+ }
302
+ const normalized = normalizeId(key);
303
+ if (normalized == null) {
304
+ return undefined;
305
+ }
306
+ return map.get(normalized);
307
+ };
308
+ /**
309
+ * Extracts the inserted row identifier across the various shapes returned by different
310
+ * clients/drivers (numbers, objects, arrays). Falls back to `null` if nothing usable.
311
+ */ const resolveInsertedId = (insertResult)=>{
312
+ if (insertResult == null) {
313
+ return null;
314
+ }
315
+ if (typeof insertResult === 'number') {
316
+ return insertResult;
317
+ }
318
+ if (Array.isArray(insertResult)) {
319
+ if (insertResult.length === 0) {
320
+ return null;
321
+ }
322
+ const first = insertResult[0];
323
+ if (first == null) {
324
+ return null;
325
+ }
326
+ if (typeof first === 'number') {
327
+ return first;
328
+ }
329
+ if (typeof first === 'object') {
330
+ if ('id' in first) {
331
+ return Number(first.id);
332
+ }
333
+ const idKey = Object.keys(first).find((key)=>key.toLowerCase() === 'id');
334
+ if (idKey) {
335
+ return Number(first[idKey]);
336
+ }
337
+ }
338
+ }
339
+ if (typeof insertResult === 'object' && 'id' in insertResult) {
340
+ return Number(insertResult.id);
341
+ }
342
+ return null;
343
+ };
344
+ /**
345
+ * Detects vendor-specific duplicate key errors so we can safely ignore them when our
346
+ * goal is to insert-or-ignore without branching on the client everywhere.
347
+ */ const isDuplicateEntryError = (error)=>{
348
+ if (!error) {
349
+ return false;
350
+ }
351
+ if (DUPLICATE_ERROR_CODES.has(error.code)) {
352
+ return true;
353
+ }
354
+ const message = typeof error.message === 'string' ? error.message : '';
355
+ return message.includes('duplicate key') || message.includes('UNIQUE constraint failed');
356
+ };
357
+ /**
358
+ * Inserts a row while tolerating duplicates across all supported clients. Used when
359
+ * bulk operations fall back to single inserts to resolve constraint conflicts.
360
+ */ const insertRowWithDuplicateHandling = async (trx, tableName, row, context = {})=>{
361
+ try {
362
+ const client = trx.client.config.client;
363
+ if (client === 'postgres' || client === 'pg' || client === 'sqlite3' || client === 'better-sqlite3') {
364
+ await trx(tableName).insert(row).onConflict().ignore();
365
+ return;
366
+ }
367
+ if (client === 'mysql' || client === 'mysql2') {
368
+ await trx.raw(`INSERT IGNORE INTO ?? SET ?`, [
369
+ tableName,
370
+ row
371
+ ]);
372
+ return;
373
+ }
374
+ await trx(tableName).insert(row);
375
+ } catch (error) {
376
+ if (!isDuplicateEntryError(error)) {
377
+ const details = JSON.stringify(context);
378
+ const wrapped = new Error(`Failed to insert row into ${tableName}: ${error.message} | context=${details}`);
379
+ wrapped.cause = error;
380
+ throw wrapped;
381
+ }
382
+ }
383
+ };
384
+ /**
385
+ * Normalizes identifiers into a comparable string so we can dedupe target ids
386
+ * regardless of whether they come in as numbers, strings, or objects.
387
+ */ const toComparisonKey = (value)=>{
388
+ if (value === null || value === undefined) {
389
+ return 'null';
390
+ }
391
+ if (typeof value === 'object') {
392
+ try {
393
+ return JSON.stringify(value);
394
+ } catch {
395
+ return String(value);
396
+ }
397
+ }
398
+ return String(value);
399
+ };
400
+ /**
401
+ * Formats ids for log output while keeping the log lightweight and JSON-safe.
402
+ */ const toDisplayValue = (value)=>{
403
+ if (value === null || value === undefined) {
404
+ return 'null';
405
+ }
406
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint') {
407
+ return String(value);
408
+ }
409
+ try {
410
+ return JSON.stringify(value);
411
+ } catch {
412
+ return String(value);
413
+ }
414
+ };
415
+ /**
416
+ * Tracks how many relation rows we skipped because their targets are missing, so we
417
+ * can emit a consolidated warning once the migration finishes copying relations.
418
+ */ function recordSkippedRelations(context, skippedIds) {
419
+ if (!skippedIds.length) {
420
+ return;
421
+ }
422
+ const key = `${context.sourceUid}::${context.attributeName}::${context.joinTable ?? 'NO_JOIN_TABLE'}`;
423
+ let stats = skippedRelationStats.get(key);
424
+ if (!stats) {
425
+ stats = {
426
+ ...context,
427
+ count: 0,
428
+ samples: new Set()
429
+ };
430
+ }
431
+ stats.count += skippedIds.length;
432
+ for (const id of skippedIds){
433
+ if (stats.samples.size >= SKIPPED_RELATION_SAMPLE_LIMIT) {
434
+ break;
435
+ }
436
+ stats.samples.add(toDisplayValue(id));
437
+ }
438
+ skippedRelationStats.set(key, stats);
439
+ }
440
+ /**
441
+ * Emits aggregated warnings for all skipped relations and resets the counters.
442
+ * This keeps the log readable even when millions of orphaned rows exist.
443
+ */ function flushSkippedRelationLogs() {
444
+ if (skippedRelationStats.size === 0) {
445
+ return;
446
+ }
447
+ for (const stats of skippedRelationStats.values()){
448
+ const sampleArray = Array.from(stats.samples);
449
+ const sampleText = sampleArray.length > 0 ? sampleArray.join(', ') : 'n/a';
450
+ const targetInfo = stats.targetUid ? `target=${stats.targetUid}` : 'target=unknown';
451
+ const joinTableInfo = stats.joinTable ? `joinTable=${stats.joinTable}` : 'joinTable=n/a';
452
+ const ellipsis = stats.count > sampleArray.length ? ', ...' : '';
453
+ strapi.log.warn(`[discard-drafts] Skipped ${stats.count} relation(s) for ${stats.sourceUid}.${stats.attributeName} (${targetInfo}, ${joinTableInfo}). Example target ids: ${sampleText}${ellipsis}`);
454
+ }
455
+ 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.');
456
+ skippedRelationStats.clear();
457
+ }
458
+ /**
459
+ * Returns every schema (content type or component) that can embed the provided component.
460
+ * Cached because we consult it repeatedly while remapping nested components.
461
+ */ function listComponentParentSchemas(componentUid) {
462
+ if (!componentParentSchemasCache.has(componentUid)) {
463
+ const schemas = [
464
+ ...Object.values(strapi.contentTypes),
465
+ ...Object.values(strapi.components)
466
+ ];
467
+ const parents = schemas.filter((schema)=>{
468
+ if (!schema?.attributes) {
469
+ return false;
470
+ }
471
+ return Object.values(schema.attributes).some((attr)=>{
472
+ if (attr.type === 'component') {
473
+ return attr.component === componentUid;
474
+ }
475
+ if (attr.type === 'dynamiczone') {
476
+ return attr.components?.includes(componentUid);
477
+ }
478
+ return false;
479
+ });
480
+ }).map((schema)=>({
481
+ uid: schema.uid,
482
+ collectionName: schema.collectionName
483
+ }));
484
+ componentParentSchemasCache.set(componentUid, parents);
485
+ }
486
+ return componentParentSchemasCache.get(componentUid);
487
+ }
488
+ /**
489
+ * Memoized helper for checking whether a table exists. Avoids repeating expensive
490
+ * information_schema queries when we touch the same join table many times.
491
+ */ async function ensureTableExists(trx, tableName) {
492
+ if (!joinTableExistsCache.has(tableName)) {
493
+ const exists = await trx.schema.hasTable(tableName);
494
+ joinTableExistsCache.set(tableName, exists);
495
+ }
496
+ return joinTableExistsCache.get(tableName);
497
+ }
498
+ /**
499
+ * Filters out relation rows whose target entity no longer exists, returning the safe
500
+ * rows along with a list of skipped ids so we can log them later.
501
+ */ async function filterRelationsWithExistingTargets({ trx, targetUid, relations, getTargetId }) {
502
+ if (!relations.length) {
503
+ return {
504
+ relations,
505
+ skippedIds: []
506
+ };
507
+ }
508
+ if (!targetUid) {
509
+ return {
510
+ relations,
511
+ skippedIds: []
512
+ };
513
+ }
514
+ const targetMeta = strapi.db.metadata.get(targetUid);
515
+ if (!targetMeta) {
516
+ return {
517
+ relations,
518
+ skippedIds: []
519
+ };
520
+ }
521
+ const tableName = targetMeta.tableName;
522
+ const primaryKeyColumn = resolvePrimaryKeyColumn(targetMeta);
523
+ if (!tableName) {
524
+ return {
525
+ relations,
526
+ skippedIds: []
527
+ };
528
+ }
529
+ const uniqueIdMap = new Map();
530
+ for (const relation of relations){
531
+ const targetId = getTargetId(relation);
532
+ if (targetId == null) {
533
+ continue;
534
+ }
535
+ const key = toComparisonKey(targetId);
536
+ if (!uniqueIdMap.has(key)) {
537
+ uniqueIdMap.set(key, targetId);
538
+ }
539
+ }
540
+ if (uniqueIdMap.size === 0) {
541
+ return {
542
+ relations,
543
+ skippedIds: []
544
+ };
545
+ }
546
+ const hasTable = await ensureTableExists(trx, tableName);
547
+ if (!hasTable) {
548
+ return {
549
+ relations: [],
550
+ skippedIds: Array.from(uniqueIdMap.values())
551
+ };
552
+ }
553
+ const existingKeys = new Set();
554
+ const uniqueIds = Array.from(uniqueIdMap.values());
555
+ const idChunks = chunkArray(uniqueIds, getBatchSize(trx, 1000));
556
+ for (const chunk of idChunks){
557
+ const rows = await trx(tableName).select(primaryKeyColumn).whereIn(primaryKeyColumn, chunk);
558
+ for (const row of rows){
559
+ const value = row[primaryKeyColumn];
560
+ existingKeys.add(toComparisonKey(value));
561
+ }
562
+ }
563
+ const filteredRelations = [];
564
+ const skippedIds = [];
565
+ for (const relation of relations){
566
+ const targetId = getTargetId(relation);
567
+ if (targetId == null) {
568
+ skippedIds.push(targetId);
569
+ continue;
570
+ }
571
+ if (existingKeys.has(toComparisonKey(targetId))) {
572
+ filteredRelations.push(relation);
573
+ } else {
574
+ skippedIds.push(targetId);
575
+ }
576
+ }
577
+ return {
578
+ relations: filteredRelations,
579
+ skippedIds
580
+ };
581
+ }
582
+ /**
583
+ * Locates the owning entity (content type or component) for a given component instance.
584
+ * This mirrors the document service logic we need in order to decide whether a relation
585
+ * should propagate to drafts, and is cached for performance.
586
+ */ async function findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches) {
587
+ const cacheKey = `${componentUid}:${componentId}:${excludeUid ?? 'ALL'}`;
588
+ if (caches.parentInstanceCache.has(cacheKey)) {
589
+ return caches.parentInstanceCache.get(cacheKey);
590
+ }
591
+ const parentComponentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
592
+ const parentComponentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
593
+ const parentEntityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
594
+ const potentialParents = listComponentParentSchemas(componentUid).filter((schema)=>schema.uid !== excludeUid);
595
+ for (const parentSchema of potentialParents){
596
+ if (!parentSchema.collectionName) {
597
+ continue;
598
+ }
599
+ const parentJoinTableName = transformContentTypesToModels.getComponentJoinTableName(parentSchema.collectionName, identifiers);
600
+ try {
601
+ if (!await ensureTableExists(trx, parentJoinTableName)) {
602
+ continue;
603
+ }
604
+ const parentRow = await trx(parentJoinTableName).where({
605
+ [parentComponentIdColumn]: componentId,
606
+ [parentComponentTypeColumn]: componentUid
607
+ }).first(parentEntityIdColumn);
608
+ if (parentRow) {
609
+ const parentInstance = {
610
+ uid: parentSchema.uid,
611
+ parentId: parentRow[parentEntityIdColumn]
612
+ };
613
+ caches.parentInstanceCache.set(cacheKey, parentInstance);
614
+ return parentInstance;
615
+ }
616
+ } catch {
617
+ continue;
618
+ }
619
+ }
620
+ caches.parentInstanceCache.set(cacheKey, null);
621
+ return null;
622
+ }
623
+ /**
624
+ * Fetches and caches database metadata for a component uid. Saves repeated lookups while
625
+ * cloning the same component type thousands of times.
626
+ */ const getComponentMeta = (componentUid)=>{
627
+ if (!componentMetaCache.has(componentUid)) {
628
+ const meta = strapi.db.metadata.get(componentUid);
629
+ componentMetaCache.set(componentUid, meta ?? null);
630
+ }
631
+ return componentMetaCache.get(componentUid);
632
+ };
633
+ /**
634
+ * Determines whether a component's parent entity participates in draft/publish,
635
+ * short-circuiting a lot of recursion when deciding relation propagation rules.
636
+ */ async function hasDraftPublishAncestorForParent(trx, identifiers, parent, caches) {
637
+ const cacheKey = `${parent.uid}:${parent.parentId}`;
638
+ if (caches.parentDpCache.has(cacheKey)) {
639
+ return caches.parentDpCache.get(cacheKey);
640
+ }
641
+ const parentContentType = strapi.contentTypes[parent.uid];
642
+ if (parentContentType) {
643
+ const result = !!parentContentType?.options?.draftAndPublish;
644
+ caches.parentDpCache.set(cacheKey, result);
645
+ return result;
646
+ }
647
+ const parentComponent = strapi.components[parent.uid];
648
+ if (!parentComponent) {
649
+ caches.parentDpCache.set(cacheKey, false);
650
+ return false;
651
+ }
652
+ const result = await hasDraftPublishAncestorForComponent(trx, identifiers, parent.uid, parent.parentId, undefined, caches);
653
+ caches.parentDpCache.set(cacheKey, result);
654
+ return result;
655
+ }
656
+ /**
657
+ * Recursively checks whether a component lies beneath a draft/publish-enabled parent
658
+ * component or content type. We mirror discardDraft's propagation guard.
659
+ */ async function hasDraftPublishAncestorForComponent(trx, identifiers, componentUid, componentId, excludeUid, caches) {
660
+ const cacheKey = `${componentUid}:${componentId}:${'ALL'}`;
661
+ if (caches.ancestorDpCache.has(cacheKey)) {
662
+ return caches.ancestorDpCache.get(cacheKey);
663
+ }
664
+ const parent = await findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches);
665
+ if (!parent) {
666
+ caches.ancestorDpCache.set(cacheKey, false);
667
+ return false;
668
+ }
669
+ const result = await hasDraftPublishAncestorForParent(trx, identifiers, parent, caches);
670
+ caches.ancestorDpCache.set(cacheKey, result);
671
+ return result;
672
+ }
673
+ /**
674
+ * Abstracts `NOW()` handling so that timestamps stay consistent across databases—
675
+ * using Knex's native function when available and falling back to JS dates otherwise.
676
+ */ const resolveNowValue = (trx)=>{
677
+ if (typeof trx.fn?.now === 'function') {
678
+ return trx.fn.now();
679
+ }
680
+ return new Date();
681
+ };
682
+ /**
683
+ * Builds or retrieves the published→draft id map for a target content type, caching
684
+ * the result so nested relation remapping can reuse the work.
685
+ */ async function getDraftMapForTarget(trx, targetUid, draftMapCache) {
686
+ if (draftMapCache.has(targetUid)) {
687
+ return draftMapCache.get(targetUid) ?? null;
688
+ }
689
+ const targetMeta = strapi.db.metadata.get(targetUid);
690
+ if (!targetMeta) {
691
+ draftMapCache.set(targetUid, null);
692
+ return null;
693
+ }
694
+ const map = await buildPublishedToDraftMap({
695
+ trx,
696
+ uid: targetUid,
697
+ meta: targetMeta,
698
+ options: {
699
+ requireDraftAndPublish: true
700
+ }
701
+ });
702
+ draftMapCache.set(targetUid, map ?? null);
703
+ return map ?? null;
704
+ }
705
+ /**
706
+ * Maps relation foreign keys so that draft entities reference draft targets when those
707
+ * targets exist; otherwise we preserve the original reference (matching discardDraft).
708
+ */ async function mapTargetId(trx, originalId, targetUid, parentUid, parentPublishedToDraftMap, draftMapCache) {
709
+ if (originalId == null || !targetUid) {
710
+ return originalId;
711
+ }
712
+ if (targetUid === parentUid) {
713
+ return parentPublishedToDraftMap.get(Number(originalId)) ?? originalId;
714
+ }
715
+ const targetMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
716
+ if (!targetMap) {
717
+ return originalId;
718
+ }
719
+ return targetMap.get(Number(originalId)) ?? originalId;
720
+ }
721
+ /**
722
+ * Clones a database row and strips the `id` column so it can be reinserted as a new row.
723
+ */ const ensureObjectWithoutId = (row)=>{
724
+ const cloned = {
725
+ ...row
726
+ };
727
+ if ('id' in cloned) {
728
+ delete cloned.id;
729
+ }
730
+ return cloned;
731
+ };
732
+ /**
733
+ * Duplicates join-table relations for a component instance while remapping any foreign
734
+ * keys to draft targets. Mirrors the runtime clone logic but operates entirely in SQL.
735
+ */ async function cloneComponentRelationJoinTables(trx, componentMeta, componentUid, originalComponentId, newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache) {
736
+ for (const [attributeName, attribute] of Object.entries(componentMeta.attributes)){
737
+ if (attribute.type !== 'relation' || !attribute.joinTable) {
738
+ continue;
739
+ }
740
+ const joinTable = attribute.joinTable;
741
+ const sourceColumnName = joinTable.joinColumn.name;
742
+ const targetColumnName = joinTable.inverseJoinColumn.name;
743
+ if (!componentMeta.relationsLogPrinted) {
744
+ debug(`[cloneComponentRelationJoinTables] Inspecting join table ${joinTable.name} for component ${componentUid}`);
745
+ componentMeta.relationsLogPrinted = true;
746
+ }
747
+ const relations = await trx(joinTable.name).select('*').where(sourceColumnName, originalComponentId);
748
+ if (relations.length === 0) {
749
+ continue;
750
+ }
751
+ const preparedRelations = [];
752
+ for (const relation of relations){
753
+ const clonedRelation = ensureObjectWithoutId(relation);
754
+ clonedRelation[sourceColumnName] = newComponentId;
755
+ if (targetColumnName in clonedRelation) {
756
+ const originalTargetId = clonedRelation[targetColumnName];
757
+ clonedRelation[targetColumnName] = await mapTargetId(trx, clonedRelation[targetColumnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache);
758
+ debug(`[cloneComponentRelationJoinTables] ${componentUid} join ${joinTable.name}: mapped ${targetColumnName} from ${originalTargetId} to ${clonedRelation[targetColumnName]} (target=${attribute.target})`);
759
+ }
760
+ preparedRelations.push(clonedRelation);
761
+ }
762
+ let relationsToInsert = preparedRelations;
763
+ if (preparedRelations.some((relation)=>targetColumnName in relation)) {
764
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
765
+ trx,
766
+ targetUid: attribute.target,
767
+ relations: preparedRelations,
768
+ getTargetId: (relation)=>relation[targetColumnName]
769
+ });
770
+ recordSkippedRelations({
771
+ sourceUid: componentUid,
772
+ attributeName,
773
+ targetUid: attribute.target,
774
+ joinTable: joinTable.name
775
+ }, skippedIds);
776
+ relationsToInsert = safeRelations;
777
+ }
778
+ if (relationsToInsert.length === 0) {
779
+ continue;
780
+ }
781
+ for (const relation of relationsToInsert){
782
+ debug(`[cloneComponentRelationJoinTables] inserting relation into ${joinTable.name} (component=${componentUid}, source=${relation[sourceColumnName]})`);
783
+ await insertRowWithDuplicateHandling(trx, joinTable.name, relation, {
784
+ componentUid,
785
+ originalComponentId,
786
+ newComponentId,
787
+ joinTable: joinTable.name,
788
+ sourceColumnName,
789
+ targetColumnName,
790
+ targetUid: attribute.target,
791
+ parentUid
792
+ });
793
+ }
794
+ }
795
+ }
796
+ /**
797
+ * Clones a component row (including nested relations) so the newly created draft entity
798
+ * owns its own copy, matching what the document service would have produced.
799
+ */ async function cloneComponentInstance({ trx, componentUid, componentId, parentUid, parentPublishedToDraftMap, draftMapCache }) {
800
+ const componentMeta = getComponentMeta(componentUid);
801
+ if (!componentMeta) {
802
+ return componentId;
803
+ }
804
+ const componentTableName = componentMeta.tableName;
805
+ const componentPrimaryKey = Number.isNaN(Number(componentId)) ? componentId : Number(componentId);
806
+ const componentRow = await trx(componentTableName).select('*').where('id', componentPrimaryKey).first();
807
+ if (!componentRow) {
808
+ return componentId;
809
+ }
810
+ const newComponentRow = ensureObjectWithoutId(componentRow);
811
+ // `document_id`, `created_at`, `updated_at` are Strapi system columns whose names remain stable across the
812
+ // identifier-shortening migration, so it’s safe to check them directly here.
813
+ if ('document_id' in newComponentRow) {
814
+ newComponentRow.document_id = cuid2.createId();
815
+ }
816
+ if ('updated_at' in newComponentRow) {
817
+ newComponentRow.updated_at = resolveNowValue(trx);
818
+ }
819
+ if ('created_at' in newComponentRow && newComponentRow.created_at == null) {
820
+ newComponentRow.created_at = resolveNowValue(trx);
821
+ }
822
+ for (const attribute of Object.values(componentMeta.attributes)){
823
+ if (attribute.type !== 'relation') {
824
+ continue;
825
+ }
826
+ const joinColumn = attribute.joinColumn;
827
+ if (!joinColumn) {
828
+ continue;
829
+ }
830
+ const columnName = joinColumn.name;
831
+ if (!columnName || !(columnName in newComponentRow)) {
832
+ continue;
833
+ }
834
+ newComponentRow[columnName] = await mapTargetId(trx, newComponentRow[columnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache);
835
+ }
836
+ let insertResult;
837
+ if (supportsReturning(trx)) {
838
+ try {
839
+ insertResult = await trx(componentTableName).insert(newComponentRow, [
840
+ 'id'
841
+ ]);
842
+ } catch (error) {
843
+ insertResult = await trx(componentTableName).insert(newComponentRow);
844
+ }
845
+ } else {
846
+ insertResult = await trx(componentTableName).insert(newComponentRow);
847
+ }
848
+ let newComponentId = resolveInsertedId(insertResult);
849
+ if (!newComponentId) {
850
+ if ('document_id' in newComponentRow && newComponentRow.document_id) {
851
+ const insertedRow = await trx(componentTableName).select('id').where('document_id', newComponentRow.document_id).orderBy('id', 'desc').first();
852
+ newComponentId = insertedRow?.id ?? null;
853
+ }
854
+ if (!newComponentId) {
855
+ const insertedRow = await trx(componentTableName).select('id').orderBy('id', 'desc').first();
856
+ newComponentId = insertedRow?.id ?? null;
857
+ }
858
+ }
859
+ if (!newComponentId) {
860
+ throw new Error(`Failed to clone component ${componentUid} (id: ${componentId})`);
861
+ }
862
+ newComponentId = Number(newComponentId);
863
+ if (Number.isNaN(newComponentId)) {
864
+ throw new Error(`Invalid cloned component identifier for ${componentUid} (id: ${componentId})`);
865
+ }
866
+ await cloneComponentRelationJoinTables(trx, componentMeta, componentUid, Number(componentPrimaryKey), newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache);
867
+ return newComponentId;
868
+ }
869
+ /**
870
+ * Generates a map between published row ids and their corresponding draft ids so we can
871
+ * rewire relations in bulk. Handles localization nuances and caches the newest draft.
872
+ */ async function buildPublishedToDraftMap({ trx, uid, meta, options = {} }) {
873
+ if (!meta) {
874
+ return null;
875
+ }
876
+ const model = strapi.getModel(uid);
877
+ const hasDraftAndPublishEnabled = strapiUtils.contentTypes.hasDraftAndPublish(model);
878
+ if (options.requireDraftAndPublish && !hasDraftAndPublishEnabled) {
879
+ return null;
880
+ }
881
+ const [publishedEntries, draftEntries] = await Promise.all([
882
+ // `document_id`, `locale`, and `published_at` are core columns that keep their exact names after the
883
+ // identifier-shortening migration, so selecting them by literal is safe.
884
+ trx(meta.tableName).select([
83
885
  'id',
84
- 'documentId',
886
+ 'document_id',
85
887
  'locale'
86
- ]).where({
87
- publishedAt: {
88
- $ne: null
888
+ ]).whereNotNull('published_at'),
889
+ trx(meta.tableName).select([
890
+ 'id',
891
+ 'document_id',
892
+ 'locale'
893
+ ]).whereNull('published_at')
894
+ ]);
895
+ if (publishedEntries.length === 0 || draftEntries.length === 0) {
896
+ return null;
897
+ }
898
+ const i18nService = strapi.plugin('i18n')?.service('content-types');
899
+ const contentType = strapi.contentTypes[uid];
900
+ const isLocalized = i18nService?.isLocalizedContentType(contentType) ?? false;
901
+ const draftByDocumentId = new Map();
902
+ for (const draft of draftEntries){
903
+ if (!draft.document_id) {
904
+ continue;
905
+ }
906
+ const key = isLocalized ? `${draft.document_id}:${draft.locale || ''}` : draft.document_id;
907
+ const existing = draftByDocumentId.get(key);
908
+ if (!existing) {
909
+ draftByDocumentId.set(key, draft);
910
+ continue;
911
+ }
912
+ const existingId = Number(existing.id);
913
+ const draftId = Number(draft.id);
914
+ if (Number.isNaN(existingId) || Number.isNaN(draftId)) {
915
+ draftByDocumentId.set(key, draft);
916
+ continue;
917
+ }
918
+ if (draftId > existingId) {
919
+ draftByDocumentId.set(key, draft);
920
+ }
921
+ }
922
+ const publishedToDraftMap = new Map();
923
+ for (const published of publishedEntries){
924
+ if (!published.document_id) {
925
+ continue;
926
+ }
927
+ const key = isLocalized ? `${published.document_id}:${published.locale || ''}` : published.document_id;
928
+ const draft = draftByDocumentId.get(key);
929
+ if (draft) {
930
+ const publishedId = normalizeId(published.id);
931
+ const draftId = normalizeId(draft.id);
932
+ if (publishedId == null || draftId == null) {
933
+ continue;
934
+ }
935
+ publishedToDraftMap.set(publishedId, draftId);
936
+ }
937
+ }
938
+ return publishedToDraftMap.size > 0 ? publishedToDraftMap : null;
939
+ }
940
+ /**
941
+ * Copy relations within the same content type (self-referential relations)
942
+ */ async function copyRelationsForContentType({ trx, uid, publishedToDraftMap }) {
943
+ const meta = strapi.db.metadata.get(uid);
944
+ if (!meta) return;
945
+ const publishedIds = Array.from(publishedToDraftMap.keys());
946
+ for (const attribute of Object.values(meta.attributes)){
947
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
948
+ continue;
949
+ }
950
+ const joinTable = attribute.joinTable;
951
+ if (!joinTable) {
952
+ continue;
953
+ }
954
+ // Skip component join tables - they are handled by copyComponentRelations
955
+ if (joinTable.name.includes('_cmps')) {
956
+ continue;
957
+ }
958
+ const { name: sourceColumnName } = joinTable.joinColumn;
959
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
960
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
961
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
962
+ for (const publishedIdsChunk of publishedIdsChunks){
963
+ // Get relations where the source is a published entry (in batches)
964
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
965
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
966
+ const relations = await relationsQuery;
967
+ if (relations.length === 0) {
968
+ continue;
969
+ }
970
+ // Create new relations pointing to draft entries
971
+ // Remove the 'id' field to avoid duplicate key errors
972
+ const newRelations = relations.map((relation)=>{
973
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
974
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
975
+ if (!newSourceId || !newTargetId) {
976
+ // Skip if no mapping found
977
+ return null;
978
+ }
979
+ // Create new relation object without the 'id' field
980
+ const { id, ...relationWithoutId } = relation;
981
+ return {
982
+ ...relationWithoutId,
983
+ [sourceColumnName]: newSourceId,
984
+ [targetColumnName]: newTargetId
985
+ };
986
+ }).filter(Boolean);
987
+ if (newRelations.length > 0) {
988
+ await trx.batchInsert(joinTable.name, newRelations, getBatchSize(trx, 1000));
989
+ }
990
+ }
991
+ }
992
+ }
993
+ /**
994
+ * Copy relations from other content types that target this content type
995
+ */ async function copyRelationsFromOtherContentTypes({ trx, uid, publishedToDraftMap }) {
996
+ const targetMeta = strapi.db.metadata.get(uid);
997
+ if (!targetMeta) {
998
+ return;
999
+ }
1000
+ const publishedTargetIds = Array.from(publishedToDraftMap.keys()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1001
+ if (publishedTargetIds.length === 0) {
1002
+ return;
1003
+ }
1004
+ const draftTargetIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1005
+ const models = [
1006
+ ...Object.values(strapi.contentTypes),
1007
+ ...Object.values(strapi.components)
1008
+ ];
1009
+ for (const model of models){
1010
+ const dbModel = strapi.db.metadata.get(model.uid);
1011
+ if (!dbModel) {
1012
+ continue;
1013
+ }
1014
+ const sourceHasDraftAndPublish = Boolean(model.options?.draftAndPublish);
1015
+ for (const attribute of Object.values(dbModel.attributes)){
1016
+ if (attribute.type !== 'relation' || attribute.target !== uid) {
1017
+ continue;
1018
+ }
1019
+ const joinTable = attribute.joinTable;
1020
+ if (!joinTable) {
1021
+ continue;
1022
+ }
1023
+ // Component join tables are handled separately when cloning components.
1024
+ if (joinTable.name.includes('_cmps')) {
1025
+ continue;
1026
+ }
1027
+ // If the source content type also has draft/publish, its own cloning routine will recreate its relations.
1028
+ if (sourceHasDraftAndPublish) {
1029
+ continue;
1030
+ }
1031
+ const { name: sourceColumnName } = joinTable.joinColumn;
1032
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1033
+ // Query existing relations by target IDs to avoid duplicates
1034
+ const existingKeys = await getExistingRelationKeys({
1035
+ trx,
1036
+ joinTable,
1037
+ sourceColumnName,
1038
+ targetColumnName,
1039
+ sourceIds: draftTargetIds
1040
+ });
1041
+ const publishedIdChunks = chunkArray(publishedTargetIds, getBatchSize(trx, 1000));
1042
+ for (const chunk of publishedIdChunks){
1043
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(targetColumnName, chunk);
1044
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1045
+ const relations = await relationsQuery;
1046
+ if (relations.length === 0) {
1047
+ continue;
1048
+ }
1049
+ const newRelations = [];
1050
+ for (const relation of relations){
1051
+ const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
1052
+ if (!newTargetId) {
1053
+ continue;
1054
+ }
1055
+ const key = buildRelationKey(relation, sourceColumnName, newTargetId);
1056
+ if (existingKeys.has(key)) {
1057
+ continue;
1058
+ }
1059
+ existingKeys.add(key);
1060
+ const { id, ...relationWithoutId } = relation;
1061
+ newRelations.push({
1062
+ ...relationWithoutId,
1063
+ [targetColumnName]: newTargetId
1064
+ });
1065
+ }
1066
+ if (newRelations.length === 0) {
1067
+ continue;
1068
+ }
1069
+ await insertRelationsWithDuplicateHandling({
1070
+ trx,
1071
+ tableName: joinTable.name,
1072
+ relations: newRelations,
1073
+ context: {
1074
+ reason: 'duplicate-draft-target-relation',
1075
+ sourceUid: model.uid,
1076
+ targetUid: uid
1077
+ }
1078
+ });
1079
+ }
1080
+ }
1081
+ }
1082
+ }
1083
+ /**
1084
+ * Copy relations from this content type that target other content types (category 3)
1085
+ * Example: Article -> Categories/Tags
1086
+ */ async function copyRelationsToOtherContentTypes({ trx, uid, publishedToDraftMap }) {
1087
+ const meta = strapi.db.metadata.get(uid);
1088
+ if (!meta) return;
1089
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1090
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1091
+ const targetMapCache = new Map();
1092
+ for (const [attributeName, attribute] of Object.entries(meta.attributes)){
1093
+ if (attribute.type !== 'relation' || attribute.target === uid) {
1094
+ continue;
1095
+ }
1096
+ const joinTable = attribute.joinTable;
1097
+ if (!joinTable) {
1098
+ continue;
1099
+ }
1100
+ // Skip component join tables - they are handled by copyComponentRelations
1101
+ if (joinTable.name.includes('_cmps')) {
1102
+ continue;
1103
+ }
1104
+ const { name: sourceColumnName } = joinTable.joinColumn;
1105
+ const { name: targetColumnName } = joinTable.inverseJoinColumn;
1106
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1107
+ const targetUid = attribute.target;
1108
+ if (!targetMapCache.has(targetUid)) {
1109
+ const targetMeta = strapi.db.metadata.get(targetUid);
1110
+ const targetMap = await buildPublishedToDraftMap({
1111
+ trx,
1112
+ uid: targetUid,
1113
+ meta: targetMeta,
1114
+ options: {
1115
+ requireDraftAndPublish: true
1116
+ }
1117
+ });
1118
+ targetMapCache.set(targetUid, targetMap);
1119
+ }
1120
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1121
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1122
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1123
+ for (const publishedIdsChunk of publishedIdsChunks){
1124
+ // Get relations where the source is a published entry of our content type (in batches)
1125
+ const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
1126
+ applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
1127
+ const relations = await relationsQuery;
1128
+ if (relations.length === 0) {
1129
+ continue;
1130
+ }
1131
+ // Create new relations pointing to draft entries
1132
+ // Remove the 'id' field to avoid duplicate key errors
1133
+ const newRelations = relations.map((relation)=>{
1134
+ const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
1135
+ if (!newSourceId) {
1136
+ return null;
1137
+ }
1138
+ // Map target ID to draft if target has draft/publish enabled
1139
+ // This matches discard() behavior: drafts relate to drafts
1140
+ let newTargetId = relation[targetColumnName];
1141
+ if (targetPublishedToDraftMap) {
1142
+ const mappedTargetId = getMappedValue(targetPublishedToDraftMap, relation[targetColumnName]);
1143
+ if (mappedTargetId) {
1144
+ newTargetId = mappedTargetId;
1145
+ }
1146
+ // If no draft mapping, keep published target (target might not have DP or was deleted)
1147
+ }
1148
+ // Create new relation object without the 'id' field
1149
+ const { id, ...relationWithoutId } = relation;
1150
+ return {
1151
+ ...relationWithoutId,
1152
+ [sourceColumnName]: newSourceId,
1153
+ [targetColumnName]: newTargetId
1154
+ };
1155
+ }).filter(Boolean);
1156
+ const { relations: safeRelations, skippedIds } = await filterRelationsWithExistingTargets({
1157
+ trx,
1158
+ targetUid,
1159
+ relations: newRelations,
1160
+ getTargetId: (relation)=>relation[targetColumnName]
1161
+ });
1162
+ recordSkippedRelations({
1163
+ sourceUid: uid,
1164
+ attributeName,
1165
+ targetUid,
1166
+ joinTable: joinTable.name
1167
+ }, skippedIds);
1168
+ if (safeRelations.length === 0) {
1169
+ continue;
1170
+ }
1171
+ // Check for existing relations to avoid duplicates (similar to copyRelationsFromOtherContentTypes)
1172
+ // This is important when the target doesn't have D&P, as copyRelationsFromOtherContentTypes
1173
+ // may have already created some relations
1174
+ const draftSourceIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
1175
+ const existingKeys = await getExistingRelationKeys({
1176
+ trx,
1177
+ joinTable,
1178
+ sourceColumnName,
1179
+ targetColumnName,
1180
+ sourceIds: draftSourceIds
1181
+ });
1182
+ // Filter out relations that already exist
1183
+ const relationsToInsert = safeRelations.filter((relation)=>{
1184
+ const targetId = normalizeId(relation[targetColumnName]) ?? relation[targetColumnName];
1185
+ const key = buildRelationKey(relation, sourceColumnName, targetId);
1186
+ return !existingKeys.has(key);
1187
+ });
1188
+ if (relationsToInsert.length > 0) {
1189
+ await insertRelationsWithDuplicateHandling({
1190
+ trx,
1191
+ tableName: joinTable.name,
1192
+ relations: relationsToInsert,
1193
+ context: {
1194
+ reason: 'duplicate-relation-check',
1195
+ sourceUid: uid,
1196
+ targetUid
1197
+ }
1198
+ });
1199
+ }
1200
+ }
1201
+ }
1202
+ }
1203
+ /**
1204
+ * Update JoinColumn relations (oneToOne, manyToOne foreign keys) to point to draft versions
1205
+ * This matches discard() behavior: when creating drafts, foreign keys should point to draft targets
1206
+ */ async function updateJoinColumnRelations({ db, trx, uid }) {
1207
+ const meta = db.metadata.get(uid);
1208
+ if (!meta) {
1209
+ return;
1210
+ }
1211
+ // Create mapping from published entry ID to draft entry ID
1212
+ const publishedToDraftMap = await buildPublishedToDraftMap({
1213
+ trx,
1214
+ uid,
1215
+ meta
1216
+ });
1217
+ if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
1218
+ return;
1219
+ }
1220
+ // Cache target publishedToDraftMap to avoid duplicate calls for same target
1221
+ const targetMapCache = new Map();
1222
+ // Find all JoinColumn relations (oneToOne, manyToOne without joinTable)
1223
+ for (const attribute of Object.values(meta.attributes)){
1224
+ if (attribute.type !== 'relation') {
1225
+ continue;
1226
+ }
1227
+ // Skip relations with joinTable (handled by copyRelationsToOtherContentTypes)
1228
+ if (attribute.joinTable) {
1229
+ continue;
1230
+ }
1231
+ // Only handle oneToOne and manyToOne relations that use joinColumn
1232
+ const joinColumn = attribute.joinColumn;
1233
+ if (!joinColumn) {
1234
+ continue;
1235
+ }
1236
+ const targetUid = attribute.target;
1237
+ const foreignKeyColumn = joinColumn.name;
1238
+ // Get target content type's publishedToDraftMap if it has draft/publish (cached)
1239
+ if (!targetMapCache.has(targetUid)) {
1240
+ const targetMeta = strapi.db.metadata.get(targetUid);
1241
+ const targetMap = await buildPublishedToDraftMap({
1242
+ trx,
1243
+ uid: targetUid,
1244
+ meta: targetMeta,
1245
+ options: {
1246
+ requireDraftAndPublish: true
1247
+ }
1248
+ });
1249
+ targetMapCache.set(targetUid, targetMap);
1250
+ }
1251
+ const targetPublishedToDraftMap = targetMapCache.get(targetUid);
1252
+ if (!targetPublishedToDraftMap) {
1253
+ continue;
1254
+ }
1255
+ const draftIds = Array.from(publishedToDraftMap.values());
1256
+ if (draftIds.length === 0) {
1257
+ continue;
1258
+ }
1259
+ const draftIdsChunks = chunkArray(draftIds, getBatchSize(trx, 1000));
1260
+ for (const draftIdsChunk of draftIdsChunks){
1261
+ // Get draft entries with their foreign key values
1262
+ const draftEntriesWithFk = await trx(meta.tableName).select([
1263
+ 'id',
1264
+ foreignKeyColumn
1265
+ ]).whereIn('id', draftIdsChunk).whereNotNull(foreignKeyColumn);
1266
+ const updates = draftEntriesWithFk.reduce((acc, draftEntry)=>{
1267
+ const publishedTargetIdRaw = draftEntry[foreignKeyColumn];
1268
+ const normalizedPublishedTargetId = normalizeId(publishedTargetIdRaw);
1269
+ const draftTargetId = normalizedPublishedTargetId == null ? undefined : targetPublishedToDraftMap.get(normalizedPublishedTargetId);
1270
+ if (draftTargetId != null && normalizeId(draftTargetId) !== normalizedPublishedTargetId) {
1271
+ acc.push({
1272
+ id: draftEntry.id,
1273
+ draftTargetId
1274
+ });
1275
+ }
1276
+ return acc;
1277
+ }, []);
1278
+ if (updates.length === 0) {
1279
+ continue;
1280
+ }
1281
+ const caseFragments = updates.map(()=>'WHEN ? THEN ?').join(' ');
1282
+ const idsPlaceholders = updates.map(()=>'?').join(', ');
1283
+ await trx.raw(`UPDATE ?? SET ?? = CASE ?? ${caseFragments} ELSE ?? END WHERE ?? IN (${idsPlaceholders})`, [
1284
+ meta.tableName,
1285
+ foreignKeyColumn,
1286
+ 'id',
1287
+ ...updates.flatMap(({ id, draftTargetId })=>[
1288
+ id,
1289
+ draftTargetId
1290
+ ]),
1291
+ foreignKeyColumn,
1292
+ 'id',
1293
+ ...updates.map(({ id })=>id)
1294
+ ]);
1295
+ }
1296
+ }
1297
+ }
1298
+ /**
1299
+ * Copy component relations from published entries to draft entries
1300
+ */ async function copyComponentRelations({ trx, uid, publishedToDraftMap }) {
1301
+ const meta = strapi.db.metadata.get(uid);
1302
+ if (!meta) {
1303
+ return;
1304
+ }
1305
+ // Get collectionName from content type schema (Meta only has tableName which may be shortened)
1306
+ const contentType = strapi.contentTypes[uid];
1307
+ const collectionName = contentType?.collectionName;
1308
+ if (!collectionName) {
1309
+ return;
1310
+ }
1311
+ const identifiers = strapi.db.metadata.identifiers;
1312
+ const joinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
1313
+ const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
1314
+ const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
1315
+ const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
1316
+ const fieldColumn = identifiers.FIELD_COLUMN;
1317
+ const orderColumn = identifiers.ORDER_COLUMN;
1318
+ // Check if component join table exists
1319
+ const hasTable = await trx.schema.hasTable(joinTableName);
1320
+ if (!hasTable) {
1321
+ return;
1322
+ }
1323
+ const publishedIds = Array.from(publishedToDraftMap.keys());
1324
+ // Process in batches to avoid MySQL query size limits and SQLite expression tree limits
1325
+ const publishedIdsChunks = chunkArray(publishedIds, getBatchSize(trx, 1000));
1326
+ for (const publishedIdsChunk of publishedIdsChunks){
1327
+ // Get component relations for published entries
1328
+ const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, publishedIdsChunk);
1329
+ if (componentRelations.length === 0) {
1330
+ continue;
1331
+ }
1332
+ const componentCloneCache = new Map();
1333
+ const componentTargetDraftMapCache = new Map();
1334
+ const componentHierarchyCaches = {
1335
+ parentInstanceCache: new Map(),
1336
+ ancestorDpCache: new Map(),
1337
+ parentDpCache: new Map()
1338
+ };
1339
+ // Filter component relations: only propagate if component's parent in the component hierarchy doesn't have draft/publish
1340
+ // This matches discardDraft() behavior via shouldPropagateComponentRelationToNewVersion
1341
+ //
1342
+ // The logic: find what contains this component instance (could be a content type or another component).
1343
+ // If it's a component, recursively check its parents. If any parent in the chain has DP, filter out the relation.
1344
+ const filteredComponentRelations = await Promise.all(componentRelations.map(async (relation)=>{
1345
+ const componentId = relation[componentIdColumn];
1346
+ const componentType = relation[componentTypeColumn];
1347
+ const entityId = relation[entityIdColumn];
1348
+ const componentSchema = strapi.components[componentType];
1349
+ if (!componentSchema) {
1350
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - unknown component type ${componentType} (entity: ${entityId}, componentId: ${componentId})`);
1351
+ return relation;
1352
+ }
1353
+ const componentParent = await findComponentParentInstance(trx, identifiers, componentSchema.uid, componentId, uid, componentHierarchyCaches);
1354
+ if (!componentParent) {
1355
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}) is directly on entity ${entityId} (no nested parent found)`);
1356
+ return relation;
1357
+ }
1358
+ debug(`[copyComponentRelations] ${uid}: Component ${componentType} (id: ${componentId}, entity: ${entityId}) has parent in hierarchy: ${componentParent.uid} (parentId: ${componentParent.parentId})`);
1359
+ const hasDPParent = await hasDraftPublishAncestorForParent(trx, identifiers, componentParent, componentHierarchyCaches);
1360
+ if (hasDPParent) {
1361
+ debug(`[copyComponentRelations] Filtering: component ${componentType} (id: ${componentId}, entity: ${entityId}) has DP parent in hierarchy (${componentParent.uid})`);
1362
+ return null;
1363
+ }
1364
+ debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}, entity: ${entityId}) has no DP parent in hierarchy`);
1365
+ return relation;
1366
+ }));
1367
+ // Filter out null values (filtered relations)
1368
+ const relationsToProcess = filteredComponentRelations.filter(Boolean);
1369
+ const filteredCount = componentRelations.length - relationsToProcess.length;
1370
+ if (filteredCount > 0) {
1371
+ debug(`[copyComponentRelations] ${uid}: Filtered ${filteredCount} of ${componentRelations.length} component relations (removed ${filteredCount} with DP parents)`);
1372
+ }
1373
+ // Create new component relations for draft entries
1374
+ // Remove the 'id' field to avoid duplicate key errors
1375
+ const mappedRelations = (await Promise.all(relationsToProcess.map(async (relation)=>{
1376
+ const newEntityId = getMappedValue(publishedToDraftMap, relation[entityIdColumn]);
1377
+ if (!newEntityId) {
1378
+ return null;
1379
+ }
1380
+ const componentId = relation[componentIdColumn];
1381
+ const componentType = relation[componentTypeColumn];
1382
+ const componentKey = `${componentId}:${newEntityId}`;
1383
+ let cloneMap = componentCloneCache.get(componentType);
1384
+ if (!cloneMap) {
1385
+ cloneMap = new Map();
1386
+ componentCloneCache.set(componentType, cloneMap);
1387
+ }
1388
+ let newComponentId = cloneMap.get(componentKey);
1389
+ if (!newComponentId) {
1390
+ newComponentId = await cloneComponentInstance({
1391
+ trx,
1392
+ componentUid: componentType,
1393
+ componentId: Number(componentId),
1394
+ parentUid: uid,
1395
+ parentPublishedToDraftMap: publishedToDraftMap,
1396
+ draftMapCache: componentTargetDraftMapCache
1397
+ });
1398
+ cloneMap.set(componentKey, newComponentId);
1399
+ }
1400
+ const { id, ...relationWithoutId } = relation;
1401
+ return {
1402
+ ...relationWithoutId,
1403
+ [entityIdColumn]: newEntityId,
1404
+ [componentIdColumn]: newComponentId
1405
+ };
1406
+ }))).filter(Boolean);
1407
+ // Deduplicate relations based on the unique constraint columns
1408
+ // This prevents duplicates within the same batch that could cause conflicts
1409
+ const uniqueKeyMap = new Map();
1410
+ for (const relation of mappedRelations){
1411
+ const uniqueKey = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
1412
+ if (!uniqueKeyMap.has(uniqueKey)) {
1413
+ uniqueKeyMap.set(uniqueKey, relation);
1414
+ }
1415
+ }
1416
+ const deduplicatedRelations = Array.from(uniqueKeyMap.values());
1417
+ if (deduplicatedRelations.length === 0) {
1418
+ continue;
1419
+ }
1420
+ // Check which relations already exist in the database to avoid conflicts
1421
+ // We need to check all unique constraint columns (entity_id, cmp_id, field, component_type)
1422
+ // Batch the check to avoid SQLite expression tree depth limits
1423
+ // Use smaller batches for OR queries (50 for SQLite, 100 for others)
1424
+ const batchSize = getBatchSize(trx, 50);
1425
+ const relationChunks = chunkArray(deduplicatedRelations, batchSize);
1426
+ const existingKeys = new Set();
1427
+ for (const relationChunk of relationChunks){
1428
+ const existingRelations = await trx(joinTableName).select([
1429
+ entityIdColumn,
1430
+ componentIdColumn,
1431
+ fieldColumn,
1432
+ componentTypeColumn
1433
+ ]).where((qb)=>{
1434
+ // Build OR conditions for each relation in this chunk
1435
+ for (const relation of relationChunk){
1436
+ qb.orWhere((subQb)=>{
1437
+ subQb.where(entityIdColumn, relation[entityIdColumn]).where(componentIdColumn, relation[componentIdColumn]).where(fieldColumn, relation[fieldColumn]).where(componentTypeColumn, relation[componentTypeColumn]);
1438
+ });
1439
+ }
1440
+ });
1441
+ // Add existing relation keys to the set
1442
+ for (const existing of existingRelations){
1443
+ const key = `${existing[entityIdColumn]}_${existing[componentIdColumn]}_${existing[fieldColumn]}_${existing[componentTypeColumn]}`;
1444
+ existingKeys.add(key);
1445
+ }
1446
+ }
1447
+ // Filter out relations that already exist
1448
+ const newComponentRelations = deduplicatedRelations.filter((relation)=>{
1449
+ const key = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
1450
+ return !existingKeys.has(key);
1451
+ });
1452
+ if (newComponentRelations.length > 0) {
1453
+ // Insert component relations with PostgreSQL-specific ON CONFLICT handling
1454
+ // Component relations use a different conflict resolution than regular relations
1455
+ const client = trx.client.config.client;
1456
+ if (client === 'postgres' || client === 'pg') {
1457
+ // PostgreSQL: Insert one at a time with ON CONFLICT DO NOTHING
1458
+ // Use raw SQL for more reliable conflict handling with specific conflict columns
1459
+ let insertedCount = 0;
1460
+ let skippedCount = 0;
1461
+ for (const relation of newComponentRelations){
1462
+ try {
1463
+ const orderValue = relation[orderColumn] ?? null;
1464
+ await trx.raw(`INSERT INTO ?? (??, ??, ??, ??, ??) VALUES (?, ?, ?, ?, ?)
1465
+ ON CONFLICT (??, ??, ??, ??) DO NOTHING`, [
1466
+ joinTableName,
1467
+ entityIdColumn,
1468
+ componentIdColumn,
1469
+ fieldColumn,
1470
+ componentTypeColumn,
1471
+ orderColumn,
1472
+ relation[entityIdColumn],
1473
+ relation[componentIdColumn],
1474
+ relation[fieldColumn],
1475
+ relation[componentTypeColumn],
1476
+ orderValue,
1477
+ entityIdColumn,
1478
+ componentIdColumn,
1479
+ fieldColumn,
1480
+ componentTypeColumn
1481
+ ]);
1482
+ insertedCount += 1;
1483
+ } catch (error) {
1484
+ if (error.code !== '23505' && !error.message?.includes('duplicate key')) {
1485
+ throw error;
1486
+ }
1487
+ skippedCount += 1;
1488
+ }
1489
+ }
1490
+ if (insertedCount > 0 || skippedCount > 0) {
1491
+ debug(`[copyComponentRelations] ${uid}: Inserted ${insertedCount} component relations, skipped ${skippedCount} duplicates`);
1492
+ }
1493
+ } else {
1494
+ // MySQL and SQLite: use standard insert with duplicate handling
1495
+ await insertRelationsWithDuplicateHandling({
1496
+ trx,
1497
+ tableName: joinTableName,
1498
+ relations: newComponentRelations,
1499
+ context: {
1500
+ reason: 'component-relation-insert',
1501
+ sourceUid: uid
1502
+ }
1503
+ });
89
1504
  }
90
- }).limit(batchSize).offset(offset).orderBy('id').transacting(trx).execute();
91
- if (batch.length < batchSize) {
92
- hasMore = false;
93
1505
  }
94
- offset += batchSize;
95
- yield batch;
96
1506
  }
97
1507
  }
98
1508
  /**
99
1509
  * 2 pass migration to create the draft entries for all the published entries.
100
- * And then discard the drafts to copy the relations.
1510
+ * And then copy relations directly using database queries.
101
1511
  */ const migrateUp = async (trx, db)=>{
1512
+ strapi.log.info('[discard-drafts] Migration started');
102
1513
  const dpModels = [];
103
1514
  for (const meta of db.metadata.values()){
104
1515
  const hasDP = await hasDraftAndPublish(trx, meta);
@@ -106,53 +1517,85 @@ var index = require('../../services/document-service/index.js');
106
1517
  dpModels.push(meta);
107
1518
  }
108
1519
  }
1520
+ debug(`Found ${dpModels.length} draft/publish content types to process`);
109
1521
  /**
110
1522
  * Create plain draft entries for all the entries that were published.
111
- */ for (const model of dpModels){
1523
+ */ strapi.log.info('[discard-drafts] Stage 1/3 – cloning published entries into draft rows');
1524
+ for (const model of dpModels){
1525
+ debug(` • cloning scalars for ${model.uid}`);
112
1526
  await copyPublishedEntriesToDraft({
113
1527
  db,
114
1528
  trx,
115
1529
  uid: model.uid
116
1530
  });
117
1531
  }
1532
+ strapi.log.info('[discard-drafts] Stage 1/3 complete');
118
1533
  /**
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
- });
1534
+ * Copy relations from published entries to draft entries using direct database queries.
1535
+ * This is much more efficient than calling discardDraft for each entry.
1536
+ */ strapi.log.info('[discard-drafts] Stage 2/3 copying relations and components to drafts');
138
1537
  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({
1538
+ debug(` copying relations for ${model.uid}`);
1539
+ await copyRelationsToDrafts({
144
1540
  db,
145
1541
  trx,
146
1542
  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
- }
1543
+ });
1544
+ }
1545
+ flushSkippedRelationLogs();
1546
+ strapi.log.info('[discard-drafts] Stage 2/3 complete');
1547
+ /**
1548
+ * Update JoinColumn relations (foreign keys) to point to draft versions
1549
+ * This matches discard() behavior: drafts relate to drafts
1550
+ */ strapi.log.info('[discard-drafts] Stage 3/3 – updating foreign key references to draft targets');
1551
+ for (const model of dpModels){
1552
+ debug(` • updating join columns for ${model.uid}`);
1553
+ await updateJoinColumnRelations({
1554
+ db,
1555
+ trx,
1556
+ uid: model.uid
1557
+ });
154
1558
  }
1559
+ strapi.log.info('[discard-drafts] Stage 3/3 complete');
1560
+ strapi.log.info('[discard-drafts] Migration completed successfully');
155
1561
  };
1562
+ /**
1563
+ * Load a batch of versions to discard.
1564
+ *
1565
+ * Versions with only a draft version will be ignored.
1566
+ * Only versions with a published version (which always have a draft version) will be discarded.
1567
+ */ async function* getBatchToDiscard({ db, trx, uid, defaultBatchSize = 1000 }) {
1568
+ const client = db.config.connection.client;
1569
+ const isSQLite = typeof client === 'string' && [
1570
+ 'sqlite',
1571
+ 'sqlite3',
1572
+ 'better-sqlite3'
1573
+ ].includes(client);
1574
+ // The SQLite documentation states that the maximum number of terms in a
1575
+ // compound SELECT statement is 500 by default.
1576
+ // See: https://www.sqlite.org/limits.html
1577
+ // To ensure a successful migration, we limit the batch size to 500 for SQLite.
1578
+ const batchSize = isSQLite ? Math.min(defaultBatchSize, 500) : defaultBatchSize;
1579
+ let offset = 0;
1580
+ let hasMore = true;
1581
+ while(hasMore){
1582
+ // Look for the published entries to discard
1583
+ const batch = await db.queryBuilder(uid).select([
1584
+ 'id',
1585
+ 'documentId',
1586
+ 'locale'
1587
+ ]).where({
1588
+ publishedAt: {
1589
+ $ne: null
1590
+ }
1591
+ }).limit(batchSize).offset(offset).orderBy('id').transacting(trx).execute();
1592
+ if (batch.length < batchSize) {
1593
+ hasMore = false;
1594
+ }
1595
+ offset += batchSize;
1596
+ yield batch;
1597
+ }
1598
+ }
156
1599
  const discardDocumentDrafts = {
157
1600
  name: 'core::5.0.0-discard-drafts',
158
1601
  async up (trx, db) {