@strapi/core 0.0.0-experimental.83f23a40206562f4b4916d31f95bf453e8511603 → 0.0.0-experimental.848e0ac442910c1ad22a7c5eaab07088827fb53c
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.
- package/dist/Strapi.d.ts +1 -0
- package/dist/Strapi.d.ts.map +1 -1
- package/dist/Strapi.js +20 -4
- package/dist/Strapi.js.map +1 -1
- package/dist/Strapi.mjs +20 -4
- package/dist/Strapi.mjs.map +1 -1
- package/dist/configuration/config-loader.js.map +1 -1
- package/dist/configuration/config-loader.mjs.map +1 -1
- package/dist/configuration/urls.js.map +1 -1
- package/dist/configuration/urls.mjs.map +1 -1
- package/dist/constants.d.ts +3 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +6 -0
- package/dist/constants.js.map +1 -0
- package/dist/constants.mjs +4 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/container.js.map +1 -1
- package/dist/container.mjs.map +1 -1
- package/dist/core-api/routes/index.js.map +1 -1
- package/dist/core-api/routes/index.mjs.map +1 -1
- package/dist/core-api/routes/validation/mappers.js.map +1 -1
- package/dist/core-api/routes/validation/mappers.mjs.map +1 -1
- package/dist/core-api/routes/validation/utils.js.map +1 -1
- package/dist/core-api/routes/validation/utils.mjs.map +1 -1
- package/dist/core-api/service/collection-type.js.map +1 -1
- package/dist/core-api/service/collection-type.mjs.map +1 -1
- package/dist/core-api/service/single-type.js.map +1 -1
- package/dist/core-api/service/single-type.mjs.map +1 -1
- package/dist/domain/content-type/index.js.map +1 -1
- package/dist/domain/content-type/index.mjs.map +1 -1
- package/dist/domain/module/index.js.map +1 -1
- package/dist/domain/module/index.mjs.map +1 -1
- package/dist/ee/index.js.map +1 -1
- package/dist/ee/index.mjs.map +1 -1
- package/dist/ee/license.js +1 -2
- package/dist/ee/license.js.map +1 -1
- package/dist/ee/license.mjs +1 -2
- package/dist/ee/license.mjs.map +1 -1
- package/dist/loaders/apis.js.map +1 -1
- package/dist/loaders/apis.mjs.map +1 -1
- package/dist/loaders/components.js.map +1 -1
- package/dist/loaders/components.mjs.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.js.map +1 -1
- package/dist/loaders/plugins/get-enabled-plugins.mjs.map +1 -1
- package/dist/loaders/plugins/index.js.map +1 -1
- package/dist/loaders/plugins/index.mjs.map +1 -1
- package/dist/loaders/src-index.js.map +1 -1
- package/dist/loaders/src-index.mjs.map +1 -1
- package/dist/middlewares/logger.js.map +1 -1
- package/dist/middlewares/logger.mjs.map +1 -1
- package/dist/middlewares/response-time.js.map +1 -1
- package/dist/middlewares/response-time.mjs.map +1 -1
- package/dist/middlewares/security.d.ts.map +1 -1
- package/dist/middlewares/security.js +2 -15
- package/dist/middlewares/security.js.map +1 -1
- package/dist/middlewares/security.mjs +2 -15
- package/dist/middlewares/security.mjs.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.d.ts +21 -7
- package/dist/migrations/database/5.0.0-discard-drafts.d.ts.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.js +1144 -60
- package/dist/migrations/database/5.0.0-discard-drafts.js.map +1 -1
- package/dist/migrations/database/5.0.0-discard-drafts.mjs +1145 -61
- package/dist/migrations/database/5.0.0-discard-drafts.mjs.map +1 -1
- package/dist/migrations/first-published-at.js.map +1 -1
- package/dist/migrations/first-published-at.mjs.map +1 -1
- package/dist/package.json.js +13 -12
- package/dist/package.json.js.map +1 -1
- package/dist/package.json.mjs +13 -12
- package/dist/package.json.mjs.map +1 -1
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +2 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/index.mjs +2 -0
- package/dist/providers/index.mjs.map +1 -1
- package/dist/providers/session-manager.d.ts +3 -0
- package/dist/providers/session-manager.d.ts.map +1 -0
- package/dist/providers/session-manager.js +23 -0
- package/dist/providers/session-manager.js.map +1 -0
- package/dist/providers/session-manager.mjs +21 -0
- package/dist/providers/session-manager.mjs.map +1 -0
- package/dist/registries/apis.js.map +1 -1
- package/dist/registries/apis.mjs.map +1 -1
- package/dist/registries/custom-fields.js.map +1 -1
- package/dist/registries/custom-fields.mjs.map +1 -1
- package/dist/registries/namespace.js.map +1 -1
- package/dist/registries/namespace.mjs.map +1 -1
- package/dist/registries/plugins.js.map +1 -1
- package/dist/registries/plugins.mjs.map +1 -1
- package/dist/registries/policies.js.map +1 -1
- package/dist/registries/policies.mjs.map +1 -1
- package/dist/services/config.js.map +1 -1
- package/dist/services/config.mjs.map +1 -1
- package/dist/services/content-api/index.js.map +1 -1
- package/dist/services/content-api/index.mjs.map +1 -1
- package/dist/services/content-api/permissions/index.js.map +1 -1
- package/dist/services/content-api/permissions/index.mjs.map +1 -1
- package/dist/services/core-store.js.map +1 -1
- package/dist/services/core-store.mjs.map +1 -1
- package/dist/services/document-service/components.d.ts +26 -1
- package/dist/services/document-service/components.d.ts.map +1 -1
- package/dist/services/document-service/components.js +16 -4
- package/dist/services/document-service/components.js.map +1 -1
- package/dist/services/document-service/components.mjs +15 -5
- package/dist/services/document-service/components.mjs.map +1 -1
- package/dist/services/document-service/repository.js +1 -1
- package/dist/services/document-service/repository.js.map +1 -1
- package/dist/services/document-service/repository.mjs +1 -1
- package/dist/services/document-service/repository.mjs.map +1 -1
- package/dist/services/document-service/transform/fields.js.map +1 -1
- package/dist/services/document-service/transform/fields.mjs.map +1 -1
- package/dist/services/document-service/transform/id-map.js.map +1 -1
- package/dist/services/document-service/transform/id-map.mjs.map +1 -1
- package/dist/services/document-service/utils/clean-component-join-table.d.ts +7 -0
- package/dist/services/document-service/utils/clean-component-join-table.d.ts.map +1 -0
- package/dist/services/document-service/utils/clean-component-join-table.js +145 -0
- package/dist/services/document-service/utils/clean-component-join-table.js.map +1 -0
- package/dist/services/document-service/utils/clean-component-join-table.mjs +143 -0
- package/dist/services/document-service/utils/clean-component-join-table.mjs.map +1 -0
- package/dist/services/entity-service/index.js.map +1 -1
- package/dist/services/entity-service/index.mjs.map +1 -1
- package/dist/services/entity-validator/blocks-validator.js.map +1 -1
- package/dist/services/entity-validator/blocks-validator.mjs.map +1 -1
- package/dist/services/entity-validator/index.js.map +1 -1
- package/dist/services/entity-validator/index.mjs.map +1 -1
- package/dist/services/metrics/sender.d.ts.map +1 -1
- package/dist/services/metrics/sender.js +2 -1
- package/dist/services/metrics/sender.js.map +1 -1
- package/dist/services/metrics/sender.mjs +2 -1
- package/dist/services/metrics/sender.mjs.map +1 -1
- package/dist/services/server/compose-endpoint.js.map +1 -1
- package/dist/services/server/compose-endpoint.mjs.map +1 -1
- package/dist/services/server/index.js.map +1 -1
- package/dist/services/server/index.mjs.map +1 -1
- package/dist/services/server/middleware.js.map +1 -1
- package/dist/services/server/middleware.mjs.map +1 -1
- package/dist/services/server/register-routes.js.map +1 -1
- package/dist/services/server/register-routes.mjs.map +1 -1
- package/dist/services/server/routing.js.map +1 -1
- package/dist/services/server/routing.mjs.map +1 -1
- package/dist/services/session-manager.d.ts +167 -0
- package/dist/services/session-manager.d.ts.map +1 -0
- package/dist/services/session-manager.js +529 -0
- package/dist/services/session-manager.js.map +1 -0
- package/dist/services/session-manager.mjs +526 -0
- package/dist/services/session-manager.mjs.map +1 -0
- package/dist/services/webhook-runner.js +2 -2
- package/dist/services/webhook-runner.js.map +1 -1
- package/dist/services/webhook-runner.mjs +2 -2
- package/dist/services/webhook-runner.mjs.map +1 -1
- package/dist/services/worker-queue.js +2 -2
- package/dist/services/worker-queue.js.map +1 -1
- package/dist/services/worker-queue.mjs +2 -2
- package/dist/services/worker-queue.mjs.map +1 -1
- package/dist/utils/fetch.js.map +1 -1
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/filepath-to-prop-path.js.map +1 -1
- package/dist/utils/filepath-to-prop-path.mjs.map +1 -1
- package/dist/utils/load-config-file.js.map +1 -1
- package/dist/utils/load-config-file.mjs.map +1 -1
- package/dist/utils/startup-logger.js.map +1 -1
- package/dist/utils/startup-logger.mjs.map +1 -1
- package/package.json +13 -12
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var cuid2 = require('@paralleldrive/cuid2');
|
|
3
4
|
var strapiUtils = require('@strapi/utils');
|
|
4
|
-
var
|
|
5
|
+
var createDebug = require('debug');
|
|
6
|
+
var transformContentTypesToModels = require('../../utils/transform-content-types-to-models.js');
|
|
5
7
|
|
|
6
8
|
/**
|
|
7
9
|
* Check if the model has draft and publish enabled.
|
|
@@ -49,7 +51,9 @@ var index = require('../../services/document-service/index.js');
|
|
|
49
51
|
])).insert((subQb)=>{
|
|
50
52
|
// SELECT columnName1, columnName2, columnName3, ...
|
|
51
53
|
subQb.select(...scalarAttributes.map((att)=>{
|
|
52
|
-
//
|
|
54
|
+
// NOTE: these literals reference Strapi's built-in system columns. They never get shortened by
|
|
55
|
+
// the identifier migration (5.0.0-01-convert-identifiers-long-than-max-length) so we can safely
|
|
56
|
+
// compare/use them directly here.
|
|
53
57
|
if (att === 'published_at') {
|
|
54
58
|
return trx.raw('NULL as ??', 'published_at');
|
|
55
59
|
}
|
|
@@ -58,6 +62,1144 @@ var index = require('../../services/document-service/index.js');
|
|
|
58
62
|
.whereNotNull('published_at');
|
|
59
63
|
});
|
|
60
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Copy relations from published entries to draft entries using direct database queries.
|
|
67
|
+
* This replaces the need to call discardDraft for each entry.
|
|
68
|
+
*/ async function copyRelationsToDrafts({ db, trx, uid }) {
|
|
69
|
+
const meta = db.metadata.get(uid);
|
|
70
|
+
if (!meta) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
// Create mapping from published entry ID to draft entry ID
|
|
74
|
+
const publishedToDraftMap = await buildPublishedToDraftMap({
|
|
75
|
+
trx,
|
|
76
|
+
uid,
|
|
77
|
+
meta
|
|
78
|
+
});
|
|
79
|
+
if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// Copy relations for this content type
|
|
83
|
+
await copyRelationsForContentType({
|
|
84
|
+
trx,
|
|
85
|
+
uid,
|
|
86
|
+
publishedToDraftMap
|
|
87
|
+
});
|
|
88
|
+
// Copy relations from other content types that target this content type
|
|
89
|
+
await copyRelationsFromOtherContentTypes({
|
|
90
|
+
trx,
|
|
91
|
+
uid,
|
|
92
|
+
publishedToDraftMap
|
|
93
|
+
});
|
|
94
|
+
// Copy relations from this content type that target other content types (category 3)
|
|
95
|
+
await copyRelationsToOtherContentTypes({
|
|
96
|
+
trx,
|
|
97
|
+
uid,
|
|
98
|
+
publishedToDraftMap
|
|
99
|
+
});
|
|
100
|
+
// Copy component relations from published entries to draft entries
|
|
101
|
+
await copyComponentRelations({
|
|
102
|
+
trx,
|
|
103
|
+
uid,
|
|
104
|
+
publishedToDraftMap
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Helper to batch process arrays in chunks
|
|
109
|
+
*/ function chunkArray(array, chunkSize) {
|
|
110
|
+
const chunks = [];
|
|
111
|
+
for(let i = 0; i < array.length; i += chunkSize){
|
|
112
|
+
chunks.push(array.slice(i, i + chunkSize));
|
|
113
|
+
}
|
|
114
|
+
return chunks;
|
|
115
|
+
}
|
|
116
|
+
const applyJoinTableOrdering = (qb, joinTable, sourceColumnName)=>{
|
|
117
|
+
const seenColumns = new Set();
|
|
118
|
+
const enqueueColumn = (column, direction = 'asc')=>{
|
|
119
|
+
if (!column || seenColumns.has(column)) {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
seenColumns.add(column);
|
|
123
|
+
qb.orderBy(column, direction);
|
|
124
|
+
};
|
|
125
|
+
enqueueColumn(sourceColumnName, 'asc');
|
|
126
|
+
if (Array.isArray(joinTable?.orderBy)) {
|
|
127
|
+
for (const clause of joinTable.orderBy){
|
|
128
|
+
if (!clause || typeof clause !== 'object') {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const [column, direction] = Object.entries(clause)[0] ?? [];
|
|
132
|
+
if (!column) {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const normalizedDirection = typeof direction === 'string' && direction.toLowerCase() === 'desc' ? 'desc' : 'asc';
|
|
136
|
+
enqueueColumn(column, normalizedDirection);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
enqueueColumn(joinTable?.orderColumnName, 'asc');
|
|
140
|
+
enqueueColumn(joinTable?.orderColumn, 'asc');
|
|
141
|
+
enqueueColumn('id', 'asc');
|
|
142
|
+
};
|
|
143
|
+
const componentParentSchemasCache = new Map();
|
|
144
|
+
const joinTableExistsCache = new Map();
|
|
145
|
+
const componentMetaCache = new Map();
|
|
146
|
+
const DUPLICATE_ERROR_CODES = new Set([
|
|
147
|
+
'23505',
|
|
148
|
+
'ER_DUP_ENTRY',
|
|
149
|
+
'SQLITE_CONSTRAINT_UNIQUE'
|
|
150
|
+
]);
|
|
151
|
+
const debug = createDebug('strapi::migration::discard-drafts');
|
|
152
|
+
const normalizeId = (value)=>{
|
|
153
|
+
if (value == null) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
const num = Number(value);
|
|
157
|
+
if (Number.isNaN(num)) {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
return num;
|
|
161
|
+
};
|
|
162
|
+
const getMappedValue = (map, key)=>{
|
|
163
|
+
if (!map) {
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
const normalized = normalizeId(key);
|
|
167
|
+
if (normalized == null) {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
return map.get(normalized);
|
|
171
|
+
};
|
|
172
|
+
const resolveInsertedId = (insertResult)=>{
|
|
173
|
+
if (insertResult == null) {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
if (typeof insertResult === 'number') {
|
|
177
|
+
return insertResult;
|
|
178
|
+
}
|
|
179
|
+
if (Array.isArray(insertResult)) {
|
|
180
|
+
if (insertResult.length === 0) {
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
const first = insertResult[0];
|
|
184
|
+
if (first == null) {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
if (typeof first === 'number') {
|
|
188
|
+
return first;
|
|
189
|
+
}
|
|
190
|
+
if (typeof first === 'object') {
|
|
191
|
+
if ('id' in first) {
|
|
192
|
+
return Number(first.id);
|
|
193
|
+
}
|
|
194
|
+
const idKey = Object.keys(first).find((key)=>key.toLowerCase() === 'id');
|
|
195
|
+
if (idKey) {
|
|
196
|
+
return Number(first[idKey]);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (typeof insertResult === 'object' && 'id' in insertResult) {
|
|
201
|
+
return Number(insertResult.id);
|
|
202
|
+
}
|
|
203
|
+
return null;
|
|
204
|
+
};
|
|
205
|
+
const isDuplicateEntryError = (error)=>{
|
|
206
|
+
if (!error) {
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
if (DUPLICATE_ERROR_CODES.has(error.code)) {
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
const message = typeof error.message === 'string' ? error.message : '';
|
|
213
|
+
return message.includes('duplicate key') || message.includes('UNIQUE constraint failed');
|
|
214
|
+
};
|
|
215
|
+
const insertRowWithDuplicateHandling = async (trx, tableName, row, context = {})=>{
|
|
216
|
+
try {
|
|
217
|
+
const client = trx.client.config.client;
|
|
218
|
+
if (client === 'postgres' || client === 'pg' || client === 'sqlite3' || client === 'better-sqlite3') {
|
|
219
|
+
await trx(tableName).insert(row).onConflict().ignore();
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (client === 'mysql' || client === 'mysql2') {
|
|
223
|
+
await trx.raw(`INSERT IGNORE INTO ?? SET ?`, [
|
|
224
|
+
tableName,
|
|
225
|
+
row
|
|
226
|
+
]);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
await trx(tableName).insert(row);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (!isDuplicateEntryError(error)) {
|
|
232
|
+
const details = JSON.stringify(context);
|
|
233
|
+
const wrapped = new Error(`Failed to insert row into ${tableName}: ${error.message} | context=${details}`);
|
|
234
|
+
wrapped.cause = error;
|
|
235
|
+
throw wrapped;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
function listComponentParentSchemas(componentUid) {
|
|
240
|
+
if (!componentParentSchemasCache.has(componentUid)) {
|
|
241
|
+
const schemas = [
|
|
242
|
+
...Object.values(strapi.contentTypes),
|
|
243
|
+
...Object.values(strapi.components)
|
|
244
|
+
];
|
|
245
|
+
const parents = schemas.filter((schema)=>{
|
|
246
|
+
if (!schema?.attributes) {
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
return Object.values(schema.attributes).some((attr)=>{
|
|
250
|
+
if (attr.type === 'component') {
|
|
251
|
+
return attr.component === componentUid;
|
|
252
|
+
}
|
|
253
|
+
if (attr.type === 'dynamiczone') {
|
|
254
|
+
return attr.components?.includes(componentUid);
|
|
255
|
+
}
|
|
256
|
+
return false;
|
|
257
|
+
});
|
|
258
|
+
}).map((schema)=>({
|
|
259
|
+
uid: schema.uid,
|
|
260
|
+
collectionName: schema.collectionName
|
|
261
|
+
}));
|
|
262
|
+
componentParentSchemasCache.set(componentUid, parents);
|
|
263
|
+
}
|
|
264
|
+
return componentParentSchemasCache.get(componentUid);
|
|
265
|
+
}
|
|
266
|
+
async function ensureTableExists(trx, tableName) {
|
|
267
|
+
if (!joinTableExistsCache.has(tableName)) {
|
|
268
|
+
const exists = await trx.schema.hasTable(tableName);
|
|
269
|
+
joinTableExistsCache.set(tableName, exists);
|
|
270
|
+
}
|
|
271
|
+
return joinTableExistsCache.get(tableName);
|
|
272
|
+
}
|
|
273
|
+
async function findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches) {
|
|
274
|
+
const cacheKey = `${componentUid}:${componentId}:${excludeUid ?? 'ALL'}`;
|
|
275
|
+
if (caches.parentInstanceCache.has(cacheKey)) {
|
|
276
|
+
return caches.parentInstanceCache.get(cacheKey);
|
|
277
|
+
}
|
|
278
|
+
const parentComponentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
|
|
279
|
+
const parentComponentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
|
|
280
|
+
const parentEntityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
|
|
281
|
+
const potentialParents = listComponentParentSchemas(componentUid).filter((schema)=>schema.uid !== excludeUid);
|
|
282
|
+
for (const parentSchema of potentialParents){
|
|
283
|
+
if (!parentSchema.collectionName) {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const parentJoinTableName = transformContentTypesToModels.getComponentJoinTableName(parentSchema.collectionName, identifiers);
|
|
287
|
+
try {
|
|
288
|
+
if (!await ensureTableExists(trx, parentJoinTableName)) {
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const parentRow = await trx(parentJoinTableName).where({
|
|
292
|
+
[parentComponentIdColumn]: componentId,
|
|
293
|
+
[parentComponentTypeColumn]: componentUid
|
|
294
|
+
}).first(parentEntityIdColumn);
|
|
295
|
+
if (parentRow) {
|
|
296
|
+
const parentInstance = {
|
|
297
|
+
uid: parentSchema.uid,
|
|
298
|
+
parentId: parentRow[parentEntityIdColumn]
|
|
299
|
+
};
|
|
300
|
+
caches.parentInstanceCache.set(cacheKey, parentInstance);
|
|
301
|
+
return parentInstance;
|
|
302
|
+
}
|
|
303
|
+
} catch {
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
caches.parentInstanceCache.set(cacheKey, null);
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
const getComponentMeta = (componentUid)=>{
|
|
311
|
+
if (!componentMetaCache.has(componentUid)) {
|
|
312
|
+
const meta = strapi.db.metadata.get(componentUid);
|
|
313
|
+
componentMetaCache.set(componentUid, meta ?? null);
|
|
314
|
+
}
|
|
315
|
+
return componentMetaCache.get(componentUid);
|
|
316
|
+
};
|
|
317
|
+
async function hasDraftPublishAncestorForParent(trx, identifiers, parent, caches) {
|
|
318
|
+
const cacheKey = `${parent.uid}:${parent.parentId}`;
|
|
319
|
+
if (caches.parentDpCache.has(cacheKey)) {
|
|
320
|
+
return caches.parentDpCache.get(cacheKey);
|
|
321
|
+
}
|
|
322
|
+
const parentContentType = strapi.contentTypes[parent.uid];
|
|
323
|
+
if (parentContentType) {
|
|
324
|
+
const result = !!parentContentType?.options?.draftAndPublish;
|
|
325
|
+
caches.parentDpCache.set(cacheKey, result);
|
|
326
|
+
return result;
|
|
327
|
+
}
|
|
328
|
+
const parentComponent = strapi.components[parent.uid];
|
|
329
|
+
if (!parentComponent) {
|
|
330
|
+
caches.parentDpCache.set(cacheKey, false);
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
const result = await hasDraftPublishAncestorForComponent(trx, identifiers, parent.uid, parent.parentId, undefined, caches);
|
|
334
|
+
caches.parentDpCache.set(cacheKey, result);
|
|
335
|
+
return result;
|
|
336
|
+
}
|
|
337
|
+
async function hasDraftPublishAncestorForComponent(trx, identifiers, componentUid, componentId, excludeUid, caches) {
|
|
338
|
+
const cacheKey = `${componentUid}:${componentId}:${'ALL'}`;
|
|
339
|
+
if (caches.ancestorDpCache.has(cacheKey)) {
|
|
340
|
+
return caches.ancestorDpCache.get(cacheKey);
|
|
341
|
+
}
|
|
342
|
+
const parent = await findComponentParentInstance(trx, identifiers, componentUid, componentId, excludeUid, caches);
|
|
343
|
+
if (!parent) {
|
|
344
|
+
caches.ancestorDpCache.set(cacheKey, false);
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
const result = await hasDraftPublishAncestorForParent(trx, identifiers, parent, caches);
|
|
348
|
+
caches.ancestorDpCache.set(cacheKey, result);
|
|
349
|
+
return result;
|
|
350
|
+
}
|
|
351
|
+
const resolveNowValue = (trx)=>{
|
|
352
|
+
if (typeof trx.fn?.now === 'function') {
|
|
353
|
+
return trx.fn.now();
|
|
354
|
+
}
|
|
355
|
+
return new Date();
|
|
356
|
+
};
|
|
357
|
+
async function getDraftMapForTarget(trx, targetUid, draftMapCache) {
|
|
358
|
+
if (draftMapCache.has(targetUid)) {
|
|
359
|
+
return draftMapCache.get(targetUid) ?? null;
|
|
360
|
+
}
|
|
361
|
+
const targetMeta = strapi.db.metadata.get(targetUid);
|
|
362
|
+
if (!targetMeta) {
|
|
363
|
+
draftMapCache.set(targetUid, null);
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
const map = await buildPublishedToDraftMap({
|
|
367
|
+
trx,
|
|
368
|
+
uid: targetUid,
|
|
369
|
+
meta: targetMeta,
|
|
370
|
+
options: {
|
|
371
|
+
requireDraftAndPublish: true
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
draftMapCache.set(targetUid, map ?? null);
|
|
375
|
+
return map ?? null;
|
|
376
|
+
}
|
|
377
|
+
async function mapTargetId(trx, originalId, targetUid, parentUid, parentPublishedToDraftMap, draftMapCache) {
|
|
378
|
+
if (originalId == null || !targetUid) {
|
|
379
|
+
return originalId;
|
|
380
|
+
}
|
|
381
|
+
if (targetUid === parentUid) {
|
|
382
|
+
return parentPublishedToDraftMap.get(Number(originalId)) ?? originalId;
|
|
383
|
+
}
|
|
384
|
+
const targetMap = await getDraftMapForTarget(trx, targetUid, draftMapCache);
|
|
385
|
+
if (!targetMap) {
|
|
386
|
+
return originalId;
|
|
387
|
+
}
|
|
388
|
+
return targetMap.get(Number(originalId)) ?? originalId;
|
|
389
|
+
}
|
|
390
|
+
const ensureObjectWithoutId = (row)=>{
|
|
391
|
+
const cloned = {
|
|
392
|
+
...row
|
|
393
|
+
};
|
|
394
|
+
if ('id' in cloned) {
|
|
395
|
+
delete cloned.id;
|
|
396
|
+
}
|
|
397
|
+
return cloned;
|
|
398
|
+
};
|
|
399
|
+
async function cloneComponentRelationJoinTables(trx, componentMeta, componentUid, originalComponentId, newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache) {
|
|
400
|
+
for (const attribute of Object.values(componentMeta.attributes)){
|
|
401
|
+
if (attribute.type !== 'relation' || !attribute.joinTable) {
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const joinTable = attribute.joinTable;
|
|
405
|
+
const sourceColumnName = joinTable.joinColumn.name;
|
|
406
|
+
const targetColumnName = joinTable.inverseJoinColumn.name;
|
|
407
|
+
if (!componentMeta.relationsLogPrinted) {
|
|
408
|
+
debug(`[cloneComponentRelationJoinTables] Inspecting join table ${joinTable.name} for component ${componentUid}`);
|
|
409
|
+
componentMeta.relationsLogPrinted = true;
|
|
410
|
+
}
|
|
411
|
+
const relations = await trx(joinTable.name).select('*').where(sourceColumnName, originalComponentId);
|
|
412
|
+
if (relations.length === 0) {
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
for (const relation of relations){
|
|
416
|
+
const clonedRelation = ensureObjectWithoutId(relation);
|
|
417
|
+
clonedRelation[sourceColumnName] = newComponentId;
|
|
418
|
+
if (targetColumnName in clonedRelation) {
|
|
419
|
+
const originalTargetId = clonedRelation[targetColumnName];
|
|
420
|
+
clonedRelation[targetColumnName] = await mapTargetId(trx, clonedRelation[targetColumnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache);
|
|
421
|
+
debug(`[cloneComponentRelationJoinTables] ${componentUid} join ${joinTable.name}: mapped ${targetColumnName} from ${originalTargetId} to ${clonedRelation[targetColumnName]} (target=${attribute.target})`);
|
|
422
|
+
}
|
|
423
|
+
debug(`[cloneComponentRelationJoinTables] inserting relation into ${joinTable.name} (component=${componentUid}, source=${newComponentId})`);
|
|
424
|
+
await insertRowWithDuplicateHandling(trx, joinTable.name, clonedRelation, {
|
|
425
|
+
componentUid,
|
|
426
|
+
originalComponentId,
|
|
427
|
+
newComponentId,
|
|
428
|
+
joinTable: joinTable.name,
|
|
429
|
+
sourceColumnName,
|
|
430
|
+
targetColumnName,
|
|
431
|
+
targetUid: attribute.target,
|
|
432
|
+
parentUid
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async function cloneComponentInstance({ trx, componentUid, componentId, parentUid, parentPublishedToDraftMap, draftMapCache }) {
|
|
438
|
+
const componentMeta = getComponentMeta(componentUid);
|
|
439
|
+
if (!componentMeta) {
|
|
440
|
+
return componentId;
|
|
441
|
+
}
|
|
442
|
+
const componentTableName = componentMeta.tableName;
|
|
443
|
+
const componentPrimaryKey = Number.isNaN(Number(componentId)) ? componentId : Number(componentId);
|
|
444
|
+
const componentRow = await trx(componentTableName).select('*').where('id', componentPrimaryKey).first();
|
|
445
|
+
if (!componentRow) {
|
|
446
|
+
return componentId;
|
|
447
|
+
}
|
|
448
|
+
const newComponentRow = ensureObjectWithoutId(componentRow);
|
|
449
|
+
// `document_id`, `created_at`, `updated_at` are Strapi system columns whose names remain stable across the
|
|
450
|
+
// identifier-shortening migration, so it’s safe to check them directly here.
|
|
451
|
+
if ('document_id' in newComponentRow) {
|
|
452
|
+
newComponentRow.document_id = cuid2.createId();
|
|
453
|
+
}
|
|
454
|
+
if ('updated_at' in newComponentRow) {
|
|
455
|
+
newComponentRow.updated_at = resolveNowValue(trx);
|
|
456
|
+
}
|
|
457
|
+
if ('created_at' in newComponentRow && newComponentRow.created_at == null) {
|
|
458
|
+
newComponentRow.created_at = resolveNowValue(trx);
|
|
459
|
+
}
|
|
460
|
+
for (const attribute of Object.values(componentMeta.attributes)){
|
|
461
|
+
if (attribute.type !== 'relation') {
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
const joinColumn = attribute.joinColumn;
|
|
465
|
+
if (!joinColumn) {
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
const columnName = joinColumn.name;
|
|
469
|
+
if (!columnName || !(columnName in newComponentRow)) {
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
newComponentRow[columnName] = await mapTargetId(trx, newComponentRow[columnName], attribute.target, parentUid, parentPublishedToDraftMap, draftMapCache);
|
|
473
|
+
}
|
|
474
|
+
let insertResult;
|
|
475
|
+
try {
|
|
476
|
+
insertResult = await trx(componentTableName).insert(newComponentRow, [
|
|
477
|
+
'id'
|
|
478
|
+
]);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
insertResult = await trx(componentTableName).insert(newComponentRow);
|
|
481
|
+
}
|
|
482
|
+
let newComponentId = resolveInsertedId(insertResult);
|
|
483
|
+
if (!newComponentId) {
|
|
484
|
+
if ('document_id' in newComponentRow && newComponentRow.document_id) {
|
|
485
|
+
const insertedRow = await trx(componentTableName).select('id').where('document_id', newComponentRow.document_id).orderBy('id', 'desc').first();
|
|
486
|
+
newComponentId = insertedRow?.id ?? null;
|
|
487
|
+
}
|
|
488
|
+
if (!newComponentId) {
|
|
489
|
+
const insertedRow = await trx(componentTableName).select('id').orderBy('id', 'desc').first();
|
|
490
|
+
newComponentId = insertedRow?.id ?? null;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (!newComponentId) {
|
|
494
|
+
throw new Error(`Failed to clone component ${componentUid} (id: ${componentId})`);
|
|
495
|
+
}
|
|
496
|
+
newComponentId = Number(newComponentId);
|
|
497
|
+
if (Number.isNaN(newComponentId)) {
|
|
498
|
+
throw new Error(`Invalid cloned component identifier for ${componentUid} (id: ${componentId})`);
|
|
499
|
+
}
|
|
500
|
+
await cloneComponentRelationJoinTables(trx, componentMeta, componentUid, Number(componentPrimaryKey), newComponentId, parentUid, parentPublishedToDraftMap, draftMapCache);
|
|
501
|
+
return newComponentId;
|
|
502
|
+
}
|
|
503
|
+
async function buildPublishedToDraftMap({ trx, uid, meta, options = {} }) {
|
|
504
|
+
if (!meta) {
|
|
505
|
+
return null;
|
|
506
|
+
}
|
|
507
|
+
const model = strapi.getModel(uid);
|
|
508
|
+
const hasDraftAndPublishEnabled = strapiUtils.contentTypes.hasDraftAndPublish(model);
|
|
509
|
+
if (options.requireDraftAndPublish && !hasDraftAndPublishEnabled) {
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
const [publishedEntries, draftEntries] = await Promise.all([
|
|
513
|
+
// `document_id`, `locale`, and `published_at` are core columns that keep their exact names after the
|
|
514
|
+
// identifier-shortening migration, so selecting them by literal is safe.
|
|
515
|
+
trx(meta.tableName).select([
|
|
516
|
+
'id',
|
|
517
|
+
'document_id',
|
|
518
|
+
'locale'
|
|
519
|
+
]).whereNotNull('published_at'),
|
|
520
|
+
trx(meta.tableName).select([
|
|
521
|
+
'id',
|
|
522
|
+
'document_id',
|
|
523
|
+
'locale'
|
|
524
|
+
]).whereNull('published_at')
|
|
525
|
+
]);
|
|
526
|
+
if (publishedEntries.length === 0 || draftEntries.length === 0) {
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
const i18nService = strapi.plugin('i18n')?.service('content-types');
|
|
530
|
+
const contentType = strapi.contentTypes[uid];
|
|
531
|
+
const isLocalized = i18nService?.isLocalizedContentType(contentType) ?? false;
|
|
532
|
+
const draftByDocumentId = new Map();
|
|
533
|
+
for (const draft of draftEntries){
|
|
534
|
+
if (!draft.document_id) {
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const key = isLocalized ? `${draft.document_id}:${draft.locale || ''}` : draft.document_id;
|
|
538
|
+
const existing = draftByDocumentId.get(key);
|
|
539
|
+
if (!existing) {
|
|
540
|
+
draftByDocumentId.set(key, draft);
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
const existingId = Number(existing.id);
|
|
544
|
+
const draftId = Number(draft.id);
|
|
545
|
+
if (Number.isNaN(existingId) || Number.isNaN(draftId)) {
|
|
546
|
+
draftByDocumentId.set(key, draft);
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
if (draftId > existingId) {
|
|
550
|
+
draftByDocumentId.set(key, draft);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const publishedToDraftMap = new Map();
|
|
554
|
+
for (const published of publishedEntries){
|
|
555
|
+
if (!published.document_id) {
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const key = isLocalized ? `${published.document_id}:${published.locale || ''}` : published.document_id;
|
|
559
|
+
const draft = draftByDocumentId.get(key);
|
|
560
|
+
if (draft) {
|
|
561
|
+
const publishedId = normalizeId(published.id);
|
|
562
|
+
const draftId = normalizeId(draft.id);
|
|
563
|
+
if (publishedId == null || draftId == null) {
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
publishedToDraftMap.set(publishedId, draftId);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return publishedToDraftMap.size > 0 ? publishedToDraftMap : null;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Copy relations within the same content type (self-referential relations)
|
|
573
|
+
*/ async function copyRelationsForContentType({ trx, uid, publishedToDraftMap }) {
|
|
574
|
+
const meta = strapi.db.metadata.get(uid);
|
|
575
|
+
if (!meta) return;
|
|
576
|
+
const publishedIds = Array.from(publishedToDraftMap.keys());
|
|
577
|
+
for (const attribute of Object.values(meta.attributes)){
|
|
578
|
+
if (attribute.type !== 'relation' || attribute.target !== uid) {
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
const joinTable = attribute.joinTable;
|
|
582
|
+
if (!joinTable) {
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
// Skip component join tables - they are handled by copyComponentRelations
|
|
586
|
+
if (joinTable.name.includes('_cmps')) {
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
const { name: sourceColumnName } = joinTable.joinColumn;
|
|
590
|
+
const { name: targetColumnName } = joinTable.inverseJoinColumn;
|
|
591
|
+
// Process in batches to avoid MySQL query size limits
|
|
592
|
+
const publishedIdsChunks = chunkArray(publishedIds, 1000);
|
|
593
|
+
for (const publishedIdsChunk of publishedIdsChunks){
|
|
594
|
+
// Get relations where the source is a published entry (in batches)
|
|
595
|
+
const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
|
|
596
|
+
applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
|
|
597
|
+
const relations = await relationsQuery;
|
|
598
|
+
if (relations.length === 0) {
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
// Create new relations pointing to draft entries
|
|
602
|
+
// Remove the 'id' field to avoid duplicate key errors
|
|
603
|
+
const newRelations = relations.map((relation)=>{
|
|
604
|
+
const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
|
|
605
|
+
const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
|
|
606
|
+
if (!newSourceId || !newTargetId) {
|
|
607
|
+
// Skip if no mapping found
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
610
|
+
// Create new relation object without the 'id' field
|
|
611
|
+
const { id, ...relationWithoutId } = relation;
|
|
612
|
+
return {
|
|
613
|
+
...relationWithoutId,
|
|
614
|
+
[sourceColumnName]: newSourceId,
|
|
615
|
+
[targetColumnName]: newTargetId
|
|
616
|
+
};
|
|
617
|
+
}).filter(Boolean);
|
|
618
|
+
if (newRelations.length > 0) {
|
|
619
|
+
await trx.batchInsert(joinTable.name, newRelations, 1000);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Copy relations from other content types that target this content type
|
|
626
|
+
*/ async function copyRelationsFromOtherContentTypes({ trx, uid, publishedToDraftMap }) {
|
|
627
|
+
const targetMeta = strapi.db.metadata.get(uid);
|
|
628
|
+
if (!targetMeta) {
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
const publishedTargetIds = Array.from(publishedToDraftMap.keys()).map((value)=>normalizeId(value)).filter((value)=>value != null);
|
|
632
|
+
if (publishedTargetIds.length === 0) {
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const draftTargetIds = Array.from(publishedToDraftMap.values()).map((value)=>normalizeId(value)).filter((value)=>value != null);
|
|
636
|
+
const models = [
|
|
637
|
+
...Object.values(strapi.contentTypes),
|
|
638
|
+
...Object.values(strapi.components)
|
|
639
|
+
];
|
|
640
|
+
const buildRelationKey = (relation, sourceColumnName, targetId)=>{
|
|
641
|
+
const sourceId = normalizeId(relation[sourceColumnName]) ?? relation[sourceColumnName];
|
|
642
|
+
const fieldValue = 'field' in relation ? relation.field ?? '' : '';
|
|
643
|
+
const componentTypeValue = 'component_type' in relation ? relation.component_type ?? '' : '';
|
|
644
|
+
return `${sourceId ?? 'null'}::${targetId ?? 'null'}::${fieldValue}::${componentTypeValue}`;
|
|
645
|
+
};
|
|
646
|
+
for (const model of models){
|
|
647
|
+
const dbModel = strapi.db.metadata.get(model.uid);
|
|
648
|
+
if (!dbModel) {
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
const sourceHasDraftAndPublish = Boolean(model.options?.draftAndPublish);
|
|
652
|
+
for (const attribute of Object.values(dbModel.attributes)){
|
|
653
|
+
if (attribute.type !== 'relation' || attribute.target !== uid) {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
const joinTable = attribute.joinTable;
|
|
657
|
+
if (!joinTable) {
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
// Component join tables are handled separately when cloning components.
|
|
661
|
+
if (joinTable.name.includes('_cmps')) {
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
// If the source content type also has draft/publish, its own cloning routine will recreate its relations.
|
|
665
|
+
if (sourceHasDraftAndPublish) {
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
const { name: sourceColumnName } = joinTable.joinColumn;
|
|
669
|
+
const { name: targetColumnName } = joinTable.inverseJoinColumn;
|
|
670
|
+
const existingKeys = new Set();
|
|
671
|
+
if (draftTargetIds.length > 0) {
|
|
672
|
+
const draftIdChunks = chunkArray(draftTargetIds, 1000);
|
|
673
|
+
for (const draftChunk of draftIdChunks){
|
|
674
|
+
const existingRelationsQuery = trx(joinTable.name).select('*').whereIn(targetColumnName, draftChunk);
|
|
675
|
+
applyJoinTableOrdering(existingRelationsQuery, joinTable, sourceColumnName);
|
|
676
|
+
const existingRelations = await existingRelationsQuery;
|
|
677
|
+
for (const relation of existingRelations){
|
|
678
|
+
existingKeys.add(buildRelationKey(relation, sourceColumnName, normalizeId(relation[targetColumnName])));
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
const publishedIdChunks = chunkArray(publishedTargetIds, 1000);
|
|
683
|
+
for (const chunk of publishedIdChunks){
|
|
684
|
+
const relationsQuery = trx(joinTable.name).select('*').whereIn(targetColumnName, chunk);
|
|
685
|
+
applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
|
|
686
|
+
const relations = await relationsQuery;
|
|
687
|
+
if (relations.length === 0) {
|
|
688
|
+
continue;
|
|
689
|
+
}
|
|
690
|
+
const newRelations = [];
|
|
691
|
+
for (const relation of relations){
|
|
692
|
+
const newTargetId = getMappedValue(publishedToDraftMap, relation[targetColumnName]);
|
|
693
|
+
if (!newTargetId) {
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
const key = buildRelationKey(relation, sourceColumnName, newTargetId);
|
|
697
|
+
if (existingKeys.has(key)) {
|
|
698
|
+
continue;
|
|
699
|
+
}
|
|
700
|
+
existingKeys.add(key);
|
|
701
|
+
const { id, ...relationWithoutId } = relation;
|
|
702
|
+
newRelations.push({
|
|
703
|
+
...relationWithoutId,
|
|
704
|
+
[targetColumnName]: newTargetId
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
if (newRelations.length === 0) {
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
try {
|
|
711
|
+
await trx.batchInsert(joinTable.name, newRelations, 1000);
|
|
712
|
+
} catch (error) {
|
|
713
|
+
if (!isDuplicateEntryError(error)) {
|
|
714
|
+
throw error;
|
|
715
|
+
}
|
|
716
|
+
for (const relation of newRelations){
|
|
717
|
+
await insertRowWithDuplicateHandling(trx, joinTable.name, relation, {
|
|
718
|
+
reason: 'duplicate-draft-target-relation',
|
|
719
|
+
sourceUid: model.uid,
|
|
720
|
+
targetUid: uid
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Copy relations from this content type that target other content types (category 3)
|
|
730
|
+
* Example: Article -> Categories/Tags
|
|
731
|
+
*/ async function copyRelationsToOtherContentTypes({ trx, uid, publishedToDraftMap }) {
|
|
732
|
+
const meta = strapi.db.metadata.get(uid);
|
|
733
|
+
if (!meta) return;
|
|
734
|
+
const publishedIds = Array.from(publishedToDraftMap.keys());
|
|
735
|
+
// Cache target publishedToDraftMap to avoid duplicate calls for same target
|
|
736
|
+
const targetMapCache = new Map();
|
|
737
|
+
for (const attribute of Object.values(meta.attributes)){
|
|
738
|
+
if (attribute.type !== 'relation' || attribute.target === uid) {
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
const joinTable = attribute.joinTable;
|
|
742
|
+
if (!joinTable) {
|
|
743
|
+
continue;
|
|
744
|
+
}
|
|
745
|
+
// Skip component join tables - they are handled by copyComponentRelations
|
|
746
|
+
if (joinTable.name.includes('_cmps')) {
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
const { name: sourceColumnName } = joinTable.joinColumn;
|
|
750
|
+
const { name: targetColumnName } = joinTable.inverseJoinColumn;
|
|
751
|
+
// Get target content type's publishedToDraftMap if it has draft/publish (cached)
|
|
752
|
+
const targetUid = attribute.target;
|
|
753
|
+
if (!targetMapCache.has(targetUid)) {
|
|
754
|
+
const targetMeta = strapi.db.metadata.get(targetUid);
|
|
755
|
+
const targetMap = await buildPublishedToDraftMap({
|
|
756
|
+
trx,
|
|
757
|
+
uid: targetUid,
|
|
758
|
+
meta: targetMeta,
|
|
759
|
+
options: {
|
|
760
|
+
requireDraftAndPublish: true
|
|
761
|
+
}
|
|
762
|
+
});
|
|
763
|
+
targetMapCache.set(targetUid, targetMap);
|
|
764
|
+
}
|
|
765
|
+
const targetPublishedToDraftMap = targetMapCache.get(targetUid);
|
|
766
|
+
// Process in batches to avoid MySQL query size limits
|
|
767
|
+
const publishedIdsChunks = chunkArray(publishedIds, 1000);
|
|
768
|
+
for (const publishedIdsChunk of publishedIdsChunks){
|
|
769
|
+
// Get relations where the source is a published entry of our content type (in batches)
|
|
770
|
+
const relationsQuery = trx(joinTable.name).select('*').whereIn(sourceColumnName, publishedIdsChunk);
|
|
771
|
+
applyJoinTableOrdering(relationsQuery, joinTable, sourceColumnName);
|
|
772
|
+
const relations = await relationsQuery;
|
|
773
|
+
if (relations.length === 0) {
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
// Create new relations pointing to draft entries
|
|
777
|
+
// Remove the 'id' field to avoid duplicate key errors
|
|
778
|
+
const newRelations = relations.map((relation)=>{
|
|
779
|
+
const newSourceId = getMappedValue(publishedToDraftMap, relation[sourceColumnName]);
|
|
780
|
+
if (!newSourceId) {
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
// Map target ID to draft if target has draft/publish enabled
|
|
784
|
+
// This matches discard() behavior: drafts relate to drafts
|
|
785
|
+
let newTargetId = relation[targetColumnName];
|
|
786
|
+
if (targetPublishedToDraftMap) {
|
|
787
|
+
const mappedTargetId = getMappedValue(targetPublishedToDraftMap, relation[targetColumnName]);
|
|
788
|
+
if (mappedTargetId) {
|
|
789
|
+
newTargetId = mappedTargetId;
|
|
790
|
+
}
|
|
791
|
+
// If no draft mapping, keep published target (target might not have DP or was deleted)
|
|
792
|
+
}
|
|
793
|
+
// Create new relation object without the 'id' field
|
|
794
|
+
const { id, ...relationWithoutId } = relation;
|
|
795
|
+
return {
|
|
796
|
+
...relationWithoutId,
|
|
797
|
+
[sourceColumnName]: newSourceId,
|
|
798
|
+
[targetColumnName]: newTargetId
|
|
799
|
+
};
|
|
800
|
+
}).filter(Boolean);
|
|
801
|
+
if (newRelations.length > 0) {
|
|
802
|
+
try {
|
|
803
|
+
await trx.batchInsert(joinTable.name, newRelations, 1000);
|
|
804
|
+
} catch (error) {
|
|
805
|
+
// If batch insert fails due to duplicates, try with conflict handling
|
|
806
|
+
if (error.code === '23505' || error.message?.includes('duplicate key')) {
|
|
807
|
+
const client = trx.client.config.client;
|
|
808
|
+
if (client === 'postgres' || client === 'pg') {
|
|
809
|
+
for (const relation of newRelations){
|
|
810
|
+
try {
|
|
811
|
+
await trx(joinTable.name).insert(relation).onConflict().ignore();
|
|
812
|
+
} catch (err) {
|
|
813
|
+
if (err.code !== '23505' && !err.message?.includes('duplicate key')) {
|
|
814
|
+
throw err;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
} else {
|
|
819
|
+
throw error;
|
|
820
|
+
}
|
|
821
|
+
} else {
|
|
822
|
+
throw error;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Update JoinColumn relations (oneToOne, manyToOne foreign keys) to point to draft versions
|
|
831
|
+
* This matches discard() behavior: when creating drafts, foreign keys should point to draft targets
|
|
832
|
+
*/ async function updateJoinColumnRelations({ db, trx, uid }) {
|
|
833
|
+
const meta = db.metadata.get(uid);
|
|
834
|
+
if (!meta) {
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
// Create mapping from published entry ID to draft entry ID
|
|
838
|
+
const publishedToDraftMap = await buildPublishedToDraftMap({
|
|
839
|
+
trx,
|
|
840
|
+
uid,
|
|
841
|
+
meta
|
|
842
|
+
});
|
|
843
|
+
if (!publishedToDraftMap || publishedToDraftMap.size === 0) {
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
// Cache target publishedToDraftMap to avoid duplicate calls for same target
|
|
847
|
+
const targetMapCache = new Map();
|
|
848
|
+
// Find all JoinColumn relations (oneToOne, manyToOne without joinTable)
|
|
849
|
+
for (const attribute of Object.values(meta.attributes)){
|
|
850
|
+
if (attribute.type !== 'relation') {
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
853
|
+
// Skip relations with joinTable (handled by copyRelationsToOtherContentTypes)
|
|
854
|
+
if (attribute.joinTable) {
|
|
855
|
+
continue;
|
|
856
|
+
}
|
|
857
|
+
// Only handle oneToOne and manyToOne relations that use joinColumn
|
|
858
|
+
const joinColumn = attribute.joinColumn;
|
|
859
|
+
if (!joinColumn) {
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
const targetUid = attribute.target;
|
|
863
|
+
const foreignKeyColumn = joinColumn.name;
|
|
864
|
+
// Get target content type's publishedToDraftMap if it has draft/publish (cached)
|
|
865
|
+
if (!targetMapCache.has(targetUid)) {
|
|
866
|
+
const targetMeta = strapi.db.metadata.get(targetUid);
|
|
867
|
+
const targetMap = await buildPublishedToDraftMap({
|
|
868
|
+
trx,
|
|
869
|
+
uid: targetUid,
|
|
870
|
+
meta: targetMeta,
|
|
871
|
+
options: {
|
|
872
|
+
requireDraftAndPublish: true
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
targetMapCache.set(targetUid, targetMap);
|
|
876
|
+
}
|
|
877
|
+
const targetPublishedToDraftMap = targetMapCache.get(targetUid);
|
|
878
|
+
if (!targetPublishedToDraftMap) {
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
const draftIds = Array.from(publishedToDraftMap.values());
|
|
882
|
+
if (draftIds.length === 0) {
|
|
883
|
+
continue;
|
|
884
|
+
}
|
|
885
|
+
const draftIdsChunks = chunkArray(draftIds, 1000);
|
|
886
|
+
for (const draftIdsChunk of draftIdsChunks){
|
|
887
|
+
// Get draft entries with their foreign key values
|
|
888
|
+
const draftEntriesWithFk = await trx(meta.tableName).select([
|
|
889
|
+
'id',
|
|
890
|
+
foreignKeyColumn
|
|
891
|
+
]).whereIn('id', draftIdsChunk).whereNotNull(foreignKeyColumn);
|
|
892
|
+
const updates = draftEntriesWithFk.reduce((acc, draftEntry)=>{
|
|
893
|
+
const publishedTargetIdRaw = draftEntry[foreignKeyColumn];
|
|
894
|
+
const normalizedPublishedTargetId = normalizeId(publishedTargetIdRaw);
|
|
895
|
+
const draftTargetId = normalizedPublishedTargetId == null ? undefined : targetPublishedToDraftMap.get(normalizedPublishedTargetId);
|
|
896
|
+
if (draftTargetId != null && normalizeId(draftTargetId) !== normalizedPublishedTargetId) {
|
|
897
|
+
acc.push({
|
|
898
|
+
id: draftEntry.id,
|
|
899
|
+
draftTargetId
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
return acc;
|
|
903
|
+
}, []);
|
|
904
|
+
if (updates.length === 0) {
|
|
905
|
+
continue;
|
|
906
|
+
}
|
|
907
|
+
const caseFragments = updates.map(()=>'WHEN ? THEN ?').join(' ');
|
|
908
|
+
const idsPlaceholders = updates.map(()=>'?').join(', ');
|
|
909
|
+
await trx.raw(`UPDATE ?? SET ?? = CASE ?? ${caseFragments} ELSE ?? END WHERE ?? IN (${idsPlaceholders})`, [
|
|
910
|
+
meta.tableName,
|
|
911
|
+
foreignKeyColumn,
|
|
912
|
+
'id',
|
|
913
|
+
...updates.flatMap(({ id, draftTargetId })=>[
|
|
914
|
+
id,
|
|
915
|
+
draftTargetId
|
|
916
|
+
]),
|
|
917
|
+
foreignKeyColumn,
|
|
918
|
+
'id',
|
|
919
|
+
...updates.map(({ id })=>id)
|
|
920
|
+
]);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Copy component relations from published entries to draft entries
|
|
926
|
+
*/ async function copyComponentRelations({ trx, uid, publishedToDraftMap }) {
|
|
927
|
+
const meta = strapi.db.metadata.get(uid);
|
|
928
|
+
if (!meta) {
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
// Get collectionName from content type schema (Meta only has tableName which may be shortened)
|
|
932
|
+
const contentType = strapi.contentTypes[uid];
|
|
933
|
+
const collectionName = contentType?.collectionName;
|
|
934
|
+
if (!collectionName) {
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
const identifiers = strapi.db.metadata.identifiers;
|
|
938
|
+
const joinTableName = transformContentTypesToModels.getComponentJoinTableName(collectionName, identifiers);
|
|
939
|
+
const entityIdColumn = transformContentTypesToModels.getComponentJoinColumnEntityName(identifiers);
|
|
940
|
+
const componentIdColumn = transformContentTypesToModels.getComponentJoinColumnInverseName(identifiers);
|
|
941
|
+
const componentTypeColumn = transformContentTypesToModels.getComponentTypeColumn(identifiers);
|
|
942
|
+
const fieldColumn = identifiers.FIELD_COLUMN;
|
|
943
|
+
const orderColumn = identifiers.ORDER_COLUMN;
|
|
944
|
+
// Check if component join table exists
|
|
945
|
+
const hasTable = await trx.schema.hasTable(joinTableName);
|
|
946
|
+
if (!hasTable) {
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
const publishedIds = Array.from(publishedToDraftMap.keys());
|
|
950
|
+
// Process in batches to avoid MySQL query size limits
|
|
951
|
+
const publishedIdsChunks = chunkArray(publishedIds, 1000);
|
|
952
|
+
for (const publishedIdsChunk of publishedIdsChunks){
|
|
953
|
+
// Get component relations for published entries
|
|
954
|
+
const componentRelations = await trx(joinTableName).select('*').whereIn(entityIdColumn, publishedIdsChunk);
|
|
955
|
+
if (componentRelations.length === 0) {
|
|
956
|
+
continue;
|
|
957
|
+
}
|
|
958
|
+
const componentCloneCache = new Map();
|
|
959
|
+
const componentTargetDraftMapCache = new Map();
|
|
960
|
+
const componentHierarchyCaches = {
|
|
961
|
+
parentInstanceCache: new Map(),
|
|
962
|
+
ancestorDpCache: new Map(),
|
|
963
|
+
parentDpCache: new Map()
|
|
964
|
+
};
|
|
965
|
+
// Filter component relations: only propagate if component's parent in the component hierarchy doesn't have draft/publish
|
|
966
|
+
// This matches discardDraft() behavior via shouldPropagateComponentRelationToNewVersion
|
|
967
|
+
//
|
|
968
|
+
// The logic: find what contains this component instance (could be a content type or another component).
|
|
969
|
+
// If it's a component, recursively check its parents. If any parent in the chain has DP, filter out the relation.
|
|
970
|
+
const filteredComponentRelations = await Promise.all(componentRelations.map(async (relation)=>{
|
|
971
|
+
const componentId = relation[componentIdColumn];
|
|
972
|
+
const componentType = relation[componentTypeColumn];
|
|
973
|
+
const entityId = relation[entityIdColumn];
|
|
974
|
+
const componentSchema = strapi.components[componentType];
|
|
975
|
+
if (!componentSchema) {
|
|
976
|
+
debug(`[copyComponentRelations] ${uid}: Keeping relation - unknown component type ${componentType} (entity: ${entityId}, componentId: ${componentId})`);
|
|
977
|
+
return relation;
|
|
978
|
+
}
|
|
979
|
+
const componentParent = await findComponentParentInstance(trx, identifiers, componentSchema.uid, componentId, uid, componentHierarchyCaches);
|
|
980
|
+
if (!componentParent) {
|
|
981
|
+
debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}) is directly on entity ${entityId} (no nested parent found)`);
|
|
982
|
+
return relation;
|
|
983
|
+
}
|
|
984
|
+
debug(`[copyComponentRelations] ${uid}: Component ${componentType} (id: ${componentId}, entity: ${entityId}) has parent in hierarchy: ${componentParent.uid} (parentId: ${componentParent.parentId})`);
|
|
985
|
+
const hasDPParent = await hasDraftPublishAncestorForParent(trx, identifiers, componentParent, componentHierarchyCaches);
|
|
986
|
+
if (hasDPParent) {
|
|
987
|
+
debug(`[copyComponentRelations] Filtering: component ${componentType} (id: ${componentId}, entity: ${entityId}) has DP parent in hierarchy (${componentParent.uid})`);
|
|
988
|
+
return null;
|
|
989
|
+
}
|
|
990
|
+
debug(`[copyComponentRelations] ${uid}: Keeping relation - component ${componentType} (id: ${componentId}, entity: ${entityId}) has no DP parent in hierarchy`);
|
|
991
|
+
return relation;
|
|
992
|
+
}));
|
|
993
|
+
// Filter out null values (filtered relations)
|
|
994
|
+
const relationsToProcess = filteredComponentRelations.filter(Boolean);
|
|
995
|
+
const filteredCount = componentRelations.length - relationsToProcess.length;
|
|
996
|
+
if (filteredCount > 0) {
|
|
997
|
+
debug(`[copyComponentRelations] ${uid}: Filtered ${filteredCount} of ${componentRelations.length} component relations (removed ${filteredCount} with DP parents)`);
|
|
998
|
+
}
|
|
999
|
+
// Create new component relations for draft entries
|
|
1000
|
+
// Remove the 'id' field to avoid duplicate key errors
|
|
1001
|
+
const mappedRelations = (await Promise.all(relationsToProcess.map(async (relation)=>{
|
|
1002
|
+
const newEntityId = getMappedValue(publishedToDraftMap, relation[entityIdColumn]);
|
|
1003
|
+
if (!newEntityId) {
|
|
1004
|
+
return null;
|
|
1005
|
+
}
|
|
1006
|
+
const componentId = relation[componentIdColumn];
|
|
1007
|
+
const componentType = relation[componentTypeColumn];
|
|
1008
|
+
const componentKey = `${componentId}:${newEntityId}`;
|
|
1009
|
+
let cloneMap = componentCloneCache.get(componentType);
|
|
1010
|
+
if (!cloneMap) {
|
|
1011
|
+
cloneMap = new Map();
|
|
1012
|
+
componentCloneCache.set(componentType, cloneMap);
|
|
1013
|
+
}
|
|
1014
|
+
let newComponentId = cloneMap.get(componentKey);
|
|
1015
|
+
if (!newComponentId) {
|
|
1016
|
+
newComponentId = await cloneComponentInstance({
|
|
1017
|
+
trx,
|
|
1018
|
+
componentUid: componentType,
|
|
1019
|
+
componentId: Number(componentId),
|
|
1020
|
+
parentUid: uid,
|
|
1021
|
+
parentPublishedToDraftMap: publishedToDraftMap,
|
|
1022
|
+
draftMapCache: componentTargetDraftMapCache
|
|
1023
|
+
});
|
|
1024
|
+
cloneMap.set(componentKey, newComponentId);
|
|
1025
|
+
}
|
|
1026
|
+
const { id, ...relationWithoutId } = relation;
|
|
1027
|
+
return {
|
|
1028
|
+
...relationWithoutId,
|
|
1029
|
+
[entityIdColumn]: newEntityId,
|
|
1030
|
+
[componentIdColumn]: newComponentId
|
|
1031
|
+
};
|
|
1032
|
+
}))).filter(Boolean);
|
|
1033
|
+
// Deduplicate relations based on the unique constraint columns
|
|
1034
|
+
// This prevents duplicates within the same batch that could cause conflicts
|
|
1035
|
+
const uniqueKeyMap = new Map();
|
|
1036
|
+
for (const relation of mappedRelations){
|
|
1037
|
+
const uniqueKey = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
|
|
1038
|
+
if (!uniqueKeyMap.has(uniqueKey)) {
|
|
1039
|
+
uniqueKeyMap.set(uniqueKey, relation);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
const deduplicatedRelations = Array.from(uniqueKeyMap.values());
|
|
1043
|
+
if (deduplicatedRelations.length === 0) {
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
// Check which relations already exist in the database to avoid conflicts
|
|
1047
|
+
// We need to check all unique constraint columns (entity_id, cmp_id, field, component_type)
|
|
1048
|
+
const existingRelations = await trx(joinTableName).select([
|
|
1049
|
+
entityIdColumn,
|
|
1050
|
+
componentIdColumn,
|
|
1051
|
+
fieldColumn,
|
|
1052
|
+
componentTypeColumn
|
|
1053
|
+
]).where((qb)=>{
|
|
1054
|
+
// Build OR conditions for each relation we want to check
|
|
1055
|
+
for (const relation of deduplicatedRelations){
|
|
1056
|
+
qb.orWhere((subQb)=>{
|
|
1057
|
+
subQb.where(entityIdColumn, relation[entityIdColumn]).where(componentIdColumn, relation[componentIdColumn]).where(fieldColumn, relation[fieldColumn]).where(componentTypeColumn, relation[componentTypeColumn]);
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
});
|
|
1061
|
+
// Create a set of existing relation keys for fast lookup
|
|
1062
|
+
const existingKeys = new Set();
|
|
1063
|
+
for (const existing of existingRelations){
|
|
1064
|
+
const key = `${existing[entityIdColumn]}_${existing[componentIdColumn]}_${existing[fieldColumn]}_${existing[componentTypeColumn]}`;
|
|
1065
|
+
existingKeys.add(key);
|
|
1066
|
+
}
|
|
1067
|
+
// Filter out relations that already exist
|
|
1068
|
+
const newComponentRelations = deduplicatedRelations.filter((relation)=>{
|
|
1069
|
+
const key = `${relation[entityIdColumn]}_${relation[componentIdColumn]}_${relation[fieldColumn]}_${relation[componentTypeColumn]}`;
|
|
1070
|
+
return !existingKeys.has(key);
|
|
1071
|
+
});
|
|
1072
|
+
if (newComponentRelations.length > 0) {
|
|
1073
|
+
// Insert component relations while surfacing unexpected constraint issues.
|
|
1074
|
+
// Use INSERT ... ON CONFLICT DO NOTHING (PostgreSQL) or catch duplicate key errors explicitly for other clients.
|
|
1075
|
+
const client = trx.client.config.client;
|
|
1076
|
+
if (client === 'postgres' || client === 'pg') {
|
|
1077
|
+
// PostgreSQL: Insert one at a time with ON CONFLICT DO NOTHING
|
|
1078
|
+
// Use raw SQL for more reliable conflict handling
|
|
1079
|
+
let insertedCount = 0;
|
|
1080
|
+
let skippedCount = 0;
|
|
1081
|
+
for (const relation of newComponentRelations){
|
|
1082
|
+
try {
|
|
1083
|
+
// Use raw SQL - ?? is for identifiers, ? is for values in Knex
|
|
1084
|
+
const orderValue = relation[orderColumn] ?? null;
|
|
1085
|
+
await trx.raw(`INSERT INTO ?? (??, ??, ??, ??, ??) VALUES (?, ?, ?, ?, ?)
|
|
1086
|
+
ON CONFLICT (??, ??, ??, ??) DO NOTHING`, [
|
|
1087
|
+
joinTableName,
|
|
1088
|
+
entityIdColumn,
|
|
1089
|
+
componentIdColumn,
|
|
1090
|
+
fieldColumn,
|
|
1091
|
+
componentTypeColumn,
|
|
1092
|
+
orderColumn,
|
|
1093
|
+
relation[entityIdColumn],
|
|
1094
|
+
relation[componentIdColumn],
|
|
1095
|
+
relation[fieldColumn],
|
|
1096
|
+
relation[componentTypeColumn],
|
|
1097
|
+
orderValue,
|
|
1098
|
+
entityIdColumn,
|
|
1099
|
+
componentIdColumn,
|
|
1100
|
+
fieldColumn,
|
|
1101
|
+
componentTypeColumn
|
|
1102
|
+
]);
|
|
1103
|
+
insertedCount += 1;
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
// Ignore duplicate key errors (PostgreSQL error code 23505)
|
|
1106
|
+
// This can happen if the record already exists in the database
|
|
1107
|
+
if (error.code !== '23505' && !error.message?.includes('duplicate key')) {
|
|
1108
|
+
throw error;
|
|
1109
|
+
} else {
|
|
1110
|
+
skippedCount += 1;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
if (insertedCount > 0 || skippedCount > 0) {
|
|
1115
|
+
debug(`[copyComponentRelations] ${uid}: Inserted ${insertedCount} component relations, skipped ${skippedCount} duplicates`);
|
|
1116
|
+
}
|
|
1117
|
+
} else if (client === 'mysql' || client === 'mysql2') {
|
|
1118
|
+
try {
|
|
1119
|
+
await trx(joinTableName).insert(newComponentRelations);
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
if (error.code !== 'ER_DUP_ENTRY') {
|
|
1122
|
+
throw error;
|
|
1123
|
+
}
|
|
1124
|
+
for (const relation of newComponentRelations){
|
|
1125
|
+
try {
|
|
1126
|
+
await trx(joinTableName).insert(relation);
|
|
1127
|
+
} catch (err) {
|
|
1128
|
+
if (err.code !== 'ER_DUP_ENTRY') {
|
|
1129
|
+
throw err;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
} else {
|
|
1135
|
+
// SQLite: Try to insert and ignore errors
|
|
1136
|
+
for (const relation of newComponentRelations){
|
|
1137
|
+
try {
|
|
1138
|
+
await trx(joinTableName).insert(relation);
|
|
1139
|
+
} catch (error) {
|
|
1140
|
+
// Ignore duplicate key errors
|
|
1141
|
+
if (error.code !== 'SQLITE_CONSTRAINT_UNIQUE' && error.code !== '23505') {
|
|
1142
|
+
throw error;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* 2 pass migration to create the draft entries for all the published entries.
|
|
1152
|
+
* And then copy relations directly using database queries.
|
|
1153
|
+
*/ const migrateUp = async (trx, db)=>{
|
|
1154
|
+
strapi.log.info('[discard-drafts] Migration started');
|
|
1155
|
+
const dpModels = [];
|
|
1156
|
+
for (const meta of db.metadata.values()){
|
|
1157
|
+
const hasDP = await hasDraftAndPublish(trx, meta);
|
|
1158
|
+
if (hasDP) {
|
|
1159
|
+
dpModels.push(meta);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
debug(`Found ${dpModels.length} draft/publish content types to process`);
|
|
1163
|
+
/**
|
|
1164
|
+
* Create plain draft entries for all the entries that were published.
|
|
1165
|
+
*/ strapi.log.info('[discard-drafts] Stage 1/3 – cloning published entries into draft rows');
|
|
1166
|
+
for (const model of dpModels){
|
|
1167
|
+
debug(` • cloning scalars for ${model.uid}`);
|
|
1168
|
+
await copyPublishedEntriesToDraft({
|
|
1169
|
+
db,
|
|
1170
|
+
trx,
|
|
1171
|
+
uid: model.uid
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
strapi.log.info('[discard-drafts] Stage 1/3 complete');
|
|
1175
|
+
/**
|
|
1176
|
+
* Copy relations from published entries to draft entries using direct database queries.
|
|
1177
|
+
* This is much more efficient than calling discardDraft for each entry.
|
|
1178
|
+
*/ strapi.log.info('[discard-drafts] Stage 2/3 – copying relations and components to drafts');
|
|
1179
|
+
for (const model of dpModels){
|
|
1180
|
+
debug(` • copying relations for ${model.uid}`);
|
|
1181
|
+
await copyRelationsToDrafts({
|
|
1182
|
+
db,
|
|
1183
|
+
trx,
|
|
1184
|
+
uid: model.uid
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
strapi.log.info('[discard-drafts] Stage 2/3 complete');
|
|
1188
|
+
/**
|
|
1189
|
+
* Update JoinColumn relations (foreign keys) to point to draft versions
|
|
1190
|
+
* This matches discard() behavior: drafts relate to drafts
|
|
1191
|
+
*/ strapi.log.info('[discard-drafts] Stage 3/3 – updating foreign key references to draft targets');
|
|
1192
|
+
for (const model of dpModels){
|
|
1193
|
+
debug(` • updating join columns for ${model.uid}`);
|
|
1194
|
+
await updateJoinColumnRelations({
|
|
1195
|
+
db,
|
|
1196
|
+
trx,
|
|
1197
|
+
uid: model.uid
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
strapi.log.info('[discard-drafts] Stage 3/3 complete');
|
|
1201
|
+
strapi.log.info('[discard-drafts] Migration completed successfully');
|
|
1202
|
+
};
|
|
61
1203
|
/**
|
|
62
1204
|
* Load a batch of versions to discard.
|
|
63
1205
|
*
|
|
@@ -95,64 +1237,6 @@ var index = require('../../services/document-service/index.js');
|
|
|
95
1237
|
yield batch;
|
|
96
1238
|
}
|
|
97
1239
|
}
|
|
98
|
-
/**
|
|
99
|
-
* 2 pass migration to create the draft entries for all the published entries.
|
|
100
|
-
* And then discard the drafts to copy the relations.
|
|
101
|
-
*/ const migrateUp = async (trx, db)=>{
|
|
102
|
-
const dpModels = [];
|
|
103
|
-
for (const meta of db.metadata.values()){
|
|
104
|
-
const hasDP = await hasDraftAndPublish(trx, meta);
|
|
105
|
-
if (hasDP) {
|
|
106
|
-
dpModels.push(meta);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* Create plain draft entries for all the entries that were published.
|
|
111
|
-
*/ for (const model of dpModels){
|
|
112
|
-
await copyPublishedEntriesToDraft({
|
|
113
|
-
db,
|
|
114
|
-
trx,
|
|
115
|
-
uid: model.uid
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
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
|
-
});
|
|
138
|
-
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({
|
|
144
|
-
db,
|
|
145
|
-
trx,
|
|
146
|
-
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
|
-
}
|
|
154
|
-
}
|
|
155
|
-
};
|
|
156
1240
|
const discardDocumentDrafts = {
|
|
157
1241
|
name: 'core::5.0.0-discard-drafts',
|
|
158
1242
|
async up (trx, db) {
|