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