@memberjunction/core 6.1.6 → 6.1.7
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/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts +14 -0
- package/dist/generic/JSONType-interfaces/IEntitySubtypeSelectorConfig.d.ts.map +1 -1
- package/dist/generic/baseEngine.d.ts +24 -0
- package/dist/generic/baseEngine.d.ts.map +1 -1
- package/dist/generic/baseEngine.js +21 -2
- package/dist/generic/baseEngine.js.map +1 -1
- package/dist/generic/baseEngineRegistry.d.ts +32 -11
- package/dist/generic/baseEngineRegistry.d.ts.map +1 -1
- package/dist/generic/baseEngineRegistry.js +77 -30
- package/dist/generic/baseEngineRegistry.js.map +1 -1
- package/dist/generic/baseEntity.d.ts +295 -1
- package/dist/generic/baseEntity.d.ts.map +1 -1
- package/dist/generic/baseEntity.js +1400 -45
- package/dist/generic/baseEntity.js.map +1 -1
- package/dist/generic/entityInfo.d.ts +12 -0
- package/dist/generic/entityInfo.d.ts.map +1 -1
- package/dist/generic/entityInfo.js +26 -2
- package/dist/generic/entityInfo.js.map +1 -1
- package/dist/generic/entitySubtypeResolver.d.ts +51 -5
- package/dist/generic/entitySubtypeResolver.d.ts.map +1 -1
- package/dist/generic/entitySubtypeResolver.js +50 -3
- package/dist/generic/entitySubtypeResolver.js.map +1 -1
- package/dist/generic/interfaces.d.ts +10 -0
- package/dist/generic/interfaces.d.ts.map +1 -1
- package/dist/generic/interfaces.js.map +1 -1
- package/dist/generic/localCacheManager.d.ts +13 -0
- package/dist/generic/localCacheManager.d.ts.map +1 -1
- package/dist/generic/localCacheManager.js +60 -0
- package/dist/generic/localCacheManager.js.map +1 -1
- package/dist/generic/logging.d.ts +15 -0
- package/dist/generic/logging.d.ts.map +1 -1
- package/dist/generic/logging.js +17 -0
- package/dist/generic/logging.js.map +1 -1
- package/dist/generic/providerBase.d.ts +19 -1
- package/dist/generic/providerBase.d.ts.map +1 -1
- package/dist/generic/providerBase.js +153 -29
- package/dist/generic/providerBase.js.map +1 -1
- package/dist/generic/util.d.ts +13 -1
- package/dist/generic/util.d.ts.map +1 -1
- package/dist/generic/util.js +56 -4
- package/dist/generic/util.js.map +1 -1
- package/package.json +3 -3
|
@@ -8,16 +8,17 @@ var __metadata = (this && this.__metadata) || function (k, v) {
|
|
|
8
8
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
9
|
};
|
|
10
10
|
var EntityField_1;
|
|
11
|
-
import { DeserializeValidationErrors, IsMemberOverridden, MJEventType, MJGlobal, OptionalKeyedSpecialization, uuidv4, UUIDsEqual, WarningManager } from '@memberjunction/global';
|
|
11
|
+
import { DeserializeValidationErrors, IsMemberOverridden, MJEventType, MJGlobal, NormalizeUUID, OptionalKeyedSpecialization, uuidv4, UUIDsEqual, WarningManager, EscapeSQLString } from '@memberjunction/global';
|
|
12
12
|
import { GetDataHooks } from './dataHooks.js';
|
|
13
13
|
import { EntityFieldInfo, EntityInfo, EntityFieldTSType, EntityPermissionType, FieldSecurityError, RecordChange, ValidationErrorInfo, ValidationResult } from './entityInfo.js';
|
|
14
14
|
import { EntitySubtypeResolver } from './entitySubtypeResolver.js';
|
|
15
|
+
import { CanonicalPrimaryKeyValue } from './util.js';
|
|
15
16
|
import { BaseEngineRegistry } from './baseEngineRegistry.js';
|
|
16
17
|
import { IsPermittedImageFieldValue, IsValidCssColor, TryParseJsonText } from './extendedTypeValue.js';
|
|
17
18
|
import { EntityDeleteOptions, EntitySaveOptions, ProviderType } from './interfaces.js';
|
|
18
19
|
import { Metadata } from './metadata.js';
|
|
19
20
|
import { RunView } from '../views/runView.js';
|
|
20
|
-
import { LogDebug, LogError } from './logging.js';
|
|
21
|
+
import { LogDebug, LogError, LogStatusEx, LogWarning } from './logging.js';
|
|
21
22
|
import { CompositeKey, KeyValuePair } from './compositeKey.js';
|
|
22
23
|
import { RelatedRecordCollection } from './relatedRecordCollection.js';
|
|
23
24
|
import { COMPANION_PAYLOAD_KEY } from './entityCompanion.js';
|
|
@@ -72,6 +73,9 @@ let EntityField = class EntityField {
|
|
|
72
73
|
get NotLoaded() {
|
|
73
74
|
return this._NotLoaded;
|
|
74
75
|
}
|
|
76
|
+
get NeverSet() {
|
|
77
|
+
return this._NeverSet;
|
|
78
|
+
}
|
|
75
79
|
/**
|
|
76
80
|
* Framework-internal: hydration paths call this for each field whose key the hydration
|
|
77
81
|
* source omitted. Application code should never need it — an explicit {@link Value} set
|
|
@@ -714,6 +718,10 @@ export class BaseEntityResult {
|
|
|
714
718
|
*/
|
|
715
719
|
export class BaseEntityEvent {
|
|
716
720
|
}
|
|
721
|
+
/** Entity names compare the way metadata lookups do: trimmed and case-insensitive. */
|
|
722
|
+
function sameEntityName(a, b) {
|
|
723
|
+
return a.trim().toLowerCase() === b.trim().toLowerCase();
|
|
724
|
+
}
|
|
717
725
|
export class BaseEntity {
|
|
718
726
|
/**
|
|
719
727
|
* Maximum number of `BaseEntityResult` entries retained in `_resultHistory` per entity
|
|
@@ -956,6 +964,17 @@ export class BaseEntity {
|
|
|
956
964
|
* loaded record. Reset to false on NewRecord() and init().
|
|
957
965
|
*/
|
|
958
966
|
this._childEntityDiscoveryDone = false;
|
|
967
|
+
/**
|
|
968
|
+
* Set only while this record's parent loads it because the parent's subtype rule named it
|
|
969
|
+
* (see {@link tryLinkHintedChildEntity}); read by {@link InnerLoad}.
|
|
970
|
+
*/
|
|
971
|
+
this._subtypeHintProbe = null;
|
|
972
|
+
/**
|
|
973
|
+
* Set only while {@link AttachToParent} loads this record as the parent it promotes. Child
|
|
974
|
+
* discovery then doesn't ask the subtype rule: the child row being added doesn't exist yet, so
|
|
975
|
+
* a hint would name it and miss.
|
|
976
|
+
*/
|
|
977
|
+
this._skipSubtypeLoadHint = false;
|
|
959
978
|
/**
|
|
960
979
|
* For **overlapping** subtype parents (AllowMultipleSubtypes = true), stores
|
|
961
980
|
* the list of child entity type names that have records for this PK.
|
|
@@ -1165,7 +1184,16 @@ export class BaseEntity {
|
|
|
1165
1184
|
name: pk.Name,
|
|
1166
1185
|
value: this._parentEntity.Get(pk.Name),
|
|
1167
1186
|
}));
|
|
1168
|
-
|
|
1187
|
+
// The parent's subtype rule isn't asked for a load hint here: it would name the child this
|
|
1188
|
+
// promotion is adding, whose row doesn't exist yet, and the miss would cost a round trip.
|
|
1189
|
+
this._parentEntity._skipSubtypeLoadHint = true;
|
|
1190
|
+
let loaded;
|
|
1191
|
+
try {
|
|
1192
|
+
loaded = await this._parentEntity.InnerLoad(parentKey);
|
|
1193
|
+
}
|
|
1194
|
+
finally {
|
|
1195
|
+
this._parentEntity._skipSubtypeLoadHint = false;
|
|
1196
|
+
}
|
|
1169
1197
|
if (!loaded) {
|
|
1170
1198
|
// Restore the fresh chain the failed load destroyed: re-seed the parent chain, then put
|
|
1171
1199
|
// the ORIGINAL minted key back (Set routes to the root), so the record the caller holds
|
|
@@ -1211,6 +1239,10 @@ export class BaseEntity {
|
|
|
1211
1239
|
* This ensures that Save/Delete operations always delegate to the leaf entity,
|
|
1212
1240
|
* running the full validation and event chain at every level.
|
|
1213
1241
|
*
|
|
1242
|
+
* For a disjoint parent, the entity's subtype rule is asked first (see
|
|
1243
|
+
* {@link resolveSubtypeLoadHint}); when it names a child, that child's load, which
|
|
1244
|
+
* happens anyway, checks the answer, and the discovery query runs only on a miss.
|
|
1245
|
+
*
|
|
1214
1246
|
* Must be called AFTER a record is loaded (PK must be available).
|
|
1215
1247
|
* Skipped for entities that are not parent types or have already been discovered.
|
|
1216
1248
|
*/
|
|
@@ -1225,12 +1257,48 @@ export class BaseEntity {
|
|
|
1225
1257
|
await this.discoverOverlappingChildren();
|
|
1226
1258
|
}
|
|
1227
1259
|
else {
|
|
1228
|
-
// Disjoint: discover single child
|
|
1229
|
-
|
|
1230
|
-
|
|
1260
|
+
// Disjoint: discover the single child and auto-chain it
|
|
1261
|
+
await this.initializeDisjointChildEntity();
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Finds and links the one child of a loaded disjoint parent.
|
|
1266
|
+
*
|
|
1267
|
+
* Without a hint this is one discovery query plus the child's load. With a hint from the
|
|
1268
|
+
* entity's subtype rule, the child's load checks the hint, and the discovery query runs
|
|
1269
|
+
* only when that load comes back empty or wasn't tried.
|
|
1270
|
+
*
|
|
1271
|
+
* For well-formed data the outcome is the one the discovery query alone would give: a hint
|
|
1272
|
+
* changes the number of round trips, not which child is linked or whether the load succeeds.
|
|
1273
|
+
* Three benign exceptions:
|
|
1274
|
+
* - a failure reading the hinted child's row falls back to the discovery query, so a transient
|
|
1275
|
+
* failure now recovers (a lasting one reads the row twice, then fails as before);
|
|
1276
|
+
* - when the data breaks the disjoint rule with two child rows, the discovery query's
|
|
1277
|
+
* unordered `UNION ALL` links either one, where a hint links the one the rule names;
|
|
1278
|
+
* - a provider without `FindISAChildEntity` links nothing without a hint, and the hinted child
|
|
1279
|
+
* with one.
|
|
1280
|
+
*/
|
|
1281
|
+
async initializeDisjointChildEntity() {
|
|
1282
|
+
const hintedName = await this.resolveSubtypeLoadHint();
|
|
1283
|
+
const hintOutcome = hintedName
|
|
1284
|
+
? await this.tryLinkHintedChildEntity(hintedName)
|
|
1285
|
+
: 'NotTried';
|
|
1286
|
+
if (hintOutcome === 'Linked')
|
|
1287
|
+
return;
|
|
1288
|
+
const childEntityName = await this.discoverChildEntityName();
|
|
1289
|
+
if (hintedName && hintOutcome === 'NotFound') {
|
|
1290
|
+
if (childEntityName && sameEntityName(childEntityName, hintedName)) {
|
|
1291
|
+
// The row exists but its load came back empty (for example, a row filter hides it).
|
|
1292
|
+
// Loading it again would too, and the discovery-only path unlinks it the same way,
|
|
1293
|
+
// after logging the empty load that the hinted attempt kept quiet.
|
|
1294
|
+
BaseEntity.logLoadFoundNoRow(hintedName, this.PrimaryKey);
|
|
1231
1295
|
return;
|
|
1232
|
-
|
|
1296
|
+
}
|
|
1297
|
+
this.reportSubtypeLoadHintMiss(hintedName, childEntityName);
|
|
1233
1298
|
}
|
|
1299
|
+
if (!childEntityName)
|
|
1300
|
+
return;
|
|
1301
|
+
await this.createAndLinkChildEntity(childEntityName);
|
|
1234
1302
|
}
|
|
1235
1303
|
/**
|
|
1236
1304
|
* Uses the provider's FindISAChildEntity method (single UNION ALL query) to
|
|
@@ -1263,12 +1331,29 @@ export class BaseEntity {
|
|
|
1263
1331
|
* Creates the child entity instance, wires up the shared instance chain
|
|
1264
1332
|
* (child._parentEntity = this, this._childEntity = child), loads the
|
|
1265
1333
|
* child's data, and recursively discovers further children.
|
|
1334
|
+
*
|
|
1335
|
+
* @returns true when the child's row loaded and the child is linked; false when the load
|
|
1336
|
+
* came back empty, in which case the link is undone.
|
|
1266
1337
|
*/
|
|
1267
1338
|
async createAndLinkChildEntity(childEntityName) {
|
|
1268
|
-
|
|
1269
|
-
|
|
1339
|
+
const childEntity = await this.createChildEntityObject(childEntityName);
|
|
1340
|
+
return this.linkAndLoadChildEntity(childEntity);
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1343
|
+
* Creates an unlinked child entity instance through this entity's provider, so the child
|
|
1344
|
+
* shares the same connection (correct in multi-provider scenarios — never the global default).
|
|
1345
|
+
*/
|
|
1346
|
+
async createChildEntityObject(childEntityName) {
|
|
1270
1347
|
const childProvider = this.ProviderToUse;
|
|
1271
|
-
|
|
1348
|
+
return childProvider.GetEntityObject(childEntityName, this._contextCurrentUser);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Links `childEntity` into this entity's chain and loads its row under the shared key.
|
|
1352
|
+
*
|
|
1353
|
+
* @returns true when the row loaded and the child is linked; false when the load came back
|
|
1354
|
+
* empty, in which case the link is undone.
|
|
1355
|
+
*/
|
|
1356
|
+
async linkAndLoadChildEntity(childEntity) {
|
|
1272
1357
|
// Wire up the shared instance chain: child's parent IS this entity (same object)
|
|
1273
1358
|
// We need to replace the child's auto-initialized parent with our existing instance
|
|
1274
1359
|
this.replaceChildParentChain(childEntity);
|
|
@@ -1280,20 +1365,245 @@ export class BaseEntity {
|
|
|
1280
1365
|
if (!loaded) {
|
|
1281
1366
|
// Load failed — clean up the link
|
|
1282
1367
|
this._childEntity = null;
|
|
1283
|
-
return;
|
|
1368
|
+
return false;
|
|
1284
1369
|
}
|
|
1285
1370
|
// Re-apply any pending modifications so child hydration does not overwrite unsaved in-memory edits
|
|
1286
1371
|
this.restoreChainDirtyState(dirtySnapshots);
|
|
1287
1372
|
// Recursively discover grandchildren (child may also be a parent type)
|
|
1288
1373
|
// InitializeChildEntity is idempotent via _childEntityDiscoveryDone flag
|
|
1289
1374
|
await childEntity.InitializeChildEntity();
|
|
1375
|
+
return true;
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Tries to link the child that the subtype rule named, by loading its row directly. That
|
|
1379
|
+
* load is the check on the hint.
|
|
1380
|
+
*
|
|
1381
|
+
* The hint isn't tried when the child object can't be created or the user can't read that
|
|
1382
|
+
* entity: the discovery-only path decides those cases, so a hint can neither expose a child
|
|
1383
|
+
* nor fail a load that works without it. A failure READING the hinted row is logged and
|
|
1384
|
+
* treated the same way: the discovery path runs, and reads the row again only if the discovery
|
|
1385
|
+
* query finds it. A failure after the row was read (the child's hydration, its eager
|
|
1386
|
+
* companions, its own child discovery) propagates, as it does on the discovery-only path.
|
|
1387
|
+
*
|
|
1388
|
+
* @returns `'Linked'` when the hinted child loaded and is linked, `'NotFound'` when its load
|
|
1389
|
+
* came back empty, and `'NotTried'` when it wasn't loaded or reading its row failed.
|
|
1390
|
+
*/
|
|
1391
|
+
async tryLinkHintedChildEntity(hintedName) {
|
|
1392
|
+
const childEntity = await this.createReadableHintedChild(hintedName);
|
|
1393
|
+
if (!childEntity) {
|
|
1394
|
+
return 'NotTried';
|
|
1395
|
+
}
|
|
1396
|
+
const probe = { RowReadFailed: false };
|
|
1397
|
+
childEntity._subtypeHintProbe = probe;
|
|
1398
|
+
try {
|
|
1399
|
+
return (await this.linkAndLoadChildEntity(childEntity)) ? 'Linked' : 'NotFound';
|
|
1400
|
+
}
|
|
1401
|
+
catch (e) {
|
|
1402
|
+
if (!probe.RowReadFailed) {
|
|
1403
|
+
throw e;
|
|
1404
|
+
}
|
|
1405
|
+
// Nothing after the row read ran, so the parent chain and its unsaved edits are untouched.
|
|
1406
|
+
this._childEntity = null;
|
|
1407
|
+
LogError(`IS-A load hint: reading the '${hintedName}' row for '${this.EntityInfo.Name}' record ${this.PrimaryKey.ToString()} failed (${BaseEntity.errorText(e)}); finding the subtype with the discovery query instead.`);
|
|
1408
|
+
return 'NotTried';
|
|
1409
|
+
}
|
|
1410
|
+
finally {
|
|
1411
|
+
childEntity._subtypeHintProbe = null;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Creates the child object the subtype rule named, or returns null when the user can't read
|
|
1416
|
+
* that entity. A failure to create it is logged and returns null too, so the discovery-only
|
|
1417
|
+
* path decides.
|
|
1418
|
+
*/
|
|
1419
|
+
async createReadableHintedChild(hintedName) {
|
|
1420
|
+
try {
|
|
1421
|
+
const childEntity = await this.createChildEntityObject(hintedName);
|
|
1422
|
+
return childEntity.CheckPermissions(EntityPermissionType.Read, false) ? childEntity : null;
|
|
1423
|
+
}
|
|
1424
|
+
catch (e) {
|
|
1425
|
+
LogError(`IS-A load hint: creating a '${hintedName}' object for '${this.EntityInfo.Name}' record ${this.PrimaryKey.ToString()} failed (${BaseEntity.errorText(e)}); finding the subtype with the discovery query instead.`);
|
|
1426
|
+
return null;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Asks the entity's subtype rule which child a LOADED record has, without running a query.
|
|
1431
|
+
*
|
|
1432
|
+
* - A registered {@link EntitySubtypeResolver} owns the rule. It gives a hint only when its
|
|
1433
|
+
* class overrides {@link EntitySubtypeResolver.ResolveLoadHint}. A resolver that doesn't
|
|
1434
|
+
* gives none, and the `SubtypeSelector` isn't consulted in its place: at create time the
|
|
1435
|
+
* resolver overrides the selector, so the selector may not describe the same rule.
|
|
1436
|
+
* - Otherwise a `SubtypeSelector` that sets `UseForLoadedRecords` is walked through rows that
|
|
1437
|
+
* loaded `BaseEngine` caches already hold. A hop that isn't cached gives no hint, not a query.
|
|
1438
|
+
* - An entity with no rule gets no hint. The single-child fallback of
|
|
1439
|
+
* {@link ResolveSubtypeEntityName} is a default for new records, not a rule about existing ones.
|
|
1440
|
+
* - While {@link AttachToParent} loads this record, no rule is asked: the child row being added
|
|
1441
|
+
* doesn't exist yet.
|
|
1442
|
+
*
|
|
1443
|
+
* An answer of "no subtype" also gives no hint: only the discovery query can tell whether an
|
|
1444
|
+
* older record still has a child row.
|
|
1445
|
+
*
|
|
1446
|
+
* @returns A declared IsA child's entity name, or null when there is no usable hint. Never throws.
|
|
1447
|
+
*/
|
|
1448
|
+
async resolveSubtypeLoadHint(batchUnfilteredCache) {
|
|
1449
|
+
if (this._skipSubtypeLoadHint) {
|
|
1450
|
+
return null;
|
|
1451
|
+
}
|
|
1452
|
+
const registration = MJGlobal.Instance.ClassFactory.GetRegistration(EntitySubtypeResolver, this.EntityInfo.Name);
|
|
1453
|
+
if (registration) {
|
|
1454
|
+
const resolver = BaseEntity.loadHintResolverFor(this.EntityInfo.Name, registration);
|
|
1455
|
+
return resolver ? this.askResolverForLoadHint(resolver) : null;
|
|
1456
|
+
}
|
|
1457
|
+
const selector = this.EntityInfo.SubtypeSelectorConfig;
|
|
1458
|
+
const selectorPath = selector?.UseForLoadedRecords ? selector.Path?.trim() : null;
|
|
1459
|
+
return selectorPath ? this.evaluateSelectorForLoadHint(selectorPath, batchUnfilteredCache) : null;
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* The resolver to ask for load hints for an entity, decided once per registration and cached:
|
|
1463
|
+
* null when the registered class doesn't override {@link EntitySubtypeResolver.ResolveLoadHint},
|
|
1464
|
+
* which is read from the class without constructing it, or when constructing it failed.
|
|
1465
|
+
*/
|
|
1466
|
+
static loadHintResolverFor(entityName, registration) {
|
|
1467
|
+
const key = entityName.trim().toLowerCase();
|
|
1468
|
+
const cached = BaseEntity._subtypeLoadHintResolvers.get(key);
|
|
1469
|
+
if (cached?.Registration === registration) {
|
|
1470
|
+
return cached.Resolver;
|
|
1471
|
+
}
|
|
1472
|
+
const resolver = BaseEntity.overridesResolveLoadHint(registration)
|
|
1473
|
+
? BaseEntity.constructLoadHintResolver(entityName)
|
|
1474
|
+
: null;
|
|
1475
|
+
BaseEntity._subtypeLoadHintResolvers.set(key, { Registration: registration, Resolver: resolver });
|
|
1476
|
+
return resolver;
|
|
1477
|
+
}
|
|
1478
|
+
/** Whether a registered resolver class overrides `ResolveLoadHint`, read from its prototype. */
|
|
1479
|
+
static overridesResolveLoadHint(registration) {
|
|
1480
|
+
const prototype = registration.SubClass?.prototype;
|
|
1481
|
+
const resolveLoadHint = prototype?.ResolveLoadHint;
|
|
1482
|
+
return typeof resolveLoadHint === 'function' && resolveLoadHint !== EntitySubtypeResolver.prototype.ResolveLoadHint;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Constructs the registered resolver once, to ask it for load hints. A failure is logged and
|
|
1486
|
+
* gives null; since the answer is cached, that is once per entity.
|
|
1487
|
+
*/
|
|
1488
|
+
static constructLoadHintResolver(entityName) {
|
|
1489
|
+
try {
|
|
1490
|
+
const resolution = MJGlobal.Instance.ClassFactory.TryCreateInstance(EntitySubtypeResolver, entityName);
|
|
1491
|
+
if (resolution.Resolved && resolution.Instance) {
|
|
1492
|
+
return resolution.Instance;
|
|
1493
|
+
}
|
|
1494
|
+
LogError(`IS-A load hint: the EntitySubtypeResolver registered for '${entityName}' did not resolve (${resolution.Reason ?? 'no reason given'}); loading its records without a hint.`);
|
|
1495
|
+
}
|
|
1496
|
+
catch (e) {
|
|
1497
|
+
LogError(`IS-A load hint: constructing the EntitySubtypeResolver registered for '${entityName}' failed (${BaseEntity.errorText(e)}); loading its records without a hint.`);
|
|
1498
|
+
}
|
|
1499
|
+
return null;
|
|
1500
|
+
}
|
|
1501
|
+
/**
|
|
1502
|
+
* Asks the resolver for a load hint. A resolver that throws or rejects gives no hint for that
|
|
1503
|
+
* record, and is logged once per entity rather than per record.
|
|
1504
|
+
*/
|
|
1505
|
+
async askResolverForLoadHint(resolver) {
|
|
1506
|
+
try {
|
|
1507
|
+
// A synchronous answer is used as-is, with no extra microtask per record.
|
|
1508
|
+
const raw = resolver.ResolveLoadHint(this);
|
|
1509
|
+
const candidate = raw instanceof Promise ? await raw : raw;
|
|
1510
|
+
return this.declaredChildForLoadHint(candidate, `EntitySubtypeResolver.ResolveLoadHint for '${this.EntityInfo.Name}'`);
|
|
1511
|
+
}
|
|
1512
|
+
catch (e) {
|
|
1513
|
+
BaseEntity.logSubtypeLoadHintOnce(`${this.EntityInfo.Name}|resolver-failed`, () => LogError(`IS-A load hint: EntitySubtypeResolver.ResolveLoadHint for '${this.EntityInfo.Name}' failed on record ${this.PrimaryKey.ToString()} (${BaseEntity.errorText(e)}). A record it fails on loads without a hint; this is reported once per entity.`));
|
|
1514
|
+
return null;
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Walks the `SubtypeSelector` path through engine caches only. A path that isn't valid for
|
|
1519
|
+
* this entity's metadata is logged once and gives no hint; the create path throws on it instead.
|
|
1520
|
+
*/
|
|
1521
|
+
async evaluateSelectorForLoadHint(path, batchUnfilteredCache) {
|
|
1522
|
+
try {
|
|
1523
|
+
const pathResult = await this.evaluateSubtypeSelectorPath(path, (entityName, pkValue) => BaseEntity.findSubtypePathTargetInEngineCache(entityName, pkValue, batchUnfilteredCache));
|
|
1524
|
+
return this.declaredChildForLoadHint(pathResult, `SubtypeSelector path '${path}' on '${this.EntityInfo.Name}'`);
|
|
1525
|
+
}
|
|
1526
|
+
catch (e) {
|
|
1527
|
+
BaseEntity.logSubtypeLoadHintOnce(`${this.EntityInfo.Name}|path|${path}`, () => LogError(`IS-A load hint: ${BaseEntity.errorText(e)} Loading '${this.EntityInfo.Name}' records without a hint.`));
|
|
1528
|
+
return null;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* Turns a rule's answer into a declared child's canonical entity name. Empty means no subtype,
|
|
1533
|
+
* which gives no hint. A name that isn't a declared IsA child is logged once and gives no hint.
|
|
1534
|
+
*/
|
|
1535
|
+
declaredChildForLoadHint(candidate, source) {
|
|
1536
|
+
const trimmed = candidate?.trim();
|
|
1537
|
+
if (!trimmed) {
|
|
1538
|
+
return null;
|
|
1539
|
+
}
|
|
1540
|
+
const match = this.findDeclaredChild(trimmed);
|
|
1541
|
+
if (!match) {
|
|
1542
|
+
BaseEntity.logSubtypeLoadHintOnce(`${this.EntityInfo.Name}|undeclared|${trimmed}`, () => LogError(`IS-A load hint: ${source} named '${trimmed}', which is not a declared IsA child entity of '${this.EntityInfo.Name}'. Loading the record without a hint.`));
|
|
1543
|
+
return null;
|
|
1544
|
+
}
|
|
1545
|
+
return match.Name;
|
|
1546
|
+
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Reports a hint the data didn't bear out: the hinted child's row wasn't there.
|
|
1549
|
+
*
|
|
1550
|
+
* When the discovery query finds no child either, that is a normal state, not an error: core
|
|
1551
|
+
* never creates a subtype row on save, so a typed record can exist without one (saved through
|
|
1552
|
+
* a generic form or an import, or older than its type's subtype). It logs one verbose line per
|
|
1553
|
+
* entity and hinted child. When the discovery query finds a DIFFERENT child, the rule and the
|
|
1554
|
+
* data disagree, and each such load costs an extra round trip until one of them is fixed; that
|
|
1555
|
+
* is logged as an error, once per entity, hinted child and child found.
|
|
1556
|
+
*/
|
|
1557
|
+
reportSubtypeLoadHintMiss(hintedName, discoveredName) {
|
|
1558
|
+
const entityName = this.EntityInfo.Name;
|
|
1559
|
+
if (!discoveredName) {
|
|
1560
|
+
BaseEntity.logSubtypeLoadHintOnce(`${entityName}|no-row|${hintedName}`, () => LogStatusEx({
|
|
1561
|
+
message: `IS-A load hint: a '${entityName}' record whose subtype rule names '${hintedName}' has no subtype row, so its load also ran the discovery query. Normal for a record saved before its subtype row; reported once.`,
|
|
1562
|
+
verboseOnly: true,
|
|
1563
|
+
}));
|
|
1564
|
+
return;
|
|
1565
|
+
}
|
|
1566
|
+
BaseEntity.logSubtypeLoadHintOnce(`${entityName}|disagree|${hintedName}|${discoveredName}`, () => LogError(`IS-A load hint: the subtype rule for '${entityName}' record ${this.PrimaryKey.ToString()} names '${hintedName}', but its subtype row is in '${discoveredName}'. The rule and the data disagree, and each such load costs an extra round trip until one of them is fixed. Reported once for this pair of subtypes.`));
|
|
1567
|
+
}
|
|
1568
|
+
/** Keys of load-hint messages already logged, so each is reported once rather than per record. */
|
|
1569
|
+
static { this._loggedSubtypeLoadHintMessages = new Set(); }
|
|
1570
|
+
/** Runs `log` the first time `key` is seen (case-insensitively), and not again until the caches are cleared. */
|
|
1571
|
+
static logSubtypeLoadHintOnce(key, log) {
|
|
1572
|
+
const normalizedKey = key.toLowerCase();
|
|
1573
|
+
if (BaseEntity._loggedSubtypeLoadHintMessages.has(normalizedKey)) {
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
BaseEntity._loggedSubtypeLoadHintMessages.add(normalizedKey);
|
|
1577
|
+
log();
|
|
1578
|
+
}
|
|
1579
|
+
static errorText(e) {
|
|
1580
|
+
return e instanceof Error ? e.message : String(e);
|
|
1290
1581
|
}
|
|
1291
1582
|
static { this._subtypeLookupCache = new Map(); }
|
|
1583
|
+
/** Per entity (lowercased name): the resolver asked for load hints, decided once per registration. */
|
|
1584
|
+
static { this._subtypeLoadHintResolvers = new Map(); }
|
|
1585
|
+
/** Indexes over engine-cached arrays, keyed by the live array itself; see {@link findEngineCachedRow}. */
|
|
1586
|
+
static { this._engineCachedRowIndexes = new WeakMap(); }
|
|
1292
1587
|
/**
|
|
1293
|
-
* Clears the static
|
|
1588
|
+
* Clears the static caches IsA subtype resolution keeps: the create path's SubtypeSelector
|
|
1589
|
+
* lookup memo, the per-entity decision about which resolver gives load hints, the indexes over
|
|
1590
|
+
* engine-cached rows, and the record of load-hint messages already logged, so each can be
|
|
1591
|
+
* reported again.
|
|
1294
1592
|
*/
|
|
1295
1593
|
static ClearSubtypeLookupCache() {
|
|
1296
1594
|
BaseEntity._subtypeLookupCache.clear();
|
|
1595
|
+
BaseEntity._subtypeLoadHintResolvers.clear();
|
|
1596
|
+
BaseEntity._engineCachedRowIndexes = new WeakMap();
|
|
1597
|
+
BaseEntity._loggedSubtypeLoadHintMessages.clear();
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* The declared IsA child entity named `name`, matched the way metadata lookups match names
|
|
1601
|
+
* (trimmed, case-insensitive), or undefined when this entity declares no such child. The one
|
|
1602
|
+
* lookup behind {@link ResolveSubtypeEntityName}, {@link EnsureISAChild} and load hints: the
|
|
1603
|
+
* create path throws on a miss, the load path logs it.
|
|
1604
|
+
*/
|
|
1605
|
+
findDeclaredChild(name) {
|
|
1606
|
+
return this.EntityInfo.ChildEntities?.find(c => sameEntityName(c.Name, name));
|
|
1297
1607
|
}
|
|
1298
1608
|
/**
|
|
1299
1609
|
* Prospective counterpart to FindISAChildEntity.
|
|
@@ -1303,6 +1613,12 @@ export class BaseEntity {
|
|
|
1303
1613
|
* 3. Unconditional single-child IsA fallback (ChildEntities.length === 1)
|
|
1304
1614
|
* 4. Otherwise null (no subtype)
|
|
1305
1615
|
*
|
|
1616
|
+
* This is the create-time ladder, and steps 1 and 2 may query. When a record is loaded,
|
|
1617
|
+
* BaseEntity asks a narrower, query-free version of it for a hint instead: the resolver's
|
|
1618
|
+
* `ResolveLoadHint` (not `Resolve`) when its class overrides it, the selector only when it sets
|
|
1619
|
+
* `UseForLoadedRecords` and only through rows that loaded `BaseEngine` caches hold, and never
|
|
1620
|
+
* step 3.
|
|
1621
|
+
*
|
|
1306
1622
|
* @see plans/sync-composition-axes.md
|
|
1307
1623
|
*/
|
|
1308
1624
|
async ResolveSubtypeEntityName() {
|
|
@@ -1317,8 +1633,7 @@ export class BaseEntity {
|
|
|
1317
1633
|
const raw = resolution.Instance.Resolve(this);
|
|
1318
1634
|
const candidate = raw instanceof Promise ? await raw : raw;
|
|
1319
1635
|
if (candidate != null && candidate.trim() !== '') {
|
|
1320
|
-
const
|
|
1321
|
-
const match = this.EntityInfo.ChildEntities.find(c => c.Name.trim().toLowerCase() === trimmed.toLowerCase());
|
|
1636
|
+
const match = this.findDeclaredChild(candidate);
|
|
1322
1637
|
if (!match) {
|
|
1323
1638
|
throw new Error(`EntitySubtypeResolver for '${this.EntityInfo.Name}' returned '${candidate}', which is not a declared IsA child entity of '${this.EntityInfo.Name}'.`);
|
|
1324
1639
|
}
|
|
@@ -1330,10 +1645,9 @@ export class BaseEntity {
|
|
|
1330
1645
|
// 2. Entity.SubtypeSelector declarative path
|
|
1331
1646
|
const selectorConfig = this.EntityInfo.SubtypeSelectorConfig;
|
|
1332
1647
|
if (selectorConfig && selectorConfig.Path && selectorConfig.Path.trim() !== '') {
|
|
1333
|
-
const pathResult = await this.evaluateSubtypeSelectorPath(selectorConfig.Path.trim());
|
|
1648
|
+
const pathResult = await this.evaluateSubtypeSelectorPath(selectorConfig.Path.trim(), (entityName, pkValue) => this.getSubtypePathTargetEntity(entityName, pkValue));
|
|
1334
1649
|
if (pathResult != null && pathResult.trim() !== '') {
|
|
1335
|
-
const
|
|
1336
|
-
const match = this.EntityInfo.ChildEntities.find(c => c.Name.trim().toLowerCase() === trimmed.toLowerCase());
|
|
1650
|
+
const match = this.findDeclaredChild(pathResult);
|
|
1337
1651
|
if (!match) {
|
|
1338
1652
|
throw new Error(`SubtypeSelector path '${selectorConfig.Path}' on '${this.EntityInfo.Name}' resolved to '${pathResult}', which is not a declared IsA child entity of '${this.EntityInfo.Name}'.`);
|
|
1339
1653
|
}
|
|
@@ -1364,7 +1678,7 @@ export class BaseEntity {
|
|
|
1364
1678
|
if (!entityName) {
|
|
1365
1679
|
return null;
|
|
1366
1680
|
}
|
|
1367
|
-
const matchedChild = this.
|
|
1681
|
+
const matchedChild = this.findDeclaredChild(entityName);
|
|
1368
1682
|
if (!matchedChild) {
|
|
1369
1683
|
throw new Error(`'${entityName}' is not a declared IsA child entity of '${this.EntityInfo.Name}'.`);
|
|
1370
1684
|
}
|
|
@@ -1438,7 +1752,19 @@ export class BaseEntity {
|
|
|
1438
1752
|
}
|
|
1439
1753
|
}
|
|
1440
1754
|
}
|
|
1441
|
-
|
|
1755
|
+
/**
|
|
1756
|
+
* Walks a `SubtypeSelector` path from this record to the column holding the subtype's entity
|
|
1757
|
+
* name, and returns that column's value, or null when a hop's foreign key is empty, a target
|
|
1758
|
+
* isn't found, or the terminal value is empty.
|
|
1759
|
+
*
|
|
1760
|
+
* @param path The dotted path, e.g. `ProductTypeID.ProductExtensionEntity`.
|
|
1761
|
+
* @param findTarget Finds the record a foreign key points at. Create time passes a finder that
|
|
1762
|
+
* may query; load time passes one that reads engine caches only, so a hop missing from them
|
|
1763
|
+
* ends the walk with null instead of a query.
|
|
1764
|
+
* @throws When the path doesn't fit this entity's metadata (a field isn't found, or a hop isn't
|
|
1765
|
+
* a foreign key).
|
|
1766
|
+
*/
|
|
1767
|
+
async evaluateSubtypeSelectorPath(path, findTarget) {
|
|
1442
1768
|
const segments = path.split('.').map(s => s.trim()).filter(Boolean);
|
|
1443
1769
|
if (segments.length === 0)
|
|
1444
1770
|
return null;
|
|
@@ -1458,7 +1784,7 @@ export class BaseEntity {
|
|
|
1458
1784
|
if (!relatedEntityName) {
|
|
1459
1785
|
throw new Error(`Invalid SubtypeSelector path '${path}' on '${this.EntityInfo.Name}': field '${fieldName}' on entity '${currentEntityInfo.Name}' is not a foreign key relationship.`);
|
|
1460
1786
|
}
|
|
1461
|
-
const targetEntity = await
|
|
1787
|
+
const targetEntity = await findTarget(relatedEntityName, fkValue);
|
|
1462
1788
|
if (!targetEntity) {
|
|
1463
1789
|
return null;
|
|
1464
1790
|
}
|
|
@@ -1482,21 +1808,10 @@ export class BaseEntity {
|
|
|
1482
1808
|
return BaseEntity._subtypeLookupCache.get(cacheKey) ?? null;
|
|
1483
1809
|
}
|
|
1484
1810
|
// 1. Check BaseEngineRegistry for loaded cached entities
|
|
1485
|
-
const
|
|
1486
|
-
if (
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
const firstPK = r.FirstPrimaryKey; // first-pk-ok: FK target — pkValue is one SubtypeSelector FK column's value
|
|
1490
|
-
if (firstPK) {
|
|
1491
|
-
return String(firstPK.Value).trim().toLowerCase() === String(pkValue).trim().toLowerCase();
|
|
1492
|
-
}
|
|
1493
|
-
return false;
|
|
1494
|
-
});
|
|
1495
|
-
if (found) {
|
|
1496
|
-
BaseEntity._subtypeLookupCache.set(cacheKey, found);
|
|
1497
|
-
return found;
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1811
|
+
const cached = BaseEntity.findSubtypePathTargetInEngineCache(entityName, pkValue);
|
|
1812
|
+
if (cached) {
|
|
1813
|
+
BaseEntity._subtypeLookupCache.set(cacheKey, cached);
|
|
1814
|
+
return cached;
|
|
1500
1815
|
}
|
|
1501
1816
|
// 2. Fall back to loading via provider
|
|
1502
1817
|
const provider = this.ProviderToUse;
|
|
@@ -1531,6 +1846,92 @@ export class BaseEntity {
|
|
|
1531
1846
|
BaseEntity._subtypeLookupCache.set(cacheKey, null);
|
|
1532
1847
|
return null;
|
|
1533
1848
|
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Finds the record a `SubtypeSelector` hop points at among the entity objects that loaded
|
|
1851
|
+
* `BaseEngine` caches (or the active `RunViews` batch) already hold. Never queries, and never
|
|
1852
|
+
* reads the create path's memo, whose entries can outlive a change to the row: engine caches
|
|
1853
|
+
* are kept current by entity events.
|
|
1854
|
+
*
|
|
1855
|
+
* `pkValue` is one foreign-key column's value, matched against the first primary key of the
|
|
1856
|
+
* cached rows' entity the way UUIDs compare (trimmed, case-insensitive).
|
|
1857
|
+
*
|
|
1858
|
+
* @returns The cached record, or null when no loaded engine holds it as an entity object.
|
|
1859
|
+
*/
|
|
1860
|
+
static findSubtypePathTargetInEngineCache(entityName, pkValue, batchUnfilteredCache) {
|
|
1861
|
+
const key = NormalizeUUID(String(pkValue));
|
|
1862
|
+
for (const match of BaseEngineRegistry.Instance.FindCachedEntity(entityName)) {
|
|
1863
|
+
const found = BaseEntity.findEngineCachedRow(match.records, key);
|
|
1864
|
+
if (found) {
|
|
1865
|
+
return found;
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
const batchRecords = batchUnfilteredCache?.get(entityName.trim().toLowerCase());
|
|
1869
|
+
if (batchRecords) {
|
|
1870
|
+
const found = BaseEntity.findEngineCachedRow(batchRecords, key);
|
|
1871
|
+
if (found) {
|
|
1872
|
+
return found;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
return null;
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* Finds the row whose key is `key` in an engine's live cached array through an index over the
|
|
1879
|
+
* array, not a scan per lookup. Keys are read with `Get()`, which leaves the rows an engine holds
|
|
1880
|
+
* in raw mode unhydrated.
|
|
1881
|
+
*
|
|
1882
|
+
* The array is the engine's own and changes under the index: a refresh replaces it, and a save,
|
|
1883
|
+
* delete or remote invalidation pushes a row, splices one out, or swaps one for a copy with the
|
|
1884
|
+
* same key. So the index is keyed by the array itself, and rebuilt when the array's length or
|
|
1885
|
+
* last element differs from when it was built, which every added or removed row changes. A hit
|
|
1886
|
+
* is checked against the row now at that position, and a row that moved makes the index rebuild
|
|
1887
|
+
* before the answer is trusted. A key that isn't indexed is a miss, which gives no hint on load
|
|
1888
|
+
* and falls back to a query at create time, as for a row no engine caches.
|
|
1889
|
+
*/
|
|
1890
|
+
static findEngineCachedRow(records, key) {
|
|
1891
|
+
let index = BaseEntity.currentEngineCachedRowIndex(records);
|
|
1892
|
+
let position = index.Positions.get(key);
|
|
1893
|
+
if (position !== undefined && BaseEntity.engineCachedRowKey(records[position], index.KeyField) !== key) {
|
|
1894
|
+
index = BaseEntity.buildEngineCachedRowIndex(records);
|
|
1895
|
+
position = index.Positions.get(key);
|
|
1896
|
+
}
|
|
1897
|
+
return position === undefined ? null : records[position];
|
|
1898
|
+
}
|
|
1899
|
+
/** The index over `records`, rebuilt when the array's length or last element changed since it was built. */
|
|
1900
|
+
static currentEngineCachedRowIndex(records) {
|
|
1901
|
+
const index = BaseEntity._engineCachedRowIndexes.get(records);
|
|
1902
|
+
if (index && index.Length === records.length && index.LastRow === records[records.length - 1]) {
|
|
1903
|
+
return index;
|
|
1904
|
+
}
|
|
1905
|
+
return BaseEntity.buildEngineCachedRowIndex(records);
|
|
1906
|
+
}
|
|
1907
|
+
/** Indexes `records` by key. Anything that isn't an entity object (a `'simple'` cache holds plain rows) is skipped. */
|
|
1908
|
+
static buildEngineCachedRowIndex(records) {
|
|
1909
|
+
const firstEntityRow = records.find(r => typeof r?.Get === 'function');
|
|
1910
|
+
const keyField = firstEntityRow?.EntityInfo?.FirstPrimaryKey?.Name ?? null; // first-pk-ok: FK target — a SubtypeSelector hop's foreign key holds one key value
|
|
1911
|
+
const positions = new Map();
|
|
1912
|
+
for (let i = 0; i < records.length; i++) {
|
|
1913
|
+
const rowKey = BaseEntity.engineCachedRowKey(records[i], keyField);
|
|
1914
|
+
if (rowKey !== null && !positions.has(rowKey)) {
|
|
1915
|
+
positions.set(rowKey, i);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
const index = {
|
|
1919
|
+
Length: records.length,
|
|
1920
|
+
LastRow: records[records.length - 1],
|
|
1921
|
+
KeyField: keyField,
|
|
1922
|
+
Positions: positions,
|
|
1923
|
+
};
|
|
1924
|
+
BaseEntity._engineCachedRowIndexes.set(records, index);
|
|
1925
|
+
return index;
|
|
1926
|
+
}
|
|
1927
|
+
/** A cached row's key, normalized with `NormalizeUUID`; null for a row that isn't an entity object or has no key value. */
|
|
1928
|
+
static engineCachedRowKey(row, keyField) {
|
|
1929
|
+
if (!keyField || typeof row?.Get !== 'function') {
|
|
1930
|
+
return null;
|
|
1931
|
+
}
|
|
1932
|
+
const value = row.Get(keyField);
|
|
1933
|
+
return value == null ? null : NormalizeUUID(String(value));
|
|
1934
|
+
}
|
|
1534
1935
|
captureChainDirtyState() {
|
|
1535
1936
|
const snapshots = [];
|
|
1536
1937
|
let curr = this;
|
|
@@ -4127,6 +4528,28 @@ export class BaseEntity {
|
|
|
4127
4528
|
const denied = select(u);
|
|
4128
4529
|
return denied.size > 0 ? denied : null;
|
|
4129
4530
|
}
|
|
4531
|
+
deniedReadFieldsForActiveUser() {
|
|
4532
|
+
return this.deniedFieldsForActiveUser(u => this.EntityInfo.GetDeniedReadFields(u));
|
|
4533
|
+
}
|
|
4534
|
+
narrowHydrationSource(source) {
|
|
4535
|
+
if (!source || typeof source !== 'object' || Array.isArray(source) || source instanceof Date) {
|
|
4536
|
+
return source;
|
|
4537
|
+
}
|
|
4538
|
+
const denied = this.deniedReadFieldsForActiveUser();
|
|
4539
|
+
if (!denied || denied.size === 0) {
|
|
4540
|
+
return source;
|
|
4541
|
+
}
|
|
4542
|
+
const record = source;
|
|
4543
|
+
let copy = null;
|
|
4544
|
+
for (const key of Object.keys(record)) {
|
|
4545
|
+
if (!denied.has(key.trim().toLowerCase())) {
|
|
4546
|
+
continue;
|
|
4547
|
+
}
|
|
4548
|
+
copy ??= { ...record };
|
|
4549
|
+
delete copy[key];
|
|
4550
|
+
}
|
|
4551
|
+
return (copy ?? source);
|
|
4552
|
+
}
|
|
4130
4553
|
/**
|
|
4131
4554
|
* {@link ActiveUser}, but null instead of throwing when no provider is configured to resolve
|
|
4132
4555
|
* one from.
|
|
@@ -4193,9 +4616,12 @@ export class BaseEntity {
|
|
|
4193
4616
|
if (!this.IsSaved) {
|
|
4194
4617
|
this.init(); // wipe out current data if we're loading on top of existing record
|
|
4195
4618
|
}
|
|
4196
|
-
const data = await this.
|
|
4619
|
+
const data = await this.readRowForLoad(CompositeKey, EntityRelationshipsToLoad);
|
|
4197
4620
|
if (!data) {
|
|
4198
|
-
|
|
4621
|
+
// A subtype-hint probe asks whether this row exists, so "no" is an answer, not an error
|
|
4622
|
+
if (!this._subtypeHintProbe) {
|
|
4623
|
+
BaseEntity.logLoadFoundNoRow(this.EntityInfo.Name, CompositeKey);
|
|
4624
|
+
}
|
|
4199
4625
|
return false; // no data loaded, return false
|
|
4200
4626
|
}
|
|
4201
4627
|
// IS-A: hydrate parent chain from loaded data before populating self.
|
|
@@ -4254,6 +4680,27 @@ export class BaseEntity {
|
|
|
4254
4680
|
this._isLoading = false;
|
|
4255
4681
|
}
|
|
4256
4682
|
}
|
|
4683
|
+
/**
|
|
4684
|
+
* The provider's read of the row {@link InnerLoad} loads. While this record is a subtype-hint
|
|
4685
|
+
* probe, a throw from the read is recorded on the probe before it propagates, so the parent
|
|
4686
|
+
* that asked can tell it apart from a failure after the row loaded.
|
|
4687
|
+
*/
|
|
4688
|
+
async readRowForLoad(key, relationshipsToLoad) {
|
|
4689
|
+
const user = this.ActiveUser;
|
|
4690
|
+
try {
|
|
4691
|
+
return await this.ProviderToUse.Load(this, key, relationshipsToLoad, user);
|
|
4692
|
+
}
|
|
4693
|
+
catch (e) {
|
|
4694
|
+
if (this._subtypeHintProbe) {
|
|
4695
|
+
this._subtypeHintProbe.RowReadFailed = true;
|
|
4696
|
+
}
|
|
4697
|
+
throw e;
|
|
4698
|
+
}
|
|
4699
|
+
}
|
|
4700
|
+
/** The error {@link InnerLoad} logs when the provider finds no row for the key. */
|
|
4701
|
+
static logLoadFoundNoRow(entityName, key) {
|
|
4702
|
+
LogError(`Error in BaseEntity.Load(${entityName}, Key: ${key.ToString()}`);
|
|
4703
|
+
}
|
|
4257
4704
|
/**
|
|
4258
4705
|
* Re-fetches the current record from the database using its existing primary key, replacing all in-memory field values
|
|
4259
4706
|
* with the latest data from the database. This is useful when you know (or suspect) the record has been modified externally
|
|
@@ -4339,12 +4786,26 @@ export class BaseEntity {
|
|
|
4339
4786
|
// This is the dominant warm-load case (cache restore in TransformSimpleObjectToEntityObject
|
|
4340
4787
|
// populating engine arrays of read-only data) and was previously the per-row bottleneck.
|
|
4341
4788
|
const isPlainObject = data && typeof data === 'object' && !Array.isArray(data) && !(data instanceof Date);
|
|
4789
|
+
const isFirstOrUnhydratedLoad = this._raw === null &&
|
|
4790
|
+
!this._recordLoaded &&
|
|
4791
|
+
!this._everSaved &&
|
|
4792
|
+
((!this._fieldsHydrated && this._Fields.length === 0) || this._Fields.every(f => f.NeverSet));
|
|
4793
|
+
const hasCompanionPayload = this.HasCompanions &&
|
|
4794
|
+
isPlainObject &&
|
|
4795
|
+
Array.isArray(data[COMPANION_PAYLOAD_KEY]);
|
|
4342
4796
|
const canTakeFastPath = isPlainObject &&
|
|
4343
|
-
|
|
4344
|
-
this._Fields.length === 0 &&
|
|
4797
|
+
isFirstOrUnhydratedLoad &&
|
|
4345
4798
|
!this._parentEntity &&
|
|
4346
|
-
!this.EntityInfo?.IsParentType
|
|
4799
|
+
!this.EntityInfo?.IsParentType &&
|
|
4800
|
+
!hasCompanionPayload;
|
|
4347
4801
|
if (canTakeFastPath) {
|
|
4802
|
+
if (this._fieldsHydrated || this._Fields.length > 0) {
|
|
4803
|
+
this._Fields = [];
|
|
4804
|
+
this._fieldsHydrated = false;
|
|
4805
|
+
this._fieldCache = null;
|
|
4806
|
+
this._codeNameCache = null;
|
|
4807
|
+
}
|
|
4808
|
+
this._compositeKey = null;
|
|
4348
4809
|
this._raw = data;
|
|
4349
4810
|
// Drop any conversions memoized from a previously-loaded row — they describe the old
|
|
4350
4811
|
// `_raw`, not this one. No isFrozen probe is needed: `Get()` never writes to `_raw`,
|
|
@@ -4415,6 +4876,866 @@ export class BaseEntity {
|
|
|
4415
4876
|
await this.deserializeCompanionsFromData(data);
|
|
4416
4877
|
return true;
|
|
4417
4878
|
}
|
|
4879
|
+
/**
|
|
4880
|
+
* Framework-internal batch IS-A parent hydration entry point used by
|
|
4881
|
+
* `TransformSimpleObjectToEntityObject` when the provider supports batched `RunViews`.
|
|
4882
|
+
*
|
|
4883
|
+
* Collapses $O(2N)$ per-record child-discovery and child-load queries into at most
|
|
4884
|
+
* 1 batched discovery query + 1 batched `RunViews` call per hierarchy depth level
|
|
4885
|
+
* (and 0 discovery queries when a `SubtypeSelector` / `EntitySubtypeResolver` resolves all rows).
|
|
4886
|
+
*/
|
|
4887
|
+
static { this.DEFAULT_ISA_BATCH_CHUNK_SIZE = 500; }
|
|
4888
|
+
/**
|
|
4889
|
+
* Maximum number of primary keys included in a single `WHERE PK IN (...)` batch query
|
|
4890
|
+
* during IS-A child discovery or hydration.
|
|
4891
|
+
*/
|
|
4892
|
+
static get ISABatchChunkSize() {
|
|
4893
|
+
return BaseEntity.DEFAULT_ISA_BATCH_CHUNK_SIZE;
|
|
4894
|
+
}
|
|
4895
|
+
async LoadFromDataBatchAsISAParent(peers, md, contextUser, batchUnfilteredCache) {
|
|
4896
|
+
const loadedParents = [];
|
|
4897
|
+
for (let i = 0; i < peers.length; i++) {
|
|
4898
|
+
const { entity, data } = peers[i];
|
|
4899
|
+
if (IsMemberOverridden(entity, 'LoadFromData', BaseEntity)) {
|
|
4900
|
+
await entity.LoadFromData(data);
|
|
4901
|
+
continue;
|
|
4902
|
+
}
|
|
4903
|
+
const allPksSet = await entity.hydrateSingleISAParentPeer(data);
|
|
4904
|
+
if (allPksSet) {
|
|
4905
|
+
loadedParents.push(entity);
|
|
4906
|
+
}
|
|
4907
|
+
}
|
|
4908
|
+
if (loadedParents.length > 0) {
|
|
4909
|
+
await BaseEntity.hydrateISAChildrenForLevel(loadedParents, md, contextUser, batchUnfilteredCache);
|
|
4910
|
+
}
|
|
4911
|
+
}
|
|
4912
|
+
/**
|
|
4913
|
+
* Clones `source` into `target` (already instantiated and bound to the destination provider/user)
|
|
4914
|
+
* while preserving an existing in-memory `ISAChild` chain without issuing redundant database
|
|
4915
|
+
* discovery or load queries. When `source` is a disjoint IS-A parent without an attached
|
|
4916
|
+
* `ISAChild`, delegates child resolution to `hydrateISAChildrenForLevel` so `BaseEngine`
|
|
4917
|
+
* caches are consulted before falling back to the provider.
|
|
4918
|
+
*/
|
|
4919
|
+
static async CloneEntityWithISAChain(source, target, md, contextUser) {
|
|
4920
|
+
if (source.EntityInfo?.IsParentType &&
|
|
4921
|
+
!source.EntityInfo.AllowMultipleSubtypes &&
|
|
4922
|
+
!IsMemberOverridden(target, 'LoadFromData', BaseEntity)) {
|
|
4923
|
+
const allPksSet = await target.hydrateSingleISAParentPeer(source);
|
|
4924
|
+
if (!allPksSet) {
|
|
4925
|
+
return;
|
|
4926
|
+
}
|
|
4927
|
+
if (source.ISAChild) {
|
|
4928
|
+
const deniedChildLogged = new Set();
|
|
4929
|
+
let currParent = target;
|
|
4930
|
+
let currSourceChild = source.ISAChild;
|
|
4931
|
+
while (currSourceChild) {
|
|
4932
|
+
const linked = [];
|
|
4933
|
+
const ok = await BaseEntity.linkSingleParentFromRawOrEntityRecord(currParent, currSourceChild.EntityInfo.Name, currSourceChild, linked, deniedChildLogged);
|
|
4934
|
+
currParent._childEntityDiscoveryDone = true;
|
|
4935
|
+
if (!ok || linked.length === 0) {
|
|
4936
|
+
break;
|
|
4937
|
+
}
|
|
4938
|
+
currParent = linked[0];
|
|
4939
|
+
currSourceChild = currSourceChild.ISAChild;
|
|
4940
|
+
}
|
|
4941
|
+
currParent._childEntityDiscoveryDone = true;
|
|
4942
|
+
}
|
|
4943
|
+
else {
|
|
4944
|
+
await BaseEntity.hydrateISAChildrenForLevel([target], md, contextUser);
|
|
4945
|
+
}
|
|
4946
|
+
return;
|
|
4947
|
+
}
|
|
4948
|
+
await target.LoadFromData(source.GetAll());
|
|
4949
|
+
}
|
|
4950
|
+
async hydrateSingleISAParentPeer(rawData) {
|
|
4951
|
+
const narrowed = this.narrowHydrationSource(rawData instanceof BaseEntity
|
|
4952
|
+
? rawData.GetAll()
|
|
4953
|
+
: rawData);
|
|
4954
|
+
if (this._parentEntity && narrowed && typeof narrowed === 'object' && !Array.isArray(narrowed)) {
|
|
4955
|
+
this._parentEntity.Hydrate(narrowed);
|
|
4956
|
+
}
|
|
4957
|
+
const isPlain = Boolean(narrowed && typeof narrowed === 'object' && !Array.isArray(narrowed) && !(narrowed instanceof Date));
|
|
4958
|
+
this.SetMany(narrowed, true, false, true);
|
|
4959
|
+
if (isPlain) {
|
|
4960
|
+
this.markFieldsOmittedBySourceAsNotLoaded(narrowed);
|
|
4961
|
+
}
|
|
4962
|
+
let allPksSet = false;
|
|
4963
|
+
if (this.PrimaryKeys && this.PrimaryKeys.length > 0) {
|
|
4964
|
+
allPksSet = true;
|
|
4965
|
+
for (const pkey of this.PrimaryKeys) {
|
|
4966
|
+
if (pkey.Value === null || pkey.Value === undefined) {
|
|
4967
|
+
allPksSet = false;
|
|
4968
|
+
break;
|
|
4969
|
+
}
|
|
4970
|
+
}
|
|
4971
|
+
this._recordLoaded = allPksSet;
|
|
4972
|
+
this._everSaved = allPksSet;
|
|
4973
|
+
if (allPksSet) {
|
|
4974
|
+
this.CacheRecordName();
|
|
4975
|
+
}
|
|
4976
|
+
}
|
|
4977
|
+
else {
|
|
4978
|
+
LogError(`BaseEntity.LoadFromDataBatchAsISAParent() called on ${this.EntityInfo.Name} with no primary keys defined. This is an error state and should not happen.`);
|
|
4979
|
+
this._recordLoaded = false;
|
|
4980
|
+
this._everSaved = false;
|
|
4981
|
+
}
|
|
4982
|
+
await this.deserializeCompanionsFromData(narrowed);
|
|
4983
|
+
return allPksSet;
|
|
4984
|
+
}
|
|
4985
|
+
static async hydrateISAChildrenForLevel(levelEntities, md, contextUser, batchUnfilteredCache) {
|
|
4986
|
+
const activeParents = levelEntities.filter(e => e._recordLoaded && e.EntityInfo.IsParentType && !e._childEntityDiscoveryDone && e.EntityInfo.ChildEntities.length > 0);
|
|
4987
|
+
if (activeParents.length === 0) {
|
|
4988
|
+
return;
|
|
4989
|
+
}
|
|
4990
|
+
const groupsByEntityId = new Map();
|
|
4991
|
+
for (const p of activeParents) {
|
|
4992
|
+
p._childEntityDiscoveryDone = true;
|
|
4993
|
+
let group = groupsByEntityId.get(p.EntityInfo.ID);
|
|
4994
|
+
if (!group) {
|
|
4995
|
+
group = [];
|
|
4996
|
+
groupsByEntityId.set(p.EntityInfo.ID, group);
|
|
4997
|
+
}
|
|
4998
|
+
group.push(p);
|
|
4999
|
+
}
|
|
5000
|
+
const nextLevelChildren = [];
|
|
5001
|
+
for (const [, groupParents] of groupsByEntityId) {
|
|
5002
|
+
const sampleParent = groupParents[0];
|
|
5003
|
+
if (sampleParent.EntityInfo.AllowMultipleSubtypes) {
|
|
5004
|
+
await BaseEntity.hydrateOverlappingChildrenForGroup(groupParents, md, contextUser, batchUnfilteredCache);
|
|
5005
|
+
}
|
|
5006
|
+
else {
|
|
5007
|
+
await BaseEntity.hydrateDisjointChildrenForGroup(groupParents, md, contextUser, nextLevelChildren, batchUnfilteredCache);
|
|
5008
|
+
}
|
|
5009
|
+
}
|
|
5010
|
+
if (nextLevelChildren.some(c => c.EntityInfo.IsParentType)) {
|
|
5011
|
+
await BaseEntity.hydrateISAChildrenForLevel(nextLevelChildren, md, contextUser, batchUnfilteredCache);
|
|
5012
|
+
}
|
|
5013
|
+
}
|
|
5014
|
+
static async hydrateOverlappingChildrenForGroup(groupParents, md, contextUser, batchUnfilteredCache) {
|
|
5015
|
+
const sampleParent = groupParents[0];
|
|
5016
|
+
const parentInfo = sampleParent.EntityInfo;
|
|
5017
|
+
const entityProvider = sampleParent.ProviderToUse;
|
|
5018
|
+
const rvProvider = sampleParent.RunViewProviderToUse;
|
|
5019
|
+
const effectiveUser = contextUser ?? sampleParent._contextCurrentUser ?? md.CurrentUser;
|
|
5020
|
+
const validChildren = parentInfo.ChildEntities.filter(c => c.FirstPrimaryKey != null); // first-pk-ok: IS-A children share the parent's single key
|
|
5021
|
+
if (validChildren.length === 0) {
|
|
5022
|
+
for (const p of groupParents) {
|
|
5023
|
+
p._childEntities = [];
|
|
5024
|
+
}
|
|
5025
|
+
return;
|
|
5026
|
+
}
|
|
5027
|
+
const childLookups = validChildren.map(childInfo => {
|
|
5028
|
+
const pkField = childInfo.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5029
|
+
const pkIsUuid = Boolean(pkField.IsUniqueIdentifier);
|
|
5030
|
+
const cachedRecords = BaseEntity.findUnfilteredInMemoryChildRecords(childInfo, entityProvider, md, effectiveUser, batchUnfilteredCache);
|
|
5031
|
+
return {
|
|
5032
|
+
childInfo,
|
|
5033
|
+
pkField,
|
|
5034
|
+
pkIsUuid,
|
|
5035
|
+
cachedByPk: cachedRecords ? BaseEntity.buildInMemoryChildLookupMap(cachedRecords, pkField.Name, pkIsUuid) : null,
|
|
5036
|
+
};
|
|
5037
|
+
});
|
|
5038
|
+
if (childLookups.every(c => c.cachedByPk !== null)) {
|
|
5039
|
+
for (const p of groupParents) {
|
|
5040
|
+
const rawPk = String(p.PrimaryKey.Values());
|
|
5041
|
+
const matched = [];
|
|
5042
|
+
for (const c of childLookups) {
|
|
5043
|
+
const pkKey = CanonicalPrimaryKeyValue(rawPk, c.pkIsUuid);
|
|
5044
|
+
if (c.cachedByPk?.has(pkKey)) {
|
|
5045
|
+
matched.push({ entityName: c.childInfo.Name });
|
|
5046
|
+
}
|
|
5047
|
+
}
|
|
5048
|
+
p._childEntities = matched;
|
|
5049
|
+
}
|
|
5050
|
+
return;
|
|
5051
|
+
}
|
|
5052
|
+
if (typeof entityProvider?.FindISAChildEntitiesBatch === 'function') {
|
|
5053
|
+
const pks = groupParents.map(p => String(p.PrimaryKey.Values()));
|
|
5054
|
+
const batchMap = await entityProvider.FindISAChildEntitiesBatch(parentInfo, pks, effectiveUser);
|
|
5055
|
+
const pkField = parentInfo.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5056
|
+
for (const p of groupParents) {
|
|
5057
|
+
const rawPk = String(p.PrimaryKey.Values());
|
|
5058
|
+
const pkKey = pkField ? pkField.FormatCanonicalValue(rawPk) : CanonicalPrimaryKeyValue(rawPk, false);
|
|
5059
|
+
const matched = batchMap.get(pkKey) ?? [];
|
|
5060
|
+
p._childEntities = matched.map(name => ({ entityName: name }));
|
|
5061
|
+
}
|
|
5062
|
+
return;
|
|
5063
|
+
}
|
|
5064
|
+
if (rvProvider && typeof rvProvider.RunViews === 'function') {
|
|
5065
|
+
const chunkSize = BaseEntity.ISABatchChunkSize;
|
|
5066
|
+
const rawPks = Array.from(new Set(groupParents.map(p => String(p.PrimaryKey.Values()))));
|
|
5067
|
+
const uncachedLookups = childLookups.filter(c => c.cachedByPk === null);
|
|
5068
|
+
const params = [];
|
|
5069
|
+
const meta = [];
|
|
5070
|
+
for (const c of uncachedLookups) {
|
|
5071
|
+
for (let i = 0; i < rawPks.length; i += chunkSize) {
|
|
5072
|
+
const chunk = rawPks.slice(i, i + chunkSize);
|
|
5073
|
+
params.push({
|
|
5074
|
+
EntityName: c.childInfo.Name,
|
|
5075
|
+
ExtraFilter: BaseEntity.buildChildPkInFilter(c.pkField, chunk),
|
|
5076
|
+
Fields: [c.pkField.Name],
|
|
5077
|
+
ResultType: 'simple',
|
|
5078
|
+
BypassCache: true,
|
|
5079
|
+
// Key-bounded (at most one row per PK in the chunk): the entity's
|
|
5080
|
+
// UserViewMaxRows cap protects nothing here and would drop subtypes.
|
|
5081
|
+
IgnoreMaxRows: true,
|
|
5082
|
+
});
|
|
5083
|
+
meta.push(c);
|
|
5084
|
+
}
|
|
5085
|
+
}
|
|
5086
|
+
for (const c of uncachedLookups) {
|
|
5087
|
+
c.cachedByPk = new Map();
|
|
5088
|
+
}
|
|
5089
|
+
if (params.length > 0) {
|
|
5090
|
+
const rv = new RunView(rvProvider);
|
|
5091
|
+
const results = await rv.RunViews(params, effectiveUser);
|
|
5092
|
+
for (let i = 0; i < results.length; i++) {
|
|
5093
|
+
const res = results[i];
|
|
5094
|
+
const c = meta[i];
|
|
5095
|
+
if (!res?.Success || !Array.isArray(res.Results)) {
|
|
5096
|
+
LogWarning(`BaseEntity: batched IS-A child load of '${c.childInfo.Name}' failed (${res?.ErrorMessage || 'no result'}); matching parent record(s) continue without their subtype`, 'IS-A');
|
|
5097
|
+
continue;
|
|
5098
|
+
}
|
|
5099
|
+
for (const row of res.Results) {
|
|
5100
|
+
const pkVal = row[c.pkField.Name];
|
|
5101
|
+
if (pkVal != null) {
|
|
5102
|
+
c.cachedByPk?.set(CanonicalPrimaryKeyValue(String(pkVal), c.pkIsUuid), row);
|
|
5103
|
+
}
|
|
5104
|
+
}
|
|
5105
|
+
}
|
|
5106
|
+
}
|
|
5107
|
+
for (const p of groupParents) {
|
|
5108
|
+
const rawPk = String(p.PrimaryKey.Values());
|
|
5109
|
+
const matched = [];
|
|
5110
|
+
for (const c of childLookups) {
|
|
5111
|
+
const pkKey = CanonicalPrimaryKeyValue(rawPk, c.pkIsUuid);
|
|
5112
|
+
if (c.cachedByPk?.has(pkKey)) {
|
|
5113
|
+
matched.push({ entityName: c.childInfo.Name });
|
|
5114
|
+
}
|
|
5115
|
+
}
|
|
5116
|
+
p._childEntities = matched;
|
|
5117
|
+
}
|
|
5118
|
+
return;
|
|
5119
|
+
}
|
|
5120
|
+
await Promise.all(groupParents.map(p => p.discoverOverlappingChildren()));
|
|
5121
|
+
}
|
|
5122
|
+
static async hydrateDisjointChildrenForGroup(groupParents, md, contextUser, nextLevelChildren, batchUnfilteredCache) {
|
|
5123
|
+
const sampleParent = groupParents[0];
|
|
5124
|
+
const parentInfo = sampleParent.EntityInfo;
|
|
5125
|
+
const entityProvider = sampleParent.ProviderToUse;
|
|
5126
|
+
const rvProvider = sampleParent.RunViewProviderToUse;
|
|
5127
|
+
const effectiveUser = contextUser ?? sampleParent._contextCurrentUser;
|
|
5128
|
+
const deniedChildLogged = new Set();
|
|
5129
|
+
// 1) Evaluate in-memory SubtypeSelector / EntitySubtypeResolver load hints
|
|
5130
|
+
const { hintedByChild, hintedNameByParent, needsDiscovery } = await BaseEntity.partitionParentsBySubtypeLoadHint(groupParents, parentInfo, md, contextUser, batchUnfilteredCache);
|
|
5131
|
+
// 2) Batch-load hinted child rows (from unfiltered memory caches first, then at most 1 RunViews call);
|
|
5132
|
+
// any missing/failed row falls back to discovery
|
|
5133
|
+
// Hinted parents whose child read succeeded and had no row (as opposed to a read that
|
|
5134
|
+
// failed or was not tried): only those are hint misses, as in the per-row path.
|
|
5135
|
+
const hintNotFound = new Set();
|
|
5136
|
+
if (hintedByChild.size > 0) {
|
|
5137
|
+
const unlinkedFromHints = await BaseEntity.batchLoadAndLinkDisjointChildren(hintedByChild, md, entityProvider, rvProvider, effectiveUser, nextLevelChildren, deniedChildLogged, batchUnfilteredCache, hintNotFound);
|
|
5138
|
+
needsDiscovery.push(...unlinkedFromHints);
|
|
5139
|
+
}
|
|
5140
|
+
// 3) Discover and hydrate remaining unresolved parents (consulting unfiltered memory caches first,
|
|
5141
|
+
// then 1 single-pass RunViews call when FindISAChildEntitiesBatch is absent)
|
|
5142
|
+
if (needsDiscovery.length > 0) {
|
|
5143
|
+
const discoveredByParent = await BaseEntity.discoverAndHydrateDisjointChildren(parentInfo, needsDiscovery, md, entityProvider, rvProvider, effectiveUser, nextLevelChildren, deniedChildLogged, batchUnfilteredCache, new Map(Array.from(hintNotFound, p => [p, hintedNameByParent.get(p) ?? ''])));
|
|
5144
|
+
for (const p of hintNotFound) {
|
|
5145
|
+
BaseEntity.reportBatchSubtypeLoadHintMiss(p, hintedNameByParent.get(p), discoveredByParent.get(p) ?? null);
|
|
5146
|
+
}
|
|
5147
|
+
}
|
|
5148
|
+
}
|
|
5149
|
+
/**
|
|
5150
|
+
* The batch twin of the per-row path's diagnostics in {@link initializeDisjointChildEntity}, for
|
|
5151
|
+
* a parent whose hinted child had no row, run once discovery has had its say. When discovery
|
|
5152
|
+
* found the hinted child but could not link it, the row exists and its load came back empty, so
|
|
5153
|
+
* the empty load is logged, as the discovery-only path logs it. Anything else goes to
|
|
5154
|
+
* {@link reportSubtypeLoadHintMiss}: quiet (verbose, once) when no subtype row exists at all,
|
|
5155
|
+
* which is a normal state, and an error once per pair when the row is in a different child.
|
|
5156
|
+
*/
|
|
5157
|
+
static reportBatchSubtypeLoadHintMiss(parent, hintedName, discoveredName) {
|
|
5158
|
+
if (!hintedName) {
|
|
5159
|
+
return;
|
|
5160
|
+
}
|
|
5161
|
+
if (discoveredName && sameEntityName(discoveredName, hintedName)) {
|
|
5162
|
+
if (!parent._childEntity) {
|
|
5163
|
+
BaseEntity.logLoadFoundNoRow(hintedName, parent.PrimaryKey);
|
|
5164
|
+
}
|
|
5165
|
+
return;
|
|
5166
|
+
}
|
|
5167
|
+
parent.reportSubtypeLoadHintMiss(hintedName, discoveredName);
|
|
5168
|
+
}
|
|
5169
|
+
/**
|
|
5170
|
+
* Discovers and links the child of each disjoint parent.
|
|
5171
|
+
*
|
|
5172
|
+
* @param readFoundNoRow - The child each parent's hinted read already found no row in. When
|
|
5173
|
+
* discovery names that same child, its row exists but reads back empty (a row filter), so it
|
|
5174
|
+
* is not read again; the per-row path stops there too.
|
|
5175
|
+
* @returns The child each parent was found to have, whether or not it could then be linked.
|
|
5176
|
+
* A parent with no child, or whose child could not be determined, is absent.
|
|
5177
|
+
*/
|
|
5178
|
+
static async discoverAndHydrateDisjointChildren(parentInfo, parents, md, entityProvider, rvProvider, contextUser, outLinkedChildren, deniedChildLogged, batchUnfilteredCache, readFoundNoRow = new Map()) {
|
|
5179
|
+
const discoveredByParent = new Map();
|
|
5180
|
+
const validChildren = parentInfo.ChildEntities.filter(c => c.FirstPrimaryKey != null); // first-pk-ok: IS-A children share the parent's single key
|
|
5181
|
+
if (validChildren.length === 0) {
|
|
5182
|
+
return discoveredByParent;
|
|
5183
|
+
}
|
|
5184
|
+
const userForPerm = contextUser ?? parents[0]?._contextCurrentUser ?? md.CurrentUser;
|
|
5185
|
+
const readableChildren = [];
|
|
5186
|
+
for (const child of validChildren) {
|
|
5187
|
+
const canRead = userForPerm ? child.GetUserPermisions(userForPerm).CanRead : true;
|
|
5188
|
+
if (!canRead) {
|
|
5189
|
+
if (!deniedChildLogged.has(child.Name)) {
|
|
5190
|
+
deniedChildLogged.add(child.Name);
|
|
5191
|
+
LogWarning(`BaseEntity: current user cannot read IS-A child '${child.Name}'; matching parent records are returned without their subtype`, 'IS-A');
|
|
5192
|
+
}
|
|
5193
|
+
continue;
|
|
5194
|
+
}
|
|
5195
|
+
const pkField = child.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5196
|
+
const pkIsUuid = Boolean(pkField.IsUniqueIdentifier);
|
|
5197
|
+
const cachedRecords = BaseEntity.findUnfilteredInMemoryChildRecords(child, entityProvider, md, userForPerm, batchUnfilteredCache);
|
|
5198
|
+
readableChildren.push({
|
|
5199
|
+
childInfo: child,
|
|
5200
|
+
pkField,
|
|
5201
|
+
pkIsUuid,
|
|
5202
|
+
cachedByPk: cachedRecords ? BaseEntity.buildInMemoryChildLookupMap(cachedRecords, pkField.Name, pkIsUuid) : null,
|
|
5203
|
+
});
|
|
5204
|
+
}
|
|
5205
|
+
if (readableChildren.length === 0) {
|
|
5206
|
+
return discoveredByParent;
|
|
5207
|
+
}
|
|
5208
|
+
// In a disjoint IS-A hierarchy (`AllowMultipleSubtypes === false`), each parent record
|
|
5209
|
+
// belongs to at most one child subtype across all `ChildEntities`. Resolve any parent whose
|
|
5210
|
+
// PK matches an unfiltered in-memory child cache (from BaseEngineRegistry or the active
|
|
5211
|
+
// RunViews batch) immediately with 0 queries, and only probe uncached child entities for
|
|
5212
|
+
// the remaining unresolved parents.
|
|
5213
|
+
const cachedChildren = readableChildren.filter(rc => rc.cachedByPk !== null);
|
|
5214
|
+
const uncachedChildren = readableChildren.filter(rc => rc.cachedByPk === null);
|
|
5215
|
+
let remainingParents = [];
|
|
5216
|
+
if (cachedChildren.length > 0) {
|
|
5217
|
+
for (const p of parents) {
|
|
5218
|
+
const rawPk = String(p.PrimaryKey.Values());
|
|
5219
|
+
let linkedFromMemory = false;
|
|
5220
|
+
for (const rc of cachedChildren) {
|
|
5221
|
+
const pkKey = CanonicalPrimaryKeyValue(rawPk, rc.pkIsUuid);
|
|
5222
|
+
const matched = rc.cachedByPk?.get(pkKey);
|
|
5223
|
+
if (matched) {
|
|
5224
|
+
discoveredByParent.set(p, rc.childInfo.Name);
|
|
5225
|
+
await BaseEntity.linkSingleParentFromRawOrEntityRecord(p, rc.childInfo.Name, matched, outLinkedChildren, deniedChildLogged);
|
|
5226
|
+
linkedFromMemory = true;
|
|
5227
|
+
break;
|
|
5228
|
+
}
|
|
5229
|
+
}
|
|
5230
|
+
if (!linkedFromMemory) {
|
|
5231
|
+
remainingParents.push(p);
|
|
5232
|
+
}
|
|
5233
|
+
}
|
|
5234
|
+
}
|
|
5235
|
+
else {
|
|
5236
|
+
remainingParents = Array.from(parents);
|
|
5237
|
+
}
|
|
5238
|
+
if (remainingParents.length === 0 || uncachedChildren.length === 0) {
|
|
5239
|
+
return discoveredByParent;
|
|
5240
|
+
}
|
|
5241
|
+
// Server-side batch UNION ALL discovery when available
|
|
5242
|
+
if (typeof entityProvider?.FindISAChildEntitiesBatch === 'function') {
|
|
5243
|
+
const discoveredByChild = await BaseEntity.batchDiscoverDisjointChildren(parentInfo, remainingParents, entityProvider, rvProvider, contextUser);
|
|
5244
|
+
BaseEntity.recordDiscoveredChildren(discoveredByChild, discoveredByParent);
|
|
5245
|
+
const toRead = BaseEntity.withoutChildrenAlreadyRead(discoveredByChild, readFoundNoRow);
|
|
5246
|
+
if (toRead.size > 0) {
|
|
5247
|
+
await BaseEntity.batchLoadAndLinkDisjointChildren(toRead, md, entityProvider, rvProvider, contextUser, outLinkedChildren, deniedChildLogged);
|
|
5248
|
+
}
|
|
5249
|
+
return discoveredByParent;
|
|
5250
|
+
}
|
|
5251
|
+
// Single-pass RunViews discovery + hydration when FindISAChildEntitiesBatch is absent (e.g. GraphQLDataProvider)
|
|
5252
|
+
if (rvProvider && typeof rvProvider.RunViews === 'function') {
|
|
5253
|
+
await BaseEntity.discoverAndLoadDisjointChildrenViaRunViews(readableChildren, remainingParents, rvProvider, contextUser, outLinkedChildren, deniedChildLogged);
|
|
5254
|
+
// Here discovery and the load are one read, so a child is known only where it linked.
|
|
5255
|
+
for (const p of remainingParents) {
|
|
5256
|
+
if (p._childEntity) {
|
|
5257
|
+
discoveredByParent.set(p, p._childEntity.EntityInfo.Name);
|
|
5258
|
+
}
|
|
5259
|
+
}
|
|
5260
|
+
return discoveredByParent;
|
|
5261
|
+
}
|
|
5262
|
+
// Last-resort per-parent fallback when neither FindISAChildEntitiesBatch nor RunViews exists
|
|
5263
|
+
if (typeof entityProvider?.FindISAChildEntity === 'function') {
|
|
5264
|
+
const discoveredByChild = new Map();
|
|
5265
|
+
for (const p of remainingParents) {
|
|
5266
|
+
const found = await entityProvider.FindISAChildEntity(parentInfo, String(p.PrimaryKey.Values()), contextUser);
|
|
5267
|
+
if (found?.ChildEntityName) {
|
|
5268
|
+
BaseEntity.appendParentToChildGroup(discoveredByChild, found.ChildEntityName, p);
|
|
5269
|
+
}
|
|
5270
|
+
}
|
|
5271
|
+
BaseEntity.recordDiscoveredChildren(discoveredByChild, discoveredByParent);
|
|
5272
|
+
const toRead = BaseEntity.withoutChildrenAlreadyRead(discoveredByChild, readFoundNoRow);
|
|
5273
|
+
if (toRead.size > 0) {
|
|
5274
|
+
await BaseEntity.batchLoadAndLinkDisjointChildren(toRead, md, entityProvider, rvProvider, contextUser, outLinkedChildren, deniedChildLogged);
|
|
5275
|
+
}
|
|
5276
|
+
}
|
|
5277
|
+
return discoveredByParent;
|
|
5278
|
+
}
|
|
5279
|
+
/** `byChild` without each parent whose read of that same child already found no row. */
|
|
5280
|
+
static withoutChildrenAlreadyRead(byChild, readFoundNoRow) {
|
|
5281
|
+
const out = new Map();
|
|
5282
|
+
for (const [childName, parents] of byChild) {
|
|
5283
|
+
const toRead = parents.filter(p => {
|
|
5284
|
+
const alreadyRead = readFoundNoRow.get(p);
|
|
5285
|
+
return !alreadyRead || !sameEntityName(alreadyRead, childName);
|
|
5286
|
+
});
|
|
5287
|
+
if (toRead.length > 0) {
|
|
5288
|
+
out.set(childName, toRead);
|
|
5289
|
+
}
|
|
5290
|
+
}
|
|
5291
|
+
return out;
|
|
5292
|
+
}
|
|
5293
|
+
/** Copies a child-name → parents grouping into a parent → child-name map. */
|
|
5294
|
+
static recordDiscoveredChildren(byChild, out) {
|
|
5295
|
+
for (const [childName, parents] of byChild) {
|
|
5296
|
+
for (const p of parents) {
|
|
5297
|
+
out.set(p, childName);
|
|
5298
|
+
}
|
|
5299
|
+
}
|
|
5300
|
+
}
|
|
5301
|
+
/**
|
|
5302
|
+
* Single-pass `RunViews` child discovery and hydration for providers without `FindISAChildEntitiesBatch`
|
|
5303
|
+
* (such as `GraphQLDataProvider`). Queries only the readable child entities not already present in an
|
|
5304
|
+
* unfiltered memory cache, fetches full child rows (`SELECT *`, no `Fields` narrowing) in 1 `RunViews`
|
|
5305
|
+
* call per chunk, and links the highest-priority matching child row per parent immediately.
|
|
5306
|
+
*/
|
|
5307
|
+
static async discoverAndLoadDisjointChildrenViaRunViews(readableChildren, parents, rvProvider, contextUser, outLinkedChildren, deniedChildLogged) {
|
|
5308
|
+
const uncachedChildren = readableChildren.filter(rc => rc.cachedByPk === null);
|
|
5309
|
+
const chunkSize = BaseEntity.ISABatchChunkSize;
|
|
5310
|
+
const rv = new RunView(rvProvider);
|
|
5311
|
+
for (let start = 0; start < parents.length; start += chunkSize) {
|
|
5312
|
+
const chunkParents = parents.slice(start, start + chunkSize);
|
|
5313
|
+
const chunkPks = chunkParents.map(p => String(p.PrimaryKey.Values()));
|
|
5314
|
+
const queriedRowsByChildName = new Map();
|
|
5315
|
+
if (uncachedChildren.length > 0) {
|
|
5316
|
+
const params = uncachedChildren.map(rc => ({
|
|
5317
|
+
EntityName: rc.childInfo.Name,
|
|
5318
|
+
ExtraFilter: BaseEntity.buildChildPkInFilter(rc.pkField, chunkPks),
|
|
5319
|
+
ResultType: 'simple',
|
|
5320
|
+
// Internal hydration read: keep per-batch IN-list reads out of the shared RunView cache.
|
|
5321
|
+
BypassCache: true,
|
|
5322
|
+
// Key-bounded (at most one row per PK in the chunk): the entity's
|
|
5323
|
+
// UserViewMaxRows cap protects nothing here and would drop subtypes.
|
|
5324
|
+
IgnoreMaxRows: true,
|
|
5325
|
+
}));
|
|
5326
|
+
const results = await rv.RunViews(params, contextUser);
|
|
5327
|
+
for (let cIdx = 0; cIdx < uncachedChildren.length; cIdx++) {
|
|
5328
|
+
const rc = uncachedChildren[cIdx];
|
|
5329
|
+
const res = results[cIdx];
|
|
5330
|
+
const rowByPk = new Map();
|
|
5331
|
+
queriedRowsByChildName.set(rc.childInfo.Name, rowByPk);
|
|
5332
|
+
if (!res?.Success || !Array.isArray(res.Results)) {
|
|
5333
|
+
LogWarning(`BaseEntity: batched IS-A child load of '${rc.childInfo.Name}' failed (${res?.ErrorMessage || 'no result'}); matching parent record(s) continue without their subtype`, 'IS-A');
|
|
5334
|
+
continue;
|
|
5335
|
+
}
|
|
5336
|
+
for (const row of res.Results) {
|
|
5337
|
+
const rawVal = row[rc.pkField.Name];
|
|
5338
|
+
if (rawVal != null) {
|
|
5339
|
+
const norm = CanonicalPrimaryKeyValue(String(rawVal), rc.pkIsUuid);
|
|
5340
|
+
if (!rowByPk.has(norm)) {
|
|
5341
|
+
rowByPk.set(norm, row);
|
|
5342
|
+
}
|
|
5343
|
+
}
|
|
5344
|
+
}
|
|
5345
|
+
}
|
|
5346
|
+
}
|
|
5347
|
+
for (const p of chunkParents) {
|
|
5348
|
+
const rawPk = String(p.PrimaryKey.Values());
|
|
5349
|
+
for (const rc of readableChildren) {
|
|
5350
|
+
const norm = CanonicalPrimaryKeyValue(rawPk, rc.pkIsUuid);
|
|
5351
|
+
const matched = rc.cachedByPk
|
|
5352
|
+
? rc.cachedByPk.get(norm)
|
|
5353
|
+
: queriedRowsByChildName.get(rc.childInfo.Name)?.get(norm);
|
|
5354
|
+
if (matched) {
|
|
5355
|
+
await BaseEntity.linkSingleParentFromRawOrEntityRecord(p, rc.childInfo.Name, matched, outLinkedChildren, deniedChildLogged);
|
|
5356
|
+
break;
|
|
5357
|
+
}
|
|
5358
|
+
}
|
|
5359
|
+
}
|
|
5360
|
+
}
|
|
5361
|
+
}
|
|
5362
|
+
static findUnfilteredInMemoryChildRecords(childInfo, entityProvider, md, userForPerm, batchUnfilteredCache) {
|
|
5363
|
+
if (userForPerm && !childInfo.GetUserPermisions(userForPerm).CanRead) {
|
|
5364
|
+
return null;
|
|
5365
|
+
}
|
|
5366
|
+
// Check unfiltered views in the caller's own RunViews batch first (fetched in the same call for the same user)
|
|
5367
|
+
const batchMatch = batchUnfilteredCache?.get(childInfo.Name.trim().toLowerCase());
|
|
5368
|
+
if (batchMatch) {
|
|
5369
|
+
return batchMatch;
|
|
5370
|
+
}
|
|
5371
|
+
// Server-side BaseEngines load as the system user; do not serve from a shared engine cache when
|
|
5372
|
+
// the calling user has Row-Level Security filters on this child entity.
|
|
5373
|
+
const providerAsMd = entityProvider ?? md;
|
|
5374
|
+
const isDatabaseProvider = providerAsMd?.ProviderType === ProviderType.Database;
|
|
5375
|
+
if (isDatabaseProvider &&
|
|
5376
|
+
userForPerm &&
|
|
5377
|
+
childInfo.GetEffectiveRowFilterWhereClause(userForPerm, EntityPermissionType.Read, '').length > 0) {
|
|
5378
|
+
return null;
|
|
5379
|
+
}
|
|
5380
|
+
const providerConn = providerAsMd?.InstanceConnectionString;
|
|
5381
|
+
for (const match of BaseEngineRegistry.Instance.FindCachedEntity(childInfo.Name, { unfilteredOnly: true })) {
|
|
5382
|
+
const engineObj = match.engine;
|
|
5383
|
+
const engineConn = engineObj?.ProviderToUse?.InstanceConnectionString;
|
|
5384
|
+
if (providerConn && engineConn && providerConn !== engineConn) {
|
|
5385
|
+
continue;
|
|
5386
|
+
}
|
|
5387
|
+
return match.records;
|
|
5388
|
+
}
|
|
5389
|
+
return null;
|
|
5390
|
+
}
|
|
5391
|
+
static buildInMemoryChildLookupMap(records, pkFieldName, pkIsUuid) {
|
|
5392
|
+
const byPk = new Map();
|
|
5393
|
+
for (const rec of records) {
|
|
5394
|
+
if (!rec || typeof rec !== 'object')
|
|
5395
|
+
continue;
|
|
5396
|
+
const rawPk = typeof rec.Get === 'function'
|
|
5397
|
+
? rec.Get(pkFieldName)
|
|
5398
|
+
: rec[pkFieldName];
|
|
5399
|
+
if (rawPk != null) {
|
|
5400
|
+
const norm = CanonicalPrimaryKeyValue(String(rawPk), pkIsUuid);
|
|
5401
|
+
if (!byPk.has(norm)) {
|
|
5402
|
+
byPk.set(norm, rec);
|
|
5403
|
+
}
|
|
5404
|
+
}
|
|
5405
|
+
}
|
|
5406
|
+
return byPk;
|
|
5407
|
+
}
|
|
5408
|
+
static async linkSingleParentFromRawOrEntityRecord(parent, childName, matchedRecord, outLinkedChildren, deniedChildLogged) {
|
|
5409
|
+
const childEntity = await parent.createChildEntityObject(childName);
|
|
5410
|
+
if (!childEntity || !childEntity.CheckPermissions(EntityPermissionType.Read, false)) {
|
|
5411
|
+
if (!deniedChildLogged.has(childName)) {
|
|
5412
|
+
deniedChildLogged.add(childName);
|
|
5413
|
+
LogWarning(`BaseEntity: current user cannot read IS-A child '${childName}'; matching parent records are returned without their subtype`, 'IS-A');
|
|
5414
|
+
}
|
|
5415
|
+
return false;
|
|
5416
|
+
}
|
|
5417
|
+
const rawChildRow = (typeof matchedRecord.GetAll === 'function'
|
|
5418
|
+
? matchedRecord.GetAll()
|
|
5419
|
+
: matchedRecord);
|
|
5420
|
+
const childRow = BaseEntity.inheritedFieldsFromParent(parent, childEntity, rawChildRow);
|
|
5421
|
+
await parent.linkHydratedChildFromBatchRow(childEntity, childRow);
|
|
5422
|
+
outLinkedChildren.push(childEntity);
|
|
5423
|
+
return true;
|
|
5424
|
+
}
|
|
5425
|
+
/**
|
|
5426
|
+
* Replaces the fields `parent` (or its IS-A ancestors) owns in an in-memory child row with
|
|
5427
|
+
* `parent`'s own loaded values, before linking the row downward onto `parent`. Keeps the
|
|
5428
|
+
* freshly loaded parent row authoritative for its own columns even when an engine cache holds
|
|
5429
|
+
* an older snapshot of the child view's joined parent columns, and still hydrates the child's
|
|
5430
|
+
* mirror fields: a mirror left NotLoaded would have no old value, so a later `child.Set()` of
|
|
5431
|
+
* an inherited field would report it as changing from null in `GetAll(true)` (and so in
|
|
5432
|
+
* Record Changes).
|
|
5433
|
+
*
|
|
5434
|
+
* "Owned by an ancestor" means the mirrored columns (`ParentEntityFieldNames`) and the
|
|
5435
|
+
* ancestors' virtual columns, which the child view also carries. The shared key and `__mj_`
|
|
5436
|
+
* timestamps are not: the child view's timestamps are its own table's. A replaced field the
|
|
5437
|
+
* parent did not load stays out of the row.
|
|
5438
|
+
*/
|
|
5439
|
+
static inheritedFieldsFromParent(parent, childEntity, childRow) {
|
|
5440
|
+
if (!childRow || typeof childRow !== 'object') {
|
|
5441
|
+
return childRow;
|
|
5442
|
+
}
|
|
5443
|
+
const pkNamesLower = new Set();
|
|
5444
|
+
for (const pk of [...childEntity.EntityInfo.PrimaryKeys, ...parent.EntityInfo.PrimaryKeys]) {
|
|
5445
|
+
pkNamesLower.add(pk.Name.trim().toLowerCase());
|
|
5446
|
+
if (pk.CodeName)
|
|
5447
|
+
pkNamesLower.add(pk.CodeName.trim().toLowerCase());
|
|
5448
|
+
}
|
|
5449
|
+
// Canonical field name → its lowercased name and code name, for every replaced field.
|
|
5450
|
+
const replaced = new Map();
|
|
5451
|
+
const addReplaced = (name, codeName) => {
|
|
5452
|
+
const lower = name.trim().toLowerCase();
|
|
5453
|
+
if (pkNamesLower.has(lower) || lower.startsWith('__mj_')) {
|
|
5454
|
+
return;
|
|
5455
|
+
}
|
|
5456
|
+
replaced.set(name, codeName ? [lower, codeName.trim().toLowerCase()] : [lower]);
|
|
5457
|
+
};
|
|
5458
|
+
for (const name of childEntity.EntityInfo.ParentEntityFieldNames) {
|
|
5459
|
+
addReplaced(name, childEntity.EntityInfo.Fields.find(f => f.Name === name)?.CodeName);
|
|
5460
|
+
}
|
|
5461
|
+
for (const ancestorInfo of childEntity.EntityInfo.ParentChain) {
|
|
5462
|
+
for (const f of ancestorInfo.Fields) {
|
|
5463
|
+
if (f.IsVirtual) {
|
|
5464
|
+
addReplaced(f.Name, f.CodeName);
|
|
5465
|
+
}
|
|
5466
|
+
}
|
|
5467
|
+
}
|
|
5468
|
+
if (replaced.size === 0) {
|
|
5469
|
+
return childRow;
|
|
5470
|
+
}
|
|
5471
|
+
const replacedLower = new Set();
|
|
5472
|
+
for (const keys of replaced.values()) {
|
|
5473
|
+
for (const k of keys)
|
|
5474
|
+
replacedLower.add(k);
|
|
5475
|
+
}
|
|
5476
|
+
const copy = {};
|
|
5477
|
+
for (const key of Object.keys(childRow)) {
|
|
5478
|
+
if (!replacedLower.has(key.trim().toLowerCase())) {
|
|
5479
|
+
copy[key] = childRow[key];
|
|
5480
|
+
}
|
|
5481
|
+
}
|
|
5482
|
+
// GetAll() holds every field the parent loaded (NotLoaded ones are omitted), keyed by
|
|
5483
|
+
// field name, with its current values. The parent was loaded in this same batch, so its
|
|
5484
|
+
// current values are its loaded values.
|
|
5485
|
+
const parentValues = parent.GetAll();
|
|
5486
|
+
for (const name of replaced.keys()) {
|
|
5487
|
+
if (Object.prototype.hasOwnProperty.call(parentValues, name)) {
|
|
5488
|
+
copy[name] = parentValues[name];
|
|
5489
|
+
}
|
|
5490
|
+
}
|
|
5491
|
+
return copy;
|
|
5492
|
+
}
|
|
5493
|
+
static async partitionParentsBySubtypeLoadHint(groupParents, parentInfo, md, contextUser, batchUnfilteredCache) {
|
|
5494
|
+
const hintedByChild = new Map();
|
|
5495
|
+
const hintedNameByParent = new Map();
|
|
5496
|
+
const needsDiscovery = [];
|
|
5497
|
+
for (const p of groupParents) {
|
|
5498
|
+
const hintedName = await p.resolveSubtypeLoadHint(batchUnfilteredCache);
|
|
5499
|
+
if (hintedName) {
|
|
5500
|
+
const childInfo = md.EntityByName?.(hintedName) ??
|
|
5501
|
+
parentInfo.ChildEntities.find(c => sameEntityName(c.Name, hintedName));
|
|
5502
|
+
const userForPerm = contextUser ?? p._contextCurrentUser ?? md.CurrentUser;
|
|
5503
|
+
const canRead = childInfo && userForPerm ? childInfo.GetUserPermisions(userForPerm).CanRead : true;
|
|
5504
|
+
if (childInfo && canRead) {
|
|
5505
|
+
BaseEntity.appendParentToChildGroup(hintedByChild, childInfo.Name, p);
|
|
5506
|
+
hintedNameByParent.set(p, childInfo.Name);
|
|
5507
|
+
}
|
|
5508
|
+
else {
|
|
5509
|
+
needsDiscovery.push(p);
|
|
5510
|
+
}
|
|
5511
|
+
}
|
|
5512
|
+
else {
|
|
5513
|
+
needsDiscovery.push(p);
|
|
5514
|
+
}
|
|
5515
|
+
}
|
|
5516
|
+
return { hintedByChild, hintedNameByParent, needsDiscovery };
|
|
5517
|
+
}
|
|
5518
|
+
static appendParentToChildGroup(grouped, childName, parent) {
|
|
5519
|
+
let bucket = grouped.get(childName);
|
|
5520
|
+
if (!bucket) {
|
|
5521
|
+
bucket = [];
|
|
5522
|
+
grouped.set(childName, bucket);
|
|
5523
|
+
}
|
|
5524
|
+
bucket.push(parent);
|
|
5525
|
+
}
|
|
5526
|
+
static buildChildPkInFilter(pkField, rawPkValues) {
|
|
5527
|
+
const formatted = rawPkValues.map(val => {
|
|
5528
|
+
if (!pkField.NeedsQuotes) {
|
|
5529
|
+
// Emit the digits as written: a bigint beyond 2^53 must not be rewritten by Number().
|
|
5530
|
+
const text = String(val).trim();
|
|
5531
|
+
if (/^-?\d+(\.\d+)?$/.test(text)) {
|
|
5532
|
+
return text;
|
|
5533
|
+
}
|
|
5534
|
+
}
|
|
5535
|
+
return `'${EscapeSQLString(String(val))}'`;
|
|
5536
|
+
});
|
|
5537
|
+
return `${pkField.Name} IN (${formatted.join(', ')})`;
|
|
5538
|
+
}
|
|
5539
|
+
static async batchDiscoverDisjointChildren(parentInfo, parents, entityProvider, rvProvider, contextUser) {
|
|
5540
|
+
const pkField = parentInfo.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5541
|
+
const pkIsUuid = Boolean(pkField?.IsUniqueIdentifier);
|
|
5542
|
+
const grouped = new Map();
|
|
5543
|
+
const pkValues = parents.map(p => String(p.PrimaryKey.Values()));
|
|
5544
|
+
if (typeof entityProvider?.FindISAChildEntitiesBatch === 'function') {
|
|
5545
|
+
const batchMap = await entityProvider.FindISAChildEntitiesBatch(parentInfo, pkValues, contextUser);
|
|
5546
|
+
for (const p of parents) {
|
|
5547
|
+
const pkKey = CanonicalPrimaryKeyValue(String(p.PrimaryKey.Values()), pkIsUuid);
|
|
5548
|
+
const firstMatch = batchMap.get(pkKey)?.[0];
|
|
5549
|
+
if (firstMatch) {
|
|
5550
|
+
BaseEntity.appendParentToChildGroup(grouped, firstMatch, p);
|
|
5551
|
+
}
|
|
5552
|
+
}
|
|
5553
|
+
return grouped;
|
|
5554
|
+
}
|
|
5555
|
+
// Last-resort per-parent fallback when FindISAChildEntitiesBatch is absent
|
|
5556
|
+
if (typeof entityProvider?.FindISAChildEntity === 'function') {
|
|
5557
|
+
for (const p of parents) {
|
|
5558
|
+
const found = await entityProvider.FindISAChildEntity(parentInfo, String(p.PrimaryKey.Values()), contextUser);
|
|
5559
|
+
if (found?.ChildEntityName) {
|
|
5560
|
+
BaseEntity.appendParentToChildGroup(grouped, found.ChildEntityName, p);
|
|
5561
|
+
}
|
|
5562
|
+
}
|
|
5563
|
+
}
|
|
5564
|
+
return grouped;
|
|
5565
|
+
}
|
|
5566
|
+
static async batchLoadAndLinkDisjointChildren(parentsByChildName, md, entityProvider, rvProvider, contextUser, outLinkedChildren, deniedChildLogged = new Set(), batchUnfilteredCache, outNotFound = new Set()) {
|
|
5567
|
+
const unlinkedParents = [];
|
|
5568
|
+
// Every parent here already has a known subtype (a load hint, or discovery against the
|
|
5569
|
+
// DB), so a miss in a BaseEngine cache means the cache is behind the DB (the engine's event
|
|
5570
|
+
// debounce window, another server node, an out-of-band write), not that the row is absent.
|
|
5571
|
+
// Those parents are read from the DB with the uncached children below. A miss in the
|
|
5572
|
+
// caller's own RunViews batch is final: that read ran in this same call, for this user.
|
|
5573
|
+
// Unhinted discovery is different: there a complete cache does prove absence, and
|
|
5574
|
+
// discoverAndHydrateDisjointChildren never sends such parents here.
|
|
5575
|
+
const remainingByChildName = new Map();
|
|
5576
|
+
for (const [childName, parents] of parentsByChildName) {
|
|
5577
|
+
const childInfo = md.EntityByName?.(childName) ??
|
|
5578
|
+
parents[0]?.EntityInfo.ChildEntities.find(c => sameEntityName(c.Name, childName));
|
|
5579
|
+
const pkField = childInfo?.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5580
|
+
const userForPerm = contextUser ?? parents[0]?._contextCurrentUser ?? md.CurrentUser;
|
|
5581
|
+
const cachedRecords = childInfo && pkField
|
|
5582
|
+
? BaseEntity.findUnfilteredInMemoryChildRecords(childInfo, entityProvider, md, userForPerm, batchUnfilteredCache)
|
|
5583
|
+
: null;
|
|
5584
|
+
if (childInfo && pkField && cachedRecords) {
|
|
5585
|
+
const pkIsUuid = Boolean(pkField.IsUniqueIdentifier);
|
|
5586
|
+
const byPk = BaseEntity.buildInMemoryChildLookupMap(cachedRecords, pkField.Name, pkIsUuid);
|
|
5587
|
+
const fromCallerBatch = batchUnfilteredCache?.has(childInfo.Name.trim().toLowerCase()) === true;
|
|
5588
|
+
const cacheMisses = [];
|
|
5589
|
+
for (const p of parents) {
|
|
5590
|
+
const pkKey = CanonicalPrimaryKeyValue(String(p.PrimaryKey.Values()), pkIsUuid);
|
|
5591
|
+
const matched = byPk.get(pkKey);
|
|
5592
|
+
if (!matched && fromCallerBatch) {
|
|
5593
|
+
unlinkedParents.push(p);
|
|
5594
|
+
outNotFound.add(p);
|
|
5595
|
+
continue;
|
|
5596
|
+
}
|
|
5597
|
+
if (!matched) {
|
|
5598
|
+
cacheMisses.push(p);
|
|
5599
|
+
continue;
|
|
5600
|
+
}
|
|
5601
|
+
const linked = await BaseEntity.linkSingleParentFromRawOrEntityRecord(p, childInfo.Name, matched, outLinkedChildren, deniedChildLogged);
|
|
5602
|
+
if (!linked) {
|
|
5603
|
+
unlinkedParents.push(p);
|
|
5604
|
+
}
|
|
5605
|
+
}
|
|
5606
|
+
if (cacheMisses.length > 0) {
|
|
5607
|
+
remainingByChildName.set(childName, cacheMisses);
|
|
5608
|
+
}
|
|
5609
|
+
}
|
|
5610
|
+
else {
|
|
5611
|
+
remainingByChildName.set(childName, parents);
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
if (remainingByChildName.size === 0) {
|
|
5615
|
+
return unlinkedParents;
|
|
5616
|
+
}
|
|
5617
|
+
if (!rvProvider || typeof rvProvider.RunViews !== 'function') {
|
|
5618
|
+
for (const [childName, parents] of remainingByChildName) {
|
|
5619
|
+
for (const p of parents) {
|
|
5620
|
+
const linked = await p.createAndLinkChildEntity(childName);
|
|
5621
|
+
if (!linked) {
|
|
5622
|
+
unlinkedParents.push(p);
|
|
5623
|
+
outNotFound.add(p);
|
|
5624
|
+
}
|
|
5625
|
+
}
|
|
5626
|
+
}
|
|
5627
|
+
return unlinkedParents;
|
|
5628
|
+
}
|
|
5629
|
+
const slices = BaseEntity.buildDisjointChildQuerySlices(remainingByChildName, md, contextUser, unlinkedParents, deniedChildLogged);
|
|
5630
|
+
if (slices.length === 0) {
|
|
5631
|
+
return unlinkedParents;
|
|
5632
|
+
}
|
|
5633
|
+
const rv = new RunView(rvProvider);
|
|
5634
|
+
const batchResults = await rv.RunViews(slices.map(s => s.param), contextUser);
|
|
5635
|
+
for (let sIdx = 0; sIdx < slices.length; sIdx++) {
|
|
5636
|
+
await BaseEntity.linkDisjointChildSliceResults(slices[sIdx], batchResults[sIdx], unlinkedParents, outLinkedChildren, deniedChildLogged, outNotFound);
|
|
5637
|
+
}
|
|
5638
|
+
return unlinkedParents;
|
|
5639
|
+
}
|
|
5640
|
+
static buildDisjointChildQuerySlices(parentsByChildName, md, contextUser, unlinkedParents, deniedChildLogged) {
|
|
5641
|
+
const chunkSize = BaseEntity.ISABatchChunkSize;
|
|
5642
|
+
const slices = [];
|
|
5643
|
+
for (const [childName, parents] of parentsByChildName) {
|
|
5644
|
+
const childInfo = md.EntityByName?.(childName) ??
|
|
5645
|
+
parents[0]?.EntityInfo.ChildEntities.find(c => sameEntityName(c.Name, childName));
|
|
5646
|
+
const pkField = childInfo?.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
5647
|
+
if (!childInfo || !pkField) {
|
|
5648
|
+
for (const p of parents)
|
|
5649
|
+
unlinkedParents.push(p);
|
|
5650
|
+
continue;
|
|
5651
|
+
}
|
|
5652
|
+
const userForPerm = contextUser ?? parents[0]?._contextCurrentUser ?? md.CurrentUser;
|
|
5653
|
+
const canRead = userForPerm ? childInfo.GetUserPermisions(userForPerm).CanRead : true;
|
|
5654
|
+
if (!canRead) {
|
|
5655
|
+
if (!deniedChildLogged.has(childInfo.Name)) {
|
|
5656
|
+
deniedChildLogged.add(childInfo.Name);
|
|
5657
|
+
LogWarning(`BaseEntity: current user cannot read IS-A child '${childInfo.Name}'; matching parent records are returned without their subtype`, 'IS-A');
|
|
5658
|
+
}
|
|
5659
|
+
for (const p of parents)
|
|
5660
|
+
unlinkedParents.push(p);
|
|
5661
|
+
continue;
|
|
5662
|
+
}
|
|
5663
|
+
for (let start = 0; start < parents.length; start += chunkSize) {
|
|
5664
|
+
const sliceParents = parents.slice(start, start + chunkSize);
|
|
5665
|
+
const pks = sliceParents.map(p => String(p.PrimaryKey.Values()));
|
|
5666
|
+
slices.push({
|
|
5667
|
+
childName: childInfo.Name,
|
|
5668
|
+
pkFieldName: pkField.Name,
|
|
5669
|
+
pkIsUuid: Boolean(pkField.IsUniqueIdentifier),
|
|
5670
|
+
parents: sliceParents,
|
|
5671
|
+
param: {
|
|
5672
|
+
EntityName: childInfo.Name,
|
|
5673
|
+
ExtraFilter: BaseEntity.buildChildPkInFilter(pkField, pks),
|
|
5674
|
+
ResultType: 'simple',
|
|
5675
|
+
// Internal hydration read: see batchDiscoverDisjointChildren — keep these
|
|
5676
|
+
// per-batch IN-list reads out of the shared RunView cache.
|
|
5677
|
+
BypassCache: true,
|
|
5678
|
+
// Key-bounded (at most one row per PK in the slice): the entity's
|
|
5679
|
+
// UserViewMaxRows cap protects nothing here and would drop subtypes.
|
|
5680
|
+
IgnoreMaxRows: true,
|
|
5681
|
+
},
|
|
5682
|
+
});
|
|
5683
|
+
}
|
|
5684
|
+
}
|
|
5685
|
+
return slices;
|
|
5686
|
+
}
|
|
5687
|
+
static async linkDisjointChildSliceResults(slice, res, unlinkedParents, outLinkedChildren, deniedChildLogged, outNotFound) {
|
|
5688
|
+
if (!res?.Success || !Array.isArray(res.Results)) {
|
|
5689
|
+
// Not silent: the per-row path surfaced a failed child load; here the parents stay
|
|
5690
|
+
// unlinked (plain parent records) and the cause goes to the log.
|
|
5691
|
+
LogWarning(`BaseEntity: batched IS-A child load of '${slice.childName}' failed (${res?.ErrorMessage || 'no result'}); ${slice.parents.length} parent record(s) continue without their subtype`, 'IS-A');
|
|
5692
|
+
for (const p of slice.parents)
|
|
5693
|
+
unlinkedParents.push(p);
|
|
5694
|
+
return;
|
|
5695
|
+
}
|
|
5696
|
+
const rowByPk = new Map();
|
|
5697
|
+
for (const row of res.Results) {
|
|
5698
|
+
const pkVal = row[slice.pkFieldName];
|
|
5699
|
+
if (pkVal != null) {
|
|
5700
|
+
rowByPk.set(CanonicalPrimaryKeyValue(String(pkVal), slice.pkIsUuid), row);
|
|
5701
|
+
}
|
|
5702
|
+
}
|
|
5703
|
+
for (const p of slice.parents) {
|
|
5704
|
+
const pkKey = CanonicalPrimaryKeyValue(String(p.PrimaryKey.Values()), slice.pkIsUuid);
|
|
5705
|
+
const childRow = rowByPk.get(pkKey);
|
|
5706
|
+
if (!childRow) {
|
|
5707
|
+
unlinkedParents.push(p);
|
|
5708
|
+
outNotFound.add(p);
|
|
5709
|
+
continue;
|
|
5710
|
+
}
|
|
5711
|
+
const childEntity = await p.createChildEntityObject(slice.childName);
|
|
5712
|
+
if (!childEntity || !childEntity.CheckPermissions(EntityPermissionType.Read, false)) {
|
|
5713
|
+
// The per-row path threw here (InnerLoad → CheckPermissions(Read, true)). The batch
|
|
5714
|
+
// path degrades to a plain parent record instead, and says so once per slice.
|
|
5715
|
+
if (!deniedChildLogged.has(slice.childName)) {
|
|
5716
|
+
deniedChildLogged.add(slice.childName);
|
|
5717
|
+
LogWarning(`BaseEntity: current user cannot read IS-A child '${slice.childName}'; matching parent records are returned without their subtype`, 'IS-A');
|
|
5718
|
+
}
|
|
5719
|
+
unlinkedParents.push(p);
|
|
5720
|
+
continue;
|
|
5721
|
+
}
|
|
5722
|
+
await p.linkHydratedChildFromBatchRow(childEntity, childRow);
|
|
5723
|
+
outLinkedChildren.push(childEntity);
|
|
5724
|
+
}
|
|
5725
|
+
}
|
|
5726
|
+
async linkHydratedChildFromBatchRow(childEntity, childRow) {
|
|
5727
|
+
this.replaceChildParentChain(childEntity);
|
|
5728
|
+
this._childEntity = childEntity;
|
|
5729
|
+
const narrowed = childEntity.narrowHydrationSource(childRow);
|
|
5730
|
+
childEntity.init();
|
|
5731
|
+
childEntity.SetMany(childEntity.ownedFieldsFrom(narrowed), true, true, true);
|
|
5732
|
+
childEntity.markFieldsOmittedBySourceAsNotLoaded(narrowed);
|
|
5733
|
+
childEntity._recordLoaded = true;
|
|
5734
|
+
childEntity._everSaved = true;
|
|
5735
|
+
childEntity._compositeKey = this.PrimaryKey;
|
|
5736
|
+
childEntity.CacheRecordName();
|
|
5737
|
+
await childEntity.deserializeCompanionsFromData(narrowed);
|
|
5738
|
+
}
|
|
4418
5739
|
/**
|
|
4419
5740
|
* Extracts and applies a companion payload carried inside a plain data object, if present.
|
|
4420
5741
|
*
|
|
@@ -4786,17 +6107,51 @@ export class BaseEntity {
|
|
|
4786
6107
|
if (childEntities.length === 0) {
|
|
4787
6108
|
return { HasChildren: false, ChildEntityName: '' };
|
|
4788
6109
|
}
|
|
4789
|
-
// Use RunView on this instance's provider — a host RunView cannot see
|
|
4790
|
-
// uncommitted child rows on a graph-scoped connection.
|
|
4791
|
-
const rv = new RunView(this.RunViewProviderToUse);
|
|
4792
6110
|
const pkValue = this.PrimaryKey.Values();
|
|
4793
|
-
|
|
6111
|
+
// Tier 1: Single UNION ALL SQL query on this entity's bound DatabaseProviderBase
|
|
6112
|
+
// (executes inside any active transaction on this.ProviderToUse in 1 round-trip instead of K).
|
|
6113
|
+
const entityProvider = this.ProviderToUse;
|
|
6114
|
+
if (typeof entityProvider?.FindISAChildEntity === 'function') {
|
|
6115
|
+
const found = await entityProvider.FindISAChildEntity(this.EntityInfo, String(pkValue), this._contextCurrentUser);
|
|
6116
|
+
if (found?.ChildEntityName) {
|
|
6117
|
+
return { HasChildren: true, ChildEntityName: found.ChildEntityName };
|
|
6118
|
+
}
|
|
6119
|
+
return { HasChildren: false, ChildEntityName: '' };
|
|
6120
|
+
}
|
|
6121
|
+
// Tier 2: Batched RunViews on this instance's RunView provider (GraphQLDataProvider or test mocks)
|
|
6122
|
+
const rvProvider = this.RunViewProviderToUse;
|
|
6123
|
+
const rv = new RunView(rvProvider);
|
|
6124
|
+
const validChildren = childEntities.filter(c => c.FirstPrimaryKey != null); // first-pk-ok: IS-A children share the parent's single key
|
|
6125
|
+
if (validChildren.length === 0) {
|
|
6126
|
+
return { HasChildren: false, ChildEntityName: '' };
|
|
6127
|
+
}
|
|
6128
|
+
if (rvProvider && typeof rvProvider.RunViews === 'function') {
|
|
6129
|
+
const viewParams = validChildren.map(childEntity => {
|
|
6130
|
+
const pkField = childEntity.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
6131
|
+
return {
|
|
6132
|
+
EntityName: childEntity.Name,
|
|
6133
|
+
ExtraFilter: `${pkField.Name} = '${EscapeSQLString(String(pkValue))}'`,
|
|
6134
|
+
ResultType: 'simple',
|
|
6135
|
+
Fields: [pkField.Name],
|
|
6136
|
+
MaxRows: 1,
|
|
6137
|
+
};
|
|
6138
|
+
});
|
|
6139
|
+
const results = await rv.RunViews(viewParams, this._contextCurrentUser);
|
|
6140
|
+
for (let i = 0; i < validChildren.length; i++) {
|
|
6141
|
+
const result = results[i];
|
|
6142
|
+
if (result?.Success && result.Results && result.Results.length > 0) {
|
|
6143
|
+
return { HasChildren: true, ChildEntityName: validChildren[i].Name };
|
|
6144
|
+
}
|
|
6145
|
+
}
|
|
6146
|
+
return { HasChildren: false, ChildEntityName: '' };
|
|
6147
|
+
}
|
|
6148
|
+
for (const childEntity of validChildren) {
|
|
4794
6149
|
const pkField = childEntity.FirstPrimaryKey; // first-pk-ok: IS-A children share the parent's single key
|
|
4795
6150
|
if (!pkField)
|
|
4796
6151
|
continue;
|
|
4797
6152
|
const result = await rv.RunView({
|
|
4798
6153
|
EntityName: childEntity.Name,
|
|
4799
|
-
ExtraFilter: `${pkField.Name} = '${pkValue}'`,
|
|
6154
|
+
ExtraFilter: `${pkField.Name} = '${EscapeSQLString(String(pkValue))}'`,
|
|
4800
6155
|
ResultType: 'simple',
|
|
4801
6156
|
Fields: [pkField.Name],
|
|
4802
6157
|
MaxRows: 1
|