@strapi/core 0.0.0-experimental.ca5f02ef2ec166e219546983049c0543bed92f8d → 0.0.0-experimental.cad2fba5593c9ceddfc264fcecd9313a7f866d1a

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.

Potentially problematic release.


This version of @strapi/core might be problematic. Click here for more details.

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