@memberjunction/generic-database-provider 6.2.0-edge.5 → 6.2.0-edge.6
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/README.md +15 -1
- package/dist/GenericDatabaseProvider.d.ts +362 -37
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +1425 -216
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.d.ts +26 -0
- package/dist/SqlLogger.d.ts.map +1 -1
- package/dist/SqlLogger.js +77 -20
- package/dist/SqlLogger.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +28 -3
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +112 -6
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/recordChangeSnapshot.d.ts +43 -0
- package/dist/recordChangeSnapshot.d.ts.map +1 -0
- package/dist/recordChangeSnapshot.js +85 -0
- package/dist/recordChangeSnapshot.js.map +1 -0
- package/dist/renderPipeline.d.ts +27 -0
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +45 -3
- package/dist/renderPipeline.js.map +1 -1
- package/dist/systemUserFieldAccess.d.ts +16 -1
- package/dist/systemUserFieldAccess.d.ts.map +1 -1
- package/dist/systemUserFieldAccess.js +39 -8
- package/dist/systemUserFieldAccess.js.map +1 -1
- package/dist/types.d.ts +47 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
18
|
-
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
|
|
19
|
-
import { BytesToBase64, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
|
|
18
|
+
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProjectEntityValueRowsForUser, FieldSecurityError, FieldSecuritySQLGate, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride, NormalizeAlternateBaseViewName, ResolveAlternateBaseView, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, } from '@memberjunction/core';
|
|
19
|
+
import { BytesToBase64, GroupByUUID, IndexByUUID, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
20
20
|
import { QueryPagingEngine } from './queryPagingEngine.js';
|
|
21
21
|
// QueryParameterProcessor is now called internally by RenderPipeline
|
|
22
22
|
import { createHash } from 'node:crypto';
|
|
@@ -27,7 +27,7 @@ import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFrag
|
|
|
27
27
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
28
28
|
import { RenderPipeline } from './renderPipeline.js';
|
|
29
29
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
30
|
-
import { QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
30
|
+
import { GetQueryApprovalStateAsync, QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
31
31
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
32
32
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
33
33
|
import { QueueManager } from '@memberjunction/queue';
|
|
@@ -37,6 +37,8 @@ import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
|
37
37
|
import { TransactionAffinity } from './TransactionAffinity.js';
|
|
38
38
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
39
39
|
import { ClientClauseScreen } from './clientClauseScreen.js';
|
|
40
|
+
import { IsSystemUser } from './systemUser.js';
|
|
41
|
+
import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
|
|
40
42
|
import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
|
|
41
43
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
42
44
|
/**
|
|
@@ -71,8 +73,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
71
73
|
constructor() {
|
|
72
74
|
// Composition engine is now owned by RenderPipeline
|
|
73
75
|
super(...arguments);
|
|
76
|
+
/**
|
|
77
|
+
* Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
|
|
78
|
+
* and Dataset slots. Within this window after a slot was written or last verified against
|
|
79
|
+
* SQL, `RunViewsWithCacheCheck` and `GetDatasetByName` can trust the in-memory slot with
|
|
80
|
+
* zero DB hits. Once this window elapses, the next check performs a lightweight batched
|
|
81
|
+
* SQL status probe (`COUNT(*)` + `MAX(__mj_UpdatedAt)`) to auto-reconcile any out-of-band
|
|
82
|
+
* SQL mutations (e.g., migrations, `mj sync push`, external scripts) without requiring a
|
|
83
|
+
* server restart.
|
|
84
|
+
*/
|
|
85
|
+
this.ServerCacheVerificationTTLMs = 5000;
|
|
86
|
+
/**
|
|
87
|
+
* Most recent authoritative SQL status result per dataset key (`datasetName + filterKey`),
|
|
88
|
+
* populated by `GetDatasetStatusByName` and consumed by `GetDatasetByName` to reconcile
|
|
89
|
+
* cached dataset item slots against live SQL row counts and timestamps.
|
|
90
|
+
*/
|
|
91
|
+
this._lastDatasetStatusByName = new Map();
|
|
74
92
|
/** Per transaction-group counts so the same hash twice in one batch gets `_hash_2`. */
|
|
75
93
|
this._saveCallSuffixCounts = new WeakMap();
|
|
94
|
+
/**
|
|
95
|
+
* Connections a save's SQL is being generated for, by entity object: the transaction a
|
|
96
|
+
* transaction group runs its items on. Set only for the duration of
|
|
97
|
+
* {@link GenerateSaveSQLReadingOn}.
|
|
98
|
+
*/
|
|
99
|
+
this._snapshotConnections = new WeakMap();
|
|
100
|
+
/** Full-width delete snapshots captured by {@link Delete}, consumed by `GenerateDeleteSQL`. */
|
|
101
|
+
this._deleteSnapshots = new WeakMap();
|
|
102
|
+
this._requestFLSKeys = new WeakMap();
|
|
76
103
|
// ─── Nested transactions ─────────────────────────────────────────
|
|
77
104
|
//
|
|
78
105
|
// Depth 1 = physical BEGIN. Depth 2+ = a dialect savepoint on that same
|
|
@@ -168,6 +195,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
168
195
|
}
|
|
169
196
|
return super.Config(data, providerToUse);
|
|
170
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Public accessor for {@link ServerCacheVerificationTTLMs}.
|
|
200
|
+
* Set to `0` to force SQL status verification on every cache check.
|
|
201
|
+
*/
|
|
202
|
+
get ServerCacheVerificationTTL() {
|
|
203
|
+
return this.ServerCacheVerificationTTLMs;
|
|
204
|
+
}
|
|
205
|
+
set ServerCacheVerificationTTL(value) {
|
|
206
|
+
this.ServerCacheVerificationTTLMs = Math.max(0, value);
|
|
207
|
+
}
|
|
171
208
|
/**************************************************************************/
|
|
172
209
|
// SQL Logging — Session Management & Statement Logging
|
|
173
210
|
/**************************************************************************/
|
|
@@ -1250,8 +1287,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1250
1287
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
1251
1288
|
// audit row for ITS writes only — the entity keeps TrackRecordChanges for everyone else.
|
|
1252
1289
|
if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
|
|
1253
|
-
const newData =
|
|
1254
|
-
const oldData = isUpdate ? entity.GetAll(true) : null;
|
|
1290
|
+
const { NewData: newData, OldData: oldData } = await this.BuildRecordChangeSnapshots(entity, isUpdate, user);
|
|
1255
1291
|
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
|
|
1256
1292
|
if (payload) {
|
|
1257
1293
|
// ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
|
|
@@ -1286,6 +1322,127 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1286
1322
|
}
|
|
1287
1323
|
return result;
|
|
1288
1324
|
}
|
|
1325
|
+
/**
|
|
1326
|
+
* The old and new snapshots a save's Record Change is built from. The audit trail stores
|
|
1327
|
+
* whole payloads and projects them per reader, so both snapshots describe the whole record
|
|
1328
|
+
* whoever saves it.
|
|
1329
|
+
*
|
|
1330
|
+
* - **A user denied nothing** (unrestricted and system-user saves): the object's own values.
|
|
1331
|
+
* No query, even when the object was loaded without some columns.
|
|
1332
|
+
* - **A restricted user's update** (their object never holds the fields they cannot read):
|
|
1333
|
+
* the stored values of those fields are read once and the snapshots are widened with them.
|
|
1334
|
+
* The diff is unchanged, because a field the object never held has the same stored value
|
|
1335
|
+
* on both sides.
|
|
1336
|
+
* - **Create**: there is no stored row yet. A field the INSERT omits because the user may
|
|
1337
|
+
* not supply it is left out rather than recorded with a value the record never got.
|
|
1338
|
+
*
|
|
1339
|
+
* The read runs on the save's connection: inside an open transaction it reads that
|
|
1340
|
+
* transaction's state. A save queued in a transaction group is generated when `Save()` is
|
|
1341
|
+
* called, so its snapshot reflects the row as of then — the same moment the object's own
|
|
1342
|
+
* old values describe.
|
|
1343
|
+
*/
|
|
1344
|
+
async BuildRecordChangeSnapshots(entity, isUpdate, user) {
|
|
1345
|
+
if (!isUpdate) {
|
|
1346
|
+
return CreateSnapshots(entity);
|
|
1347
|
+
}
|
|
1348
|
+
const narrow = { NewData: entity.GetAll(false), OldData: entity.GetAll(true) };
|
|
1349
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1350
|
+
if (lacking.size === 0) {
|
|
1351
|
+
return narrow;
|
|
1352
|
+
}
|
|
1353
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1354
|
+
return storedRow ? WidenUpdateSnapshots(entity, narrow, storedRow, lacking) : narrow;
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Generates a save's SQL with any stored-row read its Record Change snapshot needs run on
|
|
1358
|
+
* `connectionSource`. A transaction group that regenerates an item's SQL while its own
|
|
1359
|
+
* transaction is open passes that transaction, so the read sees the group's earlier writes and
|
|
1360
|
+
* never waits on the locks the group itself holds.
|
|
1361
|
+
*/
|
|
1362
|
+
async GenerateSaveSQLReadingOn(entity, isNew, user, connectionSource) {
|
|
1363
|
+
if (!connectionSource) {
|
|
1364
|
+
return this.GenerateSaveSQL(entity, isNew, user);
|
|
1365
|
+
}
|
|
1366
|
+
this._snapshotConnections.set(entity, connectionSource);
|
|
1367
|
+
try {
|
|
1368
|
+
return await this.GenerateSaveSQL(entity, isNew, user);
|
|
1369
|
+
}
|
|
1370
|
+
finally {
|
|
1371
|
+
this._snapshotConnections.delete(entity);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Deletes a record. Before the shared orchestration runs, a restricted user's delete reads the
|
|
1376
|
+
* stored values of the fields their object never held, so the delete's `FullRecordJSON` — the
|
|
1377
|
+
* snapshot a deleted record is restored from — is full width. `GenerateDeleteSQL` is
|
|
1378
|
+
* synchronous, so the snapshot is captured here and handed to it through
|
|
1379
|
+
* {@link RecordChangeDeleteSnapshot}. A user denied nothing costs no extra query.
|
|
1380
|
+
*/
|
|
1381
|
+
async Delete(entity, options, user) {
|
|
1382
|
+
const captured = await this.captureDeleteSnapshot(entity, options, user);
|
|
1383
|
+
try {
|
|
1384
|
+
return await super.Delete(entity, options, user);
|
|
1385
|
+
}
|
|
1386
|
+
finally {
|
|
1387
|
+
if (captured)
|
|
1388
|
+
this._deleteSnapshots.delete(entity);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
/** Reads and stores the full-width delete snapshot when one is needed; true when it stored one. */
|
|
1392
|
+
async captureDeleteSnapshot(entity, options, user) {
|
|
1393
|
+
if (!this.ShouldTrackRecordChanges(entity.EntityInfo) || options?.SkipRecordChanges === true || options?.ReplayOnly === true) {
|
|
1394
|
+
return false;
|
|
1395
|
+
}
|
|
1396
|
+
if (!entity.IsSaved || entity.EntityInfo.ExternalDataSourceID) {
|
|
1397
|
+
return false; // the orchestration refuses these; nothing to snapshot
|
|
1398
|
+
}
|
|
1399
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1400
|
+
if (lacking.size === 0) {
|
|
1401
|
+
return false;
|
|
1402
|
+
}
|
|
1403
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1404
|
+
if (!storedRow) {
|
|
1405
|
+
return false;
|
|
1406
|
+
}
|
|
1407
|
+
this._deleteSnapshots.set(entity, WidenDeleteSnapshot(entity, entity.GetAll(true), storedRow, lacking));
|
|
1408
|
+
return true;
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* The record snapshot a delete's Record Change carries: the full-width snapshot {@link Delete}
|
|
1412
|
+
* captured, else `narrow` (the object's own values, which are already full width whenever no
|
|
1413
|
+
* snapshot was needed).
|
|
1414
|
+
*/
|
|
1415
|
+
RecordChangeDeleteSnapshot(entity, narrow) {
|
|
1416
|
+
// Optional chaining: a provider built without running its constructor (a test host made
|
|
1417
|
+
// with Object.create) has no snapshot map, and then there is nothing captured.
|
|
1418
|
+
return this._deleteSnapshots?.get(entity) ?? narrow;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Reads the stored values of `columns` — the fields a snapshot lacks — for a Record Change
|
|
1422
|
+
* snapshot. Provider-internal: no row-level filter and no field-security check, because the
|
|
1423
|
+
* payload is stored unprojected and projected for each reader. The row gets the same
|
|
1424
|
+
* post-processing as a `Load` (binary to base64, datetime adjustment, decryption,
|
|
1425
|
+
* fixed-width trimming). Runs on the connection the save is generated for when one was named
|
|
1426
|
+
* ({@link GenerateSaveSQLReadingOn}), else on the save's usual connection. Kept out of the SQL
|
|
1427
|
+
* log, which records the save itself.
|
|
1428
|
+
*/
|
|
1429
|
+
async ReadStoredRowForRecordChange(entity, user, columns) {
|
|
1430
|
+
const entityInfo = entity.EntityInfo;
|
|
1431
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, entity.PrimaryKey);
|
|
1432
|
+
const selectList = [...columns].map(name => this.QuoteIdentifier(name)).join(', ');
|
|
1433
|
+
const sql = `SELECT ${selectList} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${where}`;
|
|
1434
|
+
const options = {
|
|
1435
|
+
description: `Record Change snapshot of ${entityInfo.Name}`,
|
|
1436
|
+
ignoreLogging: true,
|
|
1437
|
+
connectionSource: this._snapshotConnections?.get(entity),
|
|
1438
|
+
};
|
|
1439
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, options, user);
|
|
1440
|
+
const rows = await this.PostProcessRows(rawRows, entityInfo, user);
|
|
1441
|
+
if (!rows || rows.length === 0) {
|
|
1442
|
+
return null;
|
|
1443
|
+
}
|
|
1444
|
+
return this.TrimFixedWidthValues(entityInfo, rows[0]);
|
|
1445
|
+
}
|
|
1289
1446
|
/**
|
|
1290
1447
|
* Builds a platform-specific TOP/LIMIT clause for non-paginated row limits.
|
|
1291
1448
|
* SQL Server: `TOP N`; PostgreSQL returns empty (uses LIMIT via BuildPaginationSQL).
|
|
@@ -1326,30 +1483,39 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1326
1483
|
* `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
|
|
1327
1484
|
* Server — both preserve case.
|
|
1328
1485
|
*/
|
|
1329
|
-
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride) {
|
|
1486
|
+
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride, schemaNameOverride) {
|
|
1330
1487
|
const rowsAreLimited = usingPagination || maxRowsForQuery > 0;
|
|
1331
1488
|
if (!rowsAreLimited)
|
|
1332
1489
|
return null;
|
|
1333
|
-
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1490
|
+
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1334
1491
|
}
|
|
1335
1492
|
/**
|
|
1336
|
-
* Resolves the
|
|
1337
|
-
*
|
|
1338
|
-
*
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
*
|
|
1345
|
-
*
|
|
1346
|
-
*
|
|
1347
|
-
* wrong: the minted entity's CodeName need not match the query-derived view name.)
|
|
1348
|
-
*
|
|
1349
|
-
* Convention-based for the base-view case: if the entity has no such materialization the wrapper view
|
|
1350
|
-
* won't exist and the read will error — opting into `'Materialized'` asserts the snapshot exists.
|
|
1493
|
+
* Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
|
|
1494
|
+
* optional loaded `MJUserViewEntityExtended`. An explicit empty string (`""`) on
|
|
1495
|
+
* `params.AlternateBaseView` overrides any saved view pin back to `BaseView` (`undefined`).
|
|
1496
|
+
*/
|
|
1497
|
+
resolveEffectiveAbvNameFromParams(params, viewEntity) {
|
|
1498
|
+
return GetEffectiveAlternateBaseViewName(params, viewEntity);
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* Resolves the view a RunView reads from: an explicit or pinned `AlternateBaseView` when present,
|
|
1502
|
+
* the entity's materialized wrapper view when `DataSource: 'Materialized'`, or the entity's live
|
|
1503
|
+
* `BaseView` by default.
|
|
1351
1504
|
*/
|
|
1352
|
-
GetEffectiveBaseView(entityInfo, params) {
|
|
1505
|
+
GetEffectiveBaseView(entityInfo, params, viewEntity, suppressDeprecationWarning = false) {
|
|
1506
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1507
|
+
if (effectiveAbvName) {
|
|
1508
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1509
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1510
|
+
}
|
|
1511
|
+
const resolution = ResolveAlternateBaseView({
|
|
1512
|
+
entity: entityInfo,
|
|
1513
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1514
|
+
suppressDeprecationWarning,
|
|
1515
|
+
callerName: 'GetEffectiveBaseView',
|
|
1516
|
+
});
|
|
1517
|
+
return resolution.effectiveViewName;
|
|
1518
|
+
}
|
|
1353
1519
|
// Case-INSENSITIVE prefix test (matches the sibling guard in providerBase.IsServerCacheAllowedForEntity):
|
|
1354
1520
|
// a BaseView returned with non-lowercase casing (e.g. 'Materialized_vwFoo' from a case-insensitive SQL
|
|
1355
1521
|
// Server, or a hand-authored entity) is still an already-materialized view — a case-sensitive check
|
|
@@ -1361,18 +1527,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1361
1527
|
}
|
|
1362
1528
|
/**
|
|
1363
1529
|
* Async status-aware wrapper around {@link GetEffectiveBaseView} for the BASE-VIEW materialization case.
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
* cache-invalidation event), so a cached status could otherwise be stale. Non-materialized reads and minted
|
|
1371
|
-
* query virtual entities (BaseView already `materialized_vw…`) skip the lookup entirely (no extra query).
|
|
1372
|
-
*/
|
|
1373
|
-
async resolveEffectiveBaseView(entityInfo, params, contextUser) {
|
|
1530
|
+
*/
|
|
1531
|
+
async resolveEffectiveBaseView(entityInfo, params, contextUser, viewEntity) {
|
|
1532
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1533
|
+
if (effectiveAbvName) {
|
|
1534
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1535
|
+
}
|
|
1374
1536
|
if (!IsMaterializedDataSource(params.DataSource) || entityInfo.BaseView?.toLowerCase().startsWith('materialized_vw')) {
|
|
1375
|
-
return this.GetEffectiveBaseView(entityInfo, params);
|
|
1537
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1376
1538
|
}
|
|
1377
1539
|
const rv = new RunView(this);
|
|
1378
1540
|
const res = await rv.RunView({
|
|
@@ -1400,6 +1562,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1400
1562
|
// base-view materialization always mints into the source entity's own schema.)
|
|
1401
1563
|
return row.ViewName?.trim() || `materialized_vw${entityInfo.CodeName}`;
|
|
1402
1564
|
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Resolves both the effective `{ schemaName, viewName }` for a RunView call, honoring:
|
|
1567
|
+
* 1. Explicit `params.AlternateBaseView` (including `""` to force `BaseView` over a saved view pin)
|
|
1568
|
+
* 2. Saved `UserView.DisplayState.alternateBaseView` (from `viewEntity`, `params.ViewEntity`, or loaded by `ViewID`/`ViewName`)
|
|
1569
|
+
* 3. `DataSource: 'Materialized'`
|
|
1570
|
+
* 4. `entityInfo.BaseView`
|
|
1571
|
+
*/
|
|
1572
|
+
async resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity) {
|
|
1573
|
+
let resolvedViewEntity = viewEntity ?? params?.ViewEntity ?? null;
|
|
1574
|
+
if (!resolvedViewEntity && typeof params?.AlternateBaseView !== 'string') {
|
|
1575
|
+
try {
|
|
1576
|
+
if (params?.ViewID && params.ViewID.length > 0) {
|
|
1577
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntity(params.ViewID, contextUser)) ?? null;
|
|
1578
|
+
}
|
|
1579
|
+
else if (params?.ViewName && params.ViewName.length > 0) {
|
|
1580
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntityByName(params.ViewName, contextUser)) ?? null;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
catch (e) {
|
|
1584
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1585
|
+
LogError(`GenericDatabaseProvider.resolveEffectiveBaseViewTarget: failed to load User View (${params?.ViewID || params?.ViewName}) on entity "${entityInfo.Name}": ${msg}`);
|
|
1586
|
+
throw e;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, resolvedViewEntity);
|
|
1590
|
+
if (effectiveAbvName) {
|
|
1591
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1592
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1593
|
+
}
|
|
1594
|
+
const resolution = ResolveAlternateBaseView({
|
|
1595
|
+
entity: entityInfo,
|
|
1596
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1597
|
+
contextUser,
|
|
1598
|
+
callerName: 'resolveEffectiveBaseViewTarget',
|
|
1599
|
+
});
|
|
1600
|
+
return { schemaName: resolution.effectiveSchemaName, viewName: resolution.effectiveViewName };
|
|
1601
|
+
}
|
|
1602
|
+
const viewName = await this.resolveEffectiveBaseView(entityInfo, params, contextUser, resolvedViewEntity);
|
|
1603
|
+
return { schemaName: entityInfo.SchemaName, viewName };
|
|
1604
|
+
}
|
|
1403
1605
|
/**
|
|
1404
1606
|
* Reports whether a materialization-metadata `RunView` FAILED, logging the failure when it did.
|
|
1405
1607
|
*
|
|
@@ -1614,9 +1816,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1614
1816
|
* SQL Server overrides to use spCreateUserViewRunWithDetail.
|
|
1615
1817
|
* Default: returns null (no view run logging).
|
|
1616
1818
|
*/
|
|
1617
|
-
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user) {
|
|
1819
|
+
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride) {
|
|
1618
1820
|
return null;
|
|
1619
1821
|
}
|
|
1822
|
+
/**
|
|
1823
|
+
* Maximum number of concurrent database view executions allowed within a single
|
|
1824
|
+
* {@link InternalRunViews} batch. Prevents large `RunViews` batches from exhausting
|
|
1825
|
+
* the connection pool in a single tick. Set to 0 or Infinity to disable the cap.
|
|
1826
|
+
* Default: 8.
|
|
1827
|
+
*/
|
|
1828
|
+
static { this.MaxConcurrentViewsPerBatch = 8; }
|
|
1829
|
+
/**
|
|
1830
|
+
* Process-wide single-flight coalescing registry for in-flight read-only RunView executions.
|
|
1831
|
+
* When multiple concurrent requests (across any per-request provider instance on the same
|
|
1832
|
+
* server process) execute an identical non-transactional RunView simultaneously, only the
|
|
1833
|
+
* first caller queries the database; joiners await the same promise and receive a shallow-cloned
|
|
1834
|
+
* result object and Results array.
|
|
1835
|
+
*/
|
|
1836
|
+
static { this._inFlightRunViews = new Map(); }
|
|
1837
|
+
/**
|
|
1838
|
+
* Number of currently in-flight coalesced RunView executions across this process.
|
|
1839
|
+
*/
|
|
1840
|
+
static get InFlightRunViewCount() {
|
|
1841
|
+
return GenericDatabaseProvider._inFlightRunViews.size;
|
|
1842
|
+
}
|
|
1620
1843
|
/**
|
|
1621
1844
|
* Shared InternalRunView implementation.
|
|
1622
1845
|
* Handles: view resolution, permissions, field selection, WHERE clause building
|
|
@@ -1626,6 +1849,117 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1626
1849
|
async InternalRunView(params, contextUser) {
|
|
1627
1850
|
return this.RunViewCore(params, contextUser);
|
|
1628
1851
|
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Determines whether a RunView invocation is eligible for process-wide single-flight
|
|
1854
|
+
* coalescing across concurrent requests.
|
|
1855
|
+
*/
|
|
1856
|
+
canCoalesceRunViewInFlight(params, countExecutor) {
|
|
1857
|
+
if (!params || countExecutor) {
|
|
1858
|
+
return false;
|
|
1859
|
+
}
|
|
1860
|
+
if (params.ResultType && params.ResultType !== 'simple' && params.ResultType !== 'count_only') {
|
|
1861
|
+
return false;
|
|
1862
|
+
}
|
|
1863
|
+
if (params.SaveViewResults || params.ForceAuditLog) {
|
|
1864
|
+
return false;
|
|
1865
|
+
}
|
|
1866
|
+
if (this.IsCallerInAmbientTransaction() || this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction) {
|
|
1867
|
+
return false;
|
|
1868
|
+
}
|
|
1869
|
+
return true;
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Builds the deterministic single-flight key for an in-flight RunView execution.
|
|
1873
|
+
* Includes connection string, entity/view identity, filter, orderBy, fields, resultType,
|
|
1874
|
+
* pagination/keyset cursor, aggregates, and effective user role/row-filter security context.
|
|
1875
|
+
*/
|
|
1876
|
+
buildSingleFlightRunViewKey(params, contextUser) {
|
|
1877
|
+
try {
|
|
1878
|
+
const user = contextUser ?? this.CurrentUser;
|
|
1879
|
+
if (!user) {
|
|
1880
|
+
return null;
|
|
1881
|
+
}
|
|
1882
|
+
const entityInfo = params.EntityName ? this.EntityByName(params.EntityName) : undefined;
|
|
1883
|
+
if (entityInfo?.AuditViewRuns && (params.ViewID || params.ViewName || params.ViewEntity)) {
|
|
1884
|
+
return null;
|
|
1885
|
+
}
|
|
1886
|
+
const baseFingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString);
|
|
1887
|
+
const fieldsKey = params.Fields && params.Fields.length > 0
|
|
1888
|
+
? [...params.Fields].map(f => f.trim().toLowerCase()).sort().join(',')
|
|
1889
|
+
: '*';
|
|
1890
|
+
const rlsClause = entityInfo && typeof entityInfo.GetEffectiveRowFilterWhereClause === 'function'
|
|
1891
|
+
? entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '')
|
|
1892
|
+
: `user:${user.ID ?? ''}`;
|
|
1893
|
+
const roleKey = user.UserRoles && user.UserRoles.length > 0
|
|
1894
|
+
? user.UserRoles.map(r => (r.RoleID ?? '').trim().toLowerCase()).sort().join(',')
|
|
1895
|
+
: `user:${user.ID ?? ''}`;
|
|
1896
|
+
const aggregatesKey = params.Aggregates && params.Aggregates.length > 0
|
|
1897
|
+
? JSON.stringify(params.Aggregates)
|
|
1898
|
+
: '';
|
|
1899
|
+
const afterKey = params.AfterKey ? params.AfterKey.ToConcatenatedString() : '';
|
|
1900
|
+
const ve = params.ViewEntity;
|
|
1901
|
+
const viewEntityKey = ve
|
|
1902
|
+
? `${ve.ID ?? ''}:${ve.WhereClause ?? ''}:${ve.SmartFilterWhereClause ?? ''}:${ve.AlternateBaseView ?? ''}`
|
|
1903
|
+
: '';
|
|
1904
|
+
const abvKey = IsExplicitBaseViewOverride(params)
|
|
1905
|
+
? '__base_override__'
|
|
1906
|
+
: (NormalizeAlternateBaseViewName(GetEffectiveAlternateBaseViewName(params)) ?? '');
|
|
1907
|
+
return [
|
|
1908
|
+
baseFingerprint,
|
|
1909
|
+
`f:${fieldsKey}`,
|
|
1910
|
+
`rt:${params.ResultType || 'simple'}`,
|
|
1911
|
+
`uss:${params.UserSearchString ?? ''}`,
|
|
1912
|
+
`vid:${params.ViewID ?? ''}`,
|
|
1913
|
+
`vn:${params.ViewName ?? ''}`,
|
|
1914
|
+
`ve:${viewEntityKey}`,
|
|
1915
|
+
`exRun:${params.ExcludeUserViewRunID ?? ''}`,
|
|
1916
|
+
`exAll:${params.ExcludeDataFromAllPriorViewRuns ? '1' : '0'}`,
|
|
1917
|
+
`ovEx:${params.OverrideExcludeFilter ?? ''}`,
|
|
1918
|
+
`igMax:${params.IgnoreMaxRows ? '1' : '0'}`,
|
|
1919
|
+
`max:${params.MaxRows ?? ''}`,
|
|
1920
|
+
`start:${params.StartRow ?? ''}`,
|
|
1921
|
+
`after:${afterKey}`,
|
|
1922
|
+
`ds:${params.DataSource ?? ''}`,
|
|
1923
|
+
`abv:${abvKey}`,
|
|
1924
|
+
`agg:${aggregatesKey}`,
|
|
1925
|
+
`roles:${roleKey}`,
|
|
1926
|
+
`rls:${rlsClause}`,
|
|
1927
|
+
].join('|');
|
|
1928
|
+
}
|
|
1929
|
+
catch {
|
|
1930
|
+
return null;
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Shallow-clones a shared single-flight RunViewResult and its row objects so concurrent
|
|
1935
|
+
* callers cannot mutate each other's result arrays or row properties in place.
|
|
1936
|
+
*/
|
|
1937
|
+
cloneSingleFlightRunViewResult(result) {
|
|
1938
|
+
if (!result) {
|
|
1939
|
+
return result;
|
|
1940
|
+
}
|
|
1941
|
+
return {
|
|
1942
|
+
...result,
|
|
1943
|
+
Results: Array.isArray(result.Results)
|
|
1944
|
+
? result.Results.map(row => (row && typeof row === 'object' ? { ...row } : row))
|
|
1945
|
+
: [],
|
|
1946
|
+
AggregateResults: result.AggregateResults
|
|
1947
|
+
? result.AggregateResults.map(a => ({ ...a }))
|
|
1948
|
+
: undefined,
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
/**
|
|
1952
|
+
* Returns true when an identical read-only RunView is already in flight in the process-wide
|
|
1953
|
+
* single-flight registry. Used by {@link InternalRunViews} so duplicate views in a batch can
|
|
1954
|
+
* join an active query immediately without consuming a concurrency slot.
|
|
1955
|
+
*/
|
|
1956
|
+
hasInFlightSingleFlightView(params, contextUser) {
|
|
1957
|
+
if (!this.canCoalesceRunViewInFlight(params)) {
|
|
1958
|
+
return false;
|
|
1959
|
+
}
|
|
1960
|
+
const key = this.buildSingleFlightRunViewKey(params, contextUser);
|
|
1961
|
+
return !!key && GenericDatabaseProvider._inFlightRunViews.has(key);
|
|
1962
|
+
}
|
|
1629
1963
|
/**
|
|
1630
1964
|
* The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
|
|
1631
1965
|
* direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
|
|
@@ -1633,10 +1967,43 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1633
1967
|
* Everything before that step — permissions, RLS, filter screening — is unchanged.
|
|
1634
1968
|
*/
|
|
1635
1969
|
async RunViewCore(params, contextUser, countExecutor) {
|
|
1970
|
+
const singleFlightKey = this.canCoalesceRunViewInFlight(params, countExecutor)
|
|
1971
|
+
? this.buildSingleFlightRunViewKey(params, contextUser)
|
|
1972
|
+
: null;
|
|
1973
|
+
if (singleFlightKey) {
|
|
1974
|
+
const existing = GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey);
|
|
1975
|
+
if (existing) {
|
|
1976
|
+
existing.hasJoiners = true;
|
|
1977
|
+
const shared = await existing.promise;
|
|
1978
|
+
return this.cloneSingleFlightRunViewResult(shared);
|
|
1979
|
+
}
|
|
1980
|
+
const entry = {
|
|
1981
|
+
promise: null,
|
|
1982
|
+
hasJoiners: false,
|
|
1983
|
+
};
|
|
1984
|
+
const executionPromise = this.executeRunViewCore(params, contextUser, countExecutor)
|
|
1985
|
+
.finally(() => {
|
|
1986
|
+
if (GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey) === entry) {
|
|
1987
|
+
GenericDatabaseProvider._inFlightRunViews.delete(singleFlightKey);
|
|
1988
|
+
}
|
|
1989
|
+
});
|
|
1990
|
+
entry.promise = executionPromise;
|
|
1991
|
+
GenericDatabaseProvider._inFlightRunViews.set(singleFlightKey, entry);
|
|
1992
|
+
const result = await executionPromise;
|
|
1993
|
+
return entry.hasJoiners
|
|
1994
|
+
? this.cloneSingleFlightRunViewResult(result)
|
|
1995
|
+
: result;
|
|
1996
|
+
}
|
|
1997
|
+
return this.executeRunViewCore(params, contextUser, countExecutor);
|
|
1998
|
+
}
|
|
1999
|
+
async executeRunViewCore(params, contextUser, countExecutor) {
|
|
1636
2000
|
if (params?.Aggregates?.length) {
|
|
1637
2001
|
LogStatus(`[GenericDatabaseProvider] InternalRunView received aggregates: entityName=${params.EntityName}, viewID=${params.ViewID}, viewName=${params.ViewName}, aggregateCount=${params.Aggregates.length}`);
|
|
1638
2002
|
}
|
|
1639
2003
|
const startTime = new Date();
|
|
2004
|
+
// The entity the view reads, once resolved — the catch below needs it to tell a restricted
|
|
2005
|
+
// caller's "no such column" apart from any other failure.
|
|
2006
|
+
let resolvedEntity = null;
|
|
1640
2007
|
try {
|
|
1641
2008
|
if (!params)
|
|
1642
2009
|
return null;
|
|
@@ -1646,12 +2013,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1646
2013
|
// ── View / Entity resolution ──
|
|
1647
2014
|
let viewEntity = null;
|
|
1648
2015
|
let entityInfo = null;
|
|
1649
|
-
|
|
1650
|
-
viewEntity = params.ViewEntity;
|
|
1651
|
-
else if (params.ViewID && params.ViewID.length > 0)
|
|
1652
|
-
viewEntity = await ViewInfo.GetViewEntity(params.ViewID, contextUser) ?? null;
|
|
1653
|
-
else if (params.ViewName && params.ViewName.length > 0)
|
|
1654
|
-
viewEntity = await ViewInfo.GetViewEntityByName(params.ViewName, contextUser) ?? null;
|
|
2016
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
1655
2017
|
if (!viewEntity) {
|
|
1656
2018
|
if (!params.EntityName || params.EntityName.length === 0)
|
|
1657
2019
|
throw new Error('EntityName is required when ViewID or ViewName is not provided');
|
|
@@ -1665,6 +2027,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1665
2027
|
throw new Error(`Entity ID: ${viewEntity.EntityID} not found in metadata`);
|
|
1666
2028
|
}
|
|
1667
2029
|
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2030
|
+
resolvedEntity = entityInfo;
|
|
2031
|
+
// A stored view's properties: refused here (Success:false, naming the property) before any SQL runs.
|
|
2032
|
+
const propertyFilter = this.BuildViewPropertyFilter(viewEntity, entityInfo, params, user);
|
|
1668
2033
|
// ── External data source dispatch ──
|
|
1669
2034
|
// Entities backed by an external data source are proxied live through a
|
|
1670
2035
|
// driver and have no view/sproc in the MJ DB, so delegate before any SQL
|
|
@@ -1675,11 +2040,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1675
2040
|
this.assertExternalReadAllowedUnderRLS(entityInfo, user);
|
|
1676
2041
|
// Refuse params we can't honor remotely rather than silently dropping them — most
|
|
1677
2042
|
// importantly AfterKey, which would otherwise return the same page on every call.
|
|
1678
|
-
this.assertExternalRunViewParamsSupported(params, entityInfo.Name);
|
|
2043
|
+
this.assertExternalRunViewParamsSupported(params, entityInfo.Name, viewEntity);
|
|
2044
|
+
if (propertyFilter) {
|
|
2045
|
+
throw new Error(`View properties are not supported for external-data-source entity '${entityInfo.Name}'.`);
|
|
2046
|
+
}
|
|
1679
2047
|
// A saved view's stored WhereClause/OrderBy live on viewEntity, not params, and the
|
|
1680
2048
|
// normal SQL path that applies them runs below this early return — so fold them in
|
|
1681
2049
|
// here, else a UserView over an external entity silently returns unfiltered rows.
|
|
1682
2050
|
const externalParams = await this.mergeExternalViewParams(params, viewEntity, user);
|
|
2051
|
+
this.assertExternalClausesRespectFieldSecurity(entityInfo, externalParams, user);
|
|
1683
2052
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Entity '${entityInfo.Name}'`);
|
|
1684
2053
|
const externalResult = await externalRouter.RunViewExternal(entityInfo, externalParams, user, this);
|
|
1685
2054
|
// Apply the same row post-processing MJ-DB reads get (field decryption + datetime
|
|
@@ -1688,7 +2057,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1688
2057
|
// Generic-erasure boundary: PostProcessRows operates on Record<string,unknown>[]
|
|
1689
2058
|
// but Results is typed T[]; the double-cast bridges that erasure (not a lazy `any`).
|
|
1690
2059
|
const rows = externalResult.Results;
|
|
1691
|
-
|
|
2060
|
+
const processed = (await this.PostProcessRows(rows, entityInfo, user));
|
|
2061
|
+
externalResult.Results = this.projectExternalRowsForCaller(processed, entityInfo, externalParams, user);
|
|
1692
2062
|
}
|
|
1693
2063
|
return externalResult;
|
|
1694
2064
|
}
|
|
@@ -1700,6 +2070,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1700
2070
|
const saveViewResults = params.SaveViewResults ?? false;
|
|
1701
2071
|
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
1702
2072
|
this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
2073
|
+
// Field-level security on the clauses as this provider runs them, now that a ViewID- or
|
|
2074
|
+
// ViewName-only request has an entity. Before any SQL, like every other screen here.
|
|
2075
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [
|
|
2076
|
+
extraFilter,
|
|
2077
|
+
overrideExcludeFilter,
|
|
2078
|
+
...(params.Aggregates ?? []).map(a => a?.expression),
|
|
2079
|
+
], user);
|
|
1703
2080
|
// ── TOP / pagination mode ──
|
|
1704
2081
|
// Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
|
|
1705
2082
|
// and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
|
|
@@ -1744,16 +2121,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1744
2121
|
const fields = this.getRunTimeViewFieldString(params, viewEntity, user);
|
|
1745
2122
|
// ── Build SELECT and COUNT SQL ──
|
|
1746
2123
|
// DataSource:'Materialized' routes the read to the entity's materialized wrapper view
|
|
1747
|
-
// (same shape, so RLS/paging/fields all apply identically);
|
|
1748
|
-
|
|
2124
|
+
// (same shape, so RLS/paging/fields all apply identically); AlternateBaseView routes to
|
|
2125
|
+
// a registered alternate base view (which may also live in a custom schema); default stays the live base view.
|
|
2126
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity);
|
|
2127
|
+
const effectiveBaseView = effectiveTarget.viewName;
|
|
2128
|
+
const effectiveSchemaName = effectiveTarget.schemaName;
|
|
1749
2129
|
const topFragment = topSQL ? topSQL + ' ' : '';
|
|
1750
|
-
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(
|
|
2130
|
+
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`;
|
|
1751
2131
|
// count_only ALWAYS needs the count query — BuildTotalRowCountSQL only emits
|
|
1752
2132
|
// it when rows are limited (its pagination purpose), which previously left
|
|
1753
2133
|
// count_only with no COUNT at all (silently returned TotalRowCount 0).
|
|
1754
2134
|
let countSQL = params.ResultType === 'count_only'
|
|
1755
|
-
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(
|
|
1756
|
-
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView);
|
|
2135
|
+
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`
|
|
2136
|
+
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName);
|
|
1757
2137
|
// ── WHERE clause assembly ──
|
|
1758
2138
|
let whereSQL = '';
|
|
1759
2139
|
let bHasWhere = false;
|
|
@@ -1769,6 +2149,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1769
2149
|
// {%UserView%} templates) are written against entity base views, which the screens
|
|
1770
2150
|
// permit when the running user reads each of those entities unscoped.
|
|
1771
2151
|
this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
|
|
2152
|
+
// Field-level security covers CustomWhereClause views too: their clause is
|
|
2153
|
+
// admin-written, but it still runs as the acting user and could read a column
|
|
2154
|
+
// that user is denied.
|
|
2155
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [renderedWhere], user);
|
|
1772
2156
|
const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
|
|
1773
2157
|
if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
|
|
1774
2158
|
throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
|
|
@@ -1789,6 +2173,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1789
2173
|
whereSQL = bHasWhere ? `${whereSQL} AND (${extraFilter})` : `(${extraFilter})`;
|
|
1790
2174
|
bHasWhere = true;
|
|
1791
2175
|
}
|
|
2176
|
+
// 2b. View properties: one typed predicate per property with a value, after the view's
|
|
2177
|
+
// own clause and ExtraFilter. Row-level security is still ANDed on below.
|
|
2178
|
+
if (propertyFilter.length > 0) {
|
|
2179
|
+
whereSQL = bHasWhere ? `${whereSQL} AND (${propertyFilter})` : `(${propertyFilter})`;
|
|
2180
|
+
bHasWhere = true;
|
|
2181
|
+
}
|
|
1792
2182
|
// 3. User search string
|
|
1793
2183
|
//
|
|
1794
2184
|
// 🚨 NOT screened by ValidateUserProvidedSQLClause (#4392). That denylist exists for
|
|
@@ -1808,7 +2198,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1808
2198
|
// in a literal: it is what keeps the text inside the quotes, where no keyword it
|
|
1809
2199
|
// contains can mean anything to the parser.
|
|
1810
2200
|
if (userSearchString.length > 0) {
|
|
1811
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user);
|
|
2201
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
1812
2202
|
if (sUserSearchSQL.length > 0) {
|
|
1813
2203
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
1814
2204
|
bHasWhere = true;
|
|
@@ -1909,6 +2299,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1909
2299
|
: '';
|
|
1910
2300
|
if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
|
|
1911
2301
|
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
2302
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [orderBy], user);
|
|
1912
2303
|
// No caller OrderBy means the sort came from the saved view's stored sort state.
|
|
1913
2304
|
if (!params.OrderBy && viewEntity)
|
|
1914
2305
|
this.ScreenStoredViewOrderBy(orderBy, user);
|
|
@@ -1919,7 +2310,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1919
2310
|
// Pass entityInfo + effectiveBaseView so the logged read honors DataSource:'Materialized'
|
|
1920
2311
|
// (reads the snapshot). effectiveBaseView === entityInfo.BaseView on the default live path,
|
|
1921
2312
|
// so non-materialized reads are unchanged.
|
|
1922
|
-
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user);
|
|
2313
|
+
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName);
|
|
1923
2314
|
if (logResult) {
|
|
1924
2315
|
viewSQL = logResult.executeViewSQL;
|
|
1925
2316
|
userViewRunID = logResult.runID;
|
|
@@ -1960,33 +2351,59 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1960
2351
|
if (params.Aggregates && params.Aggregates.length > 0) {
|
|
1961
2352
|
// Aggregate over the SAME source the rows/count came from — effectiveBaseView, so a caller
|
|
1962
2353
|
// asking for DataSource:'Materialized' gets aggregates over the snapshot, not the live view.
|
|
1963
|
-
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo,
|
|
2354
|
+
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo, effectiveSchemaName, effectiveBaseView, whereSQL);
|
|
1964
2355
|
aggregateSQL = aggregateBuild.aggregateSQL;
|
|
1965
2356
|
aggregateValidationErrors = aggregateBuild.validationErrors;
|
|
2357
|
+
this.assertAggregateRefusalsAreNotColumnProbes(aggregateValidationErrors, entityInfo, user);
|
|
1966
2358
|
}
|
|
1967
|
-
// ── Execute queries
|
|
1968
|
-
const
|
|
1969
|
-
const
|
|
2359
|
+
// ── Execute queries (single TDS batch via ExecuteSQLBatch when multiple SQL statements are needed) ──
|
|
2360
|
+
const sqlQueries = [];
|
|
2361
|
+
const sqlQueryKeys = [];
|
|
2362
|
+
let countExecutorPromise = null;
|
|
1970
2363
|
if (params.ResultType !== 'count_only') {
|
|
1971
|
-
|
|
1972
|
-
|
|
2364
|
+
sqlQueries.push(viewSQL);
|
|
2365
|
+
sqlQueryKeys.push('data');
|
|
1973
2366
|
}
|
|
1974
2367
|
const maxRowsUsed = params.MaxRows || entityInfo.UserViewMaxRows;
|
|
1975
|
-
|
|
2368
|
+
// SkipTotalRowCount is an explicit caller opt-out of the count (see RunViewParams);
|
|
2369
|
+
// count_only still counts — that result IS the count, the flag cannot mean anything there.
|
|
2370
|
+
const skipCount = params.SkipTotalRowCount === true && params.ResultType !== 'count_only';
|
|
2371
|
+
const willNeedCount = countSQL && ((usingPagination && !skipCount) || params.ResultType === 'count_only');
|
|
1976
2372
|
if (willNeedCount) {
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
2373
|
+
if (countExecutor && params.ResultType === 'count_only') {
|
|
2374
|
+
countExecutorPromise = countExecutor(countSQL);
|
|
2375
|
+
}
|
|
2376
|
+
else {
|
|
2377
|
+
sqlQueries.push(countSQL);
|
|
2378
|
+
sqlQueryKeys.push('count');
|
|
2379
|
+
}
|
|
1981
2380
|
}
|
|
1982
2381
|
const aggregateStartTime = Date.now();
|
|
1983
2382
|
if (aggregateSQL) {
|
|
1984
|
-
|
|
1985
|
-
|
|
2383
|
+
sqlQueries.push(aggregateSQL);
|
|
2384
|
+
sqlQueryKeys.push('aggregate');
|
|
1986
2385
|
}
|
|
1987
|
-
const results = await Promise.all(queries);
|
|
1988
2386
|
const resultMap = {};
|
|
1989
|
-
|
|
2387
|
+
if (sqlQueries.length === 1 && !countExecutorPromise) {
|
|
2388
|
+
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser);
|
|
2389
|
+
}
|
|
2390
|
+
else if (sqlQueries.length > 0 && countExecutorPromise) {
|
|
2391
|
+
const [batchResults, countRes] = await Promise.all([
|
|
2392
|
+
sqlQueries.length === 1
|
|
2393
|
+
? this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser).then(r => [r])
|
|
2394
|
+
: this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser),
|
|
2395
|
+
countExecutorPromise,
|
|
2396
|
+
]);
|
|
2397
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2398
|
+
resultMap['count'] = countRes;
|
|
2399
|
+
}
|
|
2400
|
+
else if (sqlQueries.length > 1) {
|
|
2401
|
+
const batchResults = await this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser);
|
|
2402
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2403
|
+
}
|
|
2404
|
+
else if (countExecutorPromise) {
|
|
2405
|
+
resultMap['count'] = await countExecutorPromise;
|
|
2406
|
+
}
|
|
1990
2407
|
// ── Process data rows ──
|
|
1991
2408
|
let retData = resultMap['data'] || [];
|
|
1992
2409
|
if (retData.length > 0 && params.ResultType !== 'count_only') {
|
|
@@ -1999,7 +2416,34 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1999
2416
|
if (countResult && countResult.length > 0)
|
|
2000
2417
|
rowCount = countResult[0].TotalRowCount;
|
|
2001
2418
|
}
|
|
2002
|
-
else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed) {
|
|
2419
|
+
else if (countSQL && maxRowsUsed && maxRowsUsed > 1 && retData.length === maxRowsUsed && !skipCount) {
|
|
2420
|
+
// A row-limited read that came back FULL may have been truncated, so the total is
|
|
2421
|
+
// worth a second round trip: this is what makes Explorer's "100 of 299" correct.
|
|
2422
|
+
// `maxRowsUsed > 1` carves out the ONE case where it cannot be: a `MaxRows:1`
|
|
2423
|
+
// probe. Those callers ask "does a row exist / give me the one row" — a
|
|
2424
|
+
// record-map lookup, a single-key resolve — and never read TotalRowCount. The
|
|
2425
|
+
// count they triggered was pure cost, and SEQUENTIAL cost: it runs after the data
|
|
2426
|
+
// query has already resolved, so it is a full extra round trip on the critical
|
|
2427
|
+
// path, not a parallel one.
|
|
2428
|
+
//
|
|
2429
|
+
// Measured on a live tenant over a 120-second census: 1,000 record-map lookups
|
|
2430
|
+
// fired 721 of these counts and 800 row lookups fired 600 — 1,321 extra round
|
|
2431
|
+
// trips totalling 9,760 ms, 11.4% of ALL SQL time in the window. Nothing read a
|
|
2432
|
+
// single one of the results.
|
|
2433
|
+
//
|
|
2434
|
+
// Everything with `maxRowsUsed > 1` is untouched, so the "100 of 299" behaviour
|
|
2435
|
+
// is preserved exactly; only the degenerate single-row probe changes.
|
|
2436
|
+
//
|
|
2437
|
+
// What DOES change for `MaxRows:1`, stated plainly: with no `rowCount`, the return
|
|
2438
|
+
// below falls back to `rowCount ?? retData.length`, so a hit now reports
|
|
2439
|
+
// `TotalRowCount: 1` instead of the whole view's row count. That is the entire
|
|
2440
|
+
// observable difference, and it is confined to a limit of exactly one row — a shape
|
|
2441
|
+
// no caller asks for in order to learn a total, because a total is the one thing a
|
|
2442
|
+
// single-row limit cannot tell it anything about.
|
|
2443
|
+
//
|
|
2444
|
+
// `!skipCount`: a caller that never reads TotalRowCount can also opt out of this count
|
|
2445
|
+
// on a full multi-row page (RunViewParams.SkipTotalRowCount); the pagination count
|
|
2446
|
+
// above honours the same flag.
|
|
2003
2447
|
const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
|
|
2004
2448
|
if (countResult && countResult.length > 0)
|
|
2005
2449
|
rowCount = countResult[0].TotalRowCount;
|
|
@@ -2059,6 +2503,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2059
2503
|
if (this.isConnectionError(e)) {
|
|
2060
2504
|
throw e;
|
|
2061
2505
|
}
|
|
2506
|
+
// A field-security refusal throws, as the provider's pre-cache gate does, and a
|
|
2507
|
+
// restricted caller's "no such column" becomes the same refusal — so a denied column
|
|
2508
|
+
// and a missing one look identical however the request reached this point.
|
|
2509
|
+
const fieldSecurityError = this.fieldSecurityErrorFor(e, resolvedEntity, contextUser ?? this.CurrentUser);
|
|
2510
|
+
if (fieldSecurityError) {
|
|
2511
|
+
throw fieldSecurityError;
|
|
2512
|
+
}
|
|
2062
2513
|
const exceptionStopTime = new Date();
|
|
2063
2514
|
LogError(e);
|
|
2064
2515
|
return {
|
|
@@ -2072,12 +2523,155 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2072
2523
|
};
|
|
2073
2524
|
}
|
|
2074
2525
|
}
|
|
2526
|
+
/** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
|
|
2527
|
+
async LoadRunViewEntity(params, contextUser) {
|
|
2528
|
+
if (params.ViewEntity)
|
|
2529
|
+
return params.ViewEntity;
|
|
2530
|
+
if (params.ViewID && params.ViewID.length > 0)
|
|
2531
|
+
return await ViewInfo.GetViewEntity(params.ViewID, contextUser) ?? null;
|
|
2532
|
+
if (params.ViewName && params.ViewName.length > 0)
|
|
2533
|
+
return await ViewInfo.GetViewEntityByName(params.ViewName, contextUser) ?? null;
|
|
2534
|
+
return null;
|
|
2535
|
+
}
|
|
2536
|
+
/**
|
|
2537
|
+
* Works out a stored view's property values before the cache lookup (see
|
|
2538
|
+
* {@link ProviderBase.PrepareRunViewProperties}). The resolved values, token defaults included,
|
|
2539
|
+
* replace `Properties` and `ServerProperties`, so the fingerprint keys on what the run will use,
|
|
2540
|
+
* and RunViewCore resolving them again yields the same predicates. A run that would be refused
|
|
2541
|
+
* is left as it is and kept out of the cache; RunViewCore refuses it with its message. A view
|
|
2542
|
+
* that cannot be loaded is left to RunViewCore too, which reports it as it always has.
|
|
2543
|
+
*/
|
|
2544
|
+
async PrepareRunViewProperties(params, contextUser) {
|
|
2545
|
+
if (!params.ViewEntity && !params.ViewID && !params.ViewName) {
|
|
2546
|
+
return; // an entity run: RunViewCore refuses any properties it carries
|
|
2547
|
+
}
|
|
2548
|
+
let viewEntity;
|
|
2549
|
+
try {
|
|
2550
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
2551
|
+
}
|
|
2552
|
+
catch {
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
const entityInfo = viewEntity ? this.EntityByID(viewEntity.EntityID) : undefined;
|
|
2556
|
+
const user = contextUser ?? this.CurrentUser;
|
|
2557
|
+
if (!viewEntity || !entityInfo || !user) {
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
try {
|
|
2561
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2562
|
+
if (resolved) {
|
|
2563
|
+
params.ServerProperties = resolved.Values;
|
|
2564
|
+
delete params.Properties;
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
catch {
|
|
2568
|
+
params.BypassCache = true;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Checks a stored view's declared properties and works out each one's value for this run.
|
|
2573
|
+
* @returns null when the view declares none and the run sends none
|
|
2574
|
+
* @throws on a malformed definition, any refusal {@link ResolveViewPropertyValues} makes, or a
|
|
2575
|
+
* property with a value whose target field the user cannot read
|
|
2576
|
+
*/
|
|
2577
|
+
ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user) {
|
|
2578
|
+
const declared = viewEntity?.PropertiesObject ?? [];
|
|
2579
|
+
const sent = params.Properties !== undefined || params.ServerProperties !== undefined;
|
|
2580
|
+
if (!viewEntity) {
|
|
2581
|
+
if (sent)
|
|
2582
|
+
throw new Error('Properties apply only to a stored view: run it by ViewID, ViewName or ViewEntity.');
|
|
2583
|
+
return null;
|
|
2584
|
+
}
|
|
2585
|
+
if (declared.length === 0 && !sent) {
|
|
2586
|
+
return null;
|
|
2587
|
+
}
|
|
2588
|
+
const definitionErrors = ValidateUserViewProperties(declared, entityInfo.Fields.map(f => f.Name));
|
|
2589
|
+
if (definitionErrors.length > 0) {
|
|
2590
|
+
throw new Error(`View '${viewEntity.Name ?? viewEntity.ID}' has invalid properties: ${definitionErrors.join(' ')}`);
|
|
2591
|
+
}
|
|
2592
|
+
const values = ResolveViewPropertyValues(declared, params.Properties, params.ServerProperties, { User: user, TimeZone: params.TimeZone });
|
|
2593
|
+
this.assertViewPropertyFieldsReadable(declared, values, entityInfo, user);
|
|
2594
|
+
return { Declared: declared, Values: values };
|
|
2595
|
+
}
|
|
2596
|
+
/**
|
|
2597
|
+
* The WHERE clause a stored view's properties add to this run: '' when there are none.
|
|
2598
|
+
* Screened like any caller clause, though it is built only from typed literals.
|
|
2599
|
+
*/
|
|
2600
|
+
BuildViewPropertyFilter(viewEntity, entityInfo, params, user) {
|
|
2601
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2602
|
+
if (!resolved) {
|
|
2603
|
+
return '';
|
|
2604
|
+
}
|
|
2605
|
+
const filter = BuildViewPropertyFilter(resolved.Declared, resolved.Values, entityInfo.Fields.map(f => f.Name), this.Dialect);
|
|
2606
|
+
if (filter.length > 0 && !this.ValidateUserProvidedSQLClause(filter)) {
|
|
2607
|
+
throw new Error(`Invalid view property filter: contains one or more forbidden keywords`);
|
|
2608
|
+
}
|
|
2609
|
+
return filter;
|
|
2610
|
+
}
|
|
2611
|
+
/** The field-security check other predicates get: a property with a value may not filter a field the user cannot read. */
|
|
2612
|
+
assertViewPropertyFieldsReadable(declared, values, entityInfo, user) {
|
|
2613
|
+
if (!entityInfo.FieldLevelSecurityApplies) {
|
|
2614
|
+
return;
|
|
2615
|
+
}
|
|
2616
|
+
const denied = entityInfo.GetDeniedReadFields(user);
|
|
2617
|
+
for (const property of declared) {
|
|
2618
|
+
if (values[property.Name] !== null && denied.has(property.Target.Field.trim().toLowerCase())) {
|
|
2619
|
+
throw new FieldSecurityError(property.Target.Field, entityInfo.Name);
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2075
2623
|
async InternalRunViews(params, contextUser) {
|
|
2076
2624
|
if (IsCoalescibleCountBatch(params)) {
|
|
2077
2625
|
return this.RunCoalescedCountBatch(params, contextUser);
|
|
2078
2626
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2627
|
+
if (params.length === 0) {
|
|
2628
|
+
return [];
|
|
2629
|
+
}
|
|
2630
|
+
const limit = GenericDatabaseProvider.MaxConcurrentViewsPerBatch;
|
|
2631
|
+
if (!limit || !Number.isFinite(limit) || limit <= 0 || params.length <= limit) {
|
|
2632
|
+
const promises = params.map((p) => this.runBatchedView(p, contextUser));
|
|
2633
|
+
return Promise.all(promises);
|
|
2634
|
+
}
|
|
2635
|
+
const results = new Array(params.length);
|
|
2636
|
+
const started = new Array(params.length).fill(false);
|
|
2637
|
+
const joinerPromises = [];
|
|
2638
|
+
let cursor = 0;
|
|
2639
|
+
const attachInFlightDuplicates = (fromIndex) => {
|
|
2640
|
+
if (typeof this.hasInFlightSingleFlightView !== 'function') {
|
|
2641
|
+
return;
|
|
2642
|
+
}
|
|
2643
|
+
for (let j = fromIndex; j < params.length; j++) {
|
|
2644
|
+
if (!started[j] && this.hasInFlightSingleFlightView(params[j], contextUser)) {
|
|
2645
|
+
started[j] = true;
|
|
2646
|
+
const joinIdx = j;
|
|
2647
|
+
joinerPromises.push(this.runBatchedView(params[joinIdx], contextUser).then((res) => {
|
|
2648
|
+
results[joinIdx] = res;
|
|
2649
|
+
}));
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
};
|
|
2653
|
+
const runWorker = async () => {
|
|
2654
|
+
while (cursor < params.length) {
|
|
2655
|
+
const idx = cursor++;
|
|
2656
|
+
if (started[idx]) {
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
started[idx] = true;
|
|
2660
|
+
const viewPromise = this.runBatchedView(params[idx], contextUser);
|
|
2661
|
+
attachInFlightDuplicates(idx + 1);
|
|
2662
|
+
results[idx] = await viewPromise;
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
const workerCount = Math.min(limit, params.length);
|
|
2666
|
+
const workers = [];
|
|
2667
|
+
for (let w = 0; w < workerCount; w++) {
|
|
2668
|
+
workers.push(runWorker());
|
|
2669
|
+
}
|
|
2670
|
+
await Promise.all(workers);
|
|
2671
|
+
if (joinerPromises.length > 0) {
|
|
2672
|
+
await Promise.all(joinerPromises);
|
|
2673
|
+
}
|
|
2674
|
+
return results;
|
|
2081
2675
|
}
|
|
2082
2676
|
/**
|
|
2083
2677
|
* All-`count_only` batch: every view runs the normal per-view path (so every
|
|
@@ -2089,8 +2683,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2089
2683
|
async RunCoalescedCountBatch(params, contextUser) {
|
|
2090
2684
|
const batch = new CountOnlyBatchCoalescer(params.length, (sql) => this.ExecuteSQL(sql, undefined, undefined, contextUser), (name) => this.QuoteIdentifier(name), (error) => this.isConnectionError(error));
|
|
2091
2685
|
return Promise.all(params.map((p, index) => this.RunViewCore(p, contextUser, (countSQL) => batch.Execute(index, countSQL))
|
|
2686
|
+
.catch((error) => GenericDatabaseProvider.fieldSecurityRefusalAsResult(error))
|
|
2092
2687
|
.finally(() => batch.MarkSettled(index))));
|
|
2093
2688
|
}
|
|
2689
|
+
/**
|
|
2690
|
+
* One view of a `RunViews` batch. A field-security refusal of this view becomes this view's
|
|
2691
|
+
* `Success: false` result, carrying the refusal's message, so it does not fail the views
|
|
2692
|
+
* batched with it. Any other error is thrown, as a single RunView throws it.
|
|
2693
|
+
*/
|
|
2694
|
+
async runBatchedView(params, contextUser) {
|
|
2695
|
+
try {
|
|
2696
|
+
return await this.InternalRunView(params, contextUser);
|
|
2697
|
+
}
|
|
2698
|
+
catch (error) {
|
|
2699
|
+
return GenericDatabaseProvider.fieldSecurityRefusalAsResult(error);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2094
2702
|
/**************************************************************************/
|
|
2095
2703
|
// InternalRunView Helpers
|
|
2096
2704
|
/**************************************************************************/
|
|
@@ -2139,7 +2747,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2139
2747
|
* column list here buys the same protection without touching either.
|
|
2140
2748
|
*/
|
|
2141
2749
|
buildFieldSecuritySelectList(entityInfo, user) {
|
|
2142
|
-
if (!user || !entityInfo.
|
|
2750
|
+
if (!user || !entityInfo.FieldLevelSecurityApplies) {
|
|
2143
2751
|
return '*'; // the overwhelmingly common case — one boolean, unchanged SQL
|
|
2144
2752
|
}
|
|
2145
2753
|
const denied = entityInfo.GetDeniedReadFields(user);
|
|
@@ -2197,9 +2805,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2197
2805
|
// Binary columns are omitted from every implicit field list (saved-view columns and
|
|
2198
2806
|
// the no-Fields wildcard) unless requested; an explicit params.Fields entry is honoured.
|
|
2199
2807
|
const includeBinary = params.IncludeBinaryFields === true;
|
|
2808
|
+
// The request's own denied set, shared with its cache key (ResolveRequestDeniedReadFields),
|
|
2809
|
+
// so the slot this fill lands in is keyed for the columns it actually selects.
|
|
2200
2810
|
const flsUser = contextUser ?? this.CurrentUser;
|
|
2201
|
-
const denied = params.ResultType !== 'entity_object'
|
|
2202
|
-
?
|
|
2811
|
+
const denied = params.ResultType !== 'entity_object'
|
|
2812
|
+
? this.ResolveRequestDeniedReadFields(params, entityInfo, flsUser)
|
|
2203
2813
|
: new Set();
|
|
2204
2814
|
if (params.Fields) {
|
|
2205
2815
|
for (const ef of entityInfo.PrimaryKeys) {
|
|
@@ -2265,8 +2875,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2265
2875
|
* - escapes LIKE metacharacters (%, _, [, ]) in user input with ESCAPE '\\',
|
|
2266
2876
|
* - skips fields that are not sensible text-search targets (non-text types,
|
|
2267
2877
|
* unbounded text columns when FTX is off).
|
|
2878
|
+
*
|
|
2879
|
+
* @param deniedFields - The request's denied set (see ResolveRequestDeniedReadFields), so the
|
|
2880
|
+
* searched columns match the ones its cache key and SELECT list were built from. Read from
|
|
2881
|
+
* the entity for `contextUser` when omitted.
|
|
2268
2882
|
*/
|
|
2269
|
-
createViewUserSearchSQL(entityInfo, userSearchString, contextUser) {
|
|
2883
|
+
createViewUserSearchSQL(entityInfo, userSearchString, contextUser, deniedFields) {
|
|
2270
2884
|
let sUserSearchSQL = '';
|
|
2271
2885
|
const safeUserSearchString = userSearchString.replace(/'/g, "''");
|
|
2272
2886
|
// Field-level security: never search fields the user cannot read. Matching against a
|
|
@@ -2276,15 +2890,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2276
2890
|
// fields are simply excluded from the searched set. Computed once per call, never per
|
|
2277
2891
|
// field (the per-request precompute contract).
|
|
2278
2892
|
const user = contextUser ?? this.CurrentUser;
|
|
2279
|
-
const deniedSearchFields =
|
|
2280
|
-
? entityInfo.GetDeniedReadFields(user)
|
|
2281
|
-
: new Set();
|
|
2893
|
+
const deniedSearchFields = deniedFields
|
|
2894
|
+
?? (entityInfo.FieldLevelSecurityApplies && user ? entityInfo.GetDeniedReadFields(user) : new Set());
|
|
2282
2895
|
// The full-text index spans its indexed columns as one unit — a denied FTS-indexed
|
|
2283
2896
|
// column cannot be excluded from the index function. When (and only when) a denied
|
|
2284
2897
|
// field is FTS-indexed, fall back to the per-field LIKE path, which CAN exclude it.
|
|
2285
2898
|
const ftsCoversDeniedField = deniedSearchFields.size > 0 &&
|
|
2286
2899
|
entityInfo.Fields.some(f => f.FullTextSearchEnabled && deniedSearchFields.has(f.Name.trim().toLowerCase()));
|
|
2287
|
-
|
|
2900
|
+
// `FullTextSearchEnabled` alone is NOT enough to take this branch: the branch names
|
|
2901
|
+
// `FullTextSearchFunction` and, when that is null or blank, the `?? ''` below emitted
|
|
2902
|
+
// `... FROM "schema".""('term')` — a syntax error, thrown on EVERY user search of such an
|
|
2903
|
+
// entity, with no fallback. The two columns are independent (the flag can be set by hand
|
|
2904
|
+
// or by a metadata sync before CodeGen has minted the function), so the name has to be
|
|
2905
|
+
// checked, not assumed. A blank name now falls through to the per-field LIKE path, which
|
|
2906
|
+
// needs no database object and returns results.
|
|
2907
|
+
//
|
|
2908
|
+
// Composed with, not substituted for, the field-security condition above — both have to
|
|
2909
|
+
// hold to search through the index.
|
|
2910
|
+
const ftsFunctionName = entityInfo.FullTextSearchFunction;
|
|
2911
|
+
const hasFTSFunction = typeof ftsFunctionName === 'string' && ftsFunctionName.trim().length > 0;
|
|
2912
|
+
if (entityInfo.FullTextSearchEnabled && hasFTSFunction && !ftsCoversDeniedField) {
|
|
2288
2913
|
let u = safeUserSearchString;
|
|
2289
2914
|
const uUpper = u.toUpperCase();
|
|
2290
2915
|
// WORD-boundary tests, not substring tests (#4392). As substrings, `OR` matches
|
|
@@ -2328,7 +2953,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2328
2953
|
// forbidden keyword). Quoting `{0}` in the format is what actually closes that.
|
|
2329
2954
|
//
|
|
2330
2955
|
// The screen reads the quote-doubled term, because that is the text `{0}` becomes.
|
|
2331
|
-
|
|
2956
|
+
const termIsSQL = this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields);
|
|
2957
|
+
if (termIsSQL && user) {
|
|
2958
|
+
// Spliced in unquoted, the term is a predicate the caller wrote, so it gets the
|
|
2959
|
+
// field-security gate every other caller predicate gets.
|
|
2960
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [safeUserSearchString], user);
|
|
2961
|
+
}
|
|
2962
|
+
if (termIsSQL && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
|
|
2332
2963
|
throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
|
|
2333
2964
|
`which splices the term directly into SQL, and the term is not allowed there: it contains ` +
|
|
2334
2965
|
`a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
|
|
@@ -2487,6 +3118,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2487
3118
|
const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
|
|
2488
3119
|
ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
|
|
2489
3120
|
}
|
|
3121
|
+
/**
|
|
3122
|
+
* The field-security error a failed RunView must raise, or null to report the failure as
|
|
3123
|
+
* usual: a {@link FieldSecurityError} raised along the way, or — for a caller denied fields on
|
|
3124
|
+
* `entity` — a database "no such column" rejection, rewritten into the error a denied column
|
|
3125
|
+
* gets ({@link FieldSecuritySQLGate.ErrorForInvalidColumn}).
|
|
3126
|
+
*/
|
|
3127
|
+
fieldSecurityErrorFor(error, entity, user) {
|
|
3128
|
+
if (error instanceof Error && (error instanceof FieldSecurityError || error.name === FieldSecurityError.ErrorName)) {
|
|
3129
|
+
return error;
|
|
3130
|
+
}
|
|
3131
|
+
return FieldSecuritySQLGate.ErrorForInvalidColumn(error, entity, user);
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* For a caller denied fields on `entity`, throws the field-security error when an aggregate was
|
|
3135
|
+
* refused because it names a column the entity does not have. A denied column in an aggregate is
|
|
3136
|
+
* refused by the gate with that error, so an unknown one must not answer differently.
|
|
3137
|
+
*/
|
|
3138
|
+
assertAggregateRefusalsAreNotColumnProbes(errors, entity, user) {
|
|
3139
|
+
if (errors.length === 0 || !FieldSecuritySQLGate.UserCarriesDenials([entity], user)) {
|
|
3140
|
+
return;
|
|
3141
|
+
}
|
|
3142
|
+
for (const refused of errors) {
|
|
3143
|
+
const match = /references "((?:[^"]|"")*)", which (?:is not a column|matches more than one column) of this entity/.exec(refused.error ?? '');
|
|
3144
|
+
if (match) {
|
|
3145
|
+
// Named the way the gate names a denied column in the same expression, so the two
|
|
3146
|
+
// refusals read the same whatever case the caller typed.
|
|
3147
|
+
const column = FieldSecuritySQLGate.ReportedColumnName(refused.expression, match[1].replace(/""/g, '"'), this.PlatformKey);
|
|
3148
|
+
throw new FieldSecurityError(column, entity.Name);
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
2490
3152
|
/**
|
|
2491
3153
|
* SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
|
|
2492
3154
|
* Any user who can save a view can write its WhereClause, directly or through FilterState or a
|
|
@@ -2544,7 +3206,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2544
3206
|
// takes a one-column subquery — an entity with a composite key has no single column to return.
|
|
2545
3207
|
const innerEntityInfo = innerViewEntity.ViewEntityInfo;
|
|
2546
3208
|
this.assertSingleColumnPrimaryKey(innerEntityInfo, `The {%UserView%} template variable ${match}`);
|
|
2547
|
-
const
|
|
3209
|
+
const innerTarget = await this.resolveEffectiveBaseViewTarget(innerEntityInfo, { EntityName: innerEntityInfo.Name, ViewEntity: innerViewEntity }, user, innerViewEntity);
|
|
3210
|
+
const innerSQL = `SELECT ${this.QuoteIdentifier(innerEntityInfo.FirstPrimaryKey.Name)} FROM ${this.QuoteSchemaAndView(innerTarget.schemaName, innerTarget.viewName)} WHERE (${innerWhere})`; // first-pk-ok: guarded above — IN (subquery) takes one column, PrimaryKeys.length === 1 enforced
|
|
2548
3211
|
// Function replacement — `innerSQL` is generated SQL that can
|
|
2549
3212
|
// legitimately contain `$`. See issue #3171.
|
|
2550
3213
|
sWhere = sWhere.replace(match, () => innerSQL);
|
|
@@ -2658,6 +3321,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2658
3321
|
}
|
|
2659
3322
|
return items;
|
|
2660
3323
|
}
|
|
3324
|
+
/**
|
|
3325
|
+
* The field-security key of one request, built once per request (`params` object) and user.
|
|
3326
|
+
* A smart-cache-check item asks for it from each leg — its browser freshness check, the
|
|
3327
|
+
* server-cache lookup and the cache write — and the answer cannot change within the request:
|
|
3328
|
+
* the denied set it is built from is already resolved once per request.
|
|
3329
|
+
*/
|
|
3330
|
+
ComputeRunViewFLSFingerprintKey(params, contextUser) {
|
|
3331
|
+
const user = contextUser ?? this.CurrentUser;
|
|
3332
|
+
const memo = this._requestFLSKeys?.get(params);
|
|
3333
|
+
if (memo && memo.User === user && memo.Target === GenericDatabaseProvider.flsKeyTarget(params)) {
|
|
3334
|
+
return memo.Key;
|
|
3335
|
+
}
|
|
3336
|
+
const key = super.ComputeRunViewFLSFingerprintKey(params, user);
|
|
3337
|
+
this._requestFLSKeys?.set(params, { User: user, Target: GenericDatabaseProvider.flsKeyTarget(params), Key: key });
|
|
3338
|
+
return key;
|
|
3339
|
+
}
|
|
3340
|
+
/** What a request's field-security key is about: its entity, or the saved view it names. */
|
|
3341
|
+
static flsKeyTarget(params) {
|
|
3342
|
+
return `${params.EntityName ?? ''}|${params.ViewID ?? ''}|${params.ViewName ?? ''}|${params.ViewEntity ? 'loaded' : ''}`;
|
|
3343
|
+
}
|
|
3344
|
+
/** The message refusing `user` Read on `entityInfo`, or null when the user may read it. */
|
|
3345
|
+
readPermissionError(entityInfo, user) {
|
|
3346
|
+
try {
|
|
3347
|
+
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
3348
|
+
return null;
|
|
3349
|
+
}
|
|
3350
|
+
catch (e) {
|
|
3351
|
+
return e instanceof Error ? e.message : String(e);
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
2661
3354
|
/**
|
|
2662
3355
|
* Smart cache validation for batch RunViews.
|
|
2663
3356
|
* For each view request, if cacheStatus is provided, checks if the cache is current
|
|
@@ -2673,9 +3366,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2673
3366
|
}
|
|
2674
3367
|
// ── Superset/projection contract (same as the ProviderBase pipeline) ──
|
|
2675
3368
|
// For every cache-eligible item: widen Fields to ALL entity fields so any
|
|
2676
|
-
// cache write stores the
|
|
2677
|
-
//
|
|
2678
|
-
//
|
|
3369
|
+
// cache write stores every column the user's permission class may read (the
|
|
3370
|
+
// slot is keyed by that class), and remember the caller's requested shape
|
|
3371
|
+
// (∪ primary keys — platform contract) so every serve leg projects back down
|
|
3372
|
+
// before returning rows to the client. This path
|
|
2679
3373
|
// previously cached narrow rows under the Fields-agnostic fingerprint and
|
|
2680
3374
|
// served cached rows unprojected — one client's shape poisoned the slot
|
|
2681
3375
|
// for every subsequent caller.
|
|
@@ -2719,15 +3413,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2719
3413
|
const requested = p.Fields && p.Fields.length > 0
|
|
2720
3414
|
? p.Fields.map(f => f.trim().toLowerCase())
|
|
2721
3415
|
: null;
|
|
2722
|
-
// ALL fields, for every user:
|
|
2723
|
-
//
|
|
2724
|
-
//
|
|
3416
|
+
// ALL fields requested, for every user: the SELECT built from this list leaves
|
|
3417
|
+
// out the columns this user may not read, and the slot is keyed by the user's
|
|
3418
|
+
// permission class, so a slot holds only what its class may read.
|
|
3419
|
+
// ApplyFieldSecurityProjection still runs on every serve as a backstop.
|
|
2725
3420
|
this.ResolveIncludeBinaryFields(p, widenEntity);
|
|
2726
3421
|
p.Fields = this.ComputeRunViewFetchFields(widenEntity, p);
|
|
2727
3422
|
if (requested) {
|
|
2728
3423
|
callerFieldsByIndex.set(i, ProviderBase.UnionFieldsWithPrimaryKeys(requested, widenEntity));
|
|
2729
3424
|
}
|
|
2730
3425
|
}
|
|
3426
|
+
// A status the browser computed for other columns than this user may read now
|
|
3427
|
+
// describes a slot with the wrong columns, even if no row changed. Dropping it sends
|
|
3428
|
+
// the item down the "nothing cached" path, which answers with fresh rows.
|
|
3429
|
+
if (this.cacheStatusFieldSecurityDiffers(params[i].cacheStatus, p, user)) {
|
|
3430
|
+
params[i].cacheStatus = undefined;
|
|
3431
|
+
}
|
|
2731
3432
|
}
|
|
2732
3433
|
/** Projects rows down to the caller's requested shape for a given item index. */
|
|
2733
3434
|
const projectForCaller = (index, rows) => {
|
|
@@ -2749,6 +3450,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2749
3450
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: gateRejection });
|
|
2750
3451
|
continue;
|
|
2751
3452
|
}
|
|
3453
|
+
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
3454
|
+
// Read-permission gate for EVERY item whose entity is known, before any leg can answer:
|
|
3455
|
+
// an item with no cache status, and an external entity, are served from the server cache
|
|
3456
|
+
// on a hit WITHOUT re-entering InternalRunView, so a CanRead check that lived only on the
|
|
3457
|
+
// cache-miss path would let a user lacking permission receive rows another user warmed.
|
|
3458
|
+
if (entityInfo) {
|
|
3459
|
+
const permissionError = this.readPermissionError(entityInfo, user);
|
|
3460
|
+
if (permissionError !== null) {
|
|
3461
|
+
errorResults.push({ viewIndex: i, status: 'error', errorMessage: permissionError });
|
|
3462
|
+
continue;
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
2752
3465
|
// Keyset queries bypass the cache entirely (per the AfterKey API contract):
|
|
2753
3466
|
// each call uses a different seek key, so cached entries would never be
|
|
2754
3467
|
// reusable. Route directly to standard execution path.
|
|
@@ -2756,22 +3469,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2756
3469
|
itemsWithoutCacheCheck.push({ index: i, item });
|
|
2757
3470
|
continue;
|
|
2758
3471
|
}
|
|
2759
|
-
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
2760
3472
|
if (!entityInfo) {
|
|
2761
3473
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: `Entity ${item.params.EntityName} not found in metadata` });
|
|
2762
3474
|
continue;
|
|
2763
3475
|
}
|
|
2764
|
-
// Read-permission gate for EVERY entity (external + local) up front. This must run before
|
|
2765
|
-
// the external routing below: external entities are served from the server cache on a hit
|
|
2766
|
-
// WITHOUT re-entering InternalRunView, so if the CanRead check only lived on the cache-miss
|
|
2767
|
-
// path a user lacking permission could receive rows another user warmed into the cache.
|
|
2768
|
-
try {
|
|
2769
|
-
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2770
|
-
}
|
|
2771
|
-
catch (e) {
|
|
2772
|
-
errorResults.push({ viewIndex: i, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
2773
|
-
continue;
|
|
2774
|
-
}
|
|
2775
3476
|
// External-data-source entities can't participate in DB-side cache validation
|
|
2776
3477
|
// (no MJ base view / __mj_UpdatedAt to COUNT/MAX against). Route them to the
|
|
2777
3478
|
// standard execution path, which dispatches to the external driver and TTL-caches
|
|
@@ -2782,7 +3483,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2782
3483
|
}
|
|
2783
3484
|
itemsNeedingValidation.push({ index: i, item, entityInfo });
|
|
2784
3485
|
}
|
|
2785
|
-
// Phase 1: Check server's LocalCacheManager first (zero DB hits)
|
|
3486
|
+
// Phase 1: Check server's LocalCacheManager first (zero DB hits when within freshness window)
|
|
2786
3487
|
const currentResults = [];
|
|
2787
3488
|
const serverCacheStaleItems = [];
|
|
2788
3489
|
const serverCacheMissItems = [];
|
|
@@ -2793,6 +3494,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2793
3494
|
if (resolved.status === 'current') {
|
|
2794
3495
|
currentResults.push(resolved.result);
|
|
2795
3496
|
}
|
|
3497
|
+
else if (resolved.status === 'needs_verification') {
|
|
3498
|
+
serverCacheMissItems.push({
|
|
3499
|
+
index,
|
|
3500
|
+
item,
|
|
3501
|
+
entityInfo,
|
|
3502
|
+
serverCached: resolved.serverCached,
|
|
3503
|
+
fingerprint: resolved.fingerprint,
|
|
3504
|
+
});
|
|
3505
|
+
}
|
|
2796
3506
|
else {
|
|
2797
3507
|
serverCacheStaleItems.push({ index, item, entityInfo, serverCached: resolved.serverCached });
|
|
2798
3508
|
}
|
|
@@ -2801,29 +3511,63 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2801
3511
|
serverCacheMissItems.push({ index, item, entityInfo });
|
|
2802
3512
|
}
|
|
2803
3513
|
}
|
|
2804
|
-
// Phase 2: For server cache misses,
|
|
3514
|
+
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
2805
3515
|
const differentialItems = [];
|
|
2806
3516
|
const staleItemsNoTracking = [];
|
|
2807
3517
|
if (serverCacheMissItems.length > 0) {
|
|
2808
|
-
// Build WHERE clauses and run batched DB status check only for cache misses
|
|
3518
|
+
// Build WHERE clauses and run batched DB status check only for cache misses / TTL-expired slots
|
|
2809
3519
|
const itemsForDBCheck = [];
|
|
2810
|
-
for (const { index, item, entityInfo } of serverCacheMissItems) {
|
|
3520
|
+
for (const { index, item, entityInfo, serverCached, fingerprint } of serverCacheMissItems) {
|
|
2811
3521
|
try {
|
|
2812
3522
|
const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user);
|
|
2813
|
-
itemsForDBCheck.push({ index, item, entityInfo, whereSQL });
|
|
3523
|
+
itemsForDBCheck.push({ index, item, entityInfo, whereSQL, serverCached, fingerprint });
|
|
2814
3524
|
}
|
|
2815
3525
|
catch (e) {
|
|
2816
3526
|
errorResults.push({ viewIndex: index, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
2817
3527
|
}
|
|
2818
3528
|
}
|
|
2819
3529
|
const cacheStatusResults = await this.getBatchedServerCacheStatus(itemsForDBCheck, contextUser);
|
|
2820
|
-
for (const { index, item, entityInfo, whereSQL } of itemsForDBCheck) {
|
|
3530
|
+
for (const { index, item, entityInfo, whereSQL, serverCached, fingerprint } of itemsForDBCheck) {
|
|
2821
3531
|
const serverStatus = cacheStatusResults.get(index);
|
|
2822
3532
|
if (!serverStatus || !serverStatus.success) {
|
|
2823
|
-
|
|
3533
|
+
const statusError = serverStatus?.errorMessage || 'Failed to get cache status';
|
|
3534
|
+
const fieldSecurityError = FieldSecuritySQLGate.ErrorForInvalidColumn(statusError, entityInfo, user);
|
|
3535
|
+
errorResults.push({ viewIndex: index, status: 'error', errorMessage: fieldSecurityError?.message ?? statusError });
|
|
2824
3536
|
continue;
|
|
2825
3537
|
}
|
|
2826
3538
|
const entityLabel = item.params.EntityName || 'unknown';
|
|
3539
|
+
if (serverCached && fingerprint) {
|
|
3540
|
+
const cachedSlotStatus = {
|
|
3541
|
+
maxUpdatedAt: serverCached.maxUpdatedAt,
|
|
3542
|
+
rowCount: serverCached.totalRowCount ?? serverCached.rowCount,
|
|
3543
|
+
};
|
|
3544
|
+
if (this.isCacheCurrent(cachedSlotStatus, serverStatus)) {
|
|
3545
|
+
// Server cache slot is confirmed current against SQL — refresh its verification timestamp in O(1)
|
|
3546
|
+
LocalCacheManager.Instance.TouchRunViewResultVerifiedAt(fingerprint);
|
|
3547
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3548
|
+
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
3549
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3550
|
+
}
|
|
3551
|
+
else {
|
|
3552
|
+
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
|
|
3553
|
+
serverCacheStaleItems.push({ index, item, entityInfo, serverCached });
|
|
3554
|
+
}
|
|
3555
|
+
continue;
|
|
3556
|
+
}
|
|
3557
|
+
else {
|
|
3558
|
+
// Out-of-band SQL mutation or missed invalidation occurred!
|
|
3559
|
+
// Evict the stale server slot and refresh from DB so LocalCacheManager and the client self-heal.
|
|
3560
|
+
LogStatusEx({ message: ` ♻️ [SmartCache RECONCILE-EVICT] "${entityLabel}" — server cache slot disagreed with DB status; invalidating and refreshing from DB`, verboseOnly: true });
|
|
3561
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
3562
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3563
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3564
|
+
}
|
|
3565
|
+
else {
|
|
3566
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
3567
|
+
}
|
|
3568
|
+
continue;
|
|
3569
|
+
}
|
|
3570
|
+
}
|
|
2827
3571
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
2828
3572
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches DB (server cache miss)`, verboseOnly: true });
|
|
2829
3573
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
@@ -2847,22 +3591,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2847
3591
|
const noCacheStatusServedFromCache = [];
|
|
2848
3592
|
const noCacheStatusNeedsDB = [];
|
|
2849
3593
|
for (const entry of itemsWithoutCacheCheck) {
|
|
2850
|
-
// A param carrying BypassCache
|
|
3594
|
+
// A param carrying BypassCache (or any cache-ineligible request such as an AlternateBaseView
|
|
3595
|
+
// with CachePolicy === 'Bypass', an unknown/disabled AlternateBaseView, or a view-only request
|
|
3596
|
+
// denied by the read-permission gate) lands here because it is ineligible for a cache status,
|
|
2851
3597
|
// NOT because the caller has nothing cached — and those two must not be treated alike.
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
// !param.BypassCache); this is the matching read-side gate.
|
|
2857
|
-
if (entry.item.params.BypassCache) {
|
|
2858
|
-
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — BypassCache requested, going to the database`, verboseOnly: true });
|
|
3598
|
+
if (entry.item.params.BypassCache ||
|
|
3599
|
+
!this.runViewCacheEligible(entry.item.params) ||
|
|
3600
|
+
this.cacheDeniedForViewOnlyRequest(entry.item.params, contextUser)) {
|
|
3601
|
+
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — cache ineligible or BypassCache requested, going to the database`, verboseOnly: true });
|
|
2859
3602
|
noCacheStatusNeedsDB.push(entry);
|
|
2860
3603
|
continue;
|
|
2861
3604
|
}
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
const fingerprint =
|
|
3605
|
+
// A saved-view request without an entity name had no Read check above; only the
|
|
3606
|
+
// database leg resolves its entity and checks it, so it never reads the cache here.
|
|
3607
|
+
if (LocalCacheManager.Instance.IsInitialized && !this.cacheDeniedForViewOnlyRequest(entry.item.params, user)) {
|
|
3608
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(entry.item.params, user);
|
|
2866
3609
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
2867
3610
|
if (cached) {
|
|
2868
3611
|
const entityLabel = entry.item.params.EntityName || 'unknown';
|
|
@@ -2875,7 +3618,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2875
3618
|
}
|
|
2876
3619
|
// Phase 4: Run queries in parallel for items needing data.
|
|
2877
3620
|
// Every leg that returns rows projects them down to the caller's requested
|
|
2878
|
-
// shape (callerFieldsByIndex) — the cache
|
|
3621
|
+
// shape (callerFieldsByIndex) — the cache holds every field the slot's
|
|
3622
|
+
// permission class may read.
|
|
2879
3623
|
const queryPromises = [
|
|
2880
3624
|
// Items without cache check — served from server cache
|
|
2881
3625
|
...noCacheStatusServedFromCache.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
@@ -2914,8 +3658,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2914
3658
|
// BOTH projections, in this order — they are siblings, not alternatives, and
|
|
2915
3659
|
// `PostRunView` calls them as a pair at all four of its projection points. Applying
|
|
2916
3660
|
// only the first leaves the audit trail leaking: `ApplyFieldSecurityProjection`
|
|
2917
|
-
// short-circuits
|
|
2918
|
-
// `MJ: Record Changes` has
|
|
3661
|
+
// short-circuits when field security does not apply to the RunView entity, and
|
|
3662
|
+
// `MJ: Record Changes` has field security OFF by design, so it is a no-op on exactly the
|
|
2919
3663
|
// rows that matter. The denied values there are INSIDE the `ChangesJSON` /
|
|
2920
3664
|
// `FullRecordJSON` payload columns, which no amount of column stripping reaches —
|
|
2921
3665
|
// `ApplyRecordChangeFieldSecurityProjection` is what projects them against the entity
|
|
@@ -2991,7 +3735,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2991
3735
|
// Free text, not a SQL fragment — deliberately NOT run through
|
|
2992
3736
|
// ValidateUserProvidedSQLClause. See the equivalent note on the view path above (#4392).
|
|
2993
3737
|
if (params.UserSearchString && params.UserSearchString.length > 0) {
|
|
2994
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user);
|
|
3738
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
2995
3739
|
if (sUserSearchSQL.length > 0) {
|
|
2996
3740
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
2997
3741
|
bHasWhere = true;
|
|
@@ -3009,8 +3753,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3009
3753
|
* entity whose view does not carry it, instead of comparing by count alone the way
|
|
3010
3754
|
* `BaseEngine.SweepAgainstDatabase` documents.
|
|
3011
3755
|
*/
|
|
3012
|
-
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
|
|
3013
|
-
const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
3756
|
+
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL, schemaNameOverride) {
|
|
3757
|
+
const from = `FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
3014
3758
|
const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
|
|
3015
3759
|
// `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
|
|
3016
3760
|
// throwing: a freshness check must not be the thing that breaks a sweep.
|
|
@@ -3036,8 +3780,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3036
3780
|
// snapshot cache against an unrelated source, yielding a meaningless current/stale verdict.
|
|
3037
3781
|
// (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
|
|
3038
3782
|
// matches the SQL Server override and is defense-in-depth on the PG/default path.)
|
|
3039
|
-
const
|
|
3040
|
-
const statusSQL = this.BuildCacheStatusSQL(entityInfo,
|
|
3783
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
|
|
3784
|
+
const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveTarget.viewName, whereSQL, effectiveTarget.schemaName);
|
|
3041
3785
|
const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
|
|
3042
3786
|
if (rows && rows.length > 0) {
|
|
3043
3787
|
const row = rows[0];
|
|
@@ -3062,7 +3806,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3062
3806
|
* Runs a full view query and returns results with cache metadata.
|
|
3063
3807
|
*/
|
|
3064
3808
|
async runFullQueryAndReturn(params, viewIndex, contextUser) {
|
|
3065
|
-
|
|
3809
|
+
let result;
|
|
3810
|
+
try {
|
|
3811
|
+
result = await this.InternalRunView(params, contextUser);
|
|
3812
|
+
}
|
|
3813
|
+
catch (e) {
|
|
3814
|
+
// A field-security refusal fails this item only, as the up-front gate does on this path.
|
|
3815
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
3816
|
+
return { viewIndex, status: 'error', errorMessage: e.message };
|
|
3817
|
+
}
|
|
3818
|
+
throw e;
|
|
3819
|
+
}
|
|
3066
3820
|
if (!result.Success) {
|
|
3067
3821
|
return { viewIndex, status: 'error', errorMessage: result.ErrorMessage || 'Unknown error executing view' };
|
|
3068
3822
|
}
|
|
@@ -3091,9 +3845,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3091
3845
|
// external source has caching disabled — skip the write to avoid stale data.
|
|
3092
3846
|
const ttlMs = await this.resolveExternalCacheTTLMs(params, contextUser);
|
|
3093
3847
|
if (ttlMs !== 0) {
|
|
3094
|
-
const
|
|
3095
|
-
const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(params);
|
|
3096
|
-
const fingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString, rlsWhereClause, undefined, flsFieldsKey);
|
|
3848
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(params, contextUser);
|
|
3097
3849
|
const maxUpdatedAt = result.maxUpdatedAt || new Date().toISOString();
|
|
3098
3850
|
// Pass the aggregates (B38-family omission #4). This slot is ALSO written by
|
|
3099
3851
|
// InternalRunView's normal PostRunView path WITH aggregates — two writers,
|
|
@@ -3169,7 +3921,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3169
3921
|
* infinite loop / duplicate processing in deep-pagination jobs. Aggregates and a non-empty
|
|
3170
3922
|
* UserSearchString likewise can't be evaluated remotely. Throws a clear error naming the param.
|
|
3171
3923
|
*/
|
|
3172
|
-
assertExternalRunViewParamsSupported(params, entityName) {
|
|
3924
|
+
assertExternalRunViewParamsSupported(params, entityName, viewEntity) {
|
|
3925
|
+
if (this.resolveEffectiveAbvNameFromParams(params, viewEntity)) {
|
|
3926
|
+
throw new Error(`AlternateBaseView is not supported for external-data-source entity '${entityName}'.`);
|
|
3927
|
+
}
|
|
3173
3928
|
if (params.AfterKey) {
|
|
3174
3929
|
throw new Error(`Keyset pagination (AfterKey) is not supported for external-data-source entity '${entityName}'. Use StartRow/MaxRows offset paging instead.`);
|
|
3175
3930
|
}
|
|
@@ -3195,6 +3950,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3195
3950
|
throw new Error(`Invalid OrderBy clause for external-data-source entity '${entityName}': contains one or more forbidden keywords.`);
|
|
3196
3951
|
}
|
|
3197
3952
|
}
|
|
3953
|
+
/**
|
|
3954
|
+
* Field-level security on the clauses an external-data-source read hands its driver: the
|
|
3955
|
+
* caller's own, merged with a saved view's stored ones. The same gates the SQL path applies to
|
|
3956
|
+
* the clauses it runs; the external dispatch returns before that path, and the driver runs
|
|
3957
|
+
* the clauses remotely, where nothing else checks them.
|
|
3958
|
+
*/
|
|
3959
|
+
assertExternalClausesRespectFieldSecurity(entityInfo, params, user) {
|
|
3960
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [params.ExtraFilter, params.OverrideExcludeFilter], user);
|
|
3961
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [params.OrderBy], user);
|
|
3962
|
+
}
|
|
3963
|
+
/**
|
|
3964
|
+
* An external driver's rows without the columns `user` may not read. The driver returns the
|
|
3965
|
+
* entity's columns at full width, and the result-path projection resolves the entity only from
|
|
3966
|
+
* an `EntityName` or a loaded `ViewEntity`, so a request naming only a `ViewID` would keep
|
|
3967
|
+
* them: the entity resolved here is named explicitly.
|
|
3968
|
+
*/
|
|
3969
|
+
projectExternalRowsForCaller(rows, entityInfo, params, user) {
|
|
3970
|
+
return this.ApplyFieldSecurityProjection(rows, { ...params, EntityName: entityInfo.Name }, user);
|
|
3971
|
+
}
|
|
3198
3972
|
/**
|
|
3199
3973
|
* Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
|
|
3200
3974
|
* external dispatch. The external branch returns before the normal SQL path that applies
|
|
@@ -3230,21 +4004,68 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3230
4004
|
}
|
|
3231
4005
|
return merged;
|
|
3232
4006
|
}
|
|
4007
|
+
/**
|
|
4008
|
+
* True when a browser's cache status carries a field-security key (see
|
|
4009
|
+
* `ProviderBase.ComputeFieldSecurityCacheStatusKey`) other than the one this server computes
|
|
4010
|
+
* for `user` and `params`: the browser's slot was filled for a different set of columns, so
|
|
4011
|
+
* its row count and newest timestamp say nothing about whether it is current. False when the
|
|
4012
|
+
* status carries no key.
|
|
4013
|
+
*/
|
|
4014
|
+
cacheStatusFieldSecurityDiffers(status, params, user) {
|
|
4015
|
+
if (status?.fieldSecurityKey == null) {
|
|
4016
|
+
return false; // an older client: no key, no check
|
|
4017
|
+
}
|
|
4018
|
+
return status.fieldSecurityKey !== this.ComputeFieldSecurityCacheStatusKey(params, user);
|
|
4019
|
+
}
|
|
3233
4020
|
/**
|
|
3234
4021
|
* Checks the server's LocalCacheManager for cached data matching the client's request.
|
|
3235
|
-
* Returns the resolution if found (
|
|
3236
|
-
*
|
|
4022
|
+
* Returns the resolution if found ('current', 'stale' server-cached data to serve, or
|
|
4023
|
+
* 'needs_verification' when the server slot's freshness window has elapsed),
|
|
4024
|
+
* or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
|
|
3237
4025
|
*/
|
|
3238
4026
|
async resolveFromServerCache(item, index, entityLabel, contextUser) {
|
|
3239
4027
|
if (!LocalCacheManager.Instance.IsInitialized)
|
|
3240
4028
|
return null;
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
4029
|
+
if (!this.runViewCacheEligible(item.params) || this.cacheDeniedForViewOnlyRequest(item.params, contextUser)) {
|
|
4030
|
+
return null;
|
|
4031
|
+
}
|
|
4032
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(item.params, contextUser);
|
|
3244
4033
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
3245
4034
|
if (!cached)
|
|
3246
4035
|
return null;
|
|
3247
|
-
|
|
4036
|
+
// 1. Client Monotonicity Guard:
|
|
4037
|
+
// If the client's cacheStatus has a timestamp newer than the server's cached slot,
|
|
4038
|
+
// the server slot is provably stale (e.g., client received a newer write from another
|
|
4039
|
+
// replica or after an out-of-band update). Never serve stale rows backward in time:
|
|
4040
|
+
// evict the server slot immediately and route to Phase 2 DB validation.
|
|
4041
|
+
const clientDate = this.parseClientTimestamp(item.cacheStatus.maxUpdatedAt);
|
|
4042
|
+
const serverCachedDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
4043
|
+
const serverCachedRowCount = cached.totalRowCount ?? cached.rowCount;
|
|
4044
|
+
if (clientDate &&
|
|
4045
|
+
serverCachedDate &&
|
|
4046
|
+
((clientDate.getTime() - serverCachedDate.getTime()) >= 1000 ||
|
|
4047
|
+
(clientDate.getTime() > serverCachedDate.getTime() && item.cacheStatus.rowCount !== serverCachedRowCount))) {
|
|
4048
|
+
LogStatusEx({
|
|
4049
|
+
message: ` ⚠️ [SmartCache MONOTONICITY-EVICT] "${entityLabel}" — client timestamp (${item.cacheStatus.maxUpdatedAt}) is newer than server cache (${cached.maxUpdatedAt}); evicting stale server slot`,
|
|
4050
|
+
verboseOnly: true,
|
|
4051
|
+
});
|
|
4052
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
4053
|
+
return null;
|
|
4054
|
+
}
|
|
4055
|
+
// 2. Bounded Server-Slot Freshness Window:
|
|
4056
|
+
// If the server slot has not been verified against SQL within ServerCacheVerificationTTLMs,
|
|
4057
|
+
// route to Phase 2's batched SQL status check before trusting it.
|
|
4058
|
+
const verifiedAt = cached.lastVerifiedAt ?? cached.cachedAt;
|
|
4059
|
+
const needsVerification = this.ServerCacheVerificationTTLMs <= 0 ||
|
|
4060
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs);
|
|
4061
|
+
if (needsVerification) {
|
|
4062
|
+
LogStatusEx({
|
|
4063
|
+
message: ` ⏱️ [SmartCache VERIFY-TTL] "${entityLabel}" — server cache slot verification TTL expired, routing to batched DB status check`,
|
|
4064
|
+
verboseOnly: true,
|
|
4065
|
+
});
|
|
4066
|
+
return { status: 'needs_verification', serverCached: cached, fingerprint };
|
|
4067
|
+
}
|
|
4068
|
+
const serverStatus = { maxUpdatedAt: cached.maxUpdatedAt, rowCount: serverCachedRowCount };
|
|
3248
4069
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3249
4070
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches server cache, no DB hit`, verboseOnly: true });
|
|
3250
4071
|
return { status: 'current', result: { viewIndex: index, status: 'current' } };
|
|
@@ -3257,8 +4078,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3257
4078
|
* Packages server-cached data as a RunViewWithCacheCheckResult for return to the client.
|
|
3258
4079
|
*/
|
|
3259
4080
|
async serveFromServerCache(viewIndex, serverCached, callerFields = null) {
|
|
3260
|
-
// The server cache stores the
|
|
3261
|
-
// caller's requested fields (∪ PK) before returning, exactly like the
|
|
4081
|
+
// The server cache stores every field the slot's permission class may read —
|
|
4082
|
+
// project down to the caller's requested fields (∪ PK) before returning, exactly like the
|
|
3262
4083
|
// ProviderBase hit path. Serving unprojected rows here previously leaked
|
|
3263
4084
|
// whatever shape happened to be cached to every subsequent caller.
|
|
3264
4085
|
//
|
|
@@ -3389,7 +4210,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3389
4210
|
const fields = params.Fields && params.Fields.length > 0
|
|
3390
4211
|
? params.Fields.map(f => this.QuoteIdentifier(f)).join(', ')
|
|
3391
4212
|
: '*';
|
|
3392
|
-
|
|
4213
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser);
|
|
4214
|
+
let sql = `SELECT ${fields} FROM ${this.QuoteSchemaAndView(effectiveTarget.schemaName, effectiveTarget.viewName)} WHERE ${combinedWhere}`;
|
|
3393
4215
|
const orderBy = this.TransformExternalSQLClause(params.OrderBy || '', entityInfo);
|
|
3394
4216
|
if (orderBy.length > 0) {
|
|
3395
4217
|
if (!this.ValidateUserProvidedSQLClause(orderBy))
|
|
@@ -3432,15 +4254,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3432
4254
|
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: `Query not found: ${item.params.QueryID || item.params.QueryName}` });
|
|
3433
4255
|
continue;
|
|
3434
4256
|
}
|
|
3435
|
-
const
|
|
4257
|
+
const definition = this.QueryDefinitionSignatureFor(query);
|
|
4258
|
+
const runCheck = this.authorizeCacheCheckedQuery(query, item, definition, user);
|
|
3436
4259
|
if (!runCheck.canRun) {
|
|
3437
4260
|
const deniedMsg = runCheck.deniedEntities.length > 0
|
|
3438
4261
|
? ` Denied entities: ${runCheck.deniedEntities.join(', ')}.`
|
|
3439
4262
|
: '';
|
|
3440
|
-
|
|
4263
|
+
const errorMessage = runCheck.renderError ?? `User does not have permission to run query: ${query.Name}.${deniedMsg}`;
|
|
4264
|
+
errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage });
|
|
3441
4265
|
continue;
|
|
3442
4266
|
}
|
|
3443
|
-
const definition = this.QueryDefinitionSignatureFor(query);
|
|
3444
4267
|
if (definition) {
|
|
3445
4268
|
definitionHashes.set(i, definition.Hash);
|
|
3446
4269
|
}
|
|
@@ -3504,6 +4327,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3504
4327
|
return { success: false, results: [], errorMessage: e instanceof Error ? e.message : String(e) };
|
|
3505
4328
|
}
|
|
3506
4329
|
}
|
|
4330
|
+
/**
|
|
4331
|
+
* The authorization of one {@link RunQueriesWithCacheCheck} item before it is routed. An item
|
|
4332
|
+
* that may be answered "current" without running — it carries a cache status for this
|
|
4333
|
+
* definition and the query has validation SQL — is checked in full on its rendering here. Every
|
|
4334
|
+
* other item runs, and the run checks the rendering it executes, so only the render-free part
|
|
4335
|
+
* is checked here rather than rendering the query twice.
|
|
4336
|
+
*/
|
|
4337
|
+
authorizeCacheCheckedQuery(query, item, definition, user) {
|
|
4338
|
+
const mayAnswerWithoutRunning = !!item.cacheStatus
|
|
4339
|
+
&& !this.clientSlotDefinitionDiffers(item.cacheStatus, definition)
|
|
4340
|
+
&& !!query.CacheValidationSQL;
|
|
4341
|
+
return mayAnswerWithoutRunning ? this.authorizeQueryRun(query, item.params.Parameters, user) : query.UserCanRun(user);
|
|
4342
|
+
}
|
|
3507
4343
|
/**
|
|
3508
4344
|
* B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
|
|
3509
4345
|
* cache HIT that the miss path enforces. Resolution uses `resolveQuery()` (QueryEngine as
|
|
@@ -3513,6 +4349,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3513
4349
|
* applies before a real execution. The base's roles-only check would let a user read cached
|
|
3514
4350
|
* rows of a query whose underlying entities they cannot read.
|
|
3515
4351
|
*
|
|
4352
|
+
* The run-time checks (`UserCanRunRenderedSQL`: entities read by the SQL itself, and field-level
|
|
4353
|
+
* security) run against the query rendered with the request's own parameters: the SQL the miss
|
|
4354
|
+
* path would check and execute for this slot, since the slot's fingerprint carries those
|
|
4355
|
+
* parameters and its definition hash the query's SQL. A user the miss path would refuse is never
|
|
4356
|
+
* served the slot; a rendering that fails is treated as not authorized, so the request falls
|
|
4357
|
+
* through to execution and gets that path's error.
|
|
4358
|
+
*
|
|
3516
4359
|
* Non-throwing by contract: any resolution error degrades to `resolvable: false`, which the
|
|
3517
4360
|
* gate treats as "fall through to authorized execution" — one extra query run, never an
|
|
3518
4361
|
* unauthorized serve and never a crashed cache path.
|
|
@@ -3525,9 +4368,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3525
4368
|
}
|
|
3526
4369
|
return {
|
|
3527
4370
|
resolvable: true,
|
|
3528
|
-
authorized: !user || query.
|
|
4371
|
+
authorized: !user || this.authorizeQueryRun(query, params.Parameters, user).canRun,
|
|
3529
4372
|
categoryPath: query.CategoryPath,
|
|
3530
4373
|
queryName: query.Name,
|
|
4374
|
+
contextTokens: this.queryContextTokens(query),
|
|
3531
4375
|
queryId: query.ID,
|
|
3532
4376
|
definition: this.QueryDefinitionSignatureFor(query)
|
|
3533
4377
|
};
|
|
@@ -3615,16 +4459,128 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3615
4459
|
if (user) {
|
|
3616
4460
|
const result = query.UserCanRun(user);
|
|
3617
4461
|
if (!result.canRun) {
|
|
3618
|
-
|
|
3619
|
-
? ` Denied entities: ${result.deniedEntities.join(', ')}.`
|
|
3620
|
-
: '';
|
|
3621
|
-
throw new Error(`User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`);
|
|
4462
|
+
throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
|
|
3622
4463
|
}
|
|
3623
4464
|
}
|
|
3624
4465
|
if (query.Status !== 'Approved') {
|
|
3625
4466
|
LogStatus(`WARNING: Executing query '${query.Name}' (ID: ${query.ID}) with status '${query.Status}'. Query has not been approved.`);
|
|
3626
4467
|
}
|
|
3627
4468
|
}
|
|
4469
|
+
/**
|
|
4470
|
+
* For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
|
|
4471
|
+
* current approval — status Approved and a stored fingerprint equal to the fingerprint of the
|
|
4472
|
+
* definition this run executes. The fingerprint is worked out here, from the same
|
|
4473
|
+
* `QueryEngine` metadata the run renders, never from a caller's value.
|
|
4474
|
+
*
|
|
4475
|
+
* @throws Error naming the first query whose approval is not current
|
|
4476
|
+
*/
|
|
4477
|
+
async ValidateQueryApprovalAsync(query, render) {
|
|
4478
|
+
if (RenderPipeline.HasCompositionTokens(query.GetPlatformSQL(this.PlatformKey)) && !render.HasCompositions) {
|
|
4479
|
+
throw new Error(`Query '${query.Name}' (ID: ${query.ID}) composes other queries, which requires a context user so every composed query's approval can be verified.`);
|
|
4480
|
+
}
|
|
4481
|
+
const engine = QueryEngine.Instance;
|
|
4482
|
+
const depsByQueryID = GroupByUUID(engine.Dependencies, d => d.QueryID);
|
|
4483
|
+
const queriesByID = IndexByUUID(engine.Queries);
|
|
4484
|
+
const composedIDs = new UUIDSet(render.CTEs.map(c => c.QueryID));
|
|
4485
|
+
const queue = [query.ID, ...render.CTEs.map(c => c.QueryID)];
|
|
4486
|
+
while (queue.length > 0) {
|
|
4487
|
+
const currentID = queue.shift();
|
|
4488
|
+
for (const dep of depsByQueryID.Get(currentID) ?? []) {
|
|
4489
|
+
if (dep.DependsOnQueryID && !composedIDs.Has(dep.DependsOnQueryID) && !UUIDsEqual(dep.DependsOnQueryID, query.ID)) {
|
|
4490
|
+
composedIDs.Add(dep.DependsOnQueryID);
|
|
4491
|
+
queue.push(dep.DependsOnQueryID);
|
|
4492
|
+
}
|
|
4493
|
+
}
|
|
4494
|
+
}
|
|
4495
|
+
const toVerify = [query];
|
|
4496
|
+
for (const cte of render.CTEs) {
|
|
4497
|
+
const found = queriesByID.Get(cte.QueryID);
|
|
4498
|
+
if (!found) {
|
|
4499
|
+
throw new Error(`Query '${cte.QueryName || cte.QueryID}' composed by '${query.Name}' is not a saved query in QueryEngine, so its approval cannot be verified.`);
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
for (const depID of composedIDs) {
|
|
4503
|
+
const found = queriesByID.Get(depID);
|
|
4504
|
+
if (!found) {
|
|
4505
|
+
throw new Error(`Query dependency (ID: ${depID}) composed by '${query.Name}' is not found in QueryEngine, so its approval cannot be verified.`);
|
|
4506
|
+
}
|
|
4507
|
+
toVerify.push(found);
|
|
4508
|
+
}
|
|
4509
|
+
for (const q of toVerify) {
|
|
4510
|
+
const state = await GetQueryApprovalStateAsync(q);
|
|
4511
|
+
if (state !== 'Current') {
|
|
4512
|
+
const reason = state === 'NotApproved'
|
|
4513
|
+
? `its status is '${q.Status}'`
|
|
4514
|
+
: 'its definition changed after it was approved (or it was approved before approvals were fingerprinted)';
|
|
4515
|
+
throw new Error(`Query '${q.Name}' (ID: ${q.ID}) is not approved in its current form: ${reason}. The run requires an approved query.`);
|
|
4516
|
+
}
|
|
4517
|
+
}
|
|
4518
|
+
}
|
|
4519
|
+
/** The context tokens a query reads, with every query it composes, as the `QueryEngine` holds them. */
|
|
4520
|
+
queryContextTokens(query) {
|
|
4521
|
+
const engine = QueryEngine.Instance;
|
|
4522
|
+
return FindQueryContextTokens(query.ID, id => [engine.Queries.find(q => UUIDsEqual(q.ID, id))?.SQL, ...engine.QuerySQLs.filter(s => UUIDsEqual(s.QueryID, id)).map(s => s.SQL)], id => engine.Dependencies.filter(d => UUIDsEqual(d.QueryID, id)).map(d => d.DependsOnQueryID));
|
|
4523
|
+
}
|
|
4524
|
+
/**
|
|
4525
|
+
* SECURITY — authorizes a saved query against the SQL the run will execute (fully composed and
|
|
4526
|
+
* rendered), after {@link ValidateQueryForExecution} has passed: the entities that SQL reads,
|
|
4527
|
+
* and field-level security on every column it references. A template that injects an
|
|
4528
|
+
* identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
|
|
4529
|
+
* render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
|
|
4530
|
+
* The refusal does not say which field or clause caused it.
|
|
4531
|
+
*
|
|
4532
|
+
* @throws Error when the user may not run this rendering of the query
|
|
4533
|
+
*/
|
|
4534
|
+
ValidateRenderedQueryForExecution(query, renderedSQL, contextUser) {
|
|
4535
|
+
const user = contextUser || this.CurrentUser;
|
|
4536
|
+
if (!user) {
|
|
4537
|
+
return;
|
|
4538
|
+
}
|
|
4539
|
+
const result = this.checkRenderedQuery(query, renderedSQL, user);
|
|
4540
|
+
if (!result.canRun) {
|
|
4541
|
+
throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
/** The refusal for a user who may not run `query`; names entities the user cannot read, never a field. */
|
|
4545
|
+
queryRunRefusalMessage(query, deniedEntities) {
|
|
4546
|
+
const deniedMsg = deniedEntities.length > 0 ? ` Denied entities: ${deniedEntities.join(', ')}.` : '';
|
|
4547
|
+
return `User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`;
|
|
4548
|
+
}
|
|
4549
|
+
/** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
|
|
4550
|
+
checkRenderedQuery(query, renderedSQL, user) {
|
|
4551
|
+
const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey);
|
|
4552
|
+
if (result.fieldSecurityViolation) {
|
|
4553
|
+
const v = result.fieldSecurityViolation;
|
|
4554
|
+
LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}' by field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''}).`, verboseOnly: true });
|
|
4555
|
+
}
|
|
4556
|
+
return result;
|
|
4557
|
+
}
|
|
4558
|
+
/**
|
|
4559
|
+
* The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
|
|
4560
|
+
* and the run-time checks on the query rendered with `parameters`. A rendering that fails
|
|
4561
|
+
* refuses, carrying the rendering's error.
|
|
4562
|
+
*/
|
|
4563
|
+
authorizeQueryRun(query, parameters, user) {
|
|
4564
|
+
const base = query.UserCanRun(user);
|
|
4565
|
+
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
4566
|
+
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
4567
|
+
// already confirmed the user holds one of its roles: nothing to render.
|
|
4568
|
+
return base;
|
|
4569
|
+
}
|
|
4570
|
+
let renderedSQL;
|
|
4571
|
+
try {
|
|
4572
|
+
renderedSQL = this.processQueryParameters(query, parameters, user).finalSQL;
|
|
4573
|
+
}
|
|
4574
|
+
catch (e) {
|
|
4575
|
+
return { canRun: false, deniedEntities: [], renderError: e instanceof Error ? e.message : String(e) };
|
|
4576
|
+
}
|
|
4577
|
+
return this.checkRenderedQuery(query, renderedSQL, user);
|
|
4578
|
+
}
|
|
4579
|
+
/** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
|
|
4580
|
+
static roleListGrants(query) {
|
|
4581
|
+
const permissions = query.QueryPermissions;
|
|
4582
|
+
return !!permissions && permissions.length > 0;
|
|
4583
|
+
}
|
|
3628
4584
|
/**
|
|
3629
4585
|
* Resolves a category path string to a QueryCategoryInfo ID.
|
|
3630
4586
|
*/
|
|
@@ -3903,9 +4859,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3903
4859
|
* the live query (serving live is always correct — this is a transparent optimization, never a
|
|
3904
4860
|
* correctness dependency).
|
|
3905
4861
|
*/
|
|
3906
|
-
async tryBuildMaterializedQueryPlan(query, params, contextUser) {
|
|
4862
|
+
async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues) {
|
|
3907
4863
|
if (!IsMaterializedDataSource(params.DataSource))
|
|
3908
4864
|
return null; // not opted in → live
|
|
4865
|
+
// A snapshot is shared by every caller and was built without this caller's Context (user, date), so a
|
|
4866
|
+
// run whose template read Context is served live: its rows depend on who runs it and when.
|
|
4867
|
+
if (contextValues && Object.keys(contextValues).length > 0)
|
|
4868
|
+
return null;
|
|
3909
4869
|
if (query.ExternalDataSourceID)
|
|
3910
4870
|
return null; // external source → materialized table is local; live
|
|
3911
4871
|
// The query<->materialization link lives in the MaterializedResultQuery join table — there is no
|
|
@@ -4000,7 +4960,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4000
4960
|
schemaName: mat.SchemaName,
|
|
4001
4961
|
viewName: mat.ViewName,
|
|
4002
4962
|
spec,
|
|
4003
|
-
|
|
4963
|
+
// Server-set parameters take their values from ServerParameters (a caller value for one was
|
|
4964
|
+
// already refused when the template rendered), so the row filter sees both.
|
|
4965
|
+
paramValues: params.ServerParameters ? { ...params.Parameters, ...params.ServerParameters } : params.Parameters,
|
|
4004
4966
|
paramTypes,
|
|
4005
4967
|
isPostgres: this.PlatformKey === 'postgresql',
|
|
4006
4968
|
});
|
|
@@ -4008,6 +4970,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4008
4970
|
async InternalRunQuery(params, contextUser) {
|
|
4009
4971
|
// Route ad-hoc SQL queries to dedicated handler
|
|
4010
4972
|
if (params.SQL) {
|
|
4973
|
+
if (params.RequireApproved) {
|
|
4974
|
+
return {
|
|
4975
|
+
Success: false,
|
|
4976
|
+
QueryID: '',
|
|
4977
|
+
QueryName: 'Ad-Hoc Query',
|
|
4978
|
+
Results: [],
|
|
4979
|
+
RowCount: 0,
|
|
4980
|
+
TotalRowCount: 0,
|
|
4981
|
+
ExecutionTime: 0,
|
|
4982
|
+
ErrorMessage: 'Ad-hoc SQL has no approved query definition and cannot run when RequireApproved is set.',
|
|
4983
|
+
};
|
|
4984
|
+
}
|
|
4011
4985
|
return this.ExecuteAdhocQuery(params, contextUser);
|
|
4012
4986
|
}
|
|
4013
4987
|
let finalSQL;
|
|
@@ -4015,15 +4989,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4015
4989
|
// Find and validate query
|
|
4016
4990
|
const query = this.findAndValidateQuery(params, contextUser);
|
|
4017
4991
|
// Process parameters (composition + Nunjucks templates)
|
|
4018
|
-
const resolved = this.processQueryParameters(query, params.Parameters, contextUser);
|
|
4992
|
+
const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params);
|
|
4019
4993
|
finalSQL = resolved.finalSQL;
|
|
4020
4994
|
const appliedParameters = resolved.appliedParameters;
|
|
4995
|
+
// Opt-in: the approval must be current for the definition about to run
|
|
4996
|
+
if (params.RequireApproved) {
|
|
4997
|
+
await this.ValidateQueryApprovalAsync(query, resolved.renderResult);
|
|
4998
|
+
}
|
|
4999
|
+
// Authorize what will actually run, before any cache, materialized or external read.
|
|
5000
|
+
this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser);
|
|
4021
5001
|
// ── Phase 2: materialized read redirect (plan §5) ──
|
|
4022
5002
|
// If the caller opted into DataSource:'Materialized' and this query has a fresh, Active
|
|
4023
5003
|
// RowFilterBroad materialization, serve from the materialized table with the row-filter params
|
|
4024
5004
|
// injected as BOUND predicates. On ANY uncertainty tryBuildMaterializedQueryPlan returns null and
|
|
4025
5005
|
// we fall through to the live execution below — a materialized read can never diverge from live.
|
|
4026
|
-
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser);
|
|
5006
|
+
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues);
|
|
4027
5007
|
if (matPlan) {
|
|
4028
5008
|
// Use a LOCAL for the materialized SQL — never overwrite `finalSQL` (which stays the
|
|
4029
5009
|
// live-rendered SQL), so a fallback below runs the live path unchanged.
|
|
@@ -4110,7 +5090,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4110
5090
|
// credential should be least-privilege). Do not assume EDS RLS covers the Query path.
|
|
4111
5091
|
if (query.ExternalDataSourceID) {
|
|
4112
5092
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
|
|
4113
|
-
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser);
|
|
5093
|
+
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser, resolved.renderResult.ContextValues);
|
|
4114
5094
|
}
|
|
4115
5095
|
// Execute query — use SQL-level paging when requested, else fetch all rows
|
|
4116
5096
|
const useSQLPaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
|
|
@@ -4276,6 +5256,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4276
5256
|
RequireReadStatement: true,
|
|
4277
5257
|
...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
|
|
4278
5258
|
});
|
|
5259
|
+
this.AssertAdhocReadAllowed(rendered.Trace.AfterTemplates, contextUser);
|
|
4279
5260
|
const options = this.adhocSQLOptions(params);
|
|
4280
5261
|
if (!usePaging) {
|
|
4281
5262
|
const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
|
|
@@ -4290,6 +5271,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4290
5271
|
const rows = dataResult ?? [];
|
|
4291
5272
|
return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
|
|
4292
5273
|
}
|
|
5274
|
+
/**
|
|
5275
|
+
* SECURITY — what ad-hoc SQL may read, checked in the provider so that every in-process caller
|
|
5276
|
+
* (agents, data contexts, actions) is covered, not only the API's resolvers. `sql` is the
|
|
5277
|
+
* rendered statement, before the server's own paging wrap. Every table it reads must be an
|
|
5278
|
+
* entity base view the caller can read unscoped: CanRead with no row-level filter and no denied
|
|
5279
|
+
* field, because raw SQL applies neither ({@link ClientClauseScreen.AssertStatementReadsUnscopedEntityViews}).
|
|
5280
|
+
* The system user runs the server's own SQL and is not checked, but only when passed
|
|
5281
|
+
* explicitly: no user at all refuses, rather than falling back to the provider's own user,
|
|
5282
|
+
* which on a server is the system user.
|
|
5283
|
+
*
|
|
5284
|
+
* @throws Error when the caller may not run `sql`
|
|
5285
|
+
*/
|
|
5286
|
+
AssertAdhocReadAllowed(sql, contextUser) {
|
|
5287
|
+
if (!contextUser) {
|
|
5288
|
+
throw new Error('Invalid ad-hoc SQL: no acting user was passed — refusing');
|
|
5289
|
+
}
|
|
5290
|
+
if (IsSystemUser(contextUser)) {
|
|
5291
|
+
return;
|
|
5292
|
+
}
|
|
5293
|
+
ClientClauseScreen.AssertStatementReadsUnscopedEntityViews(sql, this.Entities, ClientClauseScreen.DialectFor(this), contextUser, 'ad-hoc SQL');
|
|
5294
|
+
}
|
|
4293
5295
|
/**
|
|
4294
5296
|
* The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
|
|
4295
5297
|
* fails does not fail the run: some queries page fine but cannot be counted (duplicate column
|
|
@@ -4356,11 +5358,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4356
5358
|
* Delegates to {@link RenderPipeline.Run} for the composition → template
|
|
4357
5359
|
* pipeline. Paging is handled separately by the caller (InternalRunQuery).
|
|
4358
5360
|
*/
|
|
4359
|
-
processQueryParameters(query, parameters, contextUser) {
|
|
5361
|
+
processQueryParameters(query, parameters, contextUser, serverSet) {
|
|
4360
5362
|
const result = RenderPipeline.Run(query.GetPlatformSQL(this.PlatformKey), {
|
|
4361
5363
|
Platform: this.PlatformKey,
|
|
4362
|
-
ContextUser: contextUser,
|
|
5364
|
+
ContextUser: contextUser ?? this.CurrentUser,
|
|
4363
5365
|
Parameters: parameters,
|
|
5366
|
+
ServerParameters: serverSet?.ServerParameters,
|
|
5367
|
+
TimeZone: serverSet?.TimeZone,
|
|
4364
5368
|
UsesTemplate: query.UsesTemplate ?? false,
|
|
4365
5369
|
QueryInfo: {
|
|
4366
5370
|
SQL: query.SQL ?? '',
|
|
@@ -4395,10 +5399,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4395
5399
|
* truth (a TTL of <= 0 disables caching for the source); field-drift warnings still apply to
|
|
4396
5400
|
* freshly-fetched rows. Ad-hoc SQL (params.SQL) is never cached.
|
|
4397
5401
|
*/
|
|
4398
|
-
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser) {
|
|
5402
|
+
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser, contextValues) {
|
|
4399
5403
|
const externalDataSourceID = query.ExternalDataSourceID;
|
|
4400
5404
|
const ttlSeconds = await router.GetCacheTTLSeconds(externalDataSourceID, contextUser, this);
|
|
4401
|
-
|
|
5405
|
+
// A result that read Context.Now depends on the instant it ran and is never reused.
|
|
5406
|
+
const cacheable = !params.SQL && ttlSeconds > 0 && LocalCacheManager.Instance.IsInitialized && !(contextValues && 'Now' in contextValues);
|
|
4402
5407
|
let fingerprint;
|
|
4403
5408
|
let definition;
|
|
4404
5409
|
if (cacheable) {
|
|
@@ -4408,6 +5413,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4408
5413
|
__maxRows: params.MaxRows ?? -1,
|
|
4409
5414
|
__startRow: params.StartRow ?? 0,
|
|
4410
5415
|
__eds: externalDataSourceID,
|
|
5416
|
+
// What the server set shapes the result too, so one user's slot never answers another's.
|
|
5417
|
+
...this.serverSetFingerprintSegment(params, contextValues),
|
|
4411
5418
|
};
|
|
4412
5419
|
fingerprint = LocalCacheManager.Instance.GenerateRunQueryFingerprint(query.ID, query.Name, fingerprintParams, this.InstanceConnectionString, query.CategoryPath);
|
|
4413
5420
|
definition = this.QueryDefinitionSignatureFor(query);
|
|
@@ -4447,6 +5454,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4447
5454
|
}
|
|
4448
5455
|
return { ...checked, Results: paginatedResult, RowCount: paginatedResult.length, TotalRowCount: totalRowCount };
|
|
4449
5456
|
}
|
|
5457
|
+
/**
|
|
5458
|
+
* The result-cache fingerprint segment for what the server set on a run: its `ServerParameters`
|
|
5459
|
+
* and the `Context` values the template read. Empty when there are neither, so the fingerprint
|
|
5460
|
+
* is exactly what it was before either existed.
|
|
5461
|
+
*/
|
|
5462
|
+
serverSetFingerprintSegment(params, contextValues) {
|
|
5463
|
+
const segment = {};
|
|
5464
|
+
if (params.ServerParameters && Object.keys(params.ServerParameters).length > 0) {
|
|
5465
|
+
segment.__serverParameters = params.ServerParameters;
|
|
5466
|
+
}
|
|
5467
|
+
if (contextValues && Object.keys(contextValues).length > 0) {
|
|
5468
|
+
segment.__context = contextValues;
|
|
5469
|
+
}
|
|
5470
|
+
return segment;
|
|
5471
|
+
}
|
|
4450
5472
|
warnIfExternalQueryFieldsMissing(query, result) {
|
|
4451
5473
|
if (!result.Success || !result.Results || result.Results.length === 0) {
|
|
4452
5474
|
return result;
|
|
@@ -4482,6 +5504,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4482
5504
|
try {
|
|
4483
5505
|
const resolved = this.resolveSpecParameters(spec, contextUser);
|
|
4484
5506
|
finalSQL = resolved.finalSQL;
|
|
5507
|
+
// Checked on this rendering, the one that runs: a check a caller made on its own
|
|
5508
|
+
// rendering of the same input is not proof of what this one reads.
|
|
5509
|
+
this.AssertAdhocReadAllowed(resolved.renderResult.Trace.AfterTemplates, contextUser);
|
|
4485
5510
|
// Execute
|
|
4486
5511
|
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
|
|
4487
5512
|
return {
|
|
@@ -4672,6 +5697,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4672
5697
|
/**************************************************************************/
|
|
4673
5698
|
// Load — Shared Implementation
|
|
4674
5699
|
/**************************************************************************/
|
|
5700
|
+
/**
|
|
5701
|
+
* The `WHERE` predicate that selects one record by its composite key, using dialect-neutral
|
|
5702
|
+
* quoting. Quoted key values have embedded single quotes escaped: a key value can contain
|
|
5703
|
+
* apostrophes (an object-valued soft key whose JSON carries free text), and an unescaped quote
|
|
5704
|
+
* both breaks the statement and is an injection vector.
|
|
5705
|
+
*/
|
|
5706
|
+
BuildPrimaryKeyWhereClause(entityInfo, compositeKey) {
|
|
5707
|
+
return compositeKey.KeyValuePairs.map(val => {
|
|
5708
|
+
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
5709
|
+
if (!pk)
|
|
5710
|
+
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
5711
|
+
const quotes = pk.NeedsQuotes ? "'" : '';
|
|
5712
|
+
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
5713
|
+
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
5714
|
+
}).join(' AND ');
|
|
5715
|
+
}
|
|
5716
|
+
/**
|
|
5717
|
+
* Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
|
|
5718
|
+
* Server and PostgreSQL), in place, and returns the row.
|
|
5719
|
+
*/
|
|
5720
|
+
TrimFixedWidthValues(entityInfo, row) {
|
|
5721
|
+
for (const field of entityInfo.Fields) {
|
|
5722
|
+
const isFixedWidth = field.FixedWidthColumn ?? (field.TSType === EntityFieldTSType.String && (field.Type.trim().toLowerCase() === 'char' || field.Type.trim().toLowerCase() === 'nchar'));
|
|
5723
|
+
if (isFixedWidth) {
|
|
5724
|
+
const val = row[field.Name];
|
|
5725
|
+
if (typeof val === 'string')
|
|
5726
|
+
row[field.Name] = val.trimEnd();
|
|
5727
|
+
}
|
|
5728
|
+
}
|
|
5729
|
+
return row;
|
|
5730
|
+
}
|
|
4675
5731
|
/**
|
|
4676
5732
|
* Loads a single entity record by composite key, with optional relationship loading.
|
|
4677
5733
|
* Uses dialect-neutral quoting for all SQL construction.
|
|
@@ -4702,17 +5758,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4702
5758
|
return null;
|
|
4703
5759
|
}
|
|
4704
5760
|
// Build WHERE from composite key
|
|
4705
|
-
const where =
|
|
4706
|
-
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
4707
|
-
if (!pk)
|
|
4708
|
-
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
4709
|
-
const quotes = pk.NeedsQuotes ? "'" : '';
|
|
4710
|
-
// Escape embedded single quotes when the value is wrapped in quotes. A PK value can
|
|
4711
|
-
// legitimately contain apostrophes (e.g. an object-valued soft key whose JSON carries
|
|
4712
|
-
// free-text), and an unescaped quote both breaks the SQL string and is an injection vector.
|
|
4713
|
-
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
4714
|
-
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
4715
|
-
}).join(' AND ');
|
|
5761
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, compositeKey);
|
|
4716
5762
|
// Append Read row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
4717
5763
|
let fullWhere = where;
|
|
4718
5764
|
if (user) {
|
|
@@ -4735,16 +5781,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4735
5781
|
const rawData = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4736
5782
|
const d = await this.PostProcessRows(rawData, entityInfo, user);
|
|
4737
5783
|
if (d && d.length > 0) {
|
|
4738
|
-
const ret = d[0];
|
|
4739
|
-
// Trim trailing spaces for fixed-width char fields (char/nchar pad with spaces on both SQL Server and PG)
|
|
4740
|
-
for (const field of entityInfo.Fields) {
|
|
4741
|
-
const isFixedWidth = field.FixedWidthColumn ?? (field.TSType === EntityFieldTSType.String && (field.Type.trim().toLowerCase() === 'char' || field.Type.trim().toLowerCase() === 'nchar'));
|
|
4742
|
-
if (isFixedWidth) {
|
|
4743
|
-
const val = ret[field.Name];
|
|
4744
|
-
if (typeof val === 'string')
|
|
4745
|
-
ret[field.Name] = val.trimEnd();
|
|
4746
|
-
}
|
|
4747
|
-
}
|
|
5784
|
+
const ret = this.TrimFixedWidthValues(entityInfo, d[0]);
|
|
4748
5785
|
// Load entity relationships if requested
|
|
4749
5786
|
if (entityRelationshipsToLoad && entityRelationshipsToLoad.length > 0) {
|
|
4750
5787
|
for (const rel of entityRelationshipsToLoad) {
|
|
@@ -5027,8 +6064,67 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5027
6064
|
if (!entity.GetUserPermisions(contextUser)?.CanRead) {
|
|
5028
6065
|
return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
|
|
5029
6066
|
}
|
|
6067
|
+
const fieldSecurityRefusal = this.datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser);
|
|
6068
|
+
if (fieldSecurityRefusal) {
|
|
6069
|
+
return { Filter: filter, RowFilter: '', Refusal: fieldSecurityRefusal };
|
|
6070
|
+
}
|
|
5030
6071
|
return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
|
|
5031
6072
|
}
|
|
6073
|
+
/**
|
|
6074
|
+
* Why a caller's ItemFilter is refused by the field-level security gate — the same gate every
|
|
6075
|
+
* RunView filter passes — or null when it may run. The item's stored WhereClause is
|
|
6076
|
+
* administrator-defined dataset metadata, not a predicate the caller chose, so it is not checked.
|
|
6077
|
+
*/
|
|
6078
|
+
datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser) {
|
|
6079
|
+
try {
|
|
6080
|
+
this.AssertClausesRespectFieldSecurityForEntity(entity, [clientFilter], contextUser);
|
|
6081
|
+
return null;
|
|
6082
|
+
}
|
|
6083
|
+
catch (e) {
|
|
6084
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
6085
|
+
return e.message;
|
|
6086
|
+
}
|
|
6087
|
+
throw e;
|
|
6088
|
+
}
|
|
6089
|
+
}
|
|
6090
|
+
/**
|
|
6091
|
+
* The fields of a dataset item's entity the caller may not read, lowercased; empty when none,
|
|
6092
|
+
* when there is no caller, or for MJ_Metadata, which every principal loads to learn the schema.
|
|
6093
|
+
*/
|
|
6094
|
+
datasetItemDeniedFields(datasetName, entity, contextUser) {
|
|
6095
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName || !entity.FieldLevelSecurityApplies) {
|
|
6096
|
+
return new Set();
|
|
6097
|
+
}
|
|
6098
|
+
return entity.GetDeniedReadFields(contextUser);
|
|
6099
|
+
}
|
|
6100
|
+
/**
|
|
6101
|
+
* The error a failed dataset batch reports to the caller. When the caller is denied fields on
|
|
6102
|
+
* an item's entity and the database rejected a column that does not exist, every item reports
|
|
6103
|
+
* the field-security error a denied column gets instead, so the two cannot be told apart.
|
|
6104
|
+
*/
|
|
6105
|
+
datasetBatchErrorForCaller(batchError, items, datasetName, contextUser) {
|
|
6106
|
+
if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6107
|
+
return batchError;
|
|
6108
|
+
}
|
|
6109
|
+
for (const item of items) {
|
|
6110
|
+
const converted = FieldSecuritySQLGate.ErrorForInvalidColumn(batchError, this.EntityByName(String(item['Entity'])), contextUser);
|
|
6111
|
+
if (converted)
|
|
6112
|
+
return converted.message;
|
|
6113
|
+
}
|
|
6114
|
+
return batchError;
|
|
6115
|
+
}
|
|
6116
|
+
/**
|
|
6117
|
+
* Dataset item rows as the caller may see them: denied columns removed, and Record Changes
|
|
6118
|
+
* payloads narrowed. Cached rows are shared and full width, so this always builds new rows
|
|
6119
|
+
* rather than narrowing the cached ones. MJ_Metadata is exempt for the reason given on
|
|
6120
|
+
* {@link datasetItemDeniedFields}.
|
|
6121
|
+
*/
|
|
6122
|
+
projectDatasetRowsForCaller(datasetName, entity, rows, contextUser) {
|
|
6123
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6124
|
+
return rows;
|
|
6125
|
+
}
|
|
6126
|
+
return ProjectEntityValueRowsForUser(this, entity, rows, contextUser) ?? rows;
|
|
6127
|
+
}
|
|
5032
6128
|
/**
|
|
5033
6129
|
* The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
|
|
5034
6130
|
* item's filter sits two parentheses deep because a client ItemFilter is screened inside one
|
|
@@ -5091,6 +6187,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5091
6187
|
const uncachedFingerprints = [];
|
|
5092
6188
|
let cacheHitCount = 0;
|
|
5093
6189
|
let cacheMissCount = 0;
|
|
6190
|
+
const preparedItems = [];
|
|
5094
6191
|
for (const item of items) {
|
|
5095
6192
|
const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
|
|
5096
6193
|
const entityBaseView = String(item['EntityBaseView']);
|
|
@@ -5130,28 +6227,119 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5130
6227
|
}
|
|
5131
6228
|
// The row filter keys the slot, so one user's filtered rows are never served to another.
|
|
5132
6229
|
const rowFilterKey = scope.RowFilter || undefined;
|
|
5133
|
-
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
6230
|
+
const fingerprint = cacheAvailable
|
|
6231
|
+
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
|
|
6232
|
+
: '';
|
|
6233
|
+
const cached = cacheAvailable && fingerprint
|
|
6234
|
+
? await cache.GetRunViewResult(fingerprint)
|
|
6235
|
+
: null;
|
|
6236
|
+
preparedItems.push({
|
|
6237
|
+
item,
|
|
6238
|
+
entitySchemaName,
|
|
6239
|
+
entityBaseView,
|
|
6240
|
+
code,
|
|
6241
|
+
entityName,
|
|
6242
|
+
entityID,
|
|
6243
|
+
itemEntity,
|
|
6244
|
+
scope,
|
|
6245
|
+
rowFilterKey,
|
|
6246
|
+
fingerprint,
|
|
6247
|
+
cached,
|
|
6248
|
+
});
|
|
6249
|
+
}
|
|
6250
|
+
// Reconcile cached dataset slots against live SQL status (GetDatasetStatusByName)
|
|
6251
|
+
// when status was recently fetched, when GetDatasetStatusByName is overridden/spied,
|
|
6252
|
+
// or when any cached item's verification TTL (ServerCacheVerificationTTLMs) has elapsed.
|
|
6253
|
+
let liveStatus;
|
|
6254
|
+
if (cacheAvailable && preparedItems.some(p => p.cached !== null)) {
|
|
6255
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
6256
|
+
const recorded = provider._lastDatasetStatusByName.get(statusKey) ?? this._lastDatasetStatusByName.get(statusKey);
|
|
6257
|
+
const isStatusMethodOverridden = this.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName ||
|
|
6258
|
+
provider.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName;
|
|
6259
|
+
const anyCachedExpired = preparedItems.some(p => {
|
|
6260
|
+
if (!p.cached)
|
|
6261
|
+
return false;
|
|
6262
|
+
const verifiedAt = p.cached.lastVerifiedAt ?? p.cached.cachedAt;
|
|
6263
|
+
return (this.ServerCacheVerificationTTLMs <= 0 ||
|
|
6264
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs));
|
|
6265
|
+
});
|
|
6266
|
+
if (isStatusMethodOverridden ||
|
|
6267
|
+
(anyCachedExpired && (!recorded || (Date.now() - recorded.timestamp) > this.ServerCacheVerificationTTLMs))) {
|
|
6268
|
+
try {
|
|
6269
|
+
const fetched = await provider.GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse);
|
|
6270
|
+
if (fetched?.Success) {
|
|
6271
|
+
liveStatus = fetched;
|
|
6272
|
+
}
|
|
6273
|
+
}
|
|
6274
|
+
catch (statusErr) {
|
|
6275
|
+
LogError(`GetDatasetByName("${datasetName}"): status verification failed: ${statusErr instanceof Error ? statusErr.message : String(statusErr)}`);
|
|
6276
|
+
}
|
|
6277
|
+
}
|
|
6278
|
+
else if (recorded?.status?.Success) {
|
|
6279
|
+
liveStatus = recorded.status;
|
|
6280
|
+
}
|
|
6281
|
+
}
|
|
6282
|
+
const statusByEntityID = liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)
|
|
6283
|
+
? IndexByUUID(liveStatus.EntityUpdateDates.filter(e => Boolean(e.EntityID)), e => e.EntityID)
|
|
6284
|
+
: null;
|
|
6285
|
+
const statusByEntityName = new Map();
|
|
6286
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6287
|
+
for (const e of liveStatus.EntityUpdateDates) {
|
|
6288
|
+
if (e.EntityName) {
|
|
6289
|
+
statusByEntityName.set(e.EntityName.trim().toLowerCase(), e);
|
|
6290
|
+
}
|
|
6291
|
+
}
|
|
6292
|
+
}
|
|
6293
|
+
for (const prepared of preparedItems) {
|
|
6294
|
+
const { item, entitySchemaName, entityBaseView, code, entityName, entityID, itemEntity, scope, fingerprint } = prepared;
|
|
6295
|
+
let cached = prepared.cached;
|
|
6296
|
+
if (cached) {
|
|
6297
|
+
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
6298
|
+
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
6299
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6300
|
+
const statusEntry = (entityID ? statusByEntityID?.Get(entityID) : undefined)
|
|
6301
|
+
?? statusByEntityName.get(entityName.trim().toLowerCase());
|
|
6302
|
+
if (statusEntry) {
|
|
6303
|
+
const rowCountMatches = cached.results.length === statusEntry.RowCount;
|
|
6304
|
+
const cachedMaxDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
6305
|
+
const effectiveCachedTime = Math.max(latestUpdateDate ? new Date(latestUpdateDate).getTime() : 0, cachedMaxDate ? cachedMaxDate.getTime() : 0);
|
|
6306
|
+
const statusTime = statusEntry.UpdateDate ? new Date(statusEntry.UpdateDate).getTime() : 0;
|
|
6307
|
+
const timestampMatches = isNaN(statusTime) ||
|
|
6308
|
+
statusTime <= 0 ||
|
|
6309
|
+
effectiveCachedTime <= 0 ||
|
|
6310
|
+
Math.abs(statusTime - effectiveCachedTime) < 1000;
|
|
6311
|
+
if (!rowCountMatches || !timestampMatches) {
|
|
6312
|
+
LogStatusEx({
|
|
6313
|
+
message: ` ♻️ [Dataset RECONCILE-EVICT] "${datasetName}/${code}" (${entityName}) — cached slot (rows=${cached.results.length}) disagreed with SQL status (rows=${statusEntry.RowCount}); invalidating and re-fetching from SQL`,
|
|
6314
|
+
verboseOnly: true,
|
|
6315
|
+
});
|
|
6316
|
+
await cache.InvalidateRunViewResult(fingerprint);
|
|
6317
|
+
cached = null;
|
|
6318
|
+
}
|
|
6319
|
+
else {
|
|
6320
|
+
cache.TouchRunViewResultVerifiedAt(fingerprint);
|
|
6321
|
+
}
|
|
6322
|
+
}
|
|
6323
|
+
}
|
|
5137
6324
|
if (cached) {
|
|
5138
6325
|
cacheHitCount++;
|
|
5139
|
-
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
5140
|
-
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
5141
6326
|
cachedResults.push({
|
|
5142
6327
|
EntityID: entityID,
|
|
5143
6328
|
EntityName: entityName,
|
|
5144
6329
|
Code: code,
|
|
5145
|
-
Results: cached.results,
|
|
6330
|
+
Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, cached.results, contextUser),
|
|
5146
6331
|
LatestUpdateDate: latestUpdateDate,
|
|
5147
6332
|
Success: true,
|
|
5148
6333
|
});
|
|
5149
6334
|
continue; // Skip SQL for this item
|
|
5150
6335
|
}
|
|
5151
6336
|
}
|
|
5152
|
-
// Cache miss — validate columns and build SQL
|
|
6337
|
+
// Cache miss (or invalidated stale slot) — validate columns and build SQL
|
|
5153
6338
|
cacheMissCount++;
|
|
5154
|
-
|
|
6339
|
+
// A caller denied fields never has them selected; such a narrowed read is not written to
|
|
6340
|
+
// the shared slot, which holds full-width rows for every caller.
|
|
6341
|
+
const deniedFields = this.datasetItemDeniedFields(datasetName, itemEntity, contextUser);
|
|
6342
|
+
const columns = provider.getColumnsForDatasetItem(item, datasetName, deniedFields);
|
|
5155
6343
|
if (!columns) {
|
|
5156
6344
|
errorResults.push({
|
|
5157
6345
|
EntityID: entityID,
|
|
@@ -5168,11 +6356,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5168
6356
|
const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
|
|
5169
6357
|
uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
|
|
5170
6358
|
uncachedItems.push(item);
|
|
5171
|
-
//
|
|
5172
|
-
|
|
5173
|
-
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
|
|
5174
|
-
: '';
|
|
5175
|
-
uncachedFingerprints.push(fp);
|
|
6359
|
+
// A narrowed read (the caller is denied fields) is never written to the shared slot.
|
|
6360
|
+
uncachedFingerprints.push(deniedFields.size === 0 ? fingerprint : '');
|
|
5176
6361
|
}
|
|
5177
6362
|
// Phase 2: Execute SQL only for cache misses
|
|
5178
6363
|
let batchResults = [];
|
|
@@ -5191,6 +6376,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5191
6376
|
catch (err) {
|
|
5192
6377
|
batchError = err instanceof Error ? err.message : String(err);
|
|
5193
6378
|
LogError(`GetDatasetByName("${datasetName}"): Batch execution failed: ${batchError}`);
|
|
6379
|
+
batchError = this.datasetBatchErrorForCaller(batchError, uncachedItems, datasetName, contextUser);
|
|
5194
6380
|
}
|
|
5195
6381
|
}
|
|
5196
6382
|
// Phase 3: Process SQL results and write-through to cache
|
|
@@ -5251,7 +6437,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5251
6437
|
EntityID: entityID,
|
|
5252
6438
|
EntityName: entityName,
|
|
5253
6439
|
Code: code,
|
|
5254
|
-
Results: itemData,
|
|
6440
|
+
Results: this.projectDatasetRowsForCaller(datasetName, provider.EntityByName(entityName), itemData, contextUser),
|
|
5255
6441
|
LatestUpdateDate: latestUpdateDate,
|
|
5256
6442
|
Success: itemData !== null && itemData !== undefined,
|
|
5257
6443
|
});
|
|
@@ -5414,7 +6600,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5414
6600
|
EntityUpdateDates: [],
|
|
5415
6601
|
};
|
|
5416
6602
|
}
|
|
5417
|
-
|
|
6603
|
+
const statusResult = {
|
|
5418
6604
|
DatasetID: String(items[0]['DatasetID']),
|
|
5419
6605
|
DatasetName: datasetName,
|
|
5420
6606
|
Success: true,
|
|
@@ -5422,6 +6608,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5422
6608
|
LatestUpdateDate: overallLatestDate,
|
|
5423
6609
|
EntityUpdateDates: updateDates,
|
|
5424
6610
|
};
|
|
6611
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
6612
|
+
const now = Date.now();
|
|
6613
|
+
this._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
6614
|
+
provider._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
6615
|
+
return statusResult;
|
|
6616
|
+
}
|
|
6617
|
+
/**
|
|
6618
|
+
* Builds the lookup key for {@link _lastDatasetStatusByName} from dataset name and item filters.
|
|
6619
|
+
*/
|
|
6620
|
+
buildDatasetStatusCacheKey(datasetName, itemFilters) {
|
|
6621
|
+
return `${datasetName}::${this.ConvertItemFiltersToUniqueKey(itemFilters ?? [])}`;
|
|
5425
6622
|
}
|
|
5426
6623
|
/**************************************************************************/
|
|
5427
6624
|
// getColumnsForDatasetItem — Column Validation
|
|
@@ -5435,41 +6632,53 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5435
6632
|
* binary column can still be named explicitly. When the entity's metadata is not loaded yet —
|
|
5436
6633
|
* the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
|
|
5437
6634
|
* are converted to base64 by the caller.
|
|
6635
|
+
*
|
|
6636
|
+
* `deniedFields` (lowercased) are the columns the caller may not read. They are never
|
|
6637
|
+
* selected: a named one is dropped, and an item that names none selects every readable column.
|
|
5438
6638
|
*/
|
|
5439
|
-
getColumnsForDatasetItem(item, datasetName) {
|
|
6639
|
+
getColumnsForDatasetItem(item, datasetName, deniedFields) {
|
|
5440
6640
|
const specifiedColumns = item['Columns'] ? String(item['Columns']).split(',').map(col => col.trim()) : [];
|
|
6641
|
+
const entity = this.EntityByID(item['EntityID']);
|
|
6642
|
+
const denied = deniedFields ?? new Set();
|
|
5441
6643
|
if (specifiedColumns.length === 0) {
|
|
5442
|
-
|
|
6644
|
+
if (entity && denied.size > 0) {
|
|
6645
|
+
return this.readableDatasetColumns(entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => f.Name), entity, denied);
|
|
6646
|
+
}
|
|
5443
6647
|
if (entity?.HasBinaryFields) {
|
|
5444
6648
|
return entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => this.QuoteIdentifier(f.Name)).join(',');
|
|
5445
6649
|
}
|
|
6650
|
+
return '*';
|
|
6651
|
+
}
|
|
6652
|
+
if (!entity && this.Entities.length > 0) {
|
|
6653
|
+
LogError(`Entity not found for dataset item ${item['Code']} in dataset ${datasetName}`);
|
|
6654
|
+
return null;
|
|
5446
6655
|
}
|
|
5447
|
-
if (
|
|
5448
|
-
const
|
|
5449
|
-
if (
|
|
5450
|
-
LogError(`
|
|
6656
|
+
if (entity) {
|
|
6657
|
+
const invalidColumns = specifiedColumns.filter(col => !entity.FieldByName(col));
|
|
6658
|
+
if (invalidColumns.length > 0) {
|
|
6659
|
+
LogError(`Invalid columns specified for dataset item ${item['Code']} in dataset ${datasetName}: ${invalidColumns.join(', ')}`);
|
|
5451
6660
|
return null;
|
|
5452
6661
|
}
|
|
5453
|
-
if (entity) {
|
|
5454
|
-
const invalidColumns = [];
|
|
5455
|
-
specifiedColumns.forEach(col => {
|
|
5456
|
-
if (!entity.FieldByName(col)) {
|
|
5457
|
-
invalidColumns.push(col);
|
|
5458
|
-
}
|
|
5459
|
-
});
|
|
5460
|
-
if (invalidColumns.length > 0) {
|
|
5461
|
-
LogError(`Invalid columns specified for dataset item ${item['Code']} in dataset ${datasetName}: ${invalidColumns.join(', ')}`);
|
|
5462
|
-
return null;
|
|
5463
|
-
}
|
|
5464
|
-
}
|
|
5465
|
-
// Ensure DateFieldToCheck is included
|
|
5466
|
-
const dateField = item['DateFieldToCheck'] ? String(item['DateFieldToCheck']).trim() : '';
|
|
5467
|
-
if (dateField.length > 0 && specifiedColumns.indexOf(dateField) === -1) {
|
|
5468
|
-
if (!entity || entity.FieldByName(dateField))
|
|
5469
|
-
specifiedColumns.push(dateField);
|
|
5470
|
-
}
|
|
5471
6662
|
}
|
|
5472
|
-
|
|
6663
|
+
// Ensure DateFieldToCheck is included
|
|
6664
|
+
const dateField = item['DateFieldToCheck'] ? String(item['DateFieldToCheck']).trim() : '';
|
|
6665
|
+
if (dateField.length > 0 && specifiedColumns.indexOf(dateField) === -1) {
|
|
6666
|
+
if (!entity || entity.FieldByName(dateField))
|
|
6667
|
+
specifiedColumns.push(dateField);
|
|
6668
|
+
}
|
|
6669
|
+
if (entity && denied.size > 0) {
|
|
6670
|
+
return this.readableDatasetColumns(specifiedColumns, entity, denied);
|
|
6671
|
+
}
|
|
6672
|
+
return specifiedColumns.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
6673
|
+
}
|
|
6674
|
+
/**
|
|
6675
|
+
* `columns` without the denied ones, quoted and joined. When every one is denied, the primary
|
|
6676
|
+
* key columns are selected instead, which are never denied, so the read still has a shape.
|
|
6677
|
+
*/
|
|
6678
|
+
readableDatasetColumns(columns, entity, denied) {
|
|
6679
|
+
const readable = columns.filter(col => !denied.has(col.trim().toLowerCase()));
|
|
6680
|
+
const selected = readable.length > 0 ? readable : entity.PrimaryKeys.map(pk => pk.Name);
|
|
6681
|
+
return selected.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
5473
6682
|
}
|
|
5474
6683
|
/**************************************************************************/
|
|
5475
6684
|
// Dataset Cache Helpers
|