@mikro-orm/core 7.3.0-dev.2 → 7.3.0-dev.21
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.
- package/EntityManager.js +158 -42
- package/cache/cache-key.d.ts +5 -0
- package/cache/cache-key.js +30 -0
- package/drivers/DatabaseDriver.d.ts +2 -0
- package/drivers/DatabaseDriver.js +16 -3
- package/drivers/IDatabaseDriver.d.ts +2 -0
- package/entity/EntityAssigner.js +15 -3
- package/entity/EntityFactory.d.ts +8 -0
- package/entity/EntityFactory.js +69 -3
- package/entity/EntityLoader.d.ts +1 -0
- package/entity/EntityLoader.js +66 -23
- package/entity/WrappedEntity.js +6 -1
- package/entity/defineEntity.d.ts +32 -19
- package/entity/defineEntity.js +9 -0
- package/entity/validators.js +4 -1
- package/errors.d.ts +7 -0
- package/errors.js +15 -0
- package/hydration/ObjectHydrator.js +6 -2
- package/metadata/MetadataDiscovery.d.ts +10 -0
- package/metadata/MetadataDiscovery.js +178 -30
- package/metadata/MetadataStorage.d.ts +8 -0
- package/metadata/MetadataStorage.js +47 -3
- package/metadata/MetadataValidator.js +2 -1
- package/metadata/types.d.ts +12 -0
- package/package.json +1 -1
- package/platforms/Platform.d.ts +6 -0
- package/platforms/Platform.js +26 -0
- package/serialization/EntitySerializer.js +56 -16
- package/serialization/EntityTransformer.js +4 -4
- package/serialization/SerializationContext.d.ts +2 -1
- package/serialization/SerializationContext.js +4 -3
- package/types/DecimalType.js +34 -1
- package/types/DoubleType.d.ts +7 -3
- package/types/DoubleType.js +8 -3
- package/typings.d.ts +26 -6
- package/typings.js +5 -2
- package/unit-of-work/ChangeSetComputer.js +22 -7
- package/unit-of-work/ChangeSetPersister.js +24 -5
- package/unit-of-work/CommitOrderCalculator.js +2 -1
- package/unit-of-work/IdentityMap.d.ts +3 -2
- package/unit-of-work/IdentityMap.js +30 -7
- package/unit-of-work/UnitOfWork.js +49 -9
- package/utils/Configuration.d.ts +12 -1
- package/utils/DataloaderUtils.js +19 -8
- package/utils/EntityComparator.d.ts +5 -0
- package/utils/EntityComparator.js +87 -19
- package/utils/QueryHelper.d.ts +14 -0
- package/utils/QueryHelper.js +90 -13
- package/utils/RawQueryFragment.d.ts +5 -1
- package/utils/RawQueryFragment.js +27 -19
- package/utils/TransactionManager.js +4 -0
- package/utils/Utils.d.ts +2 -0
- package/utils/Utils.js +24 -8
- package/utils/clone.js +5 -7
- package/utils/env-vars.js +2 -0
- package/utils/fs-utils.js +19 -15
- package/utils/upsert-utils.js +2 -1
package/EntityManager.js
CHANGED
|
@@ -19,6 +19,7 @@ import { TransactionEventBroadcaster } from './events/TransactionEventBroadcaste
|
|
|
19
19
|
import { MetadataError, OptimisticLockError, ValidationError } from './errors.js';
|
|
20
20
|
import { applyPopulateHints, getLoadingStrategy } from './entity/utils.js';
|
|
21
21
|
import { TransactionManager } from './utils/TransactionManager.js';
|
|
22
|
+
import { scopeCacheKey, stringifyCacheKey } from './cache/cache-key.js';
|
|
22
23
|
/**
|
|
23
24
|
* The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems
|
|
24
25
|
* such as UnitOfWork, Query Language, and Repository API.
|
|
@@ -211,9 +212,14 @@ export class EntityManager {
|
|
|
211
212
|
await em.tryFlush(entityName, options);
|
|
212
213
|
const where = (await em.processWhere(entityName, options.where ?? {}, options, 'read'));
|
|
213
214
|
validateParams(where);
|
|
214
|
-
options.orderBy = options.orderBy || {};
|
|
215
|
-
options.populate = (await em.preparePopulate(entityName, options));
|
|
216
215
|
const meta = this.metadata.get(entityName);
|
|
216
|
+
if (meta.orderBy) {
|
|
217
|
+
options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
options.orderBy ??= {};
|
|
221
|
+
}
|
|
222
|
+
options.populate = (await em.preparePopulate(entityName, options));
|
|
217
223
|
em.validateIndexUsage(meta, options.where ?? {}, options);
|
|
218
224
|
options = { ...options };
|
|
219
225
|
// save the original hint value so we know it was infer/all
|
|
@@ -743,10 +749,15 @@ export class EntityManager {
|
|
|
743
749
|
if (Utils.isEmpty(options.orderBy) && !Raw.hasObjectFragments(options.orderBy)) {
|
|
744
750
|
throw new Error('Explicit `orderBy` option required');
|
|
745
751
|
}
|
|
752
|
+
const meta = this.metadata.get(entityName);
|
|
753
|
+
// same merge as em.find, so the cursor and the query see the same orderBy
|
|
754
|
+
if (meta.orderBy) {
|
|
755
|
+
options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
|
|
756
|
+
}
|
|
746
757
|
const [entities, count] = options.includeCount !== false
|
|
747
758
|
? await em.findAndCount(entityName, options.where, options)
|
|
748
759
|
: [await em.find(entityName, options.where, options)];
|
|
749
|
-
return new Cursor(entities, count, options,
|
|
760
|
+
return new Cursor(entities, count, options, meta);
|
|
750
761
|
}
|
|
751
762
|
/**
|
|
752
763
|
* Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been
|
|
@@ -781,26 +792,46 @@ export class EntityManager {
|
|
|
781
792
|
em.#unitOfWork.unsetIdentity(entity);
|
|
782
793
|
return null;
|
|
783
794
|
}
|
|
795
|
+
// `serialize()` applies `Type.toJSON()` and `serializedName`, take only relations and embeddables from it, scalars from the entity
|
|
796
|
+
const getData = (e, data = helper(e).serialize({
|
|
797
|
+
ignoreSerializers: true,
|
|
798
|
+
includeHidden: true,
|
|
799
|
+
convertCustomTypes: false,
|
|
800
|
+
})) => {
|
|
801
|
+
for (const prop of helper(e).__meta.props) {
|
|
802
|
+
if (prop.kind === ReferenceKind.SCALAR && !prop.ref) {
|
|
803
|
+
if (helper(e).__initialized || prop.primary) {
|
|
804
|
+
data[prop.name] = e[prop.name];
|
|
805
|
+
}
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
if (prop.serializedName && prop.serializedName in data) {
|
|
809
|
+
data[prop.name] = data[prop.serializedName];
|
|
810
|
+
}
|
|
811
|
+
if (prop.kind === ReferenceKind.EMBEDDED && e[prop.name] != null) {
|
|
812
|
+
Utils.asArray(e[prop.name]).forEach((item, i) => getData(item, prop.array ? data[prop.name][i] : data[prop.name]));
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return data;
|
|
816
|
+
};
|
|
817
|
+
const hydrate = (target, source) => {
|
|
818
|
+
em.config
|
|
819
|
+
.getHydrator(this.metadata)
|
|
820
|
+
.hydrate(target, helper(target).__meta, getData(source), em.#entityFactory, 'full', false, false);
|
|
821
|
+
Utils.merge(helper(target).__originalEntityData, this.#comparator.prepareEntity(source));
|
|
822
|
+
};
|
|
784
823
|
let found = false;
|
|
785
824
|
for (const e of fork.#unitOfWork.getIdentityMap()) {
|
|
786
825
|
const ref = em.getReference(e.constructor, helper(e).getPrimaryKey());
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
.
|
|
791
|
-
|
|
826
|
+
hydrate(ref, e);
|
|
827
|
+
// index a refreshed `targetKey` value, `getByKey` ignores the old one as stale
|
|
828
|
+
if (helper(ref).__meta.root.targetKeys) {
|
|
829
|
+
em.#unitOfWork.getIdentityMap().store(ref);
|
|
830
|
+
}
|
|
792
831
|
found ||= ref === entity;
|
|
793
832
|
}
|
|
794
833
|
if (!found) {
|
|
795
|
-
|
|
796
|
-
ignoreSerializers: true,
|
|
797
|
-
includeHidden: true,
|
|
798
|
-
convertCustomTypes: false,
|
|
799
|
-
});
|
|
800
|
-
em.config
|
|
801
|
-
.getHydrator(this.metadata)
|
|
802
|
-
.hydrate(entity, wrapped.__meta, data, em.#entityFactory, 'full', false, false);
|
|
803
|
-
Utils.merge(wrapped.__originalEntityData, this.#comparator.prepareEntity(reloaded));
|
|
834
|
+
hydrate(entity, reloaded);
|
|
804
835
|
}
|
|
805
836
|
return entity;
|
|
806
837
|
}
|
|
@@ -832,6 +863,10 @@ export class EntityManager {
|
|
|
832
863
|
return em.lockAndPopulate(meta, entity, where, options);
|
|
833
864
|
}
|
|
834
865
|
validateParams(where);
|
|
866
|
+
// before the cache key so cached results share the merged orderBy
|
|
867
|
+
if (meta.orderBy) {
|
|
868
|
+
options.orderBy = QueryHelper.mergeOrderBy(options.orderBy, meta.orderBy);
|
|
869
|
+
}
|
|
835
870
|
options.populate = (await em.preparePopulate(entityName, options));
|
|
836
871
|
const cacheKey = em.cacheKey(entityName, options, 'em.findOne', where);
|
|
837
872
|
const cached = await em.tryCache(entityName, options.cache, cacheKey, options.refresh, true, options.schema);
|
|
@@ -1021,6 +1056,15 @@ export class EntityManager {
|
|
|
1021
1056
|
where[meta.primaryKeys[0]] = ret.insertId;
|
|
1022
1057
|
}
|
|
1023
1058
|
}
|
|
1059
|
+
// a `null` unique value cannot identify the row, and as it never conflicts, the row was inserted
|
|
1060
|
+
if (!Utils.hasObjectKeys(where)) {
|
|
1061
|
+
const insertId = meta.simplePK && ret.insertId != null ? { [meta.primaryKeys[0]]: ret.insertId } : {};
|
|
1062
|
+
Object.assign(where, Utils.getPrimaryKeyCond(entity, meta.primaryKeys) ?? insertId);
|
|
1063
|
+
}
|
|
1064
|
+
// an empty condition would hydrate the entity from an arbitrary row, mongo still gets one for nested conflict fields
|
|
1065
|
+
if (!Utils.hasObjectKeys(where) && platform.usesPivotTable()) {
|
|
1066
|
+
throw new Error(`Cannot find the upserted ${meta.className} row, as neither its primary key nor a unique value is known`);
|
|
1067
|
+
}
|
|
1024
1068
|
const data2 = await em.withSessionContext(options.ctx ?? em.#transactionContext, ctx => this.driver.findOne(meta.class, where, {
|
|
1025
1069
|
fields: returning.concat(...(options.onConflictMergeFields ?? [])),
|
|
1026
1070
|
ctx,
|
|
@@ -1028,6 +1072,9 @@ export class EntityManager {
|
|
|
1028
1072
|
connectionType: 'write',
|
|
1029
1073
|
schema: options.schema,
|
|
1030
1074
|
}));
|
|
1075
|
+
if (!data2) {
|
|
1076
|
+
throw new Error(`Cannot find the upserted ${meta.className} row for condition ${JSON.stringify(where)}`);
|
|
1077
|
+
}
|
|
1031
1078
|
em.getHydrator().hydrate(entity, meta, data2, em.#entityFactory, 'full', false, true);
|
|
1032
1079
|
}
|
|
1033
1080
|
// recompute the data as there might be some values missing (e.g. those with db column defaults)
|
|
@@ -1179,8 +1226,10 @@ export class EntityManager {
|
|
|
1179
1226
|
unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
|
|
1180
1227
|
const tmp = getWhereCondition(meta, options.onConflictFields, row, where);
|
|
1181
1228
|
propIndex = tmp.propIndex;
|
|
1229
|
+
// a partial composite PK cannot identify the row
|
|
1230
|
+
const partialPK = meta.compositePK && !Utils.isPlainObject(tmp.where) && meta.primaryKeys.some(pk => row[pk] == null);
|
|
1182
1231
|
where = QueryHelper.processWhere({
|
|
1183
|
-
where: tmp.where,
|
|
1232
|
+
where: partialPK ? {} : tmp.where,
|
|
1184
1233
|
entityName,
|
|
1185
1234
|
metadata: this.metadata,
|
|
1186
1235
|
platform: this.getPlatform(),
|
|
@@ -1195,6 +1244,25 @@ export class EntityManager {
|
|
|
1195
1244
|
allWhere.push(where);
|
|
1196
1245
|
dataIndexes.push(i);
|
|
1197
1246
|
}
|
|
1247
|
+
// mongo inserts the rows with an empty condition as part of the batch and reports their ids
|
|
1248
|
+
const positional = !this.getPlatform().usesPivotTable() ||
|
|
1249
|
+
((this.getPlatform().usesReturningStatement() || this.getPlatform().usesOutputStatement()) &&
|
|
1250
|
+
options.onConflictAction !== 'ignore' &&
|
|
1251
|
+
!options.onConflictWhere);
|
|
1252
|
+
const hasUniqueKey = !!options.onConflictFields || meta.uniques.length > 0 || meta.props.some(p => p.unique && !p.primary);
|
|
1253
|
+
// only an autoincrement PK can be derived from the `insertId` of the batch
|
|
1254
|
+
const autoincrement = meta.getPrimaryProps().some(p => p.autoincrement);
|
|
1255
|
+
// a TPT child table does not return its rows, so they are never mapped by position
|
|
1256
|
+
const peel = !!meta.tptParent || (!positional && (hasUniqueKey || !autoincrement));
|
|
1257
|
+
// a row with a `null` unique value has nothing to be reloaded by, the single row path maps its PK from the insert
|
|
1258
|
+
for (let idx = 0; peel && idx < allWhere.length; idx++) {
|
|
1259
|
+
if (!Utils.hasObjectKeys(allWhere[idx])) {
|
|
1260
|
+
result[dataIndexes[idx]] = await em.upsert(entityName, data[dataIndexes[idx]], options);
|
|
1261
|
+
allData.splice(idx, 1);
|
|
1262
|
+
allWhere.splice(idx, 1);
|
|
1263
|
+
dataIndexes.splice(idx--, 1);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1198
1266
|
if (allData.length === 0) {
|
|
1199
1267
|
return [...new Set(result)];
|
|
1200
1268
|
}
|
|
@@ -1244,9 +1312,13 @@ export class EntityManager {
|
|
|
1244
1312
|
// skip the reload only when RETURNING brought back a row for every input
|
|
1245
1313
|
// (onConflictWhere can suppress writes, leaving some rows out)
|
|
1246
1314
|
// oxfmt-ignore
|
|
1247
|
-
const
|
|
1315
|
+
const getUniqueFields = (where) => options.onConflictFields ?? (Utils.isPlainObject(where) ? Object.keys(where).flatMap(key => Utils.splitPrimaryKeys(key)) : meta.primaryKeys);
|
|
1316
|
+
// a row without a condition has no unique fields to derive
|
|
1317
|
+
const uniqueFields = getUniqueFields(allWhere.find(cond => Utils.hasObjectKeys(cond)) ?? allWhere[0]);
|
|
1318
|
+
// an empty condition identifies no row, it must not turn into a reload condition matching every row
|
|
1319
|
+
const getRowUniqueFields = (where) => Utils.isPlainObject(where) && !Utils.hasObjectKeys(where) ? uniqueFields : getUniqueFields(where);
|
|
1248
1320
|
const platform = this.getPlatform();
|
|
1249
|
-
const returning = getOnConflictReturningFields(meta,
|
|
1321
|
+
const returning = getOnConflictReturningFields(meta, allData[0], uniqueFields, options, platform);
|
|
1250
1322
|
if (options.onConflictWhere && res.rows?.length !== allData.length) {
|
|
1251
1323
|
returning.push(...meta.comparableProps.filter(p => !p.lazy && !p.embeddable).map(p => p.name));
|
|
1252
1324
|
}
|
|
@@ -1261,10 +1333,14 @@ export class EntityManager {
|
|
|
1261
1333
|
Utils.keys(cond).forEach(key => add.add(key));
|
|
1262
1334
|
}
|
|
1263
1335
|
const where = { $or: [] };
|
|
1336
|
+
// a row without a condition was inserted, only the primary key reported for it can identify it
|
|
1337
|
+
const insertedPKs = allData.map((row, idx) => Utils.hasObjectKeys(allWhere[idx]) ? null : Utils.getPrimaryKeyCond(entitiesByData.get(row), meta.primaryKeys));
|
|
1264
1338
|
dataIndexes.forEach((index, idx) => {
|
|
1265
1339
|
const item = data[index];
|
|
1266
|
-
where.$or[idx] = {};
|
|
1267
|
-
|
|
1340
|
+
where.$or[idx] = { ...insertedPKs[idx] };
|
|
1341
|
+
// the inputs of one batch can be identified by different unique keys
|
|
1342
|
+
const fields = insertedPKs[idx] ? [] : getRowUniqueFields(allWhere[idx]);
|
|
1343
|
+
const props = Array.isArray(fields) ? fields : Object.keys(item);
|
|
1268
1344
|
props.forEach(prop => {
|
|
1269
1345
|
where.$or[idx][prop] = item[prop];
|
|
1270
1346
|
});
|
|
@@ -1279,8 +1355,8 @@ export class EntityManager {
|
|
|
1279
1355
|
connectionType: 'write',
|
|
1280
1356
|
schema: options.schema,
|
|
1281
1357
|
}));
|
|
1282
|
-
|
|
1283
|
-
const
|
|
1358
|
+
if (loadPK.size > 0) {
|
|
1359
|
+
const comparableRows = data2.map(row => {
|
|
1284
1360
|
const tmp = {};
|
|
1285
1361
|
add.forEach(k => {
|
|
1286
1362
|
const prop = meta.properties[k];
|
|
@@ -1288,25 +1364,58 @@ export class EntityManager {
|
|
|
1288
1364
|
tmp[k] = prop?.customType ? prop.customType.convertToDatabaseValue(row[k], this.getPlatform()) : row[k];
|
|
1289
1365
|
}
|
|
1290
1366
|
});
|
|
1291
|
-
return
|
|
1367
|
+
return tmp;
|
|
1292
1368
|
});
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1369
|
+
// rows carry the keys of every condition in the batch, compare only this one's
|
|
1370
|
+
const isMatch = (cond, idx) => this.#comparator.matching(entityName, cond, Object.fromEntries(Object.entries(comparableRows[idx]).filter(([k]) => k in cond)));
|
|
1371
|
+
// When every condition key is a comparable prop checked with `!==`, a matching row has the same primitive
|
|
1372
|
+
// values, so rows can be grouped by those values once instead of comparing every row for every entity.
|
|
1373
|
+
// Props outside `comparableProps` are skipped by the comparator, so they never qualify for grouping.
|
|
1374
|
+
const groupableProps = new Set(meta.comparableProps.filter(prop => this.#comparator.isStrictlyCompared(prop)));
|
|
1375
|
+
const groups = new Map();
|
|
1376
|
+
// `null` and `undefined` share a key, which can only make a group wider than what `matching` accepts
|
|
1377
|
+
const groupKey = (data, keys) => keys.map(k => (data[k] == null ? 'null' : `${typeof data[k]}:${data[k]}`)).join('\0');
|
|
1378
|
+
const findRowIndex = (cond) => {
|
|
1379
|
+
const keys = Utils.keys(cond);
|
|
1380
|
+
if (!keys.every(k => groupableProps.has(meta.properties[k]))) {
|
|
1381
|
+
return comparableRows.findIndex((_, idx) => isMatch(cond, idx));
|
|
1382
|
+
}
|
|
1383
|
+
const signature = keys.join('\0');
|
|
1384
|
+
if (!groups.has(signature)) {
|
|
1385
|
+
const rowsByKey = new Map();
|
|
1386
|
+
comparableRows.forEach((tmp, idx) => {
|
|
1387
|
+
const rowKey = groupKey(tmp, keys);
|
|
1388
|
+
const indexes = rowsByKey.get(rowKey) ?? [];
|
|
1389
|
+
indexes.push(idx);
|
|
1390
|
+
rowsByKey.set(rowKey, indexes);
|
|
1391
|
+
});
|
|
1392
|
+
groups.set(signature, rowsByKey);
|
|
1393
|
+
}
|
|
1394
|
+
const group = groups.get(signature);
|
|
1395
|
+
return group.get(groupKey(cond, keys))?.find(idx => isMatch(cond, idx)) ?? -1;
|
|
1396
|
+
};
|
|
1397
|
+
for (const [entity, cond] of loadPK.entries()) {
|
|
1398
|
+
const row = data2[findRowIndex(cond)];
|
|
1399
|
+
/* v8 ignore next */
|
|
1400
|
+
if (!row) {
|
|
1401
|
+
throw new Error(`Cannot find matching entity for condition ${JSON.stringify(cond)}`);
|
|
1402
|
+
}
|
|
1403
|
+
em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
|
|
1296
1404
|
}
|
|
1297
|
-
em.getHydrator().hydrate(entity, meta, row, em.#entityFactory, 'full', false, true);
|
|
1298
1405
|
}
|
|
1299
1406
|
if (loadPK.size !== data2.length && Array.isArray(uniqueFields)) {
|
|
1300
1407
|
for (let i = 0; i < allData.length; i++) {
|
|
1301
1408
|
const data = allData[i];
|
|
1302
|
-
const
|
|
1303
|
-
|
|
1304
|
-
a
|
|
1305
|
-
|
|
1306
|
-
|
|
1409
|
+
const fields = (insertedPKs[i] ? meta.primaryKeys : getRowUniqueFields(allWhere[i]));
|
|
1410
|
+
const cond = insertedPKs[i] ??
|
|
1411
|
+
fields.reduce((a, b) => {
|
|
1412
|
+
// @ts-ignore
|
|
1413
|
+
a[b] = data[b];
|
|
1414
|
+
return a;
|
|
1415
|
+
}, {});
|
|
1307
1416
|
const entity = entitiesByData.get(data);
|
|
1308
1417
|
const row = data2.find(item => {
|
|
1309
|
-
const pk =
|
|
1418
|
+
const pk = fields.reduce((a, b) => {
|
|
1310
1419
|
// @ts-ignore
|
|
1311
1420
|
a[b] = item[b];
|
|
1312
1421
|
return a;
|
|
@@ -1732,6 +1841,7 @@ export class EntityManager {
|
|
|
1732
1841
|
options.populateWhere = this.createPopulateWhere({ ...where }, options);
|
|
1733
1842
|
options.populateFilter = await this.getJoinedFilters(meta, options);
|
|
1734
1843
|
validateParams(where);
|
|
1844
|
+
em.validateIndexUsage(meta, where, options);
|
|
1735
1845
|
delete options.orderBy;
|
|
1736
1846
|
await em.processUnionWhere(entityName, options, 'read');
|
|
1737
1847
|
const cacheKey = em.cacheKey(entityName, options, 'em.count', where);
|
|
@@ -2289,7 +2399,17 @@ export class EntityManager {
|
|
|
2289
2399
|
}
|
|
2290
2400
|
let autoRefresh;
|
|
2291
2401
|
if (options.fields) {
|
|
2292
|
-
|
|
2402
|
+
// inline embeddables track only their leaf properties as loaded, not the parent
|
|
2403
|
+
const isLoaded = (prop) => helper(entity).__loadedProperties.has(prop.name) ||
|
|
2404
|
+
(prop.kind === ReferenceKind.EMBEDDED && !prop.object && Object.values(prop.embeddedProps).every(isLoaded));
|
|
2405
|
+
autoRefresh = options.fields.some(field => {
|
|
2406
|
+
const [first, ...rest] = field.split('.');
|
|
2407
|
+
let prop = meta.properties[first];
|
|
2408
|
+
for (const part of rest) {
|
|
2409
|
+
prop = prop?.kind === ReferenceKind.EMBEDDED && !prop.object ? prop.embeddedProps[part] : undefined;
|
|
2410
|
+
}
|
|
2411
|
+
return !prop || !isLoaded(prop);
|
|
2412
|
+
});
|
|
2293
2413
|
}
|
|
2294
2414
|
else {
|
|
2295
2415
|
autoRefresh = meta.comparableProps.some(prop => {
|
|
@@ -2359,11 +2479,7 @@ export class EntityManager {
|
|
|
2359
2479
|
const em = this.getContext();
|
|
2360
2480
|
// a named cache key (`config[0]`) discards the computed `key`, which already carries the session context — so
|
|
2361
2481
|
// scope it here too, otherwise a fork's rows would be served to another session context under the same name
|
|
2362
|
-
const cacheKey = Array.isArray(config)
|
|
2363
|
-
? em.#sessionContext
|
|
2364
|
-
? `${config[0]}|${JSON.stringify(em.#sessionContext)}`
|
|
2365
|
-
: config[0]
|
|
2366
|
-
: JSON.stringify(key);
|
|
2482
|
+
const cacheKey = Array.isArray(config) ? scopeCacheKey(config[0], em.#sessionContext) : stringifyCacheKey(key);
|
|
2367
2483
|
const cached = await em.#resultCache.get(cacheKey);
|
|
2368
2484
|
if (!cached) {
|
|
2369
2485
|
return { key: cacheKey, data: cached };
|
|
@@ -2416,7 +2532,7 @@ export class EntityManager {
|
|
|
2416
2532
|
await em.#resultCache.remove(cacheKey);
|
|
2417
2533
|
// named keys are scoped by the session context (see `tryCache`), so clear this context's variant too
|
|
2418
2534
|
if (em.#sessionContext) {
|
|
2419
|
-
await em.#resultCache.remove(
|
|
2535
|
+
await em.#resultCache.remove(scopeCacheKey(cacheKey, em.#sessionContext));
|
|
2420
2536
|
}
|
|
2421
2537
|
}
|
|
2422
2538
|
/**
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { SessionContext } from '../typings.js';
|
|
2
|
+
/** Serializes a result cache or dataloader batch key, telling apart all values a query can contain. */
|
|
3
|
+
export declare function stringifyCacheKey(key: unknown): string;
|
|
4
|
+
/** Scopes a named result cache key by the session context, so rows are not served across session contexts. */
|
|
5
|
+
export declare function scopeCacheKey(name: string, sessionContext?: SessionContext): string;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { isRaw, isSubquery, Raw } from '../utils/RawQueryFragment.js';
|
|
2
|
+
import { Utils } from '../utils/Utils.js';
|
|
3
|
+
// JSON loses RegExp patterns, `raw()` params and `raw()` keys (symbols), and throws on bigints and sub-queries; `this[key]` is the value before `toJSON()`
|
|
4
|
+
function replacer(key, value) {
|
|
5
|
+
const original = isSubquery(this[key]) ? this[key].toRaw() : this[key];
|
|
6
|
+
if (typeof original === 'bigint') {
|
|
7
|
+
return { bigint: original.toString() };
|
|
8
|
+
}
|
|
9
|
+
if (original instanceof RegExp) {
|
|
10
|
+
return { regexp: original.source, flags: original.flags };
|
|
11
|
+
}
|
|
12
|
+
if (isRaw(original)) {
|
|
13
|
+
return { sql: original.sql, params: original.params };
|
|
14
|
+
}
|
|
15
|
+
if (Raw.hasObjectFragments(value)) {
|
|
16
|
+
return Utils.getObjectQueryKeys(value).map(k => [
|
|
17
|
+
Raw.getKnownFragment(k) ?? k,
|
|
18
|
+
value[k],
|
|
19
|
+
]);
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
/** Serializes a result cache or dataloader batch key, telling apart all values a query can contain. */
|
|
24
|
+
export function stringifyCacheKey(key) {
|
|
25
|
+
return JSON.stringify(key, replacer);
|
|
26
|
+
}
|
|
27
|
+
/** Scopes a named result cache key by the session context, so rows are not served across session contexts. */
|
|
28
|
+
export function scopeCacheKey(name, sessionContext) {
|
|
29
|
+
return sessionContext ? `${name}|${JSON.stringify(sessionContext)}` : name;
|
|
30
|
+
}
|
|
@@ -81,6 +81,8 @@ export declare abstract class DatabaseDriver<C extends Connection> implements ID
|
|
|
81
81
|
*/
|
|
82
82
|
private mapCursorOffset;
|
|
83
83
|
protected createCursorCondition<T extends object>(definition: (readonly [keyof T & string, QueryOrder])[], offsets: Dictionary[], inverse: boolean, meta: EntityMetadata<T>, fromJson?: boolean): FilterQuery<T>;
|
|
84
|
+
/** @internal Polymorphic embeddable variants can declare same-named properties with different field names. */
|
|
85
|
+
protected variantProps(prop: EntityProperty, data?: Dictionary): Dictionary<EntityProperty>;
|
|
84
86
|
/** @internal */
|
|
85
87
|
mapDataToFieldNames(data: Dictionary, stringifyJsonArrays: boolean, properties?: Record<string, EntityProperty>, convertCustomTypes?: boolean, object?: boolean): Dictionary;
|
|
86
88
|
protected inlineEmbeddables<T extends object>(meta: EntityMetadata<T>, data: T, where?: boolean): void;
|
|
@@ -403,6 +403,19 @@ export class DatabaseDriver {
|
|
|
403
403
|
}
|
|
404
404
|
return { ...atOrPast, ...past };
|
|
405
405
|
}
|
|
406
|
+
/** @internal Polymorphic embeddable variants can declare same-named properties with different field names. */
|
|
407
|
+
variantProps(prop, data) {
|
|
408
|
+
const meta = prop.targetMeta;
|
|
409
|
+
// eslint-disable-next-line eqeqeq
|
|
410
|
+
const variant = meta?.polymorphs?.find(m => m.discriminatorValue == data?.[meta.discriminatorColumn]);
|
|
411
|
+
const props = variant ? { ...prop.embeddedProps } : prop.embeddedProps;
|
|
412
|
+
for (const p of variant ? Object.values(props) : []) {
|
|
413
|
+
if (variant.properties[p.embedded[1]] && Utils.isSameKind(variant.properties[p.embedded[1]], p)) {
|
|
414
|
+
props[p.embedded[1]] = p;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return props;
|
|
418
|
+
}
|
|
406
419
|
/** @internal */
|
|
407
420
|
mapDataToFieldNames(data, stringifyJsonArrays, properties, convertCustomTypes, object) {
|
|
408
421
|
if (!properties || data == null) {
|
|
@@ -417,17 +430,17 @@ export class DatabaseDriver {
|
|
|
417
430
|
if (prop.embeddedProps && !prop.object && !object) {
|
|
418
431
|
const copy = data[k];
|
|
419
432
|
delete data[k];
|
|
420
|
-
Object.assign(data, this.mapDataToFieldNames(copy, stringifyJsonArrays, prop
|
|
433
|
+
Object.assign(data, this.mapDataToFieldNames(copy, stringifyJsonArrays, this.variantProps(prop, copy), convertCustomTypes));
|
|
421
434
|
return;
|
|
422
435
|
}
|
|
423
436
|
if (prop.embeddedProps && (object || prop.object)) {
|
|
424
437
|
const copy = data[k];
|
|
425
438
|
delete data[k];
|
|
426
439
|
if (prop.array) {
|
|
427
|
-
data[prop.fieldNames[0]] = copy?.map((item) => this.mapDataToFieldNames(item, stringifyJsonArrays, prop
|
|
440
|
+
data[prop.fieldNames[0]] = copy?.map((item) => this.mapDataToFieldNames(item, stringifyJsonArrays, this.variantProps(prop, item), convertCustomTypes, true));
|
|
428
441
|
}
|
|
429
442
|
else {
|
|
430
|
-
data[prop.fieldNames[0]] = this.mapDataToFieldNames(copy, stringifyJsonArrays, prop
|
|
443
|
+
data[prop.fieldNames[0]] = this.mapDataToFieldNames(copy, stringifyJsonArrays, this.variantProps(prop, copy), convertCustomTypes, true);
|
|
431
444
|
}
|
|
432
445
|
if (stringifyJsonArrays && prop.array && !object) {
|
|
433
446
|
data[prop.fieldNames[0]] = this.platform.convertJsonToDatabaseValue(data[prop.fieldNames[0]]);
|
|
@@ -326,6 +326,8 @@ export interface CountOptions<T extends object, P extends string = never> extend
|
|
|
326
326
|
flushMode?: FlushMode | `${FlushMode}`;
|
|
327
327
|
/** SQL: appended to FROM clause (e.g. `'force index(my_index)'`); MongoDB: index name or spec passed as `hint`. */
|
|
328
328
|
indexHint?: string | Dictionary;
|
|
329
|
+
/** @see FindOptions.using */
|
|
330
|
+
using?: IndexName<T> | IndexName<T>[];
|
|
329
331
|
/** sql only */
|
|
330
332
|
comments?: string | string[];
|
|
331
333
|
/** sql only */
|
package/entity/EntityAssigner.js
CHANGED
|
@@ -234,14 +234,26 @@ export class EntityAssigner {
|
|
|
234
234
|
entity[propName].push(...Object.values(tmp));
|
|
235
235
|
});
|
|
236
236
|
}
|
|
237
|
+
const polymorphs = prop.targetMeta?.polymorphs;
|
|
238
|
+
// eslint-disable-next-line eqeqeq
|
|
239
|
+
const variant = polymorphs?.find(m => m.discriminatorValue == value[prop.targetMeta.discriminatorColumn]);
|
|
237
240
|
const create = () => EntityAssigner.validateEM(em) &&
|
|
238
|
-
em.getEntityFactory().createEmbeddable(prop.targetMeta.class, value, {
|
|
241
|
+
em.getEntityFactory().createEmbeddable((variant ?? prop.targetMeta).class, value, {
|
|
239
242
|
convertCustomTypes: options.convertCustomTypes,
|
|
240
243
|
newEntity: options.mergeEmbeddedProperties ? !('propName' in entity) : true,
|
|
241
244
|
});
|
|
242
|
-
|
|
245
|
+
// a different polymorphic variant cannot be merged into the current one
|
|
246
|
+
const merge = options.mergeEmbeddedProperties && (!variant || entity[propName]?.constructor === variant.class);
|
|
247
|
+
entity[propName] = (merge ? entity[propName] || create() : create());
|
|
248
|
+
const props = polymorphs ? { ...prop.embeddedProps } : prop.embeddedProps;
|
|
249
|
+
// polymorphic variants can declare same-named properties of different kinds or relation targets
|
|
250
|
+
for (const p of polymorphs ? entity[propName].__meta.props : []) {
|
|
251
|
+
if (props[p.name] && props[p.name].targetMeta?.class !== p.targetMeta?.class) {
|
|
252
|
+
props[p.name] = { ...p, nullable: prop.nullable || p.nullable };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
243
255
|
Object.keys(value).forEach(key => {
|
|
244
|
-
EntityAssigner.assignProperty(entity[propName], key,
|
|
256
|
+
EntityAssigner.assignProperty(entity[propName], key, props, value, options);
|
|
245
257
|
});
|
|
246
258
|
}
|
|
247
259
|
static createCollectionItem(item, em, prop, invalid, options) {
|
|
@@ -38,6 +38,13 @@ export declare class EntityFactory {
|
|
|
38
38
|
constructor(em: EntityManager);
|
|
39
39
|
/** Creates a new entity instance or returns an existing one from the identity map, hydrating it with the provided data. */
|
|
40
40
|
create<T extends object, P extends string = string>(entityName: EntityName<T>, data: EntityData<T>, options?: FactoryOptions): New<T, P>;
|
|
41
|
+
/**
|
|
42
|
+
* Whether merging `data` into an initialized entity would change nothing: every key is a scalar the entity already
|
|
43
|
+
* holds by identity, and keys `mergeData` always re-applies (formula, version, generated, discriminator) match the snapshot.
|
|
44
|
+
*/
|
|
45
|
+
private isNoopMerge;
|
|
46
|
+
/** Whether hydrating `value` into `prop` would leave `current` as is, mirroring the hydrator's Date and boolean coercion. */
|
|
47
|
+
private holdsValue;
|
|
41
48
|
/** Merges new data into an existing entity, preserving user-modified properties. */
|
|
42
49
|
mergeData<T extends object>(meta: EntityMetadata<T>, entity: T, data: EntityData<T>, options?: FactoryOptions): void;
|
|
43
50
|
/** Creates or retrieves an uninitialized entity reference by its primary key or alternate key. */
|
|
@@ -51,6 +58,7 @@ export declare class EntityFactory {
|
|
|
51
58
|
assignDefaultValues<T extends object>(entity: T, meta: EntityMetadata<T>, onCreateOnly?: boolean): void;
|
|
52
59
|
private hydrate;
|
|
53
60
|
private findEntity;
|
|
61
|
+
private findEntityByPrimaryKey;
|
|
54
62
|
private processDiscriminatorColumn;
|
|
55
63
|
/**
|
|
56
64
|
* denormalize PK to value required by driver (e.g. ObjectId)
|
package/entity/EntityFactory.js
CHANGED
|
@@ -55,6 +55,10 @@ export class EntityFactory {
|
|
|
55
55
|
Utils.dropUndefinedProperties(data);
|
|
56
56
|
this.mergeData(meta2, exists, data, options);
|
|
57
57
|
wrapped.__processing = false;
|
|
58
|
+
// index a merged `targetKey` value, `getByKey` ignores the old one as stale
|
|
59
|
+
if (meta2.root.targetKeys) {
|
|
60
|
+
this.unitOfWork.getIdentityMap().store(exists);
|
|
61
|
+
}
|
|
58
62
|
wrapped.__initialized ||= !!options.initialized;
|
|
59
63
|
if (wrapped.isInitialized()) {
|
|
60
64
|
if (!wasInitialized) {
|
|
@@ -145,8 +149,45 @@ export class EntityFactory {
|
|
|
145
149
|
wrapped.__processing = false;
|
|
146
150
|
return entity;
|
|
147
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Whether merging `data` into an initialized entity would change nothing: every key is a scalar the entity already
|
|
154
|
+
* holds by identity, and keys `mergeData` always re-applies (formula, version, generated, discriminator) match the snapshot.
|
|
155
|
+
*/
|
|
156
|
+
isNoopMerge(meta, entity, data, options) {
|
|
157
|
+
const wrapped = helper(entity);
|
|
158
|
+
if (!wrapped.__initialized || options.normalizeAccessors) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
for (const key of Utils.keys(data)) {
|
|
162
|
+
const prop = meta.properties[key];
|
|
163
|
+
const value = data[key];
|
|
164
|
+
// custom types are left to the full merge, as their JS and database values can differ
|
|
165
|
+
if (!prop || prop.customType || value === undefined || !this.holdsValue(prop, entity[key], value)) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
const reapplied = prop.formula || prop.version || prop.generated || key === meta.root.discriminatorColumn;
|
|
169
|
+
if (reapplied && (wrapped.__originalEntityData?.[key] !== value || !wrapped.__loadedProperties.has(key))) {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return true;
|
|
174
|
+
}
|
|
175
|
+
/** Whether hydrating `value` into `prop` would leave `current` as is, mirroring the hydrator's Date and boolean coercion. */
|
|
176
|
+
holdsValue(prop, current, value) {
|
|
177
|
+
if (current instanceof Date && value instanceof Date) {
|
|
178
|
+
return current.getTime() === value.getTime();
|
|
179
|
+
}
|
|
180
|
+
if (prop.runtimeType === 'boolean' && value != null) {
|
|
181
|
+
return current === !!value;
|
|
182
|
+
}
|
|
183
|
+
return current === value;
|
|
184
|
+
}
|
|
148
185
|
/** Merges new data into an existing entity, preserving user-modified properties. */
|
|
149
186
|
mergeData(meta, entity, data, options = {}) {
|
|
187
|
+
// joined rows often repeat exactly what the entity already holds, skip the snapshot and diffing then
|
|
188
|
+
if (this.isNoopMerge(meta, entity, data, options)) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
150
191
|
// merge unchanged properties automatically
|
|
151
192
|
data = QueryHelper.processParams(data);
|
|
152
193
|
const existsData = this.#comparator.prepareEntity(entity);
|
|
@@ -232,9 +273,9 @@ export class EntityFactory {
|
|
|
232
273
|
options.convertCustomTypes ??= true;
|
|
233
274
|
const meta = this.#metadata.get(entityName);
|
|
234
275
|
const schema = this.#driver.getSchemaName(meta, options);
|
|
235
|
-
// Handle alternate key lookup
|
|
236
|
-
if (options.key) {
|
|
237
|
-
const value =
|
|
276
|
+
// Handle alternate key lookup, a `key` pointing at the single PK is a plain PK reference
|
|
277
|
+
if (options.key && !(meta.primaryKeys.length === 1 && meta.primaryKeys[0] === options.key)) {
|
|
278
|
+
const value = Array.isArray(id) ? id[0] : Utils.isPlainObject(id) ? id[options.key] : id;
|
|
238
279
|
const exists = this.unitOfWork.getByKey(entityName, options.key, value, schema, options.convertCustomTypes);
|
|
239
280
|
if (exists) {
|
|
240
281
|
return exists;
|
|
@@ -242,6 +283,8 @@ export class EntityFactory {
|
|
|
242
283
|
// Create entity stub - storeByKey will set the alternate key property and store in identity map
|
|
243
284
|
const entity = this.create(entityName, {}, { ...options, initialized: false });
|
|
244
285
|
this.unitOfWork.storeByKey(entity, options.key, value, schema, options.convertCustomTypes);
|
|
286
|
+
// snapshot the stub like a PK reference, so flush treats it as existing instead of inserting it
|
|
287
|
+
helper(entity).__originalEntityData = this.#comparator.prepareEntity(entity);
|
|
245
288
|
return entity;
|
|
246
289
|
}
|
|
247
290
|
if (meta.simplePK) {
|
|
@@ -310,6 +353,12 @@ export class EntityFactory {
|
|
|
310
353
|
if (options.merge && !options.newEntity) {
|
|
311
354
|
this.#hydrator.hydrateReference(entity, meta, data, this, options.convertCustomTypes, options.schema, options.parentSchema);
|
|
312
355
|
this.unitOfWork.register(entity);
|
|
356
|
+
// relations hydrated together with this entity (joined strategy) resolve it via `targetKey` before it is hydrated
|
|
357
|
+
for (const key of meta.root.targetKeys ?? []) {
|
|
358
|
+
if (data[key] != null) {
|
|
359
|
+
this.unitOfWork.storeByKey(entity, key, data[key], schema, options.convertCustomTypes);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
313
362
|
}
|
|
314
363
|
if (options.initialized) {
|
|
315
364
|
EntityHelper.ensurePropagation(entity);
|
|
@@ -379,6 +428,23 @@ export class EntityFactory {
|
|
|
379
428
|
}
|
|
380
429
|
findEntity(data, meta, options) {
|
|
381
430
|
const schema = this.#driver.getSchemaName(meta, options);
|
|
431
|
+
const exists = this.findEntityByPrimaryKey(data, meta, schema, options);
|
|
432
|
+
// a new entity must not adopt a reference stub, that one is never inserted
|
|
433
|
+
if (exists || Array.isArray(data) || options.newEntity) {
|
|
434
|
+
return exists;
|
|
435
|
+
}
|
|
436
|
+
// a reference created via `targetKey` is only known by that key until the entity is loaded
|
|
437
|
+
for (const key of meta.root.targetKeys ?? []) {
|
|
438
|
+
if (data[key] != null) {
|
|
439
|
+
const ref = this.unitOfWork.getByKey(meta.class, key, data[key], schema, options.convertCustomTypes);
|
|
440
|
+
if (ref && !helper(ref).__initialized) {
|
|
441
|
+
return ref;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return undefined;
|
|
446
|
+
}
|
|
447
|
+
findEntityByPrimaryKey(data, meta, schema, options) {
|
|
382
448
|
if (meta.simplePK) {
|
|
383
449
|
return this.unitOfWork.getById(meta.class, data[meta.primaryKeys[0]], schema);
|
|
384
450
|
}
|
package/entity/EntityLoader.d.ts
CHANGED