@memberjunction/generic-database-provider 6.2.0-edge.5 → 6.2.0-edge.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +165 -1
- package/dist/GenericDatabaseProvider.d.ts +599 -69
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +2055 -403
- 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 +44 -75
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +129 -267
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/composition/compositionAssembler.d.ts +33 -0
- package/dist/composition/compositionAssembler.d.ts.map +1 -0
- package/dist/composition/compositionAssembler.js +270 -0
- package/dist/composition/compositionAssembler.js.map +1 -0
- package/dist/composition/compositionInfo.d.ts +7 -0
- package/dist/composition/compositionInfo.d.ts.map +1 -0
- package/dist/composition/compositionInfo.js +31 -0
- package/dist/composition/compositionInfo.js.map +1 -0
- package/dist/composition/compositionLookup.d.ts +44 -0
- package/dist/composition/compositionLookup.d.ts.map +1 -0
- package/dist/composition/compositionLookup.js +122 -0
- package/dist/composition/compositionLookup.js.map +1 -0
- package/dist/composition/compositionRender.d.ts +136 -0
- package/dist/composition/compositionRender.d.ts.map +1 -0
- package/dist/composition/compositionRender.js +264 -0
- package/dist/composition/compositionRender.js.map +1 -0
- package/dist/composition/compositionTypes.d.ts +40 -0
- package/dist/composition/compositionTypes.d.ts.map +1 -0
- package/dist/composition/compositionTypes.js +2 -0
- package/dist/composition/compositionTypes.js.map +1 -0
- package/dist/composition/quotedTagRefusal.d.ts +44 -0
- package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
- package/dist/composition/quotedTagRefusal.js +132 -0
- package/dist/composition/quotedTagRefusal.js.map +1 -0
- package/dist/composition/renderSteps.d.ts +16 -0
- package/dist/composition/renderSteps.d.ts.map +1 -0
- package/dist/composition/renderSteps.js +42 -0
- package/dist/composition/renderSteps.js.map +1 -0
- package/dist/composition/safetyGate.d.ts +46 -0
- package/dist/composition/safetyGate.d.ts.map +1 -0
- package/dist/composition/safetyGate.js +61 -0
- package/dist/composition/safetyGate.js.map +1 -0
- package/dist/composition/templateUnit.d.ts +95 -0
- package/dist/composition/templateUnit.d.ts.map +1 -0
- package/dist/composition/templateUnit.js +189 -0
- package/dist/composition/templateUnit.js.map +1 -0
- package/dist/describeStatement.d.ts +51 -0
- package/dist/describeStatement.d.ts.map +1 -0
- package/dist/describeStatement.js +19 -0
- package/dist/describeStatement.js.map +1 -0
- package/dist/fieldSecurity/projectionStars.d.ts +15 -0
- package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
- package/dist/fieldSecurity/projectionStars.js +116 -0
- package/dist/fieldSecurity/projectionStars.js.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
- package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
- package/dist/index.d.ts +9 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/pagingLayout.d.ts +68 -0
- package/dist/pagingLayout.d.ts.map +1 -0
- package/dist/pagingLayout.js +190 -0
- package/dist/pagingLayout.js.map +1 -0
- package/dist/queryCompositionEngine.d.ts +22 -222
- package/dist/queryCompositionEngine.d.ts.map +1 -1
- package/dist/queryCompositionEngine.js +35 -729
- package/dist/queryCompositionEngine.js.map +1 -1
- package/dist/queryPagingEngine.d.ts +26 -5
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +51 -15
- package/dist/queryPagingEngine.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 +91 -72
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +71 -179
- package/dist/renderPipeline.js.map +1 -1
- package/dist/statementMemo.d.ts +29 -0
- package/dist/statementMemo.d.ts.map +1 -0
- package/dist/statementMemo.js +61 -0
- package/dist/statementMemo.js.map +1 -0
- 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/typedQueryParameter.d.ts +55 -0
- package/dist/typedQueryParameter.d.ts.map +1 -0
- package/dist/typedQueryParameter.js +122 -0
- package/dist/typedQueryParameter.js.map +1 -0
- package/dist/types.d.ts +47 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -15,28 +15,35 @@
|
|
|
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';
|
|
23
23
|
import { v4 as uuidv4 } from 'uuid';
|
|
24
24
|
import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
25
25
|
import { GetDialect } from '@memberjunction/sql-dialect';
|
|
26
|
-
import {
|
|
26
|
+
import { SqlDocument, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
27
|
+
import { DescribeStatementFailure } from './describeStatement.js';
|
|
28
|
+
import { NamedQueryParameter, TypedBindValue, TypedQueryParameter } from './typedQueryParameter.js';
|
|
29
|
+
import { StatementMemo } from './statementMemo.js';
|
|
30
|
+
import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
|
|
31
|
+
import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './fieldSecurity/queryColumnSecurity.js';
|
|
27
32
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
28
33
|
import { RenderPipeline } from './renderPipeline.js';
|
|
29
34
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
30
|
-
import { QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
35
|
+
import { GetQueryApprovalStateAsync, QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
31
36
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
32
37
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
33
38
|
import { QueueManager } from '@memberjunction/queue';
|
|
34
39
|
import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
|
|
35
|
-
import { BuildEntityChangeContext } from '@memberjunction/actions-base';
|
|
40
|
+
import { BuildEntityChangeContext, DurableEntityActionRegistry } from '@memberjunction/actions-base';
|
|
36
41
|
import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
37
42
|
import { TransactionAffinity } from './TransactionAffinity.js';
|
|
38
43
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
39
44
|
import { ClientClauseScreen } from './clientClauseScreen.js';
|
|
45
|
+
import { IsSystemUser } from './systemUser.js';
|
|
46
|
+
import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
|
|
40
47
|
import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
|
|
41
48
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
42
49
|
/**
|
|
@@ -71,8 +78,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
71
78
|
constructor() {
|
|
72
79
|
// Composition engine is now owned by RenderPipeline
|
|
73
80
|
super(...arguments);
|
|
81
|
+
/**
|
|
82
|
+
* Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
|
|
83
|
+
* and Dataset slots. Within this window after a slot was written or last verified against
|
|
84
|
+
* SQL, `RunViewsWithCacheCheck` and `GetDatasetByName` can trust the in-memory slot with
|
|
85
|
+
* zero DB hits. Once this window elapses, the next check performs a lightweight batched
|
|
86
|
+
* SQL status probe (`COUNT(*)` + `MAX(__mj_UpdatedAt)`) to auto-reconcile any out-of-band
|
|
87
|
+
* SQL mutations (e.g., migrations, `mj sync push`, external scripts) without requiring a
|
|
88
|
+
* server restart.
|
|
89
|
+
*/
|
|
90
|
+
this.ServerCacheVerificationTTLMs = 5000;
|
|
91
|
+
/**
|
|
92
|
+
* Most recent authoritative SQL status result per dataset key (`datasetName + filterKey`),
|
|
93
|
+
* populated by `GetDatasetStatusByName` and consumed by `GetDatasetByName` to reconcile
|
|
94
|
+
* cached dataset item slots against live SQL row counts and timestamps.
|
|
95
|
+
*/
|
|
96
|
+
this._lastDatasetStatusByName = new Map();
|
|
74
97
|
/** Per transaction-group counts so the same hash twice in one batch gets `_hash_2`. */
|
|
75
98
|
this._saveCallSuffixCounts = new WeakMap();
|
|
99
|
+
/**
|
|
100
|
+
* Connections a save's SQL is being generated for, by entity object: the transaction a
|
|
101
|
+
* transaction group runs its items on. Set only for the duration of
|
|
102
|
+
* {@link GenerateSaveSQLReadingOn}.
|
|
103
|
+
*/
|
|
104
|
+
this._snapshotConnections = new WeakMap();
|
|
105
|
+
/** Full-width delete snapshots captured by {@link Delete}, consumed by `GenerateDeleteSQL`. */
|
|
106
|
+
this._deleteSnapshots = new WeakMap();
|
|
107
|
+
this._requestFLSKeys = new WeakMap();
|
|
76
108
|
// ─── Nested transactions ─────────────────────────────────────────
|
|
77
109
|
//
|
|
78
110
|
// Depth 1 = physical BEGIN. Depth 2+ = a dialect savepoint on that same
|
|
@@ -168,6 +200,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
168
200
|
}
|
|
169
201
|
return super.Config(data, providerToUse);
|
|
170
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* Public accessor for {@link ServerCacheVerificationTTLMs}.
|
|
205
|
+
* Set to `0` to force SQL status verification on every cache check.
|
|
206
|
+
*/
|
|
207
|
+
get ServerCacheVerificationTTL() {
|
|
208
|
+
return this.ServerCacheVerificationTTLMs;
|
|
209
|
+
}
|
|
210
|
+
set ServerCacheVerificationTTL(value) {
|
|
211
|
+
this.ServerCacheVerificationTTLMs = Math.max(0, value);
|
|
212
|
+
}
|
|
171
213
|
/**************************************************************************/
|
|
172
214
|
// SQL Logging — Session Management & Statement Logging
|
|
173
215
|
/**************************************************************************/
|
|
@@ -400,7 +442,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
400
442
|
* `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
|
|
401
443
|
* save succeeds is not a durability improvement, it is a different feature.
|
|
402
444
|
*/
|
|
403
|
-
async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs) {
|
|
445
|
+
async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs, runModeFilter) {
|
|
404
446
|
const engine = EntityActionEngineServer.Instance;
|
|
405
447
|
if (engine.Loaded && engine.GetActionsByEntityName(entity.EntityInfo.Name, 'Active').length === 0) {
|
|
406
448
|
return [];
|
|
@@ -433,6 +475,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
433
475
|
const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
|
|
434
476
|
const results = [];
|
|
435
477
|
for (const a of activeActions) {
|
|
478
|
+
if (runModeFilter === 'DurableOnly' && a.RunMode !== 'Durable') {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (runModeFilter === 'NonDurableOnly' && a.RunMode === 'Durable') {
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
436
484
|
if (guarded && originatingEntityActionIDs?.some((id) => UUIDsEqual(id, a.ID))) {
|
|
437
485
|
// The caller declared this save IS this action's write-back. Used by work that
|
|
438
486
|
// detached from the async context the guard tracks — see
|
|
@@ -573,11 +621,38 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
573
621
|
}
|
|
574
622
|
}
|
|
575
623
|
}
|
|
576
|
-
|
|
624
|
+
async ShouldEnlistSaveInTransaction(entity, user, options, isNewRecord) {
|
|
625
|
+
if (options.SkipEntityActions === true || options.ReplayOnly === true) {
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
628
|
+
if (DurableEntityActionRegistry.Instance.Submitter === null) {
|
|
629
|
+
return false;
|
|
630
|
+
}
|
|
631
|
+
const engine = EntityActionEngineServer.Instance;
|
|
632
|
+
if (!engine.Loaded) {
|
|
633
|
+
await engine.Config(false, user);
|
|
634
|
+
}
|
|
635
|
+
const invocationType = isNewRecord ? 'AfterCreate' : 'AfterUpdate';
|
|
636
|
+
const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
|
|
637
|
+
const originatingSet = options.OriginatingEntityActionIDs && options.OriginatingEntityActionIDs.length > 0
|
|
638
|
+
? new UUIDSet(options.OriginatingEntityActionIDs)
|
|
639
|
+
: null;
|
|
640
|
+
return activeActions.some((a) => a.RunMode === 'Durable' && !originatingSet?.Has(a.ID));
|
|
641
|
+
}
|
|
642
|
+
async OnDurableAfterSaveExecute(entity, user, options, context) {
|
|
643
|
+
if (options.SkipEntityActions === true) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
context.State['durableActionsEnlistedInTx'] = true;
|
|
647
|
+
await this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, 'DurableOnly');
|
|
648
|
+
}
|
|
649
|
+
OnAfterSaveExecute(entity, user, options, context) {
|
|
577
650
|
if (options.SkipEntityAIActions !== true)
|
|
578
651
|
this.HandleEntityAIActions(entity, 'save', false, user); // NO AWAIT INTENTIONALLY
|
|
579
|
-
if (options.SkipEntityActions !== true)
|
|
580
|
-
|
|
652
|
+
if (options.SkipEntityActions !== true) {
|
|
653
|
+
const filter = context.State['durableActionsEnlistedInTx'] === true ? 'NonDurableOnly' : undefined;
|
|
654
|
+
this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, filter); // NO AWAIT INTENTIONALLY
|
|
655
|
+
}
|
|
581
656
|
}
|
|
582
657
|
async OnSaveCompleted(entity, saveSQLResult, user, options, context) {
|
|
583
658
|
const superPatches = await super.OnSaveCompleted(entity, saveSQLResult, user, options, context);
|
|
@@ -671,6 +746,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
671
746
|
/**************************************************************************/
|
|
672
747
|
// PostProcessRows — Datetime Adjustment + Encryption Decryption
|
|
673
748
|
/**************************************************************************/
|
|
749
|
+
/**
|
|
750
|
+
* Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
|
|
751
|
+
* preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
|
|
752
|
+
* Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
|
|
753
|
+
*/
|
|
754
|
+
static { this._preDecryptionRowsByResult = new WeakMap(); }
|
|
674
755
|
/**
|
|
675
756
|
* Post-processes rows: first applies platform-specific datetime adjustments
|
|
676
757
|
* via the virtual `AdjustDatetimeFields` hook, then handles field-level
|
|
@@ -679,7 +760,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
679
760
|
* Subclasses should NOT override this method. Instead, override
|
|
680
761
|
* `AdjustDatetimeFields` for platform-specific datetime corrections.
|
|
681
762
|
*/
|
|
682
|
-
async PostProcessRows(rows, entityInfo, user) {
|
|
763
|
+
async PostProcessRows(rows, entityInfo, user, options) {
|
|
683
764
|
if (!rows || rows.length === 0)
|
|
684
765
|
return rows;
|
|
685
766
|
// Step 0: binary columns → base64. Drivers return varbinary/bytea as byte arrays (Node
|
|
@@ -701,11 +782,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
701
782
|
const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
|
|
702
783
|
if (encryptedFields.length === 0)
|
|
703
784
|
return processedRows;
|
|
785
|
+
// Preserve ciphertext-bearing normalized rows for cache storage BEFORE decrypting any fields.
|
|
786
|
+
const ciphertextRowsForCache = processedRows.map(r => ({ ...r }));
|
|
787
|
+
const decryptedRows = await this.decryptRowsForConsumer(processedRows, entityInfo, encryptedFields, user, Boolean(options?.preserveRestrictedApiCiphertext));
|
|
788
|
+
GenericDatabaseProvider._preDecryptionRowsByResult.set(decryptedRows, ciphertextRowsForCache);
|
|
789
|
+
return decryptedRows;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
|
|
793
|
+
* When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
|
|
794
|
+
* remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
|
|
795
|
+
* needlessly decrypt values destined for sentinel redaction.
|
|
796
|
+
*/
|
|
797
|
+
async decryptRowsForConsumer(rows, entityInfo, encryptedFields, user, preserveRestrictedApiCiphertext) {
|
|
798
|
+
if (!rows || rows.length === 0 || encryptedFields.length === 0) {
|
|
799
|
+
return rows;
|
|
800
|
+
}
|
|
801
|
+
const fieldsToDecrypt = preserveRestrictedApiCiphertext
|
|
802
|
+
? encryptedFields.filter(f => f.AllowDecryptInAPI)
|
|
803
|
+
: encryptedFields;
|
|
804
|
+
if (fieldsToDecrypt.length === 0) {
|
|
805
|
+
return rows.map(r => ({ ...r }));
|
|
806
|
+
}
|
|
704
807
|
const encryptionEngine = EncryptionEngine.Instance;
|
|
705
808
|
await encryptionEngine.Config(false, user);
|
|
706
|
-
return Promise.all(
|
|
809
|
+
return Promise.all(rows.map(async (row) => {
|
|
707
810
|
const processedRow = { ...row };
|
|
708
|
-
for (const field of
|
|
811
|
+
for (const field of fieldsToDecrypt) {
|
|
709
812
|
const fieldValue = processedRow[field.Name];
|
|
710
813
|
if (fieldValue === null || fieldValue === undefined || fieldValue === '')
|
|
711
814
|
continue;
|
|
@@ -731,6 +834,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
731
834
|
return processedRow;
|
|
732
835
|
}));
|
|
733
836
|
}
|
|
837
|
+
PrepareRowsForCacheStorage(rows, entityInfo) {
|
|
838
|
+
if (!rows || rows.length === 0)
|
|
839
|
+
return rows;
|
|
840
|
+
const preDecrypted = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
|
|
841
|
+
if (preDecrypted) {
|
|
842
|
+
return preDecrypted;
|
|
843
|
+
}
|
|
844
|
+
if (entityInfo && GenericDatabaseProvider.getEncryptedFields(entityInfo).length > 0) {
|
|
845
|
+
// Rows passed directly without PostProcessRows: returned as-is (LocalCacheManager's
|
|
846
|
+
// server write gate rejects any row carrying plaintext on an encrypted column).
|
|
847
|
+
return rows;
|
|
848
|
+
}
|
|
849
|
+
return rows;
|
|
850
|
+
}
|
|
851
|
+
async MaterializeCachedRowsForCaller(rows, entityInfo, contextUser, preserveRestrictedApiCiphertext) {
|
|
852
|
+
if (!rows || rows.length === 0 || !entityInfo) {
|
|
853
|
+
return rows;
|
|
854
|
+
}
|
|
855
|
+
const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
|
|
856
|
+
if (encryptedFields.length === 0) {
|
|
857
|
+
return rows;
|
|
858
|
+
}
|
|
859
|
+
return this.decryptRowsForConsumer(rows, entityInfo, encryptedFields, contextUser ?? this.CurrentUser, Boolean(preserveRestrictedApiCiphertext));
|
|
860
|
+
}
|
|
734
861
|
static { this._encryptedFieldsCache = new WeakMap(); }
|
|
735
862
|
static getEncryptedFields(entityInfo) {
|
|
736
863
|
let entry = GenericDatabaseProvider._encryptedFieldsCache.get(entityInfo);
|
|
@@ -1250,8 +1377,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1250
1377
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
1251
1378
|
// audit row for ITS writes only — the entity keeps TrackRecordChanges for everyone else.
|
|
1252
1379
|
if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
|
|
1253
|
-
const newData =
|
|
1254
|
-
const oldData = isUpdate ? entity.GetAll(true) : null;
|
|
1380
|
+
const { NewData: newData, OldData: oldData } = await this.BuildRecordChangeSnapshots(entity, isUpdate, user);
|
|
1255
1381
|
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
|
|
1256
1382
|
if (payload) {
|
|
1257
1383
|
// ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
|
|
@@ -1286,6 +1412,127 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1286
1412
|
}
|
|
1287
1413
|
return result;
|
|
1288
1414
|
}
|
|
1415
|
+
/**
|
|
1416
|
+
* The old and new snapshots a save's Record Change is built from. The audit trail stores
|
|
1417
|
+
* whole payloads and projects them per reader, so both snapshots describe the whole record
|
|
1418
|
+
* whoever saves it.
|
|
1419
|
+
*
|
|
1420
|
+
* - **A user denied nothing** (unrestricted and system-user saves): the object's own values.
|
|
1421
|
+
* No query, even when the object was loaded without some columns.
|
|
1422
|
+
* - **A restricted user's update** (their object never holds the fields they cannot read):
|
|
1423
|
+
* the stored values of those fields are read once and the snapshots are widened with them.
|
|
1424
|
+
* The diff is unchanged, because a field the object never held has the same stored value
|
|
1425
|
+
* on both sides.
|
|
1426
|
+
* - **Create**: there is no stored row yet. A field the INSERT omits because the user may
|
|
1427
|
+
* not supply it is left out rather than recorded with a value the record never got.
|
|
1428
|
+
*
|
|
1429
|
+
* The read runs on the save's connection: inside an open transaction it reads that
|
|
1430
|
+
* transaction's state. A save queued in a transaction group is generated when `Save()` is
|
|
1431
|
+
* called, so its snapshot reflects the row as of then — the same moment the object's own
|
|
1432
|
+
* old values describe.
|
|
1433
|
+
*/
|
|
1434
|
+
async BuildRecordChangeSnapshots(entity, isUpdate, user) {
|
|
1435
|
+
if (!isUpdate) {
|
|
1436
|
+
return CreateSnapshots(entity);
|
|
1437
|
+
}
|
|
1438
|
+
const narrow = { NewData: entity.GetAll(false), OldData: entity.GetAll(true) };
|
|
1439
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1440
|
+
if (lacking.size === 0) {
|
|
1441
|
+
return narrow;
|
|
1442
|
+
}
|
|
1443
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1444
|
+
return storedRow ? WidenUpdateSnapshots(entity, narrow, storedRow, lacking) : narrow;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Generates a save's SQL with any stored-row read its Record Change snapshot needs run on
|
|
1448
|
+
* `connectionSource`. A transaction group that regenerates an item's SQL while its own
|
|
1449
|
+
* transaction is open passes that transaction, so the read sees the group's earlier writes and
|
|
1450
|
+
* never waits on the locks the group itself holds.
|
|
1451
|
+
*/
|
|
1452
|
+
async GenerateSaveSQLReadingOn(entity, isNew, user, connectionSource) {
|
|
1453
|
+
if (!connectionSource) {
|
|
1454
|
+
return this.GenerateSaveSQL(entity, isNew, user);
|
|
1455
|
+
}
|
|
1456
|
+
this._snapshotConnections.set(entity, connectionSource);
|
|
1457
|
+
try {
|
|
1458
|
+
return await this.GenerateSaveSQL(entity, isNew, user);
|
|
1459
|
+
}
|
|
1460
|
+
finally {
|
|
1461
|
+
this._snapshotConnections.delete(entity);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* Deletes a record. Before the shared orchestration runs, a restricted user's delete reads the
|
|
1466
|
+
* stored values of the fields their object never held, so the delete's `FullRecordJSON` — the
|
|
1467
|
+
* snapshot a deleted record is restored from — is full width. `GenerateDeleteSQL` is
|
|
1468
|
+
* synchronous, so the snapshot is captured here and handed to it through
|
|
1469
|
+
* {@link RecordChangeDeleteSnapshot}. A user denied nothing costs no extra query.
|
|
1470
|
+
*/
|
|
1471
|
+
async Delete(entity, options, user) {
|
|
1472
|
+
const captured = await this.captureDeleteSnapshot(entity, options, user);
|
|
1473
|
+
try {
|
|
1474
|
+
return await super.Delete(entity, options, user);
|
|
1475
|
+
}
|
|
1476
|
+
finally {
|
|
1477
|
+
if (captured)
|
|
1478
|
+
this._deleteSnapshots.delete(entity);
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
/** Reads and stores the full-width delete snapshot when one is needed; true when it stored one. */
|
|
1482
|
+
async captureDeleteSnapshot(entity, options, user) {
|
|
1483
|
+
if (!this.ShouldTrackRecordChanges(entity.EntityInfo) || options?.SkipRecordChanges === true || options?.ReplayOnly === true) {
|
|
1484
|
+
return false;
|
|
1485
|
+
}
|
|
1486
|
+
if (!entity.IsSaved || entity.EntityInfo.ExternalDataSourceID) {
|
|
1487
|
+
return false; // the orchestration refuses these; nothing to snapshot
|
|
1488
|
+
}
|
|
1489
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1490
|
+
if (lacking.size === 0) {
|
|
1491
|
+
return false;
|
|
1492
|
+
}
|
|
1493
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1494
|
+
if (!storedRow) {
|
|
1495
|
+
return false;
|
|
1496
|
+
}
|
|
1497
|
+
this._deleteSnapshots.set(entity, WidenDeleteSnapshot(entity, entity.GetAll(true), storedRow, lacking));
|
|
1498
|
+
return true;
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* The record snapshot a delete's Record Change carries: the full-width snapshot {@link Delete}
|
|
1502
|
+
* captured, else `narrow` (the object's own values, which are already full width whenever no
|
|
1503
|
+
* snapshot was needed).
|
|
1504
|
+
*/
|
|
1505
|
+
RecordChangeDeleteSnapshot(entity, narrow) {
|
|
1506
|
+
// Optional chaining: a provider built without running its constructor (a test host made
|
|
1507
|
+
// with Object.create) has no snapshot map, and then there is nothing captured.
|
|
1508
|
+
return this._deleteSnapshots?.get(entity) ?? narrow;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Reads the stored values of `columns` — the fields a snapshot lacks — for a Record Change
|
|
1512
|
+
* snapshot. Provider-internal: no row-level filter and no field-security check, because the
|
|
1513
|
+
* payload is stored unprojected and projected for each reader. The row gets the same
|
|
1514
|
+
* post-processing as a `Load` (binary to base64, datetime adjustment, decryption,
|
|
1515
|
+
* fixed-width trimming). Runs on the connection the save is generated for when one was named
|
|
1516
|
+
* ({@link GenerateSaveSQLReadingOn}), else on the save's usual connection. Kept out of the SQL
|
|
1517
|
+
* log, which records the save itself.
|
|
1518
|
+
*/
|
|
1519
|
+
async ReadStoredRowForRecordChange(entity, user, columns) {
|
|
1520
|
+
const entityInfo = entity.EntityInfo;
|
|
1521
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, entity.PrimaryKey);
|
|
1522
|
+
const selectList = [...columns].map(name => this.QuoteIdentifier(name)).join(', ');
|
|
1523
|
+
const sql = `SELECT ${selectList} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${where}`;
|
|
1524
|
+
const options = {
|
|
1525
|
+
description: `Record Change snapshot of ${entityInfo.Name}`,
|
|
1526
|
+
ignoreLogging: true,
|
|
1527
|
+
connectionSource: this._snapshotConnections?.get(entity),
|
|
1528
|
+
};
|
|
1529
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, options, user);
|
|
1530
|
+
const rows = await this.PostProcessRows(rawRows, entityInfo, user);
|
|
1531
|
+
if (!rows || rows.length === 0) {
|
|
1532
|
+
return null;
|
|
1533
|
+
}
|
|
1534
|
+
return this.TrimFixedWidthValues(entityInfo, rows[0]);
|
|
1535
|
+
}
|
|
1289
1536
|
/**
|
|
1290
1537
|
* Builds a platform-specific TOP/LIMIT clause for non-paginated row limits.
|
|
1291
1538
|
* SQL Server: `TOP N`; PostgreSQL returns empty (uses LIMIT via BuildPaginationSQL).
|
|
@@ -1326,30 +1573,39 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1326
1573
|
* `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
|
|
1327
1574
|
* Server — both preserve case.
|
|
1328
1575
|
*/
|
|
1329
|
-
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride) {
|
|
1576
|
+
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride, schemaNameOverride) {
|
|
1330
1577
|
const rowsAreLimited = usingPagination || maxRowsForQuery > 0;
|
|
1331
1578
|
if (!rowsAreLimited)
|
|
1332
1579
|
return null;
|
|
1333
|
-
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1580
|
+
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1334
1581
|
}
|
|
1335
1582
|
/**
|
|
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.
|
|
1583
|
+
* Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
|
|
1584
|
+
* optional loaded `MJUserViewEntityExtended`. An explicit empty string (`""`) on
|
|
1585
|
+
* `params.AlternateBaseView` overrides any saved view pin back to `BaseView` (`undefined`).
|
|
1586
|
+
*/
|
|
1587
|
+
resolveEffectiveAbvNameFromParams(params, viewEntity) {
|
|
1588
|
+
return GetEffectiveAlternateBaseViewName(params, viewEntity);
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* Resolves the view a RunView reads from: an explicit or pinned `AlternateBaseView` when present,
|
|
1592
|
+
* the entity's materialized wrapper view when `DataSource: 'Materialized'`, or the entity's live
|
|
1593
|
+
* `BaseView` by default.
|
|
1351
1594
|
*/
|
|
1352
|
-
GetEffectiveBaseView(entityInfo, params) {
|
|
1595
|
+
GetEffectiveBaseView(entityInfo, params, viewEntity, suppressDeprecationWarning = false) {
|
|
1596
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1597
|
+
if (effectiveAbvName) {
|
|
1598
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1599
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1600
|
+
}
|
|
1601
|
+
const resolution = ResolveAlternateBaseView({
|
|
1602
|
+
entity: entityInfo,
|
|
1603
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1604
|
+
suppressDeprecationWarning,
|
|
1605
|
+
callerName: 'GetEffectiveBaseView',
|
|
1606
|
+
});
|
|
1607
|
+
return resolution.effectiveViewName;
|
|
1608
|
+
}
|
|
1353
1609
|
// Case-INSENSITIVE prefix test (matches the sibling guard in providerBase.IsServerCacheAllowedForEntity):
|
|
1354
1610
|
// a BaseView returned with non-lowercase casing (e.g. 'Materialized_vwFoo' from a case-insensitive SQL
|
|
1355
1611
|
// Server, or a hand-authored entity) is still an already-materialized view — a case-sensitive check
|
|
@@ -1361,18 +1617,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1361
1617
|
}
|
|
1362
1618
|
/**
|
|
1363
1619
|
* 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) {
|
|
1620
|
+
*/
|
|
1621
|
+
async resolveEffectiveBaseView(entityInfo, params, contextUser, viewEntity) {
|
|
1622
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1623
|
+
if (effectiveAbvName) {
|
|
1624
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1625
|
+
}
|
|
1374
1626
|
if (!IsMaterializedDataSource(params.DataSource) || entityInfo.BaseView?.toLowerCase().startsWith('materialized_vw')) {
|
|
1375
|
-
return this.GetEffectiveBaseView(entityInfo, params);
|
|
1627
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1376
1628
|
}
|
|
1377
1629
|
const rv = new RunView(this);
|
|
1378
1630
|
const res = await rv.RunView({
|
|
@@ -1381,6 +1633,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1381
1633
|
Fields: ['Status', 'ViewName'],
|
|
1382
1634
|
ResultType: 'simple',
|
|
1383
1635
|
MaxRows: 1,
|
|
1636
|
+
SkipTotalRowCount: true,
|
|
1384
1637
|
BypassCache: true,
|
|
1385
1638
|
}, contextUser);
|
|
1386
1639
|
// A FAILED lookup must not masquerade as "no materialization exists" — see MaterializationLookupFailed
|
|
@@ -1400,6 +1653,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1400
1653
|
// base-view materialization always mints into the source entity's own schema.)
|
|
1401
1654
|
return row.ViewName?.trim() || `materialized_vw${entityInfo.CodeName}`;
|
|
1402
1655
|
}
|
|
1656
|
+
/**
|
|
1657
|
+
* Resolves both the effective `{ schemaName, viewName }` for a RunView call, honoring:
|
|
1658
|
+
* 1. Explicit `params.AlternateBaseView` (including `""` to force `BaseView` over a saved view pin)
|
|
1659
|
+
* 2. Saved `UserView.DisplayState.alternateBaseView` (from `viewEntity`, `params.ViewEntity`, or loaded by `ViewID`/`ViewName`)
|
|
1660
|
+
* 3. `DataSource: 'Materialized'`
|
|
1661
|
+
* 4. `entityInfo.BaseView`
|
|
1662
|
+
*/
|
|
1663
|
+
async resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity) {
|
|
1664
|
+
let resolvedViewEntity = viewEntity ?? params?.ViewEntity ?? null;
|
|
1665
|
+
if (!resolvedViewEntity && typeof params?.AlternateBaseView !== 'string') {
|
|
1666
|
+
try {
|
|
1667
|
+
if (params?.ViewID && params.ViewID.length > 0) {
|
|
1668
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntity(params.ViewID, contextUser)) ?? null;
|
|
1669
|
+
}
|
|
1670
|
+
else if (params?.ViewName && params.ViewName.length > 0) {
|
|
1671
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntityByName(params.ViewName, contextUser)) ?? null;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
catch (e) {
|
|
1675
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1676
|
+
LogError(`GenericDatabaseProvider.resolveEffectiveBaseViewTarget: failed to load User View (${params?.ViewID || params?.ViewName}) on entity "${entityInfo.Name}": ${msg}`);
|
|
1677
|
+
throw e;
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, resolvedViewEntity);
|
|
1681
|
+
if (effectiveAbvName) {
|
|
1682
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1683
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1684
|
+
}
|
|
1685
|
+
const resolution = ResolveAlternateBaseView({
|
|
1686
|
+
entity: entityInfo,
|
|
1687
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1688
|
+
contextUser,
|
|
1689
|
+
callerName: 'resolveEffectiveBaseViewTarget',
|
|
1690
|
+
});
|
|
1691
|
+
return { schemaName: resolution.effectiveSchemaName, viewName: resolution.effectiveViewName };
|
|
1692
|
+
}
|
|
1693
|
+
const viewName = await this.resolveEffectiveBaseView(entityInfo, params, contextUser, resolvedViewEntity);
|
|
1694
|
+
return { schemaName: entityInfo.SchemaName, viewName };
|
|
1695
|
+
}
|
|
1403
1696
|
/**
|
|
1404
1697
|
* Reports whether a materialization-metadata `RunView` FAILED, logging the failure when it did.
|
|
1405
1698
|
*
|
|
@@ -1614,9 +1907,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1614
1907
|
* SQL Server overrides to use spCreateUserViewRunWithDetail.
|
|
1615
1908
|
* Default: returns null (no view run logging).
|
|
1616
1909
|
*/
|
|
1617
|
-
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user) {
|
|
1910
|
+
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride) {
|
|
1618
1911
|
return null;
|
|
1619
1912
|
}
|
|
1913
|
+
/**
|
|
1914
|
+
* Maximum number of concurrent database view executions allowed within a single
|
|
1915
|
+
* {@link InternalRunViews} batch. Prevents large `RunViews` batches from exhausting
|
|
1916
|
+
* the connection pool in a single tick. Set to 0 or Infinity to disable the cap.
|
|
1917
|
+
* Default: 8.
|
|
1918
|
+
*/
|
|
1919
|
+
static { this.MaxConcurrentViewsPerBatch = 8; }
|
|
1920
|
+
/**
|
|
1921
|
+
* Process-wide single-flight coalescing registry for in-flight read-only RunView executions.
|
|
1922
|
+
* When multiple concurrent requests (across any per-request provider instance on the same
|
|
1923
|
+
* server process) execute an identical non-transactional RunView simultaneously, only the
|
|
1924
|
+
* first caller queries the database; joiners await the same promise and receive a shallow-cloned
|
|
1925
|
+
* result object and Results array.
|
|
1926
|
+
*/
|
|
1927
|
+
static { this._inFlightRunViews = new Map(); }
|
|
1928
|
+
/**
|
|
1929
|
+
* Number of currently in-flight coalesced RunView executions across this process.
|
|
1930
|
+
*/
|
|
1931
|
+
static get InFlightRunViewCount() {
|
|
1932
|
+
return GenericDatabaseProvider._inFlightRunViews.size;
|
|
1933
|
+
}
|
|
1620
1934
|
/**
|
|
1621
1935
|
* Shared InternalRunView implementation.
|
|
1622
1936
|
* Handles: view resolution, permissions, field selection, WHERE clause building
|
|
@@ -1626,6 +1940,117 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1626
1940
|
async InternalRunView(params, contextUser) {
|
|
1627
1941
|
return this.RunViewCore(params, contextUser);
|
|
1628
1942
|
}
|
|
1943
|
+
/**
|
|
1944
|
+
* Determines whether a RunView invocation is eligible for process-wide single-flight
|
|
1945
|
+
* coalescing across concurrent requests.
|
|
1946
|
+
*/
|
|
1947
|
+
canCoalesceRunViewInFlight(params, countExecutor) {
|
|
1948
|
+
if (!params || countExecutor) {
|
|
1949
|
+
return false;
|
|
1950
|
+
}
|
|
1951
|
+
if (params.ResultType && params.ResultType !== 'simple' && params.ResultType !== 'count_only') {
|
|
1952
|
+
return false;
|
|
1953
|
+
}
|
|
1954
|
+
if (params.SaveViewResults || params.ForceAuditLog) {
|
|
1955
|
+
return false;
|
|
1956
|
+
}
|
|
1957
|
+
if (this.IsCallerInAmbientTransaction() || this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction) {
|
|
1958
|
+
return false;
|
|
1959
|
+
}
|
|
1960
|
+
return true;
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* Builds the deterministic single-flight key for an in-flight RunView execution.
|
|
1964
|
+
* Includes connection string, entity/view identity, filter, orderBy, fields, resultType,
|
|
1965
|
+
* pagination/keyset cursor, aggregates, and effective user role/row-filter security context.
|
|
1966
|
+
*/
|
|
1967
|
+
buildSingleFlightRunViewKey(params, contextUser) {
|
|
1968
|
+
try {
|
|
1969
|
+
const user = contextUser ?? this.CurrentUser;
|
|
1970
|
+
if (!user) {
|
|
1971
|
+
return null;
|
|
1972
|
+
}
|
|
1973
|
+
const entityInfo = params.EntityName ? this.EntityByName(params.EntityName) : undefined;
|
|
1974
|
+
if (entityInfo?.AuditViewRuns && (params.ViewID || params.ViewName || params.ViewEntity)) {
|
|
1975
|
+
return null;
|
|
1976
|
+
}
|
|
1977
|
+
const baseFingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString);
|
|
1978
|
+
const fieldsKey = params.Fields && params.Fields.length > 0
|
|
1979
|
+
? [...params.Fields].map(f => f.trim().toLowerCase()).sort().join(',')
|
|
1980
|
+
: '*';
|
|
1981
|
+
const rlsClause = entityInfo && typeof entityInfo.GetEffectiveRowFilterWhereClause === 'function'
|
|
1982
|
+
? entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '')
|
|
1983
|
+
: `user:${user.ID ?? ''}`;
|
|
1984
|
+
const roleKey = user.UserRoles && user.UserRoles.length > 0
|
|
1985
|
+
? user.UserRoles.map(r => (r.RoleID ?? '').trim().toLowerCase()).sort().join(',')
|
|
1986
|
+
: `user:${user.ID ?? ''}`;
|
|
1987
|
+
const aggregatesKey = params.Aggregates && params.Aggregates.length > 0
|
|
1988
|
+
? JSON.stringify(params.Aggregates)
|
|
1989
|
+
: '';
|
|
1990
|
+
const afterKey = params.AfterKey ? params.AfterKey.ToConcatenatedString() : '';
|
|
1991
|
+
const ve = params.ViewEntity;
|
|
1992
|
+
const viewEntityKey = ve
|
|
1993
|
+
? `${ve.ID ?? ''}:${ve.WhereClause ?? ''}:${ve.SmartFilterWhereClause ?? ''}:${ve.AlternateBaseView ?? ''}`
|
|
1994
|
+
: '';
|
|
1995
|
+
const abvKey = IsExplicitBaseViewOverride(params)
|
|
1996
|
+
? '__base_override__'
|
|
1997
|
+
: (NormalizeAlternateBaseViewName(GetEffectiveAlternateBaseViewName(params)) ?? '');
|
|
1998
|
+
return [
|
|
1999
|
+
baseFingerprint,
|
|
2000
|
+
`f:${fieldsKey}`,
|
|
2001
|
+
`rt:${params.ResultType || 'simple'}`,
|
|
2002
|
+
`uss:${params.UserSearchString ?? ''}`,
|
|
2003
|
+
`vid:${params.ViewID ?? ''}`,
|
|
2004
|
+
`vn:${params.ViewName ?? ''}`,
|
|
2005
|
+
`ve:${viewEntityKey}`,
|
|
2006
|
+
`exRun:${params.ExcludeUserViewRunID ?? ''}`,
|
|
2007
|
+
`exAll:${params.ExcludeDataFromAllPriorViewRuns ? '1' : '0'}`,
|
|
2008
|
+
`ovEx:${params.OverrideExcludeFilter ?? ''}`,
|
|
2009
|
+
`igMax:${params.IgnoreMaxRows ? '1' : '0'}`,
|
|
2010
|
+
`max:${params.MaxRows ?? ''}`,
|
|
2011
|
+
`start:${params.StartRow ?? ''}`,
|
|
2012
|
+
`after:${afterKey}`,
|
|
2013
|
+
`ds:${params.DataSource ?? ''}`,
|
|
2014
|
+
`abv:${abvKey}`,
|
|
2015
|
+
`agg:${aggregatesKey}`,
|
|
2016
|
+
`roles:${roleKey}`,
|
|
2017
|
+
`rls:${rlsClause}`,
|
|
2018
|
+
].join('|');
|
|
2019
|
+
}
|
|
2020
|
+
catch {
|
|
2021
|
+
return null;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Shallow-clones a shared single-flight RunViewResult and its row objects so concurrent
|
|
2026
|
+
* callers cannot mutate each other's result arrays or row properties in place.
|
|
2027
|
+
*/
|
|
2028
|
+
cloneSingleFlightRunViewResult(result) {
|
|
2029
|
+
if (!result) {
|
|
2030
|
+
return result;
|
|
2031
|
+
}
|
|
2032
|
+
return {
|
|
2033
|
+
...result,
|
|
2034
|
+
Results: Array.isArray(result.Results)
|
|
2035
|
+
? result.Results.map(row => (row && typeof row === 'object' ? { ...row } : row))
|
|
2036
|
+
: [],
|
|
2037
|
+
AggregateResults: result.AggregateResults
|
|
2038
|
+
? result.AggregateResults.map(a => ({ ...a }))
|
|
2039
|
+
: undefined,
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Returns true when an identical read-only RunView is already in flight in the process-wide
|
|
2044
|
+
* single-flight registry. Used by {@link InternalRunViews} so duplicate views in a batch can
|
|
2045
|
+
* join an active query immediately without consuming a concurrency slot.
|
|
2046
|
+
*/
|
|
2047
|
+
hasInFlightSingleFlightView(params, contextUser) {
|
|
2048
|
+
if (!this.canCoalesceRunViewInFlight(params)) {
|
|
2049
|
+
return false;
|
|
2050
|
+
}
|
|
2051
|
+
const key = this.buildSingleFlightRunViewKey(params, contextUser);
|
|
2052
|
+
return !!key && GenericDatabaseProvider._inFlightRunViews.has(key);
|
|
2053
|
+
}
|
|
1629
2054
|
/**
|
|
1630
2055
|
* The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
|
|
1631
2056
|
* direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
|
|
@@ -1633,10 +2058,43 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1633
2058
|
* Everything before that step — permissions, RLS, filter screening — is unchanged.
|
|
1634
2059
|
*/
|
|
1635
2060
|
async RunViewCore(params, contextUser, countExecutor) {
|
|
2061
|
+
const singleFlightKey = this.canCoalesceRunViewInFlight(params, countExecutor)
|
|
2062
|
+
? this.buildSingleFlightRunViewKey(params, contextUser)
|
|
2063
|
+
: null;
|
|
2064
|
+
if (singleFlightKey) {
|
|
2065
|
+
const existing = GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey);
|
|
2066
|
+
if (existing) {
|
|
2067
|
+
existing.hasJoiners = true;
|
|
2068
|
+
const shared = await existing.promise;
|
|
2069
|
+
return this.cloneSingleFlightRunViewResult(shared);
|
|
2070
|
+
}
|
|
2071
|
+
const entry = {
|
|
2072
|
+
promise: null,
|
|
2073
|
+
hasJoiners: false,
|
|
2074
|
+
};
|
|
2075
|
+
const executionPromise = this.executeRunViewCore(params, contextUser, countExecutor)
|
|
2076
|
+
.finally(() => {
|
|
2077
|
+
if (GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey) === entry) {
|
|
2078
|
+
GenericDatabaseProvider._inFlightRunViews.delete(singleFlightKey);
|
|
2079
|
+
}
|
|
2080
|
+
});
|
|
2081
|
+
entry.promise = executionPromise;
|
|
2082
|
+
GenericDatabaseProvider._inFlightRunViews.set(singleFlightKey, entry);
|
|
2083
|
+
const result = await executionPromise;
|
|
2084
|
+
return entry.hasJoiners
|
|
2085
|
+
? this.cloneSingleFlightRunViewResult(result)
|
|
2086
|
+
: result;
|
|
2087
|
+
}
|
|
2088
|
+
return this.executeRunViewCore(params, contextUser, countExecutor);
|
|
2089
|
+
}
|
|
2090
|
+
async executeRunViewCore(params, contextUser, countExecutor) {
|
|
1636
2091
|
if (params?.Aggregates?.length) {
|
|
1637
2092
|
LogStatus(`[GenericDatabaseProvider] InternalRunView received aggregates: entityName=${params.EntityName}, viewID=${params.ViewID}, viewName=${params.ViewName}, aggregateCount=${params.Aggregates.length}`);
|
|
1638
2093
|
}
|
|
1639
2094
|
const startTime = new Date();
|
|
2095
|
+
// The entity the view reads, once resolved — the catch below needs it to tell a restricted
|
|
2096
|
+
// caller's "no such column" apart from any other failure.
|
|
2097
|
+
let resolvedEntity = null;
|
|
1640
2098
|
try {
|
|
1641
2099
|
if (!params)
|
|
1642
2100
|
return null;
|
|
@@ -1646,12 +2104,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1646
2104
|
// ── View / Entity resolution ──
|
|
1647
2105
|
let viewEntity = null;
|
|
1648
2106
|
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;
|
|
2107
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
1655
2108
|
if (!viewEntity) {
|
|
1656
2109
|
if (!params.EntityName || params.EntityName.length === 0)
|
|
1657
2110
|
throw new Error('EntityName is required when ViewID or ViewName is not provided');
|
|
@@ -1665,6 +2118,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1665
2118
|
throw new Error(`Entity ID: ${viewEntity.EntityID} not found in metadata`);
|
|
1666
2119
|
}
|
|
1667
2120
|
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2121
|
+
resolvedEntity = entityInfo;
|
|
2122
|
+
// A stored view's properties: refused here (Success:false, naming the property) before any SQL runs.
|
|
2123
|
+
const propertyFilter = this.BuildViewPropertyFilter(viewEntity, entityInfo, params, user);
|
|
1668
2124
|
// ── External data source dispatch ──
|
|
1669
2125
|
// Entities backed by an external data source are proxied live through a
|
|
1670
2126
|
// driver and have no view/sproc in the MJ DB, so delegate before any SQL
|
|
@@ -1675,11 +2131,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1675
2131
|
this.assertExternalReadAllowedUnderRLS(entityInfo, user);
|
|
1676
2132
|
// Refuse params we can't honor remotely rather than silently dropping them — most
|
|
1677
2133
|
// importantly AfterKey, which would otherwise return the same page on every call.
|
|
1678
|
-
this.assertExternalRunViewParamsSupported(params, entityInfo.Name);
|
|
2134
|
+
this.assertExternalRunViewParamsSupported(params, entityInfo.Name, viewEntity);
|
|
2135
|
+
if (propertyFilter) {
|
|
2136
|
+
throw new Error(`View properties are not supported for external-data-source entity '${entityInfo.Name}'.`);
|
|
2137
|
+
}
|
|
1679
2138
|
// A saved view's stored WhereClause/OrderBy live on viewEntity, not params, and the
|
|
1680
2139
|
// normal SQL path that applies them runs below this early return — so fold them in
|
|
1681
2140
|
// here, else a UserView over an external entity silently returns unfiltered rows.
|
|
1682
2141
|
const externalParams = await this.mergeExternalViewParams(params, viewEntity, user);
|
|
2142
|
+
this.assertExternalClausesRespectFieldSecurity(entityInfo, externalParams, user);
|
|
1683
2143
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Entity '${entityInfo.Name}'`);
|
|
1684
2144
|
const externalResult = await externalRouter.RunViewExternal(entityInfo, externalParams, user, this);
|
|
1685
2145
|
// Apply the same row post-processing MJ-DB reads get (field decryption + datetime
|
|
@@ -1688,7 +2148,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1688
2148
|
// Generic-erasure boundary: PostProcessRows operates on Record<string,unknown>[]
|
|
1689
2149
|
// but Results is typed T[]; the double-cast bridges that erasure (not a lazy `any`).
|
|
1690
2150
|
const rows = externalResult.Results;
|
|
1691
|
-
|
|
2151
|
+
const processed = (await this.PostProcessRows(rows, entityInfo, user, {
|
|
2152
|
+
preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
|
|
2153
|
+
}));
|
|
2154
|
+
externalResult.Results = this.projectExternalRowsForCaller(processed, entityInfo, externalParams, user);
|
|
1692
2155
|
}
|
|
1693
2156
|
return externalResult;
|
|
1694
2157
|
}
|
|
@@ -1700,6 +2163,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1700
2163
|
const saveViewResults = params.SaveViewResults ?? false;
|
|
1701
2164
|
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
1702
2165
|
this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
2166
|
+
// Field-level security on the clauses as this provider runs them, now that a ViewID- or
|
|
2167
|
+
// ViewName-only request has an entity. Before any SQL, like every other screen here.
|
|
2168
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [
|
|
2169
|
+
extraFilter,
|
|
2170
|
+
overrideExcludeFilter,
|
|
2171
|
+
...(params.Aggregates ?? []).map(a => a?.expression),
|
|
2172
|
+
], user);
|
|
1703
2173
|
// ── TOP / pagination mode ──
|
|
1704
2174
|
// Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
|
|
1705
2175
|
// and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
|
|
@@ -1744,16 +2214,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1744
2214
|
const fields = this.getRunTimeViewFieldString(params, viewEntity, user);
|
|
1745
2215
|
// ── Build SELECT and COUNT SQL ──
|
|
1746
2216
|
// DataSource:'Materialized' routes the read to the entity's materialized wrapper view
|
|
1747
|
-
// (same shape, so RLS/paging/fields all apply identically);
|
|
1748
|
-
|
|
2217
|
+
// (same shape, so RLS/paging/fields all apply identically); AlternateBaseView routes to
|
|
2218
|
+
// a registered alternate base view (which may also live in a custom schema); default stays the live base view.
|
|
2219
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity);
|
|
2220
|
+
const effectiveBaseView = effectiveTarget.viewName;
|
|
2221
|
+
const effectiveSchemaName = effectiveTarget.schemaName;
|
|
1749
2222
|
const topFragment = topSQL ? topSQL + ' ' : '';
|
|
1750
|
-
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(
|
|
2223
|
+
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`;
|
|
1751
2224
|
// count_only ALWAYS needs the count query — BuildTotalRowCountSQL only emits
|
|
1752
2225
|
// it when rows are limited (its pagination purpose), which previously left
|
|
1753
2226
|
// count_only with no COUNT at all (silently returned TotalRowCount 0).
|
|
1754
2227
|
let countSQL = params.ResultType === 'count_only'
|
|
1755
|
-
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(
|
|
1756
|
-
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView);
|
|
2228
|
+
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`
|
|
2229
|
+
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName);
|
|
1757
2230
|
// ── WHERE clause assembly ──
|
|
1758
2231
|
let whereSQL = '';
|
|
1759
2232
|
let bHasWhere = false;
|
|
@@ -1769,17 +2242,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1769
2242
|
// {%UserView%} templates) are written against entity base views, which the screens
|
|
1770
2243
|
// permit when the running user reads each of those entities unscoped.
|
|
1771
2244
|
this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
|
|
2245
|
+
// Field-level security covers CustomWhereClause views too: their clause is
|
|
2246
|
+
// admin-written, but it still runs as the acting user and could read a column
|
|
2247
|
+
// that user is denied.
|
|
2248
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [renderedWhere], user);
|
|
1772
2249
|
const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
|
|
1773
2250
|
if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
|
|
1774
2251
|
throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
|
|
1775
2252
|
}
|
|
2253
|
+
// The filter builder saves WhereClauses in SQL Server syntax (`[Field] LIKE ...`), so the
|
|
2254
|
+
// rendered clause gets the same platform rewrite as ExtraFilter. Without it PostgreSQL
|
|
2255
|
+
// rejects every filtered saved view run here: `syntax error at or near "["`.
|
|
2256
|
+
const viewWhereSQL = this.TransformExternalSQLClause(renderedWhere, entityInfo);
|
|
1776
2257
|
// CustomWhereClause views too: an unbalanced clause would take row-level security
|
|
1777
2258
|
// out of force for everyone who runs the view. Only their admin-written text may
|
|
1778
|
-
// carry comments.
|
|
1779
|
-
this.AssertClauseBalanced(
|
|
2259
|
+
// carry comments. Checked after the rewrite, since that is the text that runs.
|
|
2260
|
+
this.AssertClauseBalanced(viewWhereSQL, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
|
|
1780
2261
|
AllowComments: isCustomWhereClause,
|
|
1781
2262
|
});
|
|
1782
|
-
whereSQL = `(${
|
|
2263
|
+
whereSQL = `(${viewWhereSQL})`;
|
|
1783
2264
|
bHasWhere = true;
|
|
1784
2265
|
}
|
|
1785
2266
|
// 2. ExtraFilter
|
|
@@ -1789,6 +2270,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1789
2270
|
whereSQL = bHasWhere ? `${whereSQL} AND (${extraFilter})` : `(${extraFilter})`;
|
|
1790
2271
|
bHasWhere = true;
|
|
1791
2272
|
}
|
|
2273
|
+
// 2b. View properties: one typed predicate per property with a value, after the view's
|
|
2274
|
+
// own clause and ExtraFilter. Row-level security is still ANDed on below.
|
|
2275
|
+
if (propertyFilter.length > 0) {
|
|
2276
|
+
whereSQL = bHasWhere ? `${whereSQL} AND (${propertyFilter})` : `(${propertyFilter})`;
|
|
2277
|
+
bHasWhere = true;
|
|
2278
|
+
}
|
|
1792
2279
|
// 3. User search string
|
|
1793
2280
|
//
|
|
1794
2281
|
// 🚨 NOT screened by ValidateUserProvidedSQLClause (#4392). That denylist exists for
|
|
@@ -1808,7 +2295,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1808
2295
|
// in a literal: it is what keeps the text inside the quotes, where no keyword it
|
|
1809
2296
|
// contains can mean anything to the parser.
|
|
1810
2297
|
if (userSearchString.length > 0) {
|
|
1811
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user);
|
|
2298
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
1812
2299
|
if (sUserSearchSQL.length > 0) {
|
|
1813
2300
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
1814
2301
|
bHasWhere = true;
|
|
@@ -1909,6 +2396,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1909
2396
|
: '';
|
|
1910
2397
|
if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
|
|
1911
2398
|
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
2399
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [orderBy], user);
|
|
1912
2400
|
// No caller OrderBy means the sort came from the saved view's stored sort state.
|
|
1913
2401
|
if (!params.OrderBy && viewEntity)
|
|
1914
2402
|
this.ScreenStoredViewOrderBy(orderBy, user);
|
|
@@ -1919,7 +2407,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1919
2407
|
// Pass entityInfo + effectiveBaseView so the logged read honors DataSource:'Materialized'
|
|
1920
2408
|
// (reads the snapshot). effectiveBaseView === entityInfo.BaseView on the default live path,
|
|
1921
2409
|
// so non-materialized reads are unchanged.
|
|
1922
|
-
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user);
|
|
2410
|
+
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName);
|
|
1923
2411
|
if (logResult) {
|
|
1924
2412
|
viewSQL = logResult.executeViewSQL;
|
|
1925
2413
|
userViewRunID = logResult.runID;
|
|
@@ -1960,37 +2448,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1960
2448
|
if (params.Aggregates && params.Aggregates.length > 0) {
|
|
1961
2449
|
// Aggregate over the SAME source the rows/count came from — effectiveBaseView, so a caller
|
|
1962
2450
|
// asking for DataSource:'Materialized' gets aggregates over the snapshot, not the live view.
|
|
1963
|
-
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo,
|
|
2451
|
+
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo, effectiveSchemaName, effectiveBaseView, whereSQL);
|
|
1964
2452
|
aggregateSQL = aggregateBuild.aggregateSQL;
|
|
1965
2453
|
aggregateValidationErrors = aggregateBuild.validationErrors;
|
|
2454
|
+
this.assertAggregateRefusalsAreNotColumnProbes(aggregateValidationErrors, entityInfo, user);
|
|
1966
2455
|
}
|
|
1967
|
-
// ── Execute queries
|
|
1968
|
-
const
|
|
1969
|
-
const
|
|
2456
|
+
// ── Execute queries (single TDS batch via ExecuteSQLBatch when multiple SQL statements are needed) ──
|
|
2457
|
+
const sqlQueries = [];
|
|
2458
|
+
const sqlQueryKeys = [];
|
|
2459
|
+
let countExecutorPromise = null;
|
|
1970
2460
|
if (params.ResultType !== 'count_only') {
|
|
1971
|
-
|
|
1972
|
-
|
|
2461
|
+
sqlQueries.push(viewSQL);
|
|
2462
|
+
sqlQueryKeys.push('data');
|
|
1973
2463
|
}
|
|
1974
2464
|
const maxRowsUsed = params.MaxRows || entityInfo.UserViewMaxRows;
|
|
1975
|
-
|
|
2465
|
+
// SkipTotalRowCount is an explicit caller opt-out of the count (see RunViewParams);
|
|
2466
|
+
// count_only still counts — that result IS the count, the flag cannot mean anything there.
|
|
2467
|
+
const skipCount = params.SkipTotalRowCount === true && params.ResultType !== 'count_only';
|
|
2468
|
+
const willNeedCount = countSQL && ((usingPagination && !skipCount) || params.ResultType === 'count_only');
|
|
1976
2469
|
if (willNeedCount) {
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
2470
|
+
if (countExecutor && params.ResultType === 'count_only') {
|
|
2471
|
+
countExecutorPromise = countExecutor(countSQL);
|
|
2472
|
+
}
|
|
2473
|
+
else {
|
|
2474
|
+
sqlQueries.push(countSQL);
|
|
2475
|
+
sqlQueryKeys.push('count');
|
|
2476
|
+
}
|
|
1981
2477
|
}
|
|
1982
2478
|
const aggregateStartTime = Date.now();
|
|
1983
2479
|
if (aggregateSQL) {
|
|
1984
|
-
|
|
1985
|
-
|
|
2480
|
+
sqlQueries.push(aggregateSQL);
|
|
2481
|
+
sqlQueryKeys.push('aggregate');
|
|
1986
2482
|
}
|
|
1987
|
-
const results = await Promise.all(queries);
|
|
1988
2483
|
const resultMap = {};
|
|
1989
|
-
|
|
2484
|
+
if (sqlQueries.length === 1 && !countExecutorPromise) {
|
|
2485
|
+
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser);
|
|
2486
|
+
}
|
|
2487
|
+
else if (sqlQueries.length > 0 && countExecutorPromise) {
|
|
2488
|
+
const [batchResults, countRes] = await Promise.all([
|
|
2489
|
+
sqlQueries.length === 1
|
|
2490
|
+
? this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser).then(r => [r])
|
|
2491
|
+
: this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser),
|
|
2492
|
+
countExecutorPromise,
|
|
2493
|
+
]);
|
|
2494
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2495
|
+
resultMap['count'] = countRes;
|
|
2496
|
+
}
|
|
2497
|
+
else if (sqlQueries.length > 1) {
|
|
2498
|
+
const batchResults = await this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser);
|
|
2499
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2500
|
+
}
|
|
2501
|
+
else if (countExecutorPromise) {
|
|
2502
|
+
resultMap['count'] = await countExecutorPromise;
|
|
2503
|
+
}
|
|
1990
2504
|
// ── Process data rows ──
|
|
1991
2505
|
let retData = resultMap['data'] || [];
|
|
1992
2506
|
if (retData.length > 0 && params.ResultType !== 'count_only') {
|
|
1993
|
-
retData = await this.PostProcessRows(retData, entityInfo, user
|
|
2507
|
+
retData = await this.PostProcessRows(retData, entityInfo, user, {
|
|
2508
|
+
preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
|
|
2509
|
+
});
|
|
1994
2510
|
}
|
|
1995
2511
|
// ── Process count ──
|
|
1996
2512
|
let rowCount = null;
|
|
@@ -1999,7 +2515,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1999
2515
|
if (countResult && countResult.length > 0)
|
|
2000
2516
|
rowCount = countResult[0].TotalRowCount;
|
|
2001
2517
|
}
|
|
2002
|
-
else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed) {
|
|
2518
|
+
else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed && !skipCount) {
|
|
2519
|
+
// A row-limited read that came back FULL may have been truncated, so the total is
|
|
2520
|
+
// worth a second round trip: this is what makes Explorer's "100 of 299" correct.
|
|
2521
|
+
//
|
|
2522
|
+
// That round trip is SEQUENTIAL: it runs after the data query has already resolved,
|
|
2523
|
+
// so it is a full extra trip on the critical path, not a parallel one. For a
|
|
2524
|
+
// single-row probe it fires on every hit. Measured on a live tenant over a
|
|
2525
|
+
// 120-second census: 1,000 record-map lookups fired 721 of these counts and 800 row
|
|
2526
|
+
// lookups fired 600 — 1,321 extra round trips totalling 9,760 ms, 11.4% of ALL SQL
|
|
2527
|
+
// time in the window, with nothing reading a single result. Callers that only read
|
|
2528
|
+
// `Results` opt out explicitly with RunViewParams.SkipTotalRowCount; the provider
|
|
2529
|
+
// never infers that from the value of MaxRows.
|
|
2003
2530
|
const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
|
|
2004
2531
|
if (countResult && countResult.length > 0)
|
|
2005
2532
|
rowCount = countResult[0].TotalRowCount;
|
|
@@ -2042,7 +2569,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2042
2569
|
}
|
|
2043
2570
|
return {
|
|
2044
2571
|
RowCount: params.ResultType === 'count_only' ? rowCount : retData.length,
|
|
2045
|
-
TotalRowCount: rowCount ?? retData.length,
|
|
2572
|
+
TotalRowCount: skipCount ? undefined : rowCount ?? retData.length,
|
|
2046
2573
|
Results: retData,
|
|
2047
2574
|
UserViewRunID: userViewRunID,
|
|
2048
2575
|
ExecutionTime: stopTime.getTime() - startTime.getTime(),
|
|
@@ -2059,6 +2586,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2059
2586
|
if (this.isConnectionError(e)) {
|
|
2060
2587
|
throw e;
|
|
2061
2588
|
}
|
|
2589
|
+
// A field-security refusal throws, as the provider's pre-cache gate does, and a
|
|
2590
|
+
// restricted caller's "no such column" becomes the same refusal — so a denied column
|
|
2591
|
+
// and a missing one look identical however the request reached this point.
|
|
2592
|
+
const fieldSecurityError = this.fieldSecurityErrorFor(e, resolvedEntity, contextUser ?? this.CurrentUser);
|
|
2593
|
+
if (fieldSecurityError) {
|
|
2594
|
+
throw fieldSecurityError;
|
|
2595
|
+
}
|
|
2062
2596
|
const exceptionStopTime = new Date();
|
|
2063
2597
|
LogError(e);
|
|
2064
2598
|
return {
|
|
@@ -2072,12 +2606,155 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2072
2606
|
};
|
|
2073
2607
|
}
|
|
2074
2608
|
}
|
|
2609
|
+
/** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
|
|
2610
|
+
async LoadRunViewEntity(params, contextUser) {
|
|
2611
|
+
if (params.ViewEntity)
|
|
2612
|
+
return params.ViewEntity;
|
|
2613
|
+
if (params.ViewID && params.ViewID.length > 0)
|
|
2614
|
+
return await ViewInfo.GetViewEntity(params.ViewID, contextUser) ?? null;
|
|
2615
|
+
if (params.ViewName && params.ViewName.length > 0)
|
|
2616
|
+
return await ViewInfo.GetViewEntityByName(params.ViewName, contextUser) ?? null;
|
|
2617
|
+
return null;
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Works out a stored view's property values before the cache lookup (see
|
|
2621
|
+
* {@link ProviderBase.PrepareRunViewProperties}). The resolved values, token defaults included,
|
|
2622
|
+
* replace `Properties` and `ServerProperties`, so the fingerprint keys on what the run will use,
|
|
2623
|
+
* and RunViewCore resolving them again yields the same predicates. A run that would be refused
|
|
2624
|
+
* is left as it is and kept out of the cache; RunViewCore refuses it with its message. A view
|
|
2625
|
+
* that cannot be loaded is left to RunViewCore too, which reports it as it always has.
|
|
2626
|
+
*/
|
|
2627
|
+
async PrepareRunViewProperties(params, contextUser) {
|
|
2628
|
+
if (!params.ViewEntity && !params.ViewID && !params.ViewName) {
|
|
2629
|
+
return; // an entity run: RunViewCore refuses any properties it carries
|
|
2630
|
+
}
|
|
2631
|
+
let viewEntity;
|
|
2632
|
+
try {
|
|
2633
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
2634
|
+
}
|
|
2635
|
+
catch {
|
|
2636
|
+
return;
|
|
2637
|
+
}
|
|
2638
|
+
const entityInfo = viewEntity ? this.EntityByID(viewEntity.EntityID) : undefined;
|
|
2639
|
+
const user = contextUser ?? this.CurrentUser;
|
|
2640
|
+
if (!viewEntity || !entityInfo || !user) {
|
|
2641
|
+
return;
|
|
2642
|
+
}
|
|
2643
|
+
try {
|
|
2644
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2645
|
+
if (resolved) {
|
|
2646
|
+
params.ServerProperties = resolved.Values;
|
|
2647
|
+
delete params.Properties;
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
catch {
|
|
2651
|
+
params.BypassCache = true;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
/**
|
|
2655
|
+
* Checks a stored view's declared properties and works out each one's value for this run.
|
|
2656
|
+
* @returns null when the view declares none and the run sends none
|
|
2657
|
+
* @throws on a malformed definition, any refusal {@link ResolveViewPropertyValues} makes, or a
|
|
2658
|
+
* property with a value whose target field the user cannot read
|
|
2659
|
+
*/
|
|
2660
|
+
ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user) {
|
|
2661
|
+
const declared = viewEntity?.PropertiesObject ?? [];
|
|
2662
|
+
const sent = params.Properties !== undefined || params.ServerProperties !== undefined;
|
|
2663
|
+
if (!viewEntity) {
|
|
2664
|
+
if (sent)
|
|
2665
|
+
throw new Error('Properties apply only to a stored view: run it by ViewID, ViewName or ViewEntity.');
|
|
2666
|
+
return null;
|
|
2667
|
+
}
|
|
2668
|
+
if (declared.length === 0 && !sent) {
|
|
2669
|
+
return null;
|
|
2670
|
+
}
|
|
2671
|
+
const definitionErrors = ValidateUserViewProperties(declared, entityInfo.Fields.map(f => f.Name));
|
|
2672
|
+
if (definitionErrors.length > 0) {
|
|
2673
|
+
throw new Error(`View '${viewEntity.Name ?? viewEntity.ID}' has invalid properties: ${definitionErrors.join(' ')}`);
|
|
2674
|
+
}
|
|
2675
|
+
const values = ResolveViewPropertyValues(declared, params.Properties, params.ServerProperties, { User: user, TimeZone: params.TimeZone });
|
|
2676
|
+
this.assertViewPropertyFieldsReadable(declared, values, entityInfo, user);
|
|
2677
|
+
return { Declared: declared, Values: values };
|
|
2678
|
+
}
|
|
2679
|
+
/**
|
|
2680
|
+
* The WHERE clause a stored view's properties add to this run: '' when there are none.
|
|
2681
|
+
* Screened like any caller clause, though it is built only from typed literals.
|
|
2682
|
+
*/
|
|
2683
|
+
BuildViewPropertyFilter(viewEntity, entityInfo, params, user) {
|
|
2684
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2685
|
+
if (!resolved) {
|
|
2686
|
+
return '';
|
|
2687
|
+
}
|
|
2688
|
+
const filter = BuildViewPropertyFilter(resolved.Declared, resolved.Values, entityInfo.Fields.map(f => f.Name), this.Dialect);
|
|
2689
|
+
if (filter.length > 0 && !this.ValidateUserProvidedSQLClause(filter)) {
|
|
2690
|
+
throw new Error(`Invalid view property filter: contains one or more forbidden keywords`);
|
|
2691
|
+
}
|
|
2692
|
+
return filter;
|
|
2693
|
+
}
|
|
2694
|
+
/** The field-security check other predicates get: a property with a value may not filter a field the user cannot read. */
|
|
2695
|
+
assertViewPropertyFieldsReadable(declared, values, entityInfo, user) {
|
|
2696
|
+
if (!entityInfo.FieldLevelSecurityApplies) {
|
|
2697
|
+
return;
|
|
2698
|
+
}
|
|
2699
|
+
const denied = entityInfo.GetDeniedReadFields(user);
|
|
2700
|
+
for (const property of declared) {
|
|
2701
|
+
if (values[property.Name] !== null && denied.has(property.Target.Field.trim().toLowerCase())) {
|
|
2702
|
+
throw new FieldSecurityError(property.Target.Field, entityInfo.Name);
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2075
2706
|
async InternalRunViews(params, contextUser) {
|
|
2076
2707
|
if (IsCoalescibleCountBatch(params)) {
|
|
2077
2708
|
return this.RunCoalescedCountBatch(params, contextUser);
|
|
2078
2709
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2710
|
+
if (params.length === 0) {
|
|
2711
|
+
return [];
|
|
2712
|
+
}
|
|
2713
|
+
const limit = GenericDatabaseProvider.MaxConcurrentViewsPerBatch;
|
|
2714
|
+
if (!limit || !Number.isFinite(limit) || limit <= 0 || params.length <= limit) {
|
|
2715
|
+
const promises = params.map((p) => this.runBatchedView(p, contextUser));
|
|
2716
|
+
return Promise.all(promises);
|
|
2717
|
+
}
|
|
2718
|
+
const results = new Array(params.length);
|
|
2719
|
+
const started = new Array(params.length).fill(false);
|
|
2720
|
+
const joinerPromises = [];
|
|
2721
|
+
let cursor = 0;
|
|
2722
|
+
const attachInFlightDuplicates = (fromIndex) => {
|
|
2723
|
+
if (typeof this.hasInFlightSingleFlightView !== 'function') {
|
|
2724
|
+
return;
|
|
2725
|
+
}
|
|
2726
|
+
for (let j = fromIndex; j < params.length; j++) {
|
|
2727
|
+
if (!started[j] && this.hasInFlightSingleFlightView(params[j], contextUser)) {
|
|
2728
|
+
started[j] = true;
|
|
2729
|
+
const joinIdx = j;
|
|
2730
|
+
joinerPromises.push(this.runBatchedView(params[joinIdx], contextUser).then((res) => {
|
|
2731
|
+
results[joinIdx] = res;
|
|
2732
|
+
}));
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
};
|
|
2736
|
+
const runWorker = async () => {
|
|
2737
|
+
while (cursor < params.length) {
|
|
2738
|
+
const idx = cursor++;
|
|
2739
|
+
if (started[idx]) {
|
|
2740
|
+
continue;
|
|
2741
|
+
}
|
|
2742
|
+
started[idx] = true;
|
|
2743
|
+
const viewPromise = this.runBatchedView(params[idx], contextUser);
|
|
2744
|
+
attachInFlightDuplicates(idx + 1);
|
|
2745
|
+
results[idx] = await viewPromise;
|
|
2746
|
+
}
|
|
2747
|
+
};
|
|
2748
|
+
const workerCount = Math.min(limit, params.length);
|
|
2749
|
+
const workers = [];
|
|
2750
|
+
for (let w = 0; w < workerCount; w++) {
|
|
2751
|
+
workers.push(runWorker());
|
|
2752
|
+
}
|
|
2753
|
+
await Promise.all(workers);
|
|
2754
|
+
if (joinerPromises.length > 0) {
|
|
2755
|
+
await Promise.all(joinerPromises);
|
|
2756
|
+
}
|
|
2757
|
+
return results;
|
|
2081
2758
|
}
|
|
2082
2759
|
/**
|
|
2083
2760
|
* All-`count_only` batch: every view runs the normal per-view path (so every
|
|
@@ -2089,8 +2766,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2089
2766
|
async RunCoalescedCountBatch(params, contextUser) {
|
|
2090
2767
|
const batch = new CountOnlyBatchCoalescer(params.length, (sql) => this.ExecuteSQL(sql, undefined, undefined, contextUser), (name) => this.QuoteIdentifier(name), (error) => this.isConnectionError(error));
|
|
2091
2768
|
return Promise.all(params.map((p, index) => this.RunViewCore(p, contextUser, (countSQL) => batch.Execute(index, countSQL))
|
|
2769
|
+
.catch((error) => GenericDatabaseProvider.fieldSecurityRefusalAsResult(error))
|
|
2092
2770
|
.finally(() => batch.MarkSettled(index))));
|
|
2093
2771
|
}
|
|
2772
|
+
/**
|
|
2773
|
+
* One view of a `RunViews` batch. A field-security refusal of this view becomes this view's
|
|
2774
|
+
* `Success: false` result, carrying the refusal's message, so it does not fail the views
|
|
2775
|
+
* batched with it. Any other error is thrown, as a single RunView throws it.
|
|
2776
|
+
*/
|
|
2777
|
+
async runBatchedView(params, contextUser) {
|
|
2778
|
+
try {
|
|
2779
|
+
return await this.InternalRunView(params, contextUser);
|
|
2780
|
+
}
|
|
2781
|
+
catch (error) {
|
|
2782
|
+
return GenericDatabaseProvider.fieldSecurityRefusalAsResult(error);
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2094
2785
|
/**************************************************************************/
|
|
2095
2786
|
// InternalRunView Helpers
|
|
2096
2787
|
/**************************************************************************/
|
|
@@ -2139,7 +2830,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2139
2830
|
* column list here buys the same protection without touching either.
|
|
2140
2831
|
*/
|
|
2141
2832
|
buildFieldSecuritySelectList(entityInfo, user) {
|
|
2142
|
-
if (!user || !entityInfo.
|
|
2833
|
+
if (!user || !entityInfo.FieldLevelSecurityApplies) {
|
|
2143
2834
|
return '*'; // the overwhelmingly common case — one boolean, unchanged SQL
|
|
2144
2835
|
}
|
|
2145
2836
|
const denied = entityInfo.GetDeniedReadFields(user);
|
|
@@ -2197,9 +2888,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2197
2888
|
// Binary columns are omitted from every implicit field list (saved-view columns and
|
|
2198
2889
|
// the no-Fields wildcard) unless requested; an explicit params.Fields entry is honoured.
|
|
2199
2890
|
const includeBinary = params.IncludeBinaryFields === true;
|
|
2891
|
+
// The request's own denied set, shared with its cache key (ResolveRequestDeniedReadFields),
|
|
2892
|
+
// so the slot this fill lands in is keyed for the columns it actually selects.
|
|
2200
2893
|
const flsUser = contextUser ?? this.CurrentUser;
|
|
2201
|
-
const denied = params.ResultType !== 'entity_object'
|
|
2202
|
-
?
|
|
2894
|
+
const denied = params.ResultType !== 'entity_object'
|
|
2895
|
+
? this.ResolveRequestDeniedReadFields(params, entityInfo, flsUser)
|
|
2203
2896
|
: new Set();
|
|
2204
2897
|
if (params.Fields) {
|
|
2205
2898
|
for (const ef of entityInfo.PrimaryKeys) {
|
|
@@ -2265,8 +2958,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2265
2958
|
* - escapes LIKE metacharacters (%, _, [, ]) in user input with ESCAPE '\\',
|
|
2266
2959
|
* - skips fields that are not sensible text-search targets (non-text types,
|
|
2267
2960
|
* unbounded text columns when FTX is off).
|
|
2961
|
+
*
|
|
2962
|
+
* @param deniedFields - The request's denied set (see ResolveRequestDeniedReadFields), so the
|
|
2963
|
+
* searched columns match the ones its cache key and SELECT list were built from. Read from
|
|
2964
|
+
* the entity for `contextUser` when omitted.
|
|
2268
2965
|
*/
|
|
2269
|
-
createViewUserSearchSQL(entityInfo, userSearchString, contextUser) {
|
|
2966
|
+
createViewUserSearchSQL(entityInfo, userSearchString, contextUser, deniedFields) {
|
|
2270
2967
|
let sUserSearchSQL = '';
|
|
2271
2968
|
const safeUserSearchString = userSearchString.replace(/'/g, "''");
|
|
2272
2969
|
// Field-level security: never search fields the user cannot read. Matching against a
|
|
@@ -2276,15 +2973,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2276
2973
|
// fields are simply excluded from the searched set. Computed once per call, never per
|
|
2277
2974
|
// field (the per-request precompute contract).
|
|
2278
2975
|
const user = contextUser ?? this.CurrentUser;
|
|
2279
|
-
const deniedSearchFields =
|
|
2280
|
-
? entityInfo.GetDeniedReadFields(user)
|
|
2281
|
-
: new Set();
|
|
2976
|
+
const deniedSearchFields = deniedFields
|
|
2977
|
+
?? (entityInfo.FieldLevelSecurityApplies && user ? entityInfo.GetDeniedReadFields(user) : new Set());
|
|
2282
2978
|
// The full-text index spans its indexed columns as one unit — a denied FTS-indexed
|
|
2283
2979
|
// column cannot be excluded from the index function. When (and only when) a denied
|
|
2284
2980
|
// field is FTS-indexed, fall back to the per-field LIKE path, which CAN exclude it.
|
|
2285
2981
|
const ftsCoversDeniedField = deniedSearchFields.size > 0 &&
|
|
2286
2982
|
entityInfo.Fields.some(f => f.FullTextSearchEnabled && deniedSearchFields.has(f.Name.trim().toLowerCase()));
|
|
2287
|
-
|
|
2983
|
+
// `FullTextSearchEnabled` alone is NOT enough to take this branch: the branch names
|
|
2984
|
+
// `FullTextSearchFunction` and, when that is null or blank, the `?? ''` below emitted
|
|
2985
|
+
// `... FROM "schema".""('term')` — a syntax error, thrown on EVERY user search of such an
|
|
2986
|
+
// entity, with no fallback. The two columns are independent (the flag can be set by hand
|
|
2987
|
+
// or by a metadata sync before CodeGen has minted the function), so the name has to be
|
|
2988
|
+
// checked, not assumed. A blank name now falls through to the per-field LIKE path, which
|
|
2989
|
+
// needs no database object and returns results.
|
|
2990
|
+
//
|
|
2991
|
+
// Composed with, not substituted for, the field-security condition above — both have to
|
|
2992
|
+
// hold to search through the index.
|
|
2993
|
+
const ftsFunctionName = entityInfo.FullTextSearchFunction;
|
|
2994
|
+
const hasFTSFunction = typeof ftsFunctionName === 'string' && ftsFunctionName.trim().length > 0;
|
|
2995
|
+
if (entityInfo.FullTextSearchEnabled && hasFTSFunction && !ftsCoversDeniedField) {
|
|
2288
2996
|
let u = safeUserSearchString;
|
|
2289
2997
|
const uUpper = u.toUpperCase();
|
|
2290
2998
|
// WORD-boundary tests, not substring tests (#4392). As substrings, `OR` matches
|
|
@@ -2328,7 +3036,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2328
3036
|
// forbidden keyword). Quoting `{0}` in the format is what actually closes that.
|
|
2329
3037
|
//
|
|
2330
3038
|
// The screen reads the quote-doubled term, because that is the text `{0}` becomes.
|
|
2331
|
-
|
|
3039
|
+
const termIsSQL = this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields);
|
|
3040
|
+
if (termIsSQL && user) {
|
|
3041
|
+
// Spliced in unquoted, the term is a predicate the caller wrote, so it gets the
|
|
3042
|
+
// field-security gate every other caller predicate gets.
|
|
3043
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [safeUserSearchString], user);
|
|
3044
|
+
}
|
|
3045
|
+
if (termIsSQL && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
|
|
2332
3046
|
throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
|
|
2333
3047
|
`which splices the term directly into SQL, and the term is not allowed there: it contains ` +
|
|
2334
3048
|
`a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
|
|
@@ -2488,17 +3202,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2488
3202
|
ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
|
|
2489
3203
|
}
|
|
2490
3204
|
/**
|
|
2491
|
-
*
|
|
2492
|
-
*
|
|
2493
|
-
*
|
|
2494
|
-
*
|
|
2495
|
-
* request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
|
|
2496
|
-
* `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
|
|
3205
|
+
* The field-security error a failed RunView must raise, or null to report the failure as
|
|
3206
|
+
* usual: a {@link FieldSecurityError} raised along the way, or — for a caller denied fields on
|
|
3207
|
+
* `entity` — a database "no such column" rejection, rewritten into the error a denied column
|
|
3208
|
+
* gets ({@link FieldSecuritySQLGate.ErrorForInvalidColumn}).
|
|
2497
3209
|
*/
|
|
2498
|
-
|
|
2499
|
-
if (
|
|
2500
|
-
return;
|
|
2501
|
-
|
|
3210
|
+
fieldSecurityErrorFor(error, entity, user) {
|
|
3211
|
+
if (error instanceof Error && (error instanceof FieldSecurityError || error.name === FieldSecurityError.ErrorName)) {
|
|
3212
|
+
return error;
|
|
3213
|
+
}
|
|
3214
|
+
return FieldSecuritySQLGate.ErrorForInvalidColumn(error, entity, user);
|
|
3215
|
+
}
|
|
3216
|
+
/**
|
|
3217
|
+
* For a caller denied fields on `entity`, throws the field-security error when an aggregate was
|
|
3218
|
+
* refused because it names a column the entity does not have. A denied column in an aggregate is
|
|
3219
|
+
* refused by the gate with that error, so an unknown one must not answer differently.
|
|
3220
|
+
*/
|
|
3221
|
+
assertAggregateRefusalsAreNotColumnProbes(errors, entity, user) {
|
|
3222
|
+
if (errors.length === 0 || !FieldSecuritySQLGate.UserCarriesDenials([entity], user)) {
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
3225
|
+
for (const refused of errors) {
|
|
3226
|
+
const match = /references "((?:[^"]|"")*)", which (?:is not a column|matches more than one column) of this entity/.exec(refused.error ?? '');
|
|
3227
|
+
if (match) {
|
|
3228
|
+
// Named the way the gate names a denied column in the same expression, so the two
|
|
3229
|
+
// refusals read the same whatever case the caller typed.
|
|
3230
|
+
const column = FieldSecuritySQLGate.ReportedColumnName(refused.expression, match[1].replace(/""/g, '"'), this.PlatformKey);
|
|
3231
|
+
throw new FieldSecurityError(column, entity.Name);
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
/**
|
|
3236
|
+
* SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
|
|
3237
|
+
* Any user who can save a view can write its WhereClause, directly or through FilterState or a
|
|
3238
|
+
* Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
|
|
3239
|
+
* can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
|
|
3240
|
+
* request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
|
|
3241
|
+
* `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
|
|
3242
|
+
*/
|
|
3243
|
+
ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
|
|
3244
|
+
if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
|
|
3245
|
+
return; // truthy — the DB may hand back true or 1
|
|
3246
|
+
this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
|
|
2502
3247
|
this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
|
|
2503
3248
|
}
|
|
2504
3249
|
/**
|
|
@@ -2544,7 +3289,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2544
3289
|
// takes a one-column subquery — an entity with a composite key has no single column to return.
|
|
2545
3290
|
const innerEntityInfo = innerViewEntity.ViewEntityInfo;
|
|
2546
3291
|
this.assertSingleColumnPrimaryKey(innerEntityInfo, `The {%UserView%} template variable ${match}`);
|
|
2547
|
-
const
|
|
3292
|
+
const innerTarget = await this.resolveEffectiveBaseViewTarget(innerEntityInfo, { EntityName: innerEntityInfo.Name, ViewEntity: innerViewEntity }, user, innerViewEntity);
|
|
3293
|
+
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
3294
|
// Function replacement — `innerSQL` is generated SQL that can
|
|
2549
3295
|
// legitimately contain `$`. See issue #3171.
|
|
2550
3296
|
sWhere = sWhere.replace(match, () => innerSQL);
|
|
@@ -2658,6 +3404,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2658
3404
|
}
|
|
2659
3405
|
return items;
|
|
2660
3406
|
}
|
|
3407
|
+
/**
|
|
3408
|
+
* The field-security key of one request, built once per request (`params` object) and user.
|
|
3409
|
+
* A smart-cache-check item asks for it from each leg — its browser freshness check, the
|
|
3410
|
+
* server-cache lookup and the cache write — and the answer cannot change within the request:
|
|
3411
|
+
* the denied set it is built from is already resolved once per request.
|
|
3412
|
+
*/
|
|
3413
|
+
ComputeRunViewFLSFingerprintKey(params, contextUser) {
|
|
3414
|
+
const user = contextUser ?? this.CurrentUser;
|
|
3415
|
+
const memo = this._requestFLSKeys?.get(params);
|
|
3416
|
+
if (memo && memo.User === user && memo.Target === GenericDatabaseProvider.flsKeyTarget(params)) {
|
|
3417
|
+
return memo.Key;
|
|
3418
|
+
}
|
|
3419
|
+
const key = super.ComputeRunViewFLSFingerprintKey(params, user);
|
|
3420
|
+
this._requestFLSKeys?.set(params, { User: user, Target: GenericDatabaseProvider.flsKeyTarget(params), Key: key });
|
|
3421
|
+
return key;
|
|
3422
|
+
}
|
|
3423
|
+
/** What a request's field-security key is about: its entity, or the saved view it names. */
|
|
3424
|
+
static flsKeyTarget(params) {
|
|
3425
|
+
return `${params.EntityName ?? ''}|${params.ViewID ?? ''}|${params.ViewName ?? ''}|${params.ViewEntity ? 'loaded' : ''}`;
|
|
3426
|
+
}
|
|
3427
|
+
/** The message refusing `user` Read on `entityInfo`, or null when the user may read it. */
|
|
3428
|
+
readPermissionError(entityInfo, user) {
|
|
3429
|
+
try {
|
|
3430
|
+
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
3431
|
+
return null;
|
|
3432
|
+
}
|
|
3433
|
+
catch (e) {
|
|
3434
|
+
return e instanceof Error ? e.message : String(e);
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
2661
3437
|
/**
|
|
2662
3438
|
* Smart cache validation for batch RunViews.
|
|
2663
3439
|
* For each view request, if cacheStatus is provided, checks if the cache is current
|
|
@@ -2673,9 +3449,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2673
3449
|
}
|
|
2674
3450
|
// ── Superset/projection contract (same as the ProviderBase pipeline) ──
|
|
2675
3451
|
// For every cache-eligible item: widen Fields to ALL entity fields so any
|
|
2676
|
-
// cache write stores the
|
|
2677
|
-
//
|
|
2678
|
-
//
|
|
3452
|
+
// cache write stores every column the user's permission class may read (the
|
|
3453
|
+
// slot is keyed by that class), and remember the caller's requested shape
|
|
3454
|
+
// (∪ primary keys — platform contract) so every serve leg projects back down
|
|
3455
|
+
// before returning rows to the client. This path
|
|
2679
3456
|
// previously cached narrow rows under the Fields-agnostic fingerprint and
|
|
2680
3457
|
// served cached rows unprojected — one client's shape poisoned the slot
|
|
2681
3458
|
// for every subsequent caller.
|
|
@@ -2719,15 +3496,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2719
3496
|
const requested = p.Fields && p.Fields.length > 0
|
|
2720
3497
|
? p.Fields.map(f => f.trim().toLowerCase())
|
|
2721
3498
|
: null;
|
|
2722
|
-
// ALL fields, for every user:
|
|
2723
|
-
//
|
|
2724
|
-
//
|
|
3499
|
+
// ALL fields requested, for every user: the SELECT built from this list leaves
|
|
3500
|
+
// out the columns this user may not read, and the slot is keyed by the user's
|
|
3501
|
+
// permission class, so a slot holds only what its class may read.
|
|
3502
|
+
// ApplyFieldSecurityProjection still runs on every serve as a backstop.
|
|
2725
3503
|
this.ResolveIncludeBinaryFields(p, widenEntity);
|
|
2726
3504
|
p.Fields = this.ComputeRunViewFetchFields(widenEntity, p);
|
|
2727
3505
|
if (requested) {
|
|
2728
3506
|
callerFieldsByIndex.set(i, ProviderBase.UnionFieldsWithPrimaryKeys(requested, widenEntity));
|
|
2729
3507
|
}
|
|
2730
3508
|
}
|
|
3509
|
+
// A status the browser computed for other columns than this user may read now
|
|
3510
|
+
// describes a slot with the wrong columns, even if no row changed. Dropping it sends
|
|
3511
|
+
// the item down the "nothing cached" path, which answers with fresh rows.
|
|
3512
|
+
if (this.cacheStatusFieldSecurityDiffers(params[i].cacheStatus, p, user)) {
|
|
3513
|
+
params[i].cacheStatus = undefined;
|
|
3514
|
+
}
|
|
2731
3515
|
}
|
|
2732
3516
|
/** Projects rows down to the caller's requested shape for a given item index. */
|
|
2733
3517
|
const projectForCaller = (index, rows) => {
|
|
@@ -2749,6 +3533,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2749
3533
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: gateRejection });
|
|
2750
3534
|
continue;
|
|
2751
3535
|
}
|
|
3536
|
+
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
3537
|
+
// Read-permission gate for EVERY item whose entity is known, before any leg can answer:
|
|
3538
|
+
// an item with no cache status, and an external entity, are served from the server cache
|
|
3539
|
+
// on a hit WITHOUT re-entering InternalRunView, so a CanRead check that lived only on the
|
|
3540
|
+
// cache-miss path would let a user lacking permission receive rows another user warmed.
|
|
3541
|
+
if (entityInfo) {
|
|
3542
|
+
const permissionError = this.readPermissionError(entityInfo, user);
|
|
3543
|
+
if (permissionError !== null) {
|
|
3544
|
+
errorResults.push({ viewIndex: i, status: 'error', errorMessage: permissionError });
|
|
3545
|
+
continue;
|
|
3546
|
+
}
|
|
3547
|
+
}
|
|
2752
3548
|
// Keyset queries bypass the cache entirely (per the AfterKey API contract):
|
|
2753
3549
|
// each call uses a different seek key, so cached entries would never be
|
|
2754
3550
|
// reusable. Route directly to standard execution path.
|
|
@@ -2756,22 +3552,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2756
3552
|
itemsWithoutCacheCheck.push({ index: i, item });
|
|
2757
3553
|
continue;
|
|
2758
3554
|
}
|
|
2759
|
-
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
2760
3555
|
if (!entityInfo) {
|
|
2761
3556
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: `Entity ${item.params.EntityName} not found in metadata` });
|
|
2762
3557
|
continue;
|
|
2763
3558
|
}
|
|
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
3559
|
// External-data-source entities can't participate in DB-side cache validation
|
|
2776
3560
|
// (no MJ base view / __mj_UpdatedAt to COUNT/MAX against). Route them to the
|
|
2777
3561
|
// standard execution path, which dispatches to the external driver and TTL-caches
|
|
@@ -2782,7 +3566,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2782
3566
|
}
|
|
2783
3567
|
itemsNeedingValidation.push({ index: i, item, entityInfo });
|
|
2784
3568
|
}
|
|
2785
|
-
// Phase 1: Check server's LocalCacheManager first (zero DB hits)
|
|
3569
|
+
// Phase 1: Check server's LocalCacheManager first (zero DB hits when within freshness window)
|
|
2786
3570
|
const currentResults = [];
|
|
2787
3571
|
const serverCacheStaleItems = [];
|
|
2788
3572
|
const serverCacheMissItems = [];
|
|
@@ -2793,7 +3577,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2793
3577
|
if (resolved.status === 'current') {
|
|
2794
3578
|
currentResults.push(resolved.result);
|
|
2795
3579
|
}
|
|
3580
|
+
else if (resolved.status === 'needs_verification') {
|
|
3581
|
+
serverCacheMissItems.push({
|
|
3582
|
+
index,
|
|
3583
|
+
item,
|
|
3584
|
+
entityInfo,
|
|
3585
|
+
serverCached: resolved.serverCached,
|
|
3586
|
+
fingerprint: resolved.fingerprint,
|
|
3587
|
+
});
|
|
3588
|
+
}
|
|
3589
|
+
else if (entityInfo.TrackRecordChanges) {
|
|
3590
|
+
// The client's copy is older and the entity tracks record changes: Phase 2 reads
|
|
3591
|
+
// the DB status and sends only the changed rows, not the full cached copy.
|
|
3592
|
+
serverCacheMissItems.push({ index, item, entityInfo });
|
|
3593
|
+
}
|
|
2796
3594
|
else {
|
|
3595
|
+
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${resolved.serverCached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
2797
3596
|
serverCacheStaleItems.push({ index, item, entityInfo, serverCached: resolved.serverCached });
|
|
2798
3597
|
}
|
|
2799
3598
|
}
|
|
@@ -2801,41 +3600,82 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2801
3600
|
serverCacheMissItems.push({ index, item, entityInfo });
|
|
2802
3601
|
}
|
|
2803
3602
|
}
|
|
2804
|
-
// Phase 2: For server cache misses,
|
|
3603
|
+
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
2805
3604
|
const differentialItems = [];
|
|
2806
3605
|
const staleItemsNoTracking = [];
|
|
3606
|
+
/** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
|
|
3607
|
+
const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus) => {
|
|
3608
|
+
LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
|
|
3609
|
+
differentialItems.push({
|
|
3610
|
+
index, params: item.params, entityInfo, whereSQL,
|
|
3611
|
+
clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
|
|
3612
|
+
clientRowCount: item.cacheStatus.rowCount,
|
|
3613
|
+
serverStatus,
|
|
3614
|
+
});
|
|
3615
|
+
};
|
|
2807
3616
|
if (serverCacheMissItems.length > 0) {
|
|
2808
|
-
// Build WHERE clauses and run batched DB status check only for cache misses
|
|
3617
|
+
// Build WHERE clauses and run batched DB status check only for cache misses / TTL-expired slots
|
|
2809
3618
|
const itemsForDBCheck = [];
|
|
2810
|
-
for (const { index, item, entityInfo } of serverCacheMissItems) {
|
|
3619
|
+
for (const { index, item, entityInfo, serverCached, fingerprint } of serverCacheMissItems) {
|
|
2811
3620
|
try {
|
|
2812
3621
|
const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user);
|
|
2813
|
-
itemsForDBCheck.push({ index, item, entityInfo, whereSQL });
|
|
3622
|
+
itemsForDBCheck.push({ index, item, entityInfo, whereSQL, serverCached, fingerprint });
|
|
2814
3623
|
}
|
|
2815
3624
|
catch (e) {
|
|
2816
3625
|
errorResults.push({ viewIndex: index, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
2817
3626
|
}
|
|
2818
3627
|
}
|
|
2819
3628
|
const cacheStatusResults = await this.getBatchedServerCacheStatus(itemsForDBCheck, contextUser);
|
|
2820
|
-
for (const { index, item, entityInfo, whereSQL } of itemsForDBCheck) {
|
|
3629
|
+
for (const { index, item, entityInfo, whereSQL, serverCached, fingerprint } of itemsForDBCheck) {
|
|
2821
3630
|
const serverStatus = cacheStatusResults.get(index);
|
|
2822
3631
|
if (!serverStatus || !serverStatus.success) {
|
|
2823
|
-
|
|
3632
|
+
const statusError = serverStatus?.errorMessage || 'Failed to get cache status';
|
|
3633
|
+
const fieldSecurityError = FieldSecuritySQLGate.ErrorForInvalidColumn(statusError, entityInfo, user);
|
|
3634
|
+
errorResults.push({ viewIndex: index, status: 'error', errorMessage: fieldSecurityError?.message ?? statusError });
|
|
2824
3635
|
continue;
|
|
2825
3636
|
}
|
|
2826
3637
|
const entityLabel = item.params.EntityName || 'unknown';
|
|
3638
|
+
if (serverCached && fingerprint) {
|
|
3639
|
+
const cachedSlotStatus = {
|
|
3640
|
+
maxUpdatedAt: serverCached.maxUpdatedAt,
|
|
3641
|
+
rowCount: serverCached.totalRowCount ?? serverCached.rowCount,
|
|
3642
|
+
};
|
|
3643
|
+
if (this.isCacheCurrent(cachedSlotStatus, serverStatus)) {
|
|
3644
|
+
// Server cache slot is confirmed current against SQL — refresh its verification timestamp in O(1)
|
|
3645
|
+
LocalCacheManager.Instance.TouchRunViewResultVerifiedAt(fingerprint);
|
|
3646
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3647
|
+
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
3648
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3649
|
+
}
|
|
3650
|
+
else if (entityInfo.TrackRecordChanges) {
|
|
3651
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
3652
|
+
}
|
|
3653
|
+
else {
|
|
3654
|
+
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
|
|
3655
|
+
serverCacheStaleItems.push({ index, item, entityInfo, serverCached });
|
|
3656
|
+
}
|
|
3657
|
+
continue;
|
|
3658
|
+
}
|
|
3659
|
+
else {
|
|
3660
|
+
// Out-of-band SQL mutation or missed invalidation occurred!
|
|
3661
|
+
// Evict the stale server slot and refresh from DB so LocalCacheManager and the client self-heal.
|
|
3662
|
+
LogStatusEx({ message: ` ♻️ [SmartCache RECONCILE-EVICT] "${entityLabel}" — server cache slot disagreed with DB status; invalidating and refreshing from DB`, verboseOnly: true });
|
|
3663
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
3664
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3665
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3666
|
+
}
|
|
3667
|
+
else {
|
|
3668
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
3669
|
+
}
|
|
3670
|
+
continue;
|
|
3671
|
+
}
|
|
3672
|
+
}
|
|
2827
3673
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
2828
3674
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches DB (server cache miss)`, verboseOnly: true });
|
|
2829
3675
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
2830
3676
|
}
|
|
2831
3677
|
else if (entityInfo.TrackRecordChanges) {
|
|
2832
|
-
|
|
2833
|
-
differentialItems.push({
|
|
2834
|
-
index, params: item.params, entityInfo, whereSQL,
|
|
2835
|
-
clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
|
|
2836
|
-
clientRowCount: item.cacheStatus.rowCount,
|
|
2837
|
-
serverStatus,
|
|
2838
|
-
});
|
|
3678
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
2839
3679
|
}
|
|
2840
3680
|
else {
|
|
2841
3681
|
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
|
|
@@ -2847,27 +3687,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2847
3687
|
const noCacheStatusServedFromCache = [];
|
|
2848
3688
|
const noCacheStatusNeedsDB = [];
|
|
2849
3689
|
for (const entry of itemsWithoutCacheCheck) {
|
|
2850
|
-
// A param carrying BypassCache
|
|
3690
|
+
// A param carrying BypassCache (or any cache-ineligible request such as an AlternateBaseView
|
|
3691
|
+
// with CachePolicy === 'Bypass', an unknown/disabled AlternateBaseView, or a view-only request
|
|
3692
|
+
// denied by the read-permission gate) lands here because it is ineligible for a cache status,
|
|
2851
3693
|
// 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 });
|
|
3694
|
+
if (entry.item.params.BypassCache ||
|
|
3695
|
+
!this.runViewCacheEligible(entry.item.params) ||
|
|
3696
|
+
this.cacheDeniedForViewOnlyRequest(entry.item.params, contextUser)) {
|
|
3697
|
+
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — cache ineligible or BypassCache requested, going to the database`, verboseOnly: true });
|
|
2859
3698
|
noCacheStatusNeedsDB.push(entry);
|
|
2860
3699
|
continue;
|
|
2861
3700
|
}
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
const fingerprint =
|
|
3701
|
+
// A saved-view request without an entity name had no Read check above; only the
|
|
3702
|
+
// database leg resolves its entity and checks it, so it never reads the cache here.
|
|
3703
|
+
if (LocalCacheManager.Instance.IsInitialized && !this.cacheDeniedForViewOnlyRequest(entry.item.params, user)) {
|
|
3704
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(entry.item.params, user);
|
|
2866
3705
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
2867
3706
|
if (cached) {
|
|
2868
3707
|
const entityLabel = entry.item.params.EntityName || 'unknown';
|
|
2869
3708
|
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — client has no cache, serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
2870
|
-
noCacheStatusServedFromCache.push({ index: entry.index, serverCached: cached });
|
|
3709
|
+
noCacheStatusServedFromCache.push({ index: entry.index, params: entry.item.params, serverCached: cached });
|
|
2871
3710
|
continue;
|
|
2872
3711
|
}
|
|
2873
3712
|
}
|
|
@@ -2875,14 +3714,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2875
3714
|
}
|
|
2876
3715
|
// Phase 4: Run queries in parallel for items needing data.
|
|
2877
3716
|
// Every leg that returns rows projects them down to the caller's requested
|
|
2878
|
-
// shape (callerFieldsByIndex) — the cache
|
|
3717
|
+
// shape (callerFieldsByIndex) — the cache holds every field the slot's
|
|
3718
|
+
// permission class may read.
|
|
2879
3719
|
const queryPromises = [
|
|
2880
3720
|
// Items without cache check — served from server cache
|
|
2881
|
-
...noCacheStatusServedFromCache.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
3721
|
+
...noCacheStatusServedFromCache.map(({ index, params: viewParams, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, viewParams, user)),
|
|
2882
3722
|
// Items without cache check — server cache miss, must hit DB
|
|
2883
3723
|
...noCacheStatusNeedsDB.map(({ index, item }) => this.runFullQueryAndCacheResult(item.params, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
2884
|
-
// Server cache
|
|
2885
|
-
...serverCacheStaleItems.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
3724
|
+
// Server cache newer than the client, no change tracking — serve from server's cached data (zero DB)
|
|
3725
|
+
...serverCacheStaleItems.map(({ index, item, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, item.params, user)),
|
|
2886
3726
|
// DB-validated stale items (no change tracking)
|
|
2887
3727
|
...staleItemsNoTracking.map(({ index, params: viewParams }) => this.runFullQueryAndCacheResult(viewParams, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
2888
3728
|
// DB-validated differential items
|
|
@@ -2914,8 +3754,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2914
3754
|
// BOTH projections, in this order — they are siblings, not alternatives, and
|
|
2915
3755
|
// `PostRunView` calls them as a pair at all four of its projection points. Applying
|
|
2916
3756
|
// only the first leaves the audit trail leaking: `ApplyFieldSecurityProjection`
|
|
2917
|
-
// short-circuits
|
|
2918
|
-
// `MJ: Record Changes` has
|
|
3757
|
+
// short-circuits when field security does not apply to the RunView entity, and
|
|
3758
|
+
// `MJ: Record Changes` has field security OFF by design, so it is a no-op on exactly the
|
|
2919
3759
|
// rows that matter. The denied values there are INSIDE the `ChangesJSON` /
|
|
2920
3760
|
// `FullRecordJSON` payload columns, which no amount of column stripping reaches —
|
|
2921
3761
|
// `ApplyRecordChangeFieldSecurityProjection` is what projects them against the entity
|
|
@@ -2991,7 +3831,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2991
3831
|
// Free text, not a SQL fragment — deliberately NOT run through
|
|
2992
3832
|
// ValidateUserProvidedSQLClause. See the equivalent note on the view path above (#4392).
|
|
2993
3833
|
if (params.UserSearchString && params.UserSearchString.length > 0) {
|
|
2994
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user);
|
|
3834
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
2995
3835
|
if (sUserSearchSQL.length > 0) {
|
|
2996
3836
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
2997
3837
|
bHasWhere = true;
|
|
@@ -3009,8 +3849,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3009
3849
|
* entity whose view does not carry it, instead of comparing by count alone the way
|
|
3010
3850
|
* `BaseEngine.SweepAgainstDatabase` documents.
|
|
3011
3851
|
*/
|
|
3012
|
-
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
|
|
3013
|
-
const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
3852
|
+
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL, schemaNameOverride) {
|
|
3853
|
+
const from = `FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
3014
3854
|
const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
|
|
3015
3855
|
// `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
|
|
3016
3856
|
// throwing: a freshness check must not be the thing that breaks a sweep.
|
|
@@ -3036,8 +3876,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3036
3876
|
// snapshot cache against an unrelated source, yielding a meaningless current/stale verdict.
|
|
3037
3877
|
// (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
|
|
3038
3878
|
// matches the SQL Server override and is defense-in-depth on the PG/default path.)
|
|
3039
|
-
const
|
|
3040
|
-
const statusSQL = this.BuildCacheStatusSQL(entityInfo,
|
|
3879
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
|
|
3880
|
+
const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveTarget.viewName, whereSQL, effectiveTarget.schemaName);
|
|
3041
3881
|
const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
|
|
3042
3882
|
if (rows && rows.length > 0) {
|
|
3043
3883
|
const row = rows[0];
|
|
@@ -3062,7 +3902,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3062
3902
|
* Runs a full view query and returns results with cache metadata.
|
|
3063
3903
|
*/
|
|
3064
3904
|
async runFullQueryAndReturn(params, viewIndex, contextUser) {
|
|
3065
|
-
|
|
3905
|
+
let result;
|
|
3906
|
+
try {
|
|
3907
|
+
result = await this.InternalRunView({ ...params, PreserveRestrictedApiCiphertext: true }, contextUser);
|
|
3908
|
+
}
|
|
3909
|
+
catch (e) {
|
|
3910
|
+
// A field-security refusal fails this item only, as the up-front gate does on this path.
|
|
3911
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
3912
|
+
return { viewIndex, status: 'error', errorMessage: e.message };
|
|
3913
|
+
}
|
|
3914
|
+
throw e;
|
|
3915
|
+
}
|
|
3066
3916
|
if (!result.Success) {
|
|
3067
3917
|
return { viewIndex, status: 'error', errorMessage: result.ErrorMessage || 'Unknown error executing view' };
|
|
3068
3918
|
}
|
|
@@ -3091,17 +3941,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3091
3941
|
// external source has caching disabled — skip the write to avoid stale data.
|
|
3092
3942
|
const ttlMs = await this.resolveExternalCacheTTLMs(params, contextUser);
|
|
3093
3943
|
if (ttlMs !== 0) {
|
|
3094
|
-
const
|
|
3095
|
-
const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(params);
|
|
3096
|
-
const fingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString, rlsWhereClause, undefined, flsFieldsKey);
|
|
3944
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(params, contextUser);
|
|
3097
3945
|
const maxUpdatedAt = result.maxUpdatedAt || new Date().toISOString();
|
|
3946
|
+
const cacheEntity = this.resolveEntityForRunViewParams(params);
|
|
3098
3947
|
// Pass the aggregates (B38-family omission #4). This slot is ALSO written by
|
|
3099
3948
|
// InternalRunView's normal PostRunView path WITH aggregates — two writers,
|
|
3100
3949
|
// one slot, and this one dropped them. Whichever write landed last won, so a
|
|
3101
3950
|
// later server-cache hit served rows with or without aggregates depending on
|
|
3102
3951
|
// a write race. That is exactly the standalone-passes / aggregator-fails
|
|
3103
3952
|
// flake client-cache C13 exhibited.
|
|
3104
|
-
await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, result.results, maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
|
|
3953
|
+
await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, this.PrepareRowsForCacheStorage(result.results, cacheEntity), maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
|
|
3105
3954
|
}
|
|
3106
3955
|
}
|
|
3107
3956
|
// Project the response down to the caller's requested shape AFTER the
|
|
@@ -3169,7 +4018,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3169
4018
|
* infinite loop / duplicate processing in deep-pagination jobs. Aggregates and a non-empty
|
|
3170
4019
|
* UserSearchString likewise can't be evaluated remotely. Throws a clear error naming the param.
|
|
3171
4020
|
*/
|
|
3172
|
-
assertExternalRunViewParamsSupported(params, entityName) {
|
|
4021
|
+
assertExternalRunViewParamsSupported(params, entityName, viewEntity) {
|
|
4022
|
+
if (this.resolveEffectiveAbvNameFromParams(params, viewEntity)) {
|
|
4023
|
+
throw new Error(`AlternateBaseView is not supported for external-data-source entity '${entityName}'.`);
|
|
4024
|
+
}
|
|
3173
4025
|
if (params.AfterKey) {
|
|
3174
4026
|
throw new Error(`Keyset pagination (AfterKey) is not supported for external-data-source entity '${entityName}'. Use StartRow/MaxRows offset paging instead.`);
|
|
3175
4027
|
}
|
|
@@ -3195,6 +4047,41 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3195
4047
|
throw new Error(`Invalid OrderBy clause for external-data-source entity '${entityName}': contains one or more forbidden keywords.`);
|
|
3196
4048
|
}
|
|
3197
4049
|
}
|
|
4050
|
+
/**
|
|
4051
|
+
* Field-level security on the clauses an external-data-source read hands its driver: the
|
|
4052
|
+
* caller's own, merged with a saved view's stored ones. The same gates the SQL path applies to
|
|
4053
|
+
* the clauses it runs; the external dispatch returns before that path, and the driver runs
|
|
4054
|
+
* the clauses remotely, where nothing else checks them.
|
|
4055
|
+
*/
|
|
4056
|
+
assertExternalClausesRespectFieldSecurity(entityInfo, params, user) {
|
|
4057
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [params.ExtraFilter, params.OverrideExcludeFilter], user);
|
|
4058
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [params.OrderBy], user);
|
|
4059
|
+
}
|
|
4060
|
+
/**
|
|
4061
|
+
* An external driver's rows without the columns `user` may not read. The driver returns the
|
|
4062
|
+
* entity's columns at full width, and the result-path projection resolves the entity only from
|
|
4063
|
+
* an `EntityName` or a loaded `ViewEntity`, so a request naming only a `ViewID` would keep
|
|
4064
|
+
* them: the entity resolved here is named explicitly.
|
|
4065
|
+
*/
|
|
4066
|
+
projectExternalRowsForCaller(rows, entityInfo, params, user) {
|
|
4067
|
+
const entityParams = { ...params, EntityName: entityInfo.Name };
|
|
4068
|
+
const projected = this.ApplyFieldSecurityProjection(rows, entityParams, user);
|
|
4069
|
+
this.carryCiphertextRowsForCache(rows, projected, entityParams, user);
|
|
4070
|
+
return projected;
|
|
4071
|
+
}
|
|
4072
|
+
/**
|
|
4073
|
+
* Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
|
|
4074
|
+
* narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
|
|
4075
|
+
* caller's width instead of finding no copy and falling back to the decrypted rows.
|
|
4076
|
+
*/
|
|
4077
|
+
carryCiphertextRowsForCache(rows, projected, params, user) {
|
|
4078
|
+
if (projected === rows)
|
|
4079
|
+
return;
|
|
4080
|
+
const ciphertextRows = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
|
|
4081
|
+
if (ciphertextRows) {
|
|
4082
|
+
GenericDatabaseProvider._preDecryptionRowsByResult.set(projected, this.ApplyFieldSecurityProjection(ciphertextRows, params, user));
|
|
4083
|
+
}
|
|
4084
|
+
}
|
|
3198
4085
|
/**
|
|
3199
4086
|
* Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
|
|
3200
4087
|
* external dispatch. The external branch returns before the normal SQL path that applies
|
|
@@ -3230,43 +4117,88 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3230
4117
|
}
|
|
3231
4118
|
return merged;
|
|
3232
4119
|
}
|
|
4120
|
+
/**
|
|
4121
|
+
* True when a browser's cache status carries a field-security key (see
|
|
4122
|
+
* `ProviderBase.ComputeFieldSecurityCacheStatusKey`) other than the one this server computes
|
|
4123
|
+
* for `user` and `params`: the browser's slot was filled for a different set of columns, so
|
|
4124
|
+
* its row count and newest timestamp say nothing about whether it is current. False when the
|
|
4125
|
+
* status carries no key.
|
|
4126
|
+
*/
|
|
4127
|
+
cacheStatusFieldSecurityDiffers(status, params, user) {
|
|
4128
|
+
if (status?.fieldSecurityKey == null) {
|
|
4129
|
+
return false; // an older client: no key, no check
|
|
4130
|
+
}
|
|
4131
|
+
return status.fieldSecurityKey !== this.ComputeFieldSecurityCacheStatusKey(params, user);
|
|
4132
|
+
}
|
|
3233
4133
|
/**
|
|
3234
4134
|
* Checks the server's LocalCacheManager for cached data matching the client's request.
|
|
3235
|
-
* Returns the resolution if found (
|
|
3236
|
-
*
|
|
4135
|
+
* Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
|
|
4136
|
+
* 'needs_verification' when the server slot's freshness window has elapsed),
|
|
4137
|
+
* or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
|
|
3237
4138
|
*/
|
|
3238
4139
|
async resolveFromServerCache(item, index, entityLabel, contextUser) {
|
|
3239
4140
|
if (!LocalCacheManager.Instance.IsInitialized)
|
|
3240
4141
|
return null;
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
4142
|
+
if (!this.runViewCacheEligible(item.params) || this.cacheDeniedForViewOnlyRequest(item.params, contextUser)) {
|
|
4143
|
+
return null;
|
|
4144
|
+
}
|
|
4145
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(item.params, contextUser);
|
|
3244
4146
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
3245
4147
|
if (!cached)
|
|
3246
4148
|
return null;
|
|
3247
|
-
|
|
4149
|
+
// 1. Client Monotonicity Guard:
|
|
4150
|
+
// If the client's cacheStatus has a timestamp newer than the server's cached slot,
|
|
4151
|
+
// the server slot is provably stale (e.g., client received a newer write from another
|
|
4152
|
+
// replica or after an out-of-band update). Never serve stale rows backward in time:
|
|
4153
|
+
// evict the server slot immediately and route to Phase 2 DB validation.
|
|
4154
|
+
const clientDate = this.parseClientTimestamp(item.cacheStatus.maxUpdatedAt);
|
|
4155
|
+
const serverCachedDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
4156
|
+
const serverCachedRowCount = cached.totalRowCount ?? cached.rowCount;
|
|
4157
|
+
if (clientDate &&
|
|
4158
|
+
serverCachedDate &&
|
|
4159
|
+
((clientDate.getTime() - serverCachedDate.getTime()) >= 1000 ||
|
|
4160
|
+
(clientDate.getTime() > serverCachedDate.getTime() && item.cacheStatus.rowCount !== serverCachedRowCount))) {
|
|
4161
|
+
LogStatusEx({
|
|
4162
|
+
message: ` ⚠️ [SmartCache MONOTONICITY-EVICT] "${entityLabel}" — client timestamp (${item.cacheStatus.maxUpdatedAt}) is newer than server cache (${cached.maxUpdatedAt}); evicting stale server slot`,
|
|
4163
|
+
verboseOnly: true,
|
|
4164
|
+
});
|
|
4165
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
4166
|
+
return null;
|
|
4167
|
+
}
|
|
4168
|
+
// 2. Bounded Server-Slot Freshness Window:
|
|
4169
|
+
// If the server slot has not been verified against SQL within ServerCacheVerificationTTLMs,
|
|
4170
|
+
// route to Phase 2's batched SQL status check before trusting it.
|
|
4171
|
+
const verifiedAt = cached.lastVerifiedAt ?? cached.cachedAt;
|
|
4172
|
+
const needsVerification = this.ServerCacheVerificationTTLMs <= 0 ||
|
|
4173
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs);
|
|
4174
|
+
if (needsVerification) {
|
|
4175
|
+
LogStatusEx({
|
|
4176
|
+
message: ` ⏱️ [SmartCache VERIFY-TTL] "${entityLabel}" — server cache slot verification TTL expired, routing to batched DB status check`,
|
|
4177
|
+
verboseOnly: true,
|
|
4178
|
+
});
|
|
4179
|
+
return { status: 'needs_verification', serverCached: cached, fingerprint };
|
|
4180
|
+
}
|
|
4181
|
+
const serverStatus = { maxUpdatedAt: cached.maxUpdatedAt, rowCount: serverCachedRowCount };
|
|
3248
4182
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3249
4183
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches server cache, no DB hit`, verboseOnly: true });
|
|
3250
4184
|
return { status: 'current', result: { viewIndex: index, status: 'current' } };
|
|
3251
4185
|
}
|
|
3252
|
-
// Server has newer data than client
|
|
3253
|
-
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
4186
|
+
// Server has newer data than the client; the caller decides between the cached copy and a differential
|
|
3254
4187
|
return { status: 'stale', serverCached: cached };
|
|
3255
4188
|
}
|
|
3256
4189
|
/**
|
|
3257
4190
|
* Packages server-cached data as a RunViewWithCacheCheckResult for return to the client.
|
|
3258
4191
|
*/
|
|
3259
|
-
async serveFromServerCache(viewIndex, serverCached, callerFields = null) {
|
|
3260
|
-
// The server cache stores the
|
|
3261
|
-
//
|
|
3262
|
-
//
|
|
3263
|
-
//
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
// is what actually protects the cache. See ProviderBase's hit path.
|
|
4192
|
+
async serveFromServerCache(viewIndex, serverCached, callerFields = null, viewParams, contextUser) {
|
|
4193
|
+
// The server cache stores every field the slot's permission class may read (with encrypted
|
|
4194
|
+
// fields stored as ciphertext at rest). Materialize allowed API decryptions first, then
|
|
4195
|
+
// project down to the caller's requested fields (∪ PK) before returning, exactly like the
|
|
4196
|
+
// ProviderBase hit path.
|
|
4197
|
+
const cacheEntity = viewParams ? this.resolveEntityForRunViewParams(viewParams) : undefined;
|
|
4198
|
+
const materialized = await this.MaterializeCachedRowsForCaller(serverCached.results, cacheEntity, contextUser, true);
|
|
3267
4199
|
const results = callerFields
|
|
3268
|
-
? ProjectRowsToFields(
|
|
3269
|
-
:
|
|
4200
|
+
? ProjectRowsToFields(materialized, callerFields)
|
|
4201
|
+
: materialized;
|
|
3270
4202
|
return {
|
|
3271
4203
|
viewIndex,
|
|
3272
4204
|
status: 'stale',
|
|
@@ -3283,19 +4215,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3283
4215
|
/**
|
|
3284
4216
|
* Runs a differential query and returns only changes since the client's cached state.
|
|
3285
4217
|
* Includes updated/created rows and deleted record IDs.
|
|
3286
|
-
* Falls back to full query if hidden deletes are detected.
|
|
4218
|
+
* Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
|
|
3287
4219
|
*/
|
|
3288
4220
|
async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null) {
|
|
3289
4221
|
try {
|
|
3290
|
-
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, clientMaxUpdatedAt, whereSQL, contextUser);
|
|
3291
|
-
const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, clientMaxUpdatedAt, contextUser);
|
|
3292
|
-
// Validation: detect hidden deletes not tracked in RecordChanges
|
|
3293
4222
|
const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
|
|
3294
4223
|
if (!clientMaxUpdatedDate) {
|
|
3295
4224
|
// Unparseable client timestamp — can't trust the differential math; fall
|
|
3296
4225
|
// back to a full refresh (cached wide + projected, like every other leg).
|
|
3297
4226
|
return this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
|
|
3298
4227
|
}
|
|
4228
|
+
const since = clientMaxUpdatedDate.toISOString();
|
|
4229
|
+
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser);
|
|
4230
|
+
const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, since, contextUser);
|
|
4231
|
+
// Validation: detect hidden deletes not tracked in RecordChanges
|
|
3299
4232
|
const newInserts = updatedRows.filter(row => {
|
|
3300
4233
|
const createdAt = row['__mj_CreatedAt'];
|
|
3301
4234
|
if (!createdAt)
|
|
@@ -3361,13 +4294,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3361
4294
|
return { viewIndex, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) };
|
|
3362
4295
|
}
|
|
3363
4296
|
}
|
|
4297
|
+
/**
|
|
4298
|
+
* Formats a client timestamp as ISO 8601 for a SQL literal.
|
|
4299
|
+
* Throws when the value is not a date.
|
|
4300
|
+
*/
|
|
4301
|
+
toSQLTimestamp(raw) {
|
|
4302
|
+
const date = this.parseClientTimestamp(raw);
|
|
4303
|
+
if (!date)
|
|
4304
|
+
throw new Error('Client timestamp is not a valid date');
|
|
4305
|
+
return date.toISOString();
|
|
4306
|
+
}
|
|
3364
4307
|
/**
|
|
3365
4308
|
* Gets IDs of records deleted since a given timestamp.
|
|
3366
|
-
* Uses dialect-neutral quoting
|
|
4309
|
+
* Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
|
|
4310
|
+
* Subclasses can override for parameterized queries.
|
|
3367
4311
|
*/
|
|
3368
4312
|
async getDeletedRecordIDsSince(entityID, sinceTimestamp, contextUser) {
|
|
3369
4313
|
try {
|
|
3370
|
-
const
|
|
4314
|
+
const since = this.toSQLTimestamp(sinceTimestamp);
|
|
4315
|
+
const sql = `SELECT DISTINCT ${this.QuoteIdentifier('RecordID')} FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwRecordChanges')} WHERE ${this.QuoteIdentifier('EntityID')} = '${entityID}' AND ${this.QuoteIdentifier('Type')} = 'Delete' AND (${this.QuoteIdentifier('ChangedAt')} > '${since}')`;
|
|
3371
4316
|
const results = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
3372
4317
|
return results.map(r => String(r['RecordID']));
|
|
3373
4318
|
}
|
|
@@ -3378,18 +4323,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3378
4323
|
}
|
|
3379
4324
|
/**
|
|
3380
4325
|
* Gets rows updated/created since a given timestamp.
|
|
3381
|
-
* Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy
|
|
4326
|
+
* Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
|
|
4327
|
+
* timestamp in ISO 8601 form as its own predicate group.
|
|
3382
4328
|
*/
|
|
3383
4329
|
async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser) {
|
|
3384
4330
|
try {
|
|
3385
|
-
const timestampFilter =
|
|
4331
|
+
const timestampFilter = `(${this.QuoteIdentifier('__mj_UpdatedAt')} > '${this.toSQLTimestamp(sinceTimestamp)}')`;
|
|
3386
4332
|
const combinedWhere = whereSQL
|
|
3387
4333
|
? `(${whereSQL}) AND ${timestampFilter}`
|
|
3388
4334
|
: timestampFilter;
|
|
3389
4335
|
const fields = params.Fields && params.Fields.length > 0
|
|
3390
4336
|
? params.Fields.map(f => this.QuoteIdentifier(f)).join(', ')
|
|
3391
4337
|
: '*';
|
|
3392
|
-
|
|
4338
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser);
|
|
4339
|
+
let sql = `SELECT ${fields} FROM ${this.QuoteSchemaAndView(effectiveTarget.schemaName, effectiveTarget.viewName)} WHERE ${combinedWhere}`;
|
|
3393
4340
|
const orderBy = this.TransformExternalSQLClause(params.OrderBy || '', entityInfo);
|
|
3394
4341
|
if (orderBy.length > 0) {
|
|
3395
4342
|
if (!this.ValidateUserProvidedSQLClause(orderBy))
|
|
@@ -3397,7 +4344,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3397
4344
|
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
3398
4345
|
sql += ` ORDER BY ${orderBy}`;
|
|
3399
4346
|
}
|
|
3400
|
-
|
|
4347
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
4348
|
+
const processed = await this.PostProcessRows(rawRows, entityInfo, (contextUser ?? this.CurrentUser), { preserveRestrictedApiCiphertext: true });
|
|
4349
|
+
return processed;
|
|
3401
4350
|
}
|
|
3402
4351
|
catch (e) {
|
|
3403
4352
|
LogError(e);
|
|
@@ -3429,18 +4378,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3429
4378
|
const item = params[i];
|
|
3430
4379
|
const query = this.resolveQuery(item.params);
|
|
3431
4380
|
if (!query) {
|
|
3432
|
-
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage:
|
|
4381
|
+
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params)) });
|
|
3433
4382
|
continue;
|
|
3434
4383
|
}
|
|
3435
|
-
const
|
|
4384
|
+
const definition = this.QueryDefinitionSignatureFor(query);
|
|
4385
|
+
const runCheck = this.authorizeCacheCheckedQuery(query, item, definition, user);
|
|
3436
4386
|
if (!runCheck.canRun) {
|
|
3437
|
-
const
|
|
3438
|
-
|
|
3439
|
-
: '';
|
|
3440
|
-
errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage: `User does not have permission to run query: ${query.Name}.${deniedMsg}` });
|
|
4387
|
+
const errorMessage = runCheck.renderError ?? this.queryRunRefusalMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params));
|
|
4388
|
+
errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage });
|
|
3441
4389
|
continue;
|
|
3442
4390
|
}
|
|
3443
|
-
const definition = this.QueryDefinitionSignatureFor(query);
|
|
3444
4391
|
if (definition) {
|
|
3445
4392
|
definitionHashes.set(i, definition.Hash);
|
|
3446
4393
|
}
|
|
@@ -3504,6 +4451,28 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3504
4451
|
return { success: false, results: [], errorMessage: e instanceof Error ? e.message : String(e) };
|
|
3505
4452
|
}
|
|
3506
4453
|
}
|
|
4454
|
+
/**
|
|
4455
|
+
* The authorization of one {@link RunQueriesWithCacheCheck} item before it is routed. An item
|
|
4456
|
+
* that may be answered "current" without running — it carries a cache status for this
|
|
4457
|
+
* definition and the query has validation SQL — is checked in full on its rendering here. Every
|
|
4458
|
+
* other item runs, and the run checks the rendering it executes, so only the render-free part
|
|
4459
|
+
* is checked here rather than rendering the query twice.
|
|
4460
|
+
*/
|
|
4461
|
+
authorizeCacheCheckedQuery(query, item, definition, user) {
|
|
4462
|
+
const mayAnswerWithoutRunning = !!item.cacheStatus
|
|
4463
|
+
&& !this.clientSlotDefinitionDiffers(item.cacheStatus, definition)
|
|
4464
|
+
&& !!query.CacheValidationSQL;
|
|
4465
|
+
if (mayAnswerWithoutRunning) {
|
|
4466
|
+
return this.authorizeQueryRun(query, item.params.Parameters, user);
|
|
4467
|
+
}
|
|
4468
|
+
const result = query.UserCanRun(user);
|
|
4469
|
+
if (!result.canRun) {
|
|
4470
|
+
// RunQueriesWithCacheCheck short-circuits on !canRun before reaching
|
|
4471
|
+
// runFullQueryAndReturnForQuery, so this refusal would otherwise never log.
|
|
4472
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4473
|
+
}
|
|
4474
|
+
return result;
|
|
4475
|
+
}
|
|
3507
4476
|
/**
|
|
3508
4477
|
* B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
|
|
3509
4478
|
* cache HIT that the miss path enforces. Resolution uses `resolveQuery()` (QueryEngine as
|
|
@@ -3513,6 +4482,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3513
4482
|
* applies before a real execution. The base's roles-only check would let a user read cached
|
|
3514
4483
|
* rows of a query whose underlying entities they cannot read.
|
|
3515
4484
|
*
|
|
4485
|
+
* The run-time checks (`UserCanRunRenderedSQL`: entities read by the SQL itself, and field-level
|
|
4486
|
+
* security) run against the query rendered with the request's own parameters: the SQL the miss
|
|
4487
|
+
* path would check and execute for this slot, since the slot's fingerprint carries those
|
|
4488
|
+
* parameters and its definition hash the query's SQL. A user the miss path would refuse is never
|
|
4489
|
+
* served the slot; a rendering that fails is treated as not authorized, so the request falls
|
|
4490
|
+
* through to execution and gets that path's error.
|
|
4491
|
+
*
|
|
3516
4492
|
* Non-throwing by contract: any resolution error degrades to `resolvable: false`, which the
|
|
3517
4493
|
* gate treats as "fall through to authorized execution" — one extra query run, never an
|
|
3518
4494
|
* unauthorized serve and never a crashed cache path.
|
|
@@ -3523,11 +4499,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3523
4499
|
if (!query) {
|
|
3524
4500
|
return { resolvable: false, authorized: false };
|
|
3525
4501
|
}
|
|
4502
|
+
// Pre-cache probe: a denial here falls through to execution, which logs at its own
|
|
4503
|
+
// gate, so this probe does not log (no duplicate refusal lines on cached runs).
|
|
4504
|
+
const run = user ? this.authorizeQueryRun(query, params.Parameters, user, false) : null;
|
|
3526
4505
|
return {
|
|
3527
4506
|
resolvable: true,
|
|
3528
|
-
authorized: !
|
|
4507
|
+
authorized: !run || run.canRun,
|
|
4508
|
+
// A run that drops denied columns returns rows shaped by the user's denials, so its
|
|
4509
|
+
// slot is the user's field-security segment's alone.
|
|
4510
|
+
fieldSecurityKey: user && run?.needsColumnFiltering ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : undefined,
|
|
3529
4511
|
categoryPath: query.CategoryPath,
|
|
3530
4512
|
queryName: query.Name,
|
|
4513
|
+
contextTokens: this.queryContextTokens(query),
|
|
3531
4514
|
queryId: query.ID,
|
|
3532
4515
|
definition: this.QueryDefinitionSignatureFor(query)
|
|
3533
4516
|
};
|
|
@@ -3608,23 +4591,226 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3608
4591
|
*
|
|
3609
4592
|
* @param query - The resolved MJQueryEntityExtended to validate
|
|
3610
4593
|
* @param contextUser - The user attempting to execute the query
|
|
4594
|
+
* @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
|
|
4595
|
+
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
3611
4596
|
* @throws Error if the user does not have permission to run the query
|
|
3612
4597
|
*/
|
|
3613
|
-
ValidateQueryForExecution(query, contextUser) {
|
|
4598
|
+
ValidateQueryForExecution(query, contextUser, requestedLabel = query.ID) {
|
|
3614
4599
|
const user = contextUser || this.CurrentUser;
|
|
3615
4600
|
if (user) {
|
|
3616
4601
|
const result = query.UserCanRun(user);
|
|
3617
4602
|
if (!result.canRun) {
|
|
3618
|
-
|
|
3619
|
-
|
|
3620
|
-
|
|
3621
|
-
throw new Error(
|
|
4603
|
+
// This gate, not the rendered-SQL one, is where a role-list denial lands: it
|
|
4604
|
+
// short-circuits before any SQL is rendered.
|
|
4605
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4606
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
3622
4607
|
}
|
|
3623
4608
|
}
|
|
3624
4609
|
if (query.Status !== 'Approved') {
|
|
3625
4610
|
LogStatus(`WARNING: Executing query '${query.Name}' (ID: ${query.ID}) with status '${query.Status}'. Query has not been approved.`);
|
|
3626
4611
|
}
|
|
3627
4612
|
}
|
|
4613
|
+
/**
|
|
4614
|
+
* For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
|
|
4615
|
+
* current approval — status Approved and a stored fingerprint equal to the fingerprint of the
|
|
4616
|
+
* definition this run executes. The fingerprint is worked out here, from the same
|
|
4617
|
+
* `QueryEngine` metadata the run renders, never from a caller's value.
|
|
4618
|
+
*
|
|
4619
|
+
* @throws Error naming the first query whose approval is not current
|
|
4620
|
+
*/
|
|
4621
|
+
async ValidateQueryApprovalAsync(query, render) {
|
|
4622
|
+
if (RenderPipeline.HasCompositionTokens(query.GetPlatformSQL(this.PlatformKey)) && !render.HasCompositions) {
|
|
4623
|
+
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.`);
|
|
4624
|
+
}
|
|
4625
|
+
const engine = QueryEngine.Instance;
|
|
4626
|
+
const depsByQueryID = GroupByUUID(engine.Dependencies, d => d.QueryID);
|
|
4627
|
+
const queriesByID = IndexByUUID(engine.Queries);
|
|
4628
|
+
const composedIDs = new UUIDSet(render.CTEs.map(c => c.QueryID));
|
|
4629
|
+
const queue = [query.ID, ...render.CTEs.map(c => c.QueryID)];
|
|
4630
|
+
while (queue.length > 0) {
|
|
4631
|
+
const currentID = queue.shift();
|
|
4632
|
+
for (const dep of depsByQueryID.Get(currentID) ?? []) {
|
|
4633
|
+
if (dep.DependsOnQueryID && !composedIDs.Has(dep.DependsOnQueryID) && !UUIDsEqual(dep.DependsOnQueryID, query.ID)) {
|
|
4634
|
+
composedIDs.Add(dep.DependsOnQueryID);
|
|
4635
|
+
queue.push(dep.DependsOnQueryID);
|
|
4636
|
+
}
|
|
4637
|
+
}
|
|
4638
|
+
}
|
|
4639
|
+
const toVerify = [query];
|
|
4640
|
+
for (const cte of render.CTEs) {
|
|
4641
|
+
const found = queriesByID.Get(cte.QueryID);
|
|
4642
|
+
if (!found) {
|
|
4643
|
+
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.`);
|
|
4644
|
+
}
|
|
4645
|
+
}
|
|
4646
|
+
for (const depID of composedIDs) {
|
|
4647
|
+
const found = queriesByID.Get(depID);
|
|
4648
|
+
if (!found) {
|
|
4649
|
+
throw new Error(`Query dependency (ID: ${depID}) composed by '${query.Name}' is not found in QueryEngine, so its approval cannot be verified.`);
|
|
4650
|
+
}
|
|
4651
|
+
toVerify.push(found);
|
|
4652
|
+
}
|
|
4653
|
+
for (const q of toVerify) {
|
|
4654
|
+
const state = await GetQueryApprovalStateAsync(q);
|
|
4655
|
+
if (state !== 'Current') {
|
|
4656
|
+
const reason = state === 'NotApproved'
|
|
4657
|
+
? `its status is '${q.Status}'`
|
|
4658
|
+
: 'its definition changed after it was approved (or it was approved before approvals were fingerprinted)';
|
|
4659
|
+
throw new Error(`Query '${q.Name}' (ID: ${q.ID}) is not approved in its current form: ${reason}. The run requires an approved query.`);
|
|
4660
|
+
}
|
|
4661
|
+
}
|
|
4662
|
+
}
|
|
4663
|
+
/** The context tokens a query reads, with every query it composes, as the `QueryEngine` holds them. */
|
|
4664
|
+
queryContextTokens(query) {
|
|
4665
|
+
const engine = QueryEngine.Instance;
|
|
4666
|
+
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));
|
|
4667
|
+
}
|
|
4668
|
+
/**
|
|
4669
|
+
* SECURITY — authorizes a saved query against the SQL the run will execute (fully composed and
|
|
4670
|
+
* rendered), after {@link ValidateQueryForExecution} has passed: the entities that SQL reads,
|
|
4671
|
+
* and field-level security on every column it references. A template that injects an
|
|
4672
|
+
* identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
|
|
4673
|
+
* render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
|
|
4674
|
+
*
|
|
4675
|
+
* A refusal reads exactly like the message for a query that does not exist
|
|
4676
|
+
* ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
|
|
4677
|
+
*
|
|
4678
|
+
* @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
|
|
4679
|
+
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
4680
|
+
* @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
|
|
4681
|
+
* `alias.*` that reaches only the output reads an entity the user is denied a field on.
|
|
4682
|
+
* @throws Error when the user may not run this rendering of the query
|
|
4683
|
+
*/
|
|
4684
|
+
ValidateRenderedQueryForExecution(query, renderedSQL, contextUser, requestedLabel = query.ID) {
|
|
4685
|
+
const user = contextUser || this.CurrentUser;
|
|
4686
|
+
if (!user) {
|
|
4687
|
+
return { NeedsColumnFiltering: false };
|
|
4688
|
+
}
|
|
4689
|
+
const result = this.checkRenderedQuery(query, renderedSQL, user);
|
|
4690
|
+
if (!result.canRun) {
|
|
4691
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
4692
|
+
}
|
|
4693
|
+
return { NeedsColumnFiltering: result.needsColumnFiltering === true };
|
|
4694
|
+
}
|
|
4695
|
+
/**
|
|
4696
|
+
* The message for a saved query that does not exist or that the caller may not run. The two
|
|
4697
|
+
* are worded identically, so a refusal does not confirm that the query, or anything it reads,
|
|
4698
|
+
* exists.
|
|
4699
|
+
*
|
|
4700
|
+
* It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
|
|
4701
|
+
* looked up from the resolved query: a refusal of a request by ID that named the query would
|
|
4702
|
+
* both differ from that request's not-found message and disclose the query's name.
|
|
4703
|
+
*
|
|
4704
|
+
* @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
|
|
4705
|
+
*/
|
|
4706
|
+
static QueryUnavailableMessage(label) {
|
|
4707
|
+
return `Query '${label}' does not exist or you do not have permission to run it.`;
|
|
4708
|
+
}
|
|
4709
|
+
/**
|
|
4710
|
+
* The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
|
|
4711
|
+
* name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
|
|
4712
|
+
*/
|
|
4713
|
+
static RequestedQueryLabel(params) {
|
|
4714
|
+
if (params.QueryName) {
|
|
4715
|
+
const path = (params.CategoryPath ?? '').split('/').map(s => s.trim()).filter(s => s.length > 0).join('/');
|
|
4716
|
+
return path ? `${path}/${params.QueryName}` : params.QueryName;
|
|
4717
|
+
}
|
|
4718
|
+
return params.QueryID ?? '';
|
|
4719
|
+
}
|
|
4720
|
+
/** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
|
|
4721
|
+
queryRunRefusalMessage(requestedLabel) {
|
|
4722
|
+
return GenericDatabaseProvider.QueryUnavailableMessage(requestedLabel);
|
|
4723
|
+
}
|
|
4724
|
+
/**
|
|
4725
|
+
* The OPERATOR's record of why a run was refused. The refusal returned to the caller is
|
|
4726
|
+
* {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
|
|
4727
|
+
* that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
|
|
4728
|
+
*
|
|
4729
|
+
* Without it a refusal is unattributable: the query's own role list, SQL the field-security
|
|
4730
|
+
* gate could not read, and a field-security violation all end in the same caller message.
|
|
4731
|
+
*
|
|
4732
|
+
* Previously only the field-security case logged anything, and only at `verboseOnly`, which
|
|
4733
|
+
* CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
|
|
4734
|
+
* bundles refusing together) could not be diagnosed from the logs at all. Called from every
|
|
4735
|
+
* refusal gate, so no path is silent.
|
|
4736
|
+
*
|
|
4737
|
+
* The loaded-role count is here because an empty or undefined `UserRoles` denies every
|
|
4738
|
+
* permission-bearing query at once — exactly the all-or-nothing signature those runs show.
|
|
4739
|
+
* Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
|
|
4740
|
+
* to ask and it costs one integer.
|
|
4741
|
+
*/
|
|
4742
|
+
logQueryRunRefusal(query, user, result) {
|
|
4743
|
+
const v = result.fieldSecurityViolation;
|
|
4744
|
+
const queryRoles = (query.QueryPermissions ?? []).map(p => p.Role).join(', ');
|
|
4745
|
+
const reason = v
|
|
4746
|
+
? `field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''})`
|
|
4747
|
+
: result.deniedEntities.length > 0
|
|
4748
|
+
? `unreadable entities (${result.deniedEntities.join(', ')})`
|
|
4749
|
+
: `the query's own role list (MJ: Query Permissions: [${queryRoles}])`;
|
|
4750
|
+
const userRoles = user.UserRoles
|
|
4751
|
+
? `${user.UserRoles.length} ([${user.UserRoles.map(r => r.Role).join(', ')}])`
|
|
4752
|
+
: 'undefined';
|
|
4753
|
+
LogStatus(`RunQuery: query '${query.Name}' (${query.ID}) refused for user '${user.Email}' by ${reason}. ` +
|
|
4754
|
+
`Roles loaded for this user: ${userRoles}.`);
|
|
4755
|
+
}
|
|
4756
|
+
/**
|
|
4757
|
+
* The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
|
|
4758
|
+
* refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
|
|
4759
|
+
* projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
|
|
4760
|
+
* its denied columns dropped instead of being refused.
|
|
4761
|
+
*/
|
|
4762
|
+
checkRenderedQuery(query, renderedSQL, user, logRefusal = true) {
|
|
4763
|
+
const stars = this.projectionStarOffsets(renderedSQL, user);
|
|
4764
|
+
const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey, stars ? { ProjectionStarOffsets: stars } : undefined);
|
|
4765
|
+
if (!result.canRun && logRefusal) {
|
|
4766
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4767
|
+
}
|
|
4768
|
+
return result;
|
|
4769
|
+
}
|
|
4770
|
+
/** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
|
|
4771
|
+
static { this.projectionStarMemo = new StatementMemo(500); }
|
|
4772
|
+
/**
|
|
4773
|
+
* The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
|
|
4774
|
+
* denied a field on some entity and only when the text holds a `*`; undefined otherwise.
|
|
4775
|
+
*/
|
|
4776
|
+
projectionStarOffsets(renderedSQL, user) {
|
|
4777
|
+
if (!renderedSQL.includes('*') || !FieldSecuritySQLGate.CatalogHasDenialsForUser(this.Entities, user)) {
|
|
4778
|
+
return undefined;
|
|
4779
|
+
}
|
|
4780
|
+
const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
|
|
4781
|
+
return GenericDatabaseProvider.projectionStarMemo.GetOrCompute(key, () => FindProjectionStars(renderedSQL, this.Dialect));
|
|
4782
|
+
}
|
|
4783
|
+
/**
|
|
4784
|
+
* The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
|
|
4785
|
+
* and the run-time checks on the query rendered with `parameters`. A rendering that fails
|
|
4786
|
+
* refuses, carrying the rendering's error.
|
|
4787
|
+
*/
|
|
4788
|
+
authorizeQueryRun(query, parameters, user, logRefusal = true) {
|
|
4789
|
+
const base = query.UserCanRun(user);
|
|
4790
|
+
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
4791
|
+
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
4792
|
+
// already confirmed the user holds one of its roles: nothing to render.
|
|
4793
|
+
if (!base.canRun && logRefusal) {
|
|
4794
|
+
// The batch/cache-checked path returns rather than throws, so this refusal would
|
|
4795
|
+
// otherwise never reach a log at all.
|
|
4796
|
+
this.logQueryRunRefusal(query, user, base);
|
|
4797
|
+
}
|
|
4798
|
+
return base;
|
|
4799
|
+
}
|
|
4800
|
+
let renderedSQL;
|
|
4801
|
+
try {
|
|
4802
|
+
renderedSQL = this.processQueryParameters(query, parameters, user).finalSQL;
|
|
4803
|
+
}
|
|
4804
|
+
catch (e) {
|
|
4805
|
+
return { canRun: false, deniedEntities: [], renderError: e instanceof Error ? e.message : String(e) };
|
|
4806
|
+
}
|
|
4807
|
+
return this.checkRenderedQuery(query, renderedSQL, user, logRefusal);
|
|
4808
|
+
}
|
|
4809
|
+
/** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
|
|
4810
|
+
static roleListGrants(query) {
|
|
4811
|
+
const permissions = query.QueryPermissions;
|
|
4812
|
+
return !!permissions && permissions.length > 0;
|
|
4813
|
+
}
|
|
3628
4814
|
/**
|
|
3629
4815
|
* Resolves a category path string to a QueryCategoryInfo ID.
|
|
3630
4816
|
*/
|
|
@@ -3742,102 +4928,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3742
4928
|
* {@link buildMaterializedReadQuery}).
|
|
3743
4929
|
*/
|
|
3744
4930
|
static { this.MATERIALIZED_SURROGATE_ORDER_COLUMN = '__mj_MaterializedRowID'; }
|
|
3745
|
-
/** Quotes a SQL identifier for the target engine (SQL Server `[x]`, PostgreSQL `"x"`), escaping the closer. */
|
|
3746
|
-
static quoteMaterializedIdentifier(name, isPostgres) {
|
|
3747
|
-
return isPostgres ? `"${name.replace(/"/g, '""')}"` : `[${name.replace(/]/g, ']]')}]`;
|
|
3748
|
-
}
|
|
3749
4931
|
/**
|
|
3750
4932
|
* PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
|
|
3751
4933
|
* output columns, the materialized view (schema + name), the persisted read-filter spec, the caller's
|
|
3752
|
-
* parameter values, and the
|
|
3753
|
-
* predicate as `column <op> <placeholder>` with the value **bound**
|
|
3754
|
-
*
|
|
4934
|
+
* parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
|
|
4935
|
+
* predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
|
|
4936
|
+
* value (SQL-injection-safe by construction).
|
|
4937
|
+
*
|
|
4938
|
+
* With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
|
|
4939
|
+
* a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
|
|
4940
|
+
* placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
|
|
4941
|
+
* varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
|
|
4942
|
+
* Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
|
|
4943
|
+
* ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
|
|
4944
|
+
* dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
|
|
3755
4945
|
*
|
|
3756
4946
|
* Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
|
|
3757
4947
|
* the caller falls back to running live (always correct): an operator outside the safe set, a spec
|
|
3758
4948
|
* parameter the caller did not supply (the live query would apply the param's default), a null value,
|
|
3759
|
-
*
|
|
3760
|
-
|
|
3761
|
-
/**
|
|
3762
|
-
* True if `sql`'s top-level SELECT carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
|
|
3763
|
-
* {@link buildMaterializedReadQuery} emits no ORDER BY and the snapshot is built with the source's top-level
|
|
3764
|
-
* ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and therefore its
|
|
3765
|
-
* pagination under StartRow/MaxRows — is preserved) rather than from the unordered snapshot. Parse failure or
|
|
3766
|
-
* an un-reasoned statement shape returns `true` (refuse-to-live: treat unknown as ordered rather than risk
|
|
3767
|
-
* serving mis-ordered pages). Mirrors MaterializationRefresher.stripTopLevelOrderBy's AST detection.
|
|
3768
|
-
*
|
|
3769
|
-
* @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
|
|
3770
|
-
* `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
|
|
4949
|
+
* an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
|
|
4950
|
+
* known type or a value its type cannot hold. No IO — fully unit-testable.
|
|
3771
4951
|
*/
|
|
3772
|
-
static queryHasTopLevelOrderBy(sql, platformKey) {
|
|
3773
|
-
if (!sql || sql.trim().length === 0)
|
|
3774
|
-
return false;
|
|
3775
|
-
try {
|
|
3776
|
-
const parsed = SQLParser.Astify(sql, GetDialect(platformKey ?? 'sqlserver'));
|
|
3777
|
-
if (!parsed.astParsed || parsed.ast == null)
|
|
3778
|
-
return true; // unparseable → refuse to live
|
|
3779
|
-
const stmtNode = Array.isArray(parsed.ast) ? (parsed.ast.length === 1 ? parsed.ast[0] : null) : parsed.ast;
|
|
3780
|
-
if (stmtNode == null || typeof stmtNode !== 'object')
|
|
3781
|
-
return true;
|
|
3782
|
-
const s = stmtNode;
|
|
3783
|
-
if (s.type !== 'select')
|
|
3784
|
-
return true; // not a simple SELECT we can reason about → refuse to live
|
|
3785
|
-
return s.orderby != null;
|
|
3786
|
-
}
|
|
3787
|
-
catch {
|
|
3788
|
-
return true; // parser threw → refuse to live (safe: served correctly by the live path)
|
|
3789
|
-
}
|
|
3790
|
-
}
|
|
3791
4952
|
static buildMaterializedReadQuery(opts) {
|
|
3792
|
-
const { outputColumns, schemaName, viewName, spec
|
|
4953
|
+
const { outputColumns, schemaName, viewName, spec } = opts;
|
|
3793
4954
|
if (!outputColumns || outputColumns.length === 0)
|
|
3794
4955
|
return null;
|
|
3795
4956
|
if (!spec || spec.length === 0)
|
|
3796
4957
|
return null;
|
|
3797
|
-
const
|
|
3798
|
-
const
|
|
4958
|
+
const dialect = opts.dialect ?? GetDialect(opts.isPostgres ? 'postgresql' : 'sqlserver');
|
|
4959
|
+
const binder = GenericDatabaseProvider.materializedBinder(opts, dialect);
|
|
4960
|
+
// A typed binding converts the value itself, so it takes native forms (a boolean, a UTC ISO date with
|
|
4961
|
+
// its 'Z'); so does an untyped one whose driver binds booleans natively (PostgreSQL). SQL Server's
|
|
4962
|
+
// untyped binding takes BIT 1/0 and a zone-less ISO string.
|
|
4963
|
+
const nativeForms = binder.Typed || (opts.dialect ? typeof dialect.Binding.BooleanParameterValue(true) === 'boolean' : opts.isPostgres === true);
|
|
3799
4964
|
const predicates = [];
|
|
3800
|
-
// Placeholder for the NEXT bound value: SQL Server uses positional `?`; PostgreSQL uses `$n` (1-based,
|
|
3801
|
-
// computed BEFORE the value is pushed so the index aligns with the array position).
|
|
3802
|
-
const nextPlaceholder = () => (isPostgres ? `$${parameters.length + 1}` : '?');
|
|
3803
4965
|
for (const e of spec) {
|
|
3804
|
-
|
|
3805
|
-
|
|
3806
|
-
// (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
|
|
3807
|
-
if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
|
|
4966
|
+
const predicate = GenericDatabaseProvider.materializedPredicate(e, opts, dialect, binder, nativeForms);
|
|
4967
|
+
if (predicate === null)
|
|
3808
4968
|
return null;
|
|
3809
|
-
|
|
3810
|
-
return null;
|
|
3811
|
-
const val = paramValues ? paramValues[e.paramName] : undefined;
|
|
3812
|
-
if (val === undefined || val === null)
|
|
3813
|
-
return null; // caller omitted it → live applies the default
|
|
3814
|
-
const col = q(e.column);
|
|
3815
|
-
const isListOp = e.operator === 'IN' || e.operator === 'NOT IN';
|
|
3816
|
-
if (isListOp) {
|
|
3817
|
-
if (!Array.isArray(val) || val.length === 0)
|
|
3818
|
-
return null; // empty/non-array IN → live
|
|
3819
|
-
const phs = val.map((item) => {
|
|
3820
|
-
const ph = nextPlaceholder();
|
|
3821
|
-
parameters.push(item); // list elements bound as-is (array element type is not declared)
|
|
3822
|
-
return ph;
|
|
3823
|
-
});
|
|
3824
|
-
predicates.push(`${col} ${e.operator} (${phs.join(', ')})`);
|
|
3825
|
-
}
|
|
3826
|
-
else {
|
|
3827
|
-
// Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
|
|
3828
|
-
// Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
|
|
3829
|
-
// which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
|
|
3830
|
-
// than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
|
|
3831
|
-
// aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
|
|
3832
|
-
const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, paramTypes?.[e.paramName], isPostgres);
|
|
3833
|
-
if (!coerced.ok)
|
|
3834
|
-
return null;
|
|
3835
|
-
const ph = nextPlaceholder();
|
|
3836
|
-
parameters.push(coerced.value);
|
|
3837
|
-
predicates.push(`${col} ${e.operator} ${ph}`);
|
|
3838
|
-
}
|
|
4969
|
+
predicates.push(predicate);
|
|
3839
4970
|
}
|
|
3840
|
-
const
|
|
4971
|
+
const q = (name) => dialect.Writer.QuoteIdentifier(name);
|
|
4972
|
+
const cols = outputColumns.map(c => q(c)).join(', ');
|
|
3841
4973
|
// Deterministic page order. A materialized read carries no user ORDER BY (an ordered source query falls
|
|
3842
4974
|
// back to live), so without an explicit order the paging engine would append `ORDER BY (SELECT NULL)` and
|
|
3843
4975
|
// successive pages could skip or duplicate rows whenever the execution plan differs between calls. The
|
|
@@ -3846,7 +4978,90 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3846
4978
|
// buildDataSQL detects this ORDER BY and pages against it instead of the dialect default.
|
|
3847
4979
|
const orderBy = q(GenericDatabaseProvider.MATERIALIZED_SURROGATE_ORDER_COLUMN);
|
|
3848
4980
|
const sql = `SELECT ${cols} FROM ${q(schemaName)}.${q(viewName)} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`;
|
|
3849
|
-
return { sql, parameters };
|
|
4981
|
+
return { sql, parameters: binder.Parameters };
|
|
4982
|
+
}
|
|
4983
|
+
/**
|
|
4984
|
+
* The parameter list one materialized read builds, and how a value joins it: typed by the filtered
|
|
4985
|
+
* column when the snapshot's column types are known, otherwise untyped (the deprecated form).
|
|
4986
|
+
*/
|
|
4987
|
+
static materializedBinder(opts, dialect) {
|
|
4988
|
+
const parameters = [];
|
|
4989
|
+
const types = opts.columnTypes
|
|
4990
|
+
? new Map(Object.entries(opts.columnTypes).map(([name, type]) => [name.toLowerCase(), type]))
|
|
4991
|
+
: null;
|
|
4992
|
+
const untypedPlaceholder = (index) => (opts.isPostgres ? `$${index + 1}` : '?');
|
|
4993
|
+
return {
|
|
4994
|
+
Parameters: parameters,
|
|
4995
|
+
Typed: types !== null,
|
|
4996
|
+
Bind(column, value) {
|
|
4997
|
+
if (types === null && opts.dialect) {
|
|
4998
|
+
return GenericDatabaseProvider.bindNamedParameter(parameters, dialect, value);
|
|
4999
|
+
}
|
|
5000
|
+
if (types === null) {
|
|
5001
|
+
parameters.push(value);
|
|
5002
|
+
return untypedPlaceholder(parameters.length - 1);
|
|
5003
|
+
}
|
|
5004
|
+
const sqlType = types.get(column.toLowerCase());
|
|
5005
|
+
const bound = sqlType === undefined ? undefined : TypedBindValue(value, sqlType);
|
|
5006
|
+
if (sqlType === undefined || bound === undefined)
|
|
5007
|
+
return null;
|
|
5008
|
+
const reference = dialect.Binding.TypedParameter(parameters.length, sqlType);
|
|
5009
|
+
parameters.push(new TypedQueryParameter(reference.Name, sqlType, bound));
|
|
5010
|
+
return reference.Placeholder;
|
|
5011
|
+
},
|
|
5012
|
+
};
|
|
5013
|
+
}
|
|
5014
|
+
/**
|
|
5015
|
+
* Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
|
|
5016
|
+
* it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
|
|
5017
|
+
* provider from rewriting `?` in the statement text, which the legacy positional array form does
|
|
5018
|
+
* everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
|
|
5019
|
+
*/
|
|
5020
|
+
static bindNamedParameter(parameters, dialect, value) {
|
|
5021
|
+
const bound = GenericDatabaseProvider.namedParameterValue(value);
|
|
5022
|
+
if (bound === undefined)
|
|
5023
|
+
return null;
|
|
5024
|
+
const placeholder = dialect.Binding.ParameterPlaceholder(parameters.length);
|
|
5025
|
+
parameters.push(new NamedQueryParameter(placeholder.startsWith('@') ? placeholder.slice(1) : placeholder, bound));
|
|
5026
|
+
return placeholder;
|
|
5027
|
+
}
|
|
5028
|
+
/** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
|
|
5029
|
+
static namedParameterValue(value) {
|
|
5030
|
+
if (value === null || value instanceof Date)
|
|
5031
|
+
return value;
|
|
5032
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
5033
|
+
return value;
|
|
5034
|
+
return undefined;
|
|
5035
|
+
}
|
|
5036
|
+
/** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
|
|
5037
|
+
static materializedPredicate(e, opts, dialect, binder, nativeForms) {
|
|
5038
|
+
// Defensive: the spec is parsed from a persisted JSON string, so validate each element's shape
|
|
5039
|
+
// before use — a malformed element (missing/non-string column/operator/paramName) returns null
|
|
5040
|
+
// (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
|
|
5041
|
+
if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
|
|
5042
|
+
return null;
|
|
5043
|
+
if (!GenericDatabaseProvider.RUNTIME_SAFE_READ_FILTER_OPERATORS.has(e.operator))
|
|
5044
|
+
return null;
|
|
5045
|
+
const val = opts.paramValues ? opts.paramValues[e.paramName] : undefined;
|
|
5046
|
+
if (val === undefined || val === null)
|
|
5047
|
+
return null; // caller omitted it → live applies the default
|
|
5048
|
+
const col = dialect.Writer.QuoteIdentifier(e.column);
|
|
5049
|
+
if (e.operator === 'IN' || e.operator === 'NOT IN') {
|
|
5050
|
+
if (!Array.isArray(val) || val.length === 0)
|
|
5051
|
+
return null; // empty/non-array IN → live
|
|
5052
|
+
const placeholders = val.map(item => binder.Bind(e.column, item));
|
|
5053
|
+
return placeholders.some(p => p === null) ? null : `${col} ${e.operator} (${placeholders.join(', ')})`;
|
|
5054
|
+
}
|
|
5055
|
+
// Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
|
|
5056
|
+
// Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
|
|
5057
|
+
// which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
|
|
5058
|
+
// than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
|
|
5059
|
+
// aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
|
|
5060
|
+
const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, opts.paramTypes?.[e.paramName], nativeForms);
|
|
5061
|
+
if (!coerced.ok)
|
|
5062
|
+
return null;
|
|
5063
|
+
const placeholder = binder.Bind(e.column, coerced.value);
|
|
5064
|
+
return placeholder === null ? null : `${col} ${e.operator} ${placeholder}`;
|
|
3850
5065
|
}
|
|
3851
5066
|
/**
|
|
3852
5067
|
* Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
|
|
@@ -3862,13 +5077,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3862
5077
|
* the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
|
|
3863
5078
|
* - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
|
|
3864
5079
|
* - `boolean` → live truthiness: ONLY 'true' (case-insensitive) or a real boolean `true` is true; everything
|
|
3865
|
-
* else is false (live never refuses a boolean).
|
|
5080
|
+
* else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
|
|
3866
5081
|
* - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
|
|
3867
5082
|
* the naive input string: live applies the local→UTC shift, so binding the raw string would
|
|
3868
|
-
* diverge for any timed value. Invalid date → refuse.
|
|
5083
|
+
* diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
|
|
5084
|
+
* suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
|
|
5085
|
+
* (error 241); the zone-less string is the same UTC wall-clock.
|
|
3869
5086
|
* - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
|
|
5087
|
+
*
|
|
5088
|
+
* @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
|
|
3870
5089
|
*/
|
|
3871
|
-
static coerceMaterializedScalarValue(value, type,
|
|
5090
|
+
static coerceMaterializedScalarValue(value, type, nativeForms) {
|
|
3872
5091
|
switch (type) {
|
|
3873
5092
|
case 'number': {
|
|
3874
5093
|
const n = Number(typeof value === 'string' ? value.trim() : value);
|
|
@@ -3876,19 +5095,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3876
5095
|
}
|
|
3877
5096
|
case 'boolean': {
|
|
3878
5097
|
const b = typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true';
|
|
3879
|
-
return { ok: true, value:
|
|
5098
|
+
return { ok: true, value: nativeForms ? b : b ? 1 : 0 };
|
|
3880
5099
|
}
|
|
3881
5100
|
case 'date': {
|
|
3882
5101
|
const d = value instanceof Date ? value : new Date(String(value));
|
|
3883
5102
|
if (Number.isNaN(d.getTime()))
|
|
3884
5103
|
return { ok: false };
|
|
3885
5104
|
const iso = d.toISOString();
|
|
3886
|
-
|
|
3887
|
-
// for datetimeoffset), so binding it would throw and force a fallback to live. Strip it for SS: the
|
|
3888
|
-
// value is already the UTC moment and a zone-less ISO string binds as that same datetime2 wall-clock,
|
|
3889
|
-
// matching the live path's rendered literal (no row divergence). PostgreSQL's timestamptz accepts
|
|
3890
|
-
// 'Z', so keep it there.
|
|
3891
|
-
return { ok: true, value: isPostgres ? iso : iso.replace(/Z$/, '') };
|
|
5105
|
+
return { ok: true, value: nativeForms ? iso : iso.replace(/Z$/, '') };
|
|
3892
5106
|
}
|
|
3893
5107
|
case 'string':
|
|
3894
5108
|
return { ok: true, value: String(value) };
|
|
@@ -3896,16 +5110,76 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3896
5110
|
return { ok: true, value };
|
|
3897
5111
|
}
|
|
3898
5112
|
}
|
|
5113
|
+
/**
|
|
5114
|
+
* The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
|
|
5115
|
+
* describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
|
|
5116
|
+
* the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
|
|
5117
|
+
* be described (→ live).
|
|
5118
|
+
*/
|
|
5119
|
+
async materializedColumnTypes(mat, contextUser) {
|
|
5120
|
+
const refreshed = mat.LastRefreshedAt instanceof Date ? mat.LastRefreshedAt.toISOString() : String(mat.LastRefreshedAt ?? '');
|
|
5121
|
+
const key = StatementMemo.KeyOf(`${NormalizeUUID(mat.ID)}|${refreshed}|${mat.SchemaName}.${mat.ViewName}`, this.Dialect.Key);
|
|
5122
|
+
const kept = GenericDatabaseProvider.materializedColumnTypeMemo.Get(key);
|
|
5123
|
+
if (kept)
|
|
5124
|
+
return kept;
|
|
5125
|
+
const writer = this.Dialect.Writer;
|
|
5126
|
+
const described = await this.DescribeStatement(`SELECT * FROM ${writer.QuoteIdentifier(mat.SchemaName)}.${writer.QuoteIdentifier(mat.ViewName)}`, contextUser);
|
|
5127
|
+
if (!described.Success) {
|
|
5128
|
+
LogStatusEx({ message: `Materialized read: the column types of ${mat.SchemaName}.${mat.ViewName} could not be read (${described.Diagnostics.join('; ')}) — serving live.`, verboseOnly: true });
|
|
5129
|
+
return null;
|
|
5130
|
+
}
|
|
5131
|
+
const types = {};
|
|
5132
|
+
for (const c of described.Columns)
|
|
5133
|
+
types[c.Name.toLowerCase()] = c.SQLFullType;
|
|
5134
|
+
GenericDatabaseProvider.materializedColumnTypeMemo.Set(key, types);
|
|
5135
|
+
return types;
|
|
5136
|
+
}
|
|
5137
|
+
/** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
|
|
5138
|
+
static { this.materializedColumnTypeMemo = new StatementMemo(500); }
|
|
5139
|
+
/** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
|
|
5140
|
+
static { this.topLevelOrderByMemo = new StatementMemo(1000); }
|
|
5141
|
+
/**
|
|
5142
|
+
* True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
|
|
5143
|
+
* {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
|
|
5144
|
+
* source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
|
|
5145
|
+
* therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
|
|
5146
|
+
* `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
|
|
5147
|
+
* (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
|
|
5148
|
+
* (SQL, dialect) in a bounded memo.
|
|
5149
|
+
*
|
|
5150
|
+
* @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
|
|
5151
|
+
* `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
|
|
5152
|
+
*/
|
|
5153
|
+
static queryHasTopLevelOrderBy(sql, platformKey) {
|
|
5154
|
+
if (!sql || sql.trim().length === 0)
|
|
5155
|
+
return false;
|
|
5156
|
+
const dialect = GetDialect(platformKey ?? 'sqlserver');
|
|
5157
|
+
return GenericDatabaseProvider.topLevelOrderByMemo.GetOrCompute(StatementMemo.KeyOf(sql, dialect.Key), () => {
|
|
5158
|
+
const doc = SqlDocument.Parse(sql, dialect);
|
|
5159
|
+
if (doc.TopLevelQuery() === null || doc.HasStackedStatements().Value)
|
|
5160
|
+
return true;
|
|
5161
|
+
const orderBy = doc.TopLevelOrderBy();
|
|
5162
|
+
return !orderBy.Complete || orderBy.Value !== null;
|
|
5163
|
+
});
|
|
5164
|
+
}
|
|
3899
5165
|
/**
|
|
3900
5166
|
* Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
|
|
3901
5167
|
* `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
|
|
3902
5168
|
* persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
|
|
3903
5169
|
* the live query (serving live is always correct — this is a transparent optimization, never a
|
|
3904
5170
|
* correctness dependency).
|
|
5171
|
+
*
|
|
5172
|
+
* @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
|
|
5173
|
+
* check reads it; without it the check reads the platform SQL, where template syntax makes any
|
|
5174
|
+
* template query read as ordered (→ live).
|
|
3905
5175
|
*/
|
|
3906
|
-
async tryBuildMaterializedQueryPlan(query, params, contextUser) {
|
|
5176
|
+
async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues, renderedSQL) {
|
|
3907
5177
|
if (!IsMaterializedDataSource(params.DataSource))
|
|
3908
5178
|
return null; // not opted in → live
|
|
5179
|
+
// A snapshot is shared by every caller and was built without this caller's Context (user, date), so a
|
|
5180
|
+
// run whose template read Context is served live: its rows depend on who runs it and when.
|
|
5181
|
+
if (contextValues && Object.keys(contextValues).length > 0)
|
|
5182
|
+
return null;
|
|
3909
5183
|
if (query.ExternalDataSourceID)
|
|
3910
5184
|
return null; // external source → materialized table is local; live
|
|
3911
5185
|
// The query<->materialization link lives in the MaterializedResultQuery join table — there is no
|
|
@@ -3919,6 +5193,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3919
5193
|
Fields: ['MaterializedResultID'],
|
|
3920
5194
|
ResultType: 'simple',
|
|
3921
5195
|
MaxRows: 1,
|
|
5196
|
+
SkipTotalRowCount: true,
|
|
3922
5197
|
}, contextUser);
|
|
3923
5198
|
// Same failure-vs-absence distinction as the base-view path: a permission/query failure here would
|
|
3924
5199
|
// otherwise be indistinguishable from "this query is not materialized", silently pinning the caller to
|
|
@@ -3934,10 +5209,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3934
5209
|
// source's top-level ORDER BY stripped (it has no inherent order). A query that carries a top-level ORDER
|
|
3935
5210
|
// BY would therefore page differently from the live query. Refuse → live (which preserves the ordering)
|
|
3936
5211
|
// rather than serve a divergent page order — consistent with this method's "any uncertainty → live".
|
|
3937
|
-
// Check the
|
|
3938
|
-
//
|
|
5212
|
+
// Check the SQL the live path executes: the rendered statement when the caller has it (a template decides
|
|
5213
|
+
// its ORDER BY only when it renders, and the structural reader does not read template syntax, so the
|
|
5214
|
+
// template text of every template query would read as ordered), otherwise the PLATFORM-resolved SQL — not
|
|
5215
|
+
// the base query.SQL: a per-platform QuerySQL variant (e.g. a PostgreSQL variant) may add a top-level
|
|
3939
5216
|
// ORDER BY the base SQL lacks, and parsing the base SQL would miss it and serve mis-ordered snapshot pages.
|
|
3940
|
-
|
|
5217
|
+
const orderingSQL = renderedSQL ?? query.GetPlatformSQL(this.PlatformKey) ?? '';
|
|
5218
|
+
if (GenericDatabaseProvider.queryHasTopLevelOrderBy(orderingSQL, this.PlatformKey))
|
|
3941
5219
|
return null;
|
|
3942
5220
|
// Load the materialization metadata. matId is our own UUID (from committed metadata), so it is safe
|
|
3943
5221
|
// to interpolate into ExtraFilter — it never carries caller input.
|
|
@@ -3950,9 +5228,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3950
5228
|
const res = await rv.RunView({
|
|
3951
5229
|
EntityName: 'MJ: Materialized Results',
|
|
3952
5230
|
ExtraFilter: `ID='${matId}'`,
|
|
3953
|
-
Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName'],
|
|
5231
|
+
Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName', 'LastRefreshedAt'],
|
|
3954
5232
|
ResultType: 'simple',
|
|
3955
5233
|
MaxRows: 1,
|
|
5234
|
+
SkipTotalRowCount: true,
|
|
3956
5235
|
BypassCache: true,
|
|
3957
5236
|
}, contextUser);
|
|
3958
5237
|
if (this.MaterializationLookupFailed(res, `query "${query.Name}" (materialization metadata)`))
|
|
@@ -3995,35 +5274,72 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3995
5274
|
const paramTypes = {};
|
|
3996
5275
|
for (const p of query.QueryParameters ?? [])
|
|
3997
5276
|
paramTypes[p.Name] = p.Type;
|
|
5277
|
+
// Each value binds with the type of the snapshot column it is compared with (read once per refresh;
|
|
5278
|
+
// the status read above stays uncached). Unknown types → live.
|
|
5279
|
+
const columnTypes = await this.materializedColumnTypes({ ID: matId, SchemaName: mat.SchemaName, ViewName: mat.ViewName, LastRefreshedAt: mat.LastRefreshedAt ?? null }, contextUser);
|
|
5280
|
+
if (!columnTypes)
|
|
5281
|
+
return null;
|
|
3998
5282
|
return GenericDatabaseProvider.buildMaterializedReadQuery({
|
|
3999
5283
|
outputColumns,
|
|
4000
5284
|
schemaName: mat.SchemaName,
|
|
4001
5285
|
viewName: mat.ViewName,
|
|
4002
5286
|
spec,
|
|
4003
|
-
|
|
5287
|
+
// Server-set parameters take their values from ServerParameters (a caller value for one was
|
|
5288
|
+
// already refused when the template rendered), so the row filter sees both.
|
|
5289
|
+
paramValues: params.ServerParameters ? { ...params.Parameters, ...params.ServerParameters } : params.Parameters,
|
|
4004
5290
|
paramTypes,
|
|
4005
|
-
|
|
5291
|
+
dialect: this.Dialect,
|
|
5292
|
+
columnTypes,
|
|
4006
5293
|
});
|
|
4007
5294
|
}
|
|
4008
5295
|
async InternalRunQuery(params, contextUser) {
|
|
4009
5296
|
// Route ad-hoc SQL queries to dedicated handler
|
|
4010
5297
|
if (params.SQL) {
|
|
5298
|
+
if (params.RequireApproved) {
|
|
5299
|
+
return {
|
|
5300
|
+
Success: false,
|
|
5301
|
+
QueryID: '',
|
|
5302
|
+
QueryName: 'Ad-Hoc Query',
|
|
5303
|
+
Results: [],
|
|
5304
|
+
RowCount: 0,
|
|
5305
|
+
TotalRowCount: 0,
|
|
5306
|
+
ExecutionTime: 0,
|
|
5307
|
+
ErrorMessage: 'Ad-hoc SQL has no approved query definition and cannot run when RequireApproved is set.',
|
|
5308
|
+
};
|
|
5309
|
+
}
|
|
4011
5310
|
return this.ExecuteAdhocQuery(params, contextUser);
|
|
4012
5311
|
}
|
|
4013
5312
|
let finalSQL;
|
|
4014
5313
|
try {
|
|
4015
5314
|
// Find and validate query
|
|
4016
5315
|
const query = this.findAndValidateQuery(params, contextUser);
|
|
4017
|
-
|
|
4018
|
-
|
|
5316
|
+
const requestedLabel = GenericDatabaseProvider.RequestedQueryLabel(params);
|
|
5317
|
+
// Process parameters (composition + Nunjucks templates). A query on an external data source
|
|
5318
|
+
// renders its values with that source's dialect, so its literals read as the remote database reads them.
|
|
5319
|
+
const dialectKey = query.ExternalDataSourceID ? await this.externalQueryDialectKey(query, contextUser) : undefined;
|
|
5320
|
+
const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params, dialectKey);
|
|
4019
5321
|
finalSQL = resolved.finalSQL;
|
|
4020
5322
|
const appliedParameters = resolved.appliedParameters;
|
|
5323
|
+
// Opt-in: the approval must be current for the definition about to run
|
|
5324
|
+
if (params.RequireApproved) {
|
|
5325
|
+
await this.ValidateQueryApprovalAsync(query, resolved.renderResult);
|
|
5326
|
+
}
|
|
5327
|
+
// Authorize what will actually run, before any cache, materialized or external read.
|
|
5328
|
+
const authorization = this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser, requestedLabel);
|
|
5329
|
+
// A projection star over an entity the user is denied a field on: the run drops the denied
|
|
5330
|
+
// columns, chosen by the database's description of the statement. An external source's
|
|
5331
|
+
// statement cannot be described here, so such a run is refused.
|
|
5332
|
+
if (authorization.NeedsColumnFiltering && query.ExternalDataSourceID) {
|
|
5333
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5334
|
+
}
|
|
5335
|
+
const columnFilter = authorization.NeedsColumnFiltering ? await this.queryColumnFilter(query, finalSQL, requestedLabel, contextUser) : null;
|
|
5336
|
+
const cacheSlot = this.queryResultCacheSlot(query, finalSQL, authorization.NeedsColumnFiltering, contextUser);
|
|
4021
5337
|
// ── Phase 2: materialized read redirect (plan §5) ──
|
|
4022
5338
|
// If the caller opted into DataSource:'Materialized' and this query has a fresh, Active
|
|
4023
5339
|
// RowFilterBroad materialization, serve from the materialized table with the row-filter params
|
|
4024
5340
|
// injected as BOUND predicates. On ANY uncertainty tryBuildMaterializedQueryPlan returns null and
|
|
4025
5341
|
// 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);
|
|
5342
|
+
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues, finalSQL);
|
|
4027
5343
|
if (matPlan) {
|
|
4028
5344
|
// Use a LOCAL for the materialized SQL — never overwrite `finalSQL` (which stays the
|
|
4029
5345
|
// live-rendered SQL), so a fallback below runs the live path unchanged.
|
|
@@ -4064,6 +5380,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4064
5380
|
rows = paginated.paginatedResult;
|
|
4065
5381
|
matTotalRowCount = paginated.totalRowCount;
|
|
4066
5382
|
}
|
|
5383
|
+
rows = this.filterQueryRows(rows, columnFilter);
|
|
4067
5384
|
if (params.Enrichment?.EnricherKey) {
|
|
4068
5385
|
rows = await this.enrichQueryResults(rows, params, query, contextUser);
|
|
4069
5386
|
}
|
|
@@ -4110,7 +5427,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4110
5427
|
// credential should be least-privilege). Do not assume EDS RLS covers the Query path.
|
|
4111
5428
|
if (query.ExternalDataSourceID) {
|
|
4112
5429
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
|
|
4113
|
-
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser);
|
|
5430
|
+
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser, resolved.renderResult.ContextValues);
|
|
4114
5431
|
}
|
|
4115
5432
|
// Execute query — use SQL-level paging when requested, else fetch all rows
|
|
4116
5433
|
const useSQLPaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
|
|
@@ -4119,10 +5436,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4119
5436
|
let executionTime;
|
|
4120
5437
|
let fullResult;
|
|
4121
5438
|
if (useSQLPaging) {
|
|
5439
|
+
// The paging wrapper may order by output position (`ORDER BY 1` on PostgreSQL); a page ordered
|
|
5440
|
+
// by a column the caller is denied would reveal how its values rank, so such a run is refused.
|
|
5441
|
+
if (columnFilter && columnFilter.Columns.length > 0 && columnFilter.Withheld.has(columnFilter.Columns[0].Name)) {
|
|
5442
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5443
|
+
}
|
|
4122
5444
|
// Check paged cache before executing SQL
|
|
4123
|
-
const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters);
|
|
5445
|
+
const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters, cacheSlot.PageKey(params));
|
|
4124
5446
|
if (pagedCacheHit) {
|
|
4125
|
-
return pagedCacheHit;
|
|
5447
|
+
return { ...pagedCacheHit, Results: this.filterQueryRows(pagedCacheHit.Results, columnFilter) };
|
|
4126
5448
|
}
|
|
4127
5449
|
const paging = QueryPagingEngine.WrapWithPaging(finalSQL, QueryPagingEngine.ResolveStartRow(params.StartRow), params.MaxRows, this.PlatformKey);
|
|
4128
5450
|
// Execute data + count queries in parallel
|
|
@@ -4134,27 +5456,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4134
5456
|
executionTime = Date.now() - start;
|
|
4135
5457
|
if (!dataResult)
|
|
4136
5458
|
throw new Error('Error executing paged query SQL');
|
|
4137
|
-
|
|
4138
|
-
this.
|
|
5459
|
+
this.ConvertByteArrayValuesToBase64(dataResult);
|
|
5460
|
+
paginatedResult = this.filterQueryRows(dataResult, columnFilter);
|
|
4139
5461
|
totalRowCount = countResult?.[0]?.TotalRowCount != null
|
|
4140
5462
|
? Number(countResult[0].TotalRowCount)
|
|
4141
5463
|
: paginatedResult.length;
|
|
4142
5464
|
}
|
|
4143
5465
|
else {
|
|
4144
5466
|
// Check full-result cache before executing
|
|
4145
|
-
const cachedResult = await this.checkQueryCache(query, params, appliedParameters);
|
|
5467
|
+
const cachedResult = await this.checkQueryCache(query, params, appliedParameters, cacheSlot.Key);
|
|
4146
5468
|
if (cachedResult) {
|
|
4147
|
-
return cachedResult;
|
|
5469
|
+
return { ...cachedResult, Results: this.filterQueryRows(cachedResult.Results, columnFilter) };
|
|
4148
5470
|
}
|
|
4149
5471
|
// No paging requested — execute full query, apply in-memory pagination as fallback
|
|
4150
5472
|
const timing = await this.executeQueryWithTiming(finalSQL, contextUser);
|
|
4151
5473
|
executionTime = timing.executionTime;
|
|
4152
5474
|
fullResult = timing.result;
|
|
4153
5475
|
const paginated = this.applyQueryPagination(fullResult, params);
|
|
4154
|
-
paginatedResult = paginated.paginatedResult;
|
|
5476
|
+
paginatedResult = this.filterQueryRows(paginated.paginatedResult, columnFilter);
|
|
4155
5477
|
totalRowCount = paginated.totalRowCount;
|
|
4156
5478
|
// Cache full (unpaginated) results if enabled (fire-and-forget)
|
|
4157
|
-
void this.cacheQueryResults(query, params.Parameters || {}, fullResult);
|
|
5479
|
+
void this.cacheQueryResults(query, params.Parameters || {}, fullResult, cacheSlot.Key);
|
|
4158
5480
|
}
|
|
4159
5481
|
// Optional, additive post-query enrichment (e.g. append an ML prediction
|
|
4160
5482
|
// column). Awaited so the appended columns are present in the response.
|
|
@@ -4204,6 +5526,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4204
5526
|
};
|
|
4205
5527
|
}
|
|
4206
5528
|
}
|
|
5529
|
+
/** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
|
|
5530
|
+
static { this.describedStatementMemo = new StatementMemo(500, 10 * 60 * 1000); }
|
|
5531
|
+
/**
|
|
5532
|
+
* Describes the result set of `sql` without returning its rows: each output column's name,
|
|
5533
|
+
* position, exact type, nullability and, for a pass-through column, the table or view column it
|
|
5534
|
+
* comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
|
|
5535
|
+
* runs it under `LIMIT 0` in a transaction that is rolled back).
|
|
5536
|
+
*
|
|
5537
|
+
* This base implementation describes nothing: it reports a failure. Providers for a database
|
|
5538
|
+
* that can describe a statement override it.
|
|
5539
|
+
*
|
|
5540
|
+
* @param sql - The rendered statement, in this provider's dialect.
|
|
5541
|
+
* @param _contextUser - The user the description is for.
|
|
5542
|
+
*/
|
|
5543
|
+
async DescribeStatement(sql, _contextUser) {
|
|
5544
|
+
return DescribeStatementFailure(`${this.constructor.name} cannot describe a statement.`);
|
|
5545
|
+
}
|
|
5546
|
+
/**
|
|
5547
|
+
* SECURITY — the output columns of `renderedSQL` that `user` must not receive
|
|
5548
|
+
* ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
|
|
5549
|
+
*
|
|
5550
|
+
* @throws Error with the refusal message when the statement cannot be described: without the
|
|
5551
|
+
* description no column can be shown to be safe, so the run is refused.
|
|
5552
|
+
*/
|
|
5553
|
+
async queryColumnFilter(query, renderedSQL, requestedLabel, contextUser) {
|
|
5554
|
+
const user = contextUser || this.CurrentUser;
|
|
5555
|
+
const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
|
|
5556
|
+
let columns = GenericDatabaseProvider.describedStatementMemo.Get(key);
|
|
5557
|
+
if (!columns) {
|
|
5558
|
+
const described = await this.DescribeStatement(renderedSQL, user);
|
|
5559
|
+
if (!described.Success) {
|
|
5560
|
+
LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}': its columns could not be described for field-level security (${described.Diagnostics.join('; ')}).`, verboseOnly: true });
|
|
5561
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5562
|
+
}
|
|
5563
|
+
columns = described.Columns;
|
|
5564
|
+
GenericDatabaseProvider.describedStatementMemo.Set(key, columns);
|
|
5565
|
+
}
|
|
5566
|
+
const readEntities = [...(FieldSecuritySQLGate.RelationEntities(renderedSQL, this.Entities, this.PlatformKey) ?? []), ...this.declaredQueryEntities(query)];
|
|
5567
|
+
return { Key: key, Columns: columns, Withheld: WithheldColumnNames(columns, this.Entities, readEntities, user) };
|
|
5568
|
+
}
|
|
5569
|
+
/** The catalog entities `query`'s `QueryEntities` rows name. */
|
|
5570
|
+
declaredQueryEntities(query) {
|
|
5571
|
+
const byID = IndexByUUID(this.Entities);
|
|
5572
|
+
return (query.QueryEntities ?? []).map(qe => byID.Get(qe.EntityID)).filter((e) => !!e);
|
|
5573
|
+
}
|
|
5574
|
+
/**
|
|
5575
|
+
* `rows` with the filter's withheld columns dropped, as new row objects. A column the
|
|
5576
|
+
* description does not list is dropped too, and the description is forgotten: the statement's
|
|
5577
|
+
* shape changed since it was described (a view redefined), so the next run describes it again.
|
|
5578
|
+
*/
|
|
5579
|
+
filterQueryRows(rows, filter) {
|
|
5580
|
+
if (!filter || rows.length === 0)
|
|
5581
|
+
return rows;
|
|
5582
|
+
const undescribed = UndescribedColumnNames(rows, filter.Columns);
|
|
5583
|
+
if (undescribed.size > 0) {
|
|
5584
|
+
GenericDatabaseProvider.describedStatementMemo.Delete(filter.Key);
|
|
5585
|
+
}
|
|
5586
|
+
return WithholdColumns(rows, undescribed.size > 0 ? new Set([...filter.Withheld, ...undescribed]) : filter.Withheld);
|
|
5587
|
+
}
|
|
4207
5588
|
/**
|
|
4208
5589
|
* Batch query execution — runs all queries in parallel.
|
|
4209
5590
|
*/
|
|
@@ -4276,6 +5657,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4276
5657
|
RequireReadStatement: true,
|
|
4277
5658
|
...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
|
|
4278
5659
|
});
|
|
5660
|
+
this.AssertAdhocReadAllowed(rendered.Trace.AfterTemplates, contextUser);
|
|
4279
5661
|
const options = this.adhocSQLOptions(params);
|
|
4280
5662
|
if (!usePaging) {
|
|
4281
5663
|
const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
|
|
@@ -4290,6 +5672,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4290
5672
|
const rows = dataResult ?? [];
|
|
4291
5673
|
return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
|
|
4292
5674
|
}
|
|
5675
|
+
/**
|
|
5676
|
+
* SECURITY — what ad-hoc SQL may read, checked in the provider so that every in-process caller
|
|
5677
|
+
* (agents, data contexts, actions) is covered, not only the API's resolvers. `sql` is the
|
|
5678
|
+
* rendered statement, before the server's own paging wrap. Every table it reads must be an
|
|
5679
|
+
* entity base view the caller can read unscoped: CanRead with no row-level filter and no denied
|
|
5680
|
+
* field, because raw SQL applies neither ({@link ClientClauseScreen.AssertStatementReadsUnscopedEntityViews}).
|
|
5681
|
+
* The system user runs the server's own SQL and is not checked, but only when passed
|
|
5682
|
+
* explicitly: no user at all refuses, rather than falling back to the provider's own user,
|
|
5683
|
+
* which on a server is the system user.
|
|
5684
|
+
*
|
|
5685
|
+
* @throws Error when the caller may not run `sql`
|
|
5686
|
+
*/
|
|
5687
|
+
AssertAdhocReadAllowed(sql, contextUser) {
|
|
5688
|
+
if (!contextUser) {
|
|
5689
|
+
throw new Error('Invalid ad-hoc SQL: no acting user was passed — refusing');
|
|
5690
|
+
}
|
|
5691
|
+
if (IsSystemUser(contextUser)) {
|
|
5692
|
+
return;
|
|
5693
|
+
}
|
|
5694
|
+
ClientClauseScreen.AssertStatementReadsUnscopedEntityViews(sql, this.Entities, ClientClauseScreen.DialectFor(this), contextUser, 'ad-hoc SQL');
|
|
5695
|
+
}
|
|
4293
5696
|
/**
|
|
4294
5697
|
* The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
|
|
4295
5698
|
* fails does not fail the run: some queries page fine but cannot be counted (duplicate column
|
|
@@ -4331,22 +5734,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4331
5734
|
findAndValidateQuery(params, contextUser) {
|
|
4332
5735
|
const query = this.resolveQuery(params);
|
|
4333
5736
|
if (!query) {
|
|
4334
|
-
|
|
4335
|
-
|
|
4336
|
-
errorDetails = `Query '${params.QueryName}' not found`;
|
|
4337
|
-
if (params.CategoryPath) {
|
|
4338
|
-
errorDetails += ` in category path '${params.CategoryPath}'`;
|
|
4339
|
-
}
|
|
4340
|
-
else if (params.CategoryID) {
|
|
4341
|
-
errorDetails += ` in category ID '${params.CategoryID}'`;
|
|
4342
|
-
}
|
|
4343
|
-
}
|
|
4344
|
-
else if (params.QueryID) {
|
|
4345
|
-
errorDetails = `Query with ID '${params.QueryID}' not found`;
|
|
4346
|
-
}
|
|
4347
|
-
throw new Error(errorDetails);
|
|
5737
|
+
// Worded exactly as a refusal (QueryUnavailableMessage), so neither confirms the query exists.
|
|
5738
|
+
throw new Error(GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(params)));
|
|
4348
5739
|
}
|
|
4349
|
-
this.ValidateQueryForExecution(query, contextUser);
|
|
5740
|
+
this.ValidateQueryForExecution(query, contextUser, GenericDatabaseProvider.RequestedQueryLabel(params));
|
|
4350
5741
|
return query;
|
|
4351
5742
|
}
|
|
4352
5743
|
/**
|
|
@@ -4355,12 +5746,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4355
5746
|
*
|
|
4356
5747
|
* Delegates to {@link RenderPipeline.Run} for the composition → template
|
|
4357
5748
|
* pipeline. Paging is handled separately by the caller (InternalRunQuery).
|
|
5749
|
+
*
|
|
5750
|
+
* @param dialectKey - The dialect the template's values render for (`sqlString` literals,
|
|
5751
|
+
* booleans); this provider's platform when omitted. An external data source's query passes
|
|
5752
|
+
* the source's dialect.
|
|
4358
5753
|
*/
|
|
4359
|
-
processQueryParameters(query, parameters, contextUser) {
|
|
5754
|
+
processQueryParameters(query, parameters, contextUser, serverSet, dialectKey) {
|
|
4360
5755
|
const result = RenderPipeline.Run(query.GetPlatformSQL(this.PlatformKey), {
|
|
4361
5756
|
Platform: this.PlatformKey,
|
|
4362
|
-
|
|
5757
|
+
DialectKey: dialectKey,
|
|
5758
|
+
QueryID: query.ID,
|
|
5759
|
+
QueryName: query.Name,
|
|
5760
|
+
ContextUser: contextUser ?? this.CurrentUser,
|
|
4363
5761
|
Parameters: parameters,
|
|
5762
|
+
ServerParameters: serverSet?.ServerParameters,
|
|
5763
|
+
TimeZone: serverSet?.TimeZone,
|
|
4364
5764
|
UsesTemplate: query.UsesTemplate ?? false,
|
|
4365
5765
|
QueryInfo: {
|
|
4366
5766
|
SQL: query.SQL ?? '',
|
|
@@ -4373,6 +5773,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4373
5773
|
}
|
|
4374
5774
|
return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
|
|
4375
5775
|
}
|
|
5776
|
+
/**
|
|
5777
|
+
* The dialect key of the external data source `query` reads, so its template values render as
|
|
5778
|
+
* that database reads literals; undefined when the source has no SQL dialect (a document
|
|
5779
|
+
* store), in which case the query renders with this provider's platform as before.
|
|
5780
|
+
*/
|
|
5781
|
+
async externalQueryDialectKey(query, contextUser) {
|
|
5782
|
+
const router = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
|
|
5783
|
+
const key = await router.GetQueryDialectKey(query.ExternalDataSourceID, contextUser, this);
|
|
5784
|
+
return key ?? undefined;
|
|
5785
|
+
}
|
|
4376
5786
|
/**
|
|
4377
5787
|
* Checks the columns an external-data-source query returned against the fields the Query
|
|
4378
5788
|
* *declares* (its QueryField metadata) and logs a warning naming any declared field that
|
|
@@ -4395,10 +5805,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4395
5805
|
* truth (a TTL of <= 0 disables caching for the source); field-drift warnings still apply to
|
|
4396
5806
|
* freshly-fetched rows. Ad-hoc SQL (params.SQL) is never cached.
|
|
4397
5807
|
*/
|
|
4398
|
-
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser) {
|
|
5808
|
+
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser, contextValues) {
|
|
4399
5809
|
const externalDataSourceID = query.ExternalDataSourceID;
|
|
4400
5810
|
const ttlSeconds = await router.GetCacheTTLSeconds(externalDataSourceID, contextUser, this);
|
|
4401
|
-
|
|
5811
|
+
// A result that read Context.Now depends on the instant it ran and is never reused.
|
|
5812
|
+
const cacheable = !params.SQL && ttlSeconds > 0 && LocalCacheManager.Instance.IsInitialized && !(contextValues && 'Now' in contextValues);
|
|
4402
5813
|
let fingerprint;
|
|
4403
5814
|
let definition;
|
|
4404
5815
|
if (cacheable) {
|
|
@@ -4408,6 +5819,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4408
5819
|
__maxRows: params.MaxRows ?? -1,
|
|
4409
5820
|
__startRow: params.StartRow ?? 0,
|
|
4410
5821
|
__eds: externalDataSourceID,
|
|
5822
|
+
// What the server set shapes the result too, so one user's slot never answers another's.
|
|
5823
|
+
...this.serverSetFingerprintSegment(params, contextValues),
|
|
4411
5824
|
};
|
|
4412
5825
|
fingerprint = LocalCacheManager.Instance.GenerateRunQueryFingerprint(query.ID, query.Name, fingerprintParams, this.InstanceConnectionString, query.CategoryPath);
|
|
4413
5826
|
definition = this.QueryDefinitionSignatureFor(query);
|
|
@@ -4447,6 +5860,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4447
5860
|
}
|
|
4448
5861
|
return { ...checked, Results: paginatedResult, RowCount: paginatedResult.length, TotalRowCount: totalRowCount };
|
|
4449
5862
|
}
|
|
5863
|
+
/**
|
|
5864
|
+
* The result-cache fingerprint segment for what the server set on a run: its `ServerParameters`
|
|
5865
|
+
* and the `Context` values the template read. Empty when there are neither, so the fingerprint
|
|
5866
|
+
* is exactly what it was before either existed.
|
|
5867
|
+
*/
|
|
5868
|
+
serverSetFingerprintSegment(params, contextValues) {
|
|
5869
|
+
const segment = {};
|
|
5870
|
+
if (params.ServerParameters && Object.keys(params.ServerParameters).length > 0) {
|
|
5871
|
+
segment.__serverParameters = params.ServerParameters;
|
|
5872
|
+
}
|
|
5873
|
+
if (contextValues && Object.keys(contextValues).length > 0) {
|
|
5874
|
+
segment.__context = contextValues;
|
|
5875
|
+
}
|
|
5876
|
+
return segment;
|
|
5877
|
+
}
|
|
4450
5878
|
warnIfExternalQueryFieldsMissing(query, result) {
|
|
4451
5879
|
if (!result.Success || !result.Results || result.Results.length === 0) {
|
|
4452
5880
|
return result;
|
|
@@ -4482,6 +5910,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4482
5910
|
try {
|
|
4483
5911
|
const resolved = this.resolveSpecParameters(spec, contextUser);
|
|
4484
5912
|
finalSQL = resolved.finalSQL;
|
|
5913
|
+
// Checked on this rendering, the one that runs: a check a caller made on its own
|
|
5914
|
+
// rendering of the same input is not proof of what this one reads.
|
|
5915
|
+
this.AssertAdhocReadAllowed(resolved.renderResult.Trace.AfterTemplates, contextUser);
|
|
4485
5916
|
// Execute
|
|
4486
5917
|
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
|
|
4487
5918
|
return {
|
|
@@ -4541,19 +5972,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4541
5972
|
return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
|
|
4542
5973
|
}
|
|
4543
5974
|
// wrapWithMaxRows is now handled by RenderPipeline.applyMaxRows
|
|
5975
|
+
/**
|
|
5976
|
+
* Where a server-side result cache keeps this run's rows: one slot per rendered statement and
|
|
5977
|
+
* dialect, and, when the caller is denied a field the statement's projection star reads, per
|
|
5978
|
+
* field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
|
|
5979
|
+
* runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
|
|
5980
|
+
* The rendered statement carries every parameter value, server-set ones included, so they need
|
|
5981
|
+
* no separate part of the key.
|
|
5982
|
+
*/
|
|
5983
|
+
queryResultCacheSlot(query, renderedSQL, needsColumnFiltering, contextUser) {
|
|
5984
|
+
const user = contextUser || this.CurrentUser;
|
|
5985
|
+
const profile = needsColumnFiltering && user ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : '';
|
|
5986
|
+
const key = `${query.ID}|${StatementMemo.KeyOf(renderedSQL, this.Dialect.Key)}|fs:${profile}`;
|
|
5987
|
+
return {
|
|
5988
|
+
Key: key,
|
|
5989
|
+
PageKey: (params) => `${key}|page:${QueryPagingEngine.ResolveStartRow(params.StartRow)}:${params.MaxRows ?? ''}`,
|
|
5990
|
+
};
|
|
5991
|
+
}
|
|
4544
5992
|
/**
|
|
4545
5993
|
* Checks the query cache for existing results and returns them if valid.
|
|
4546
5994
|
* Currently always returns null (query caching is not active).
|
|
5995
|
+
*
|
|
5996
|
+
* An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
|
|
5997
|
+
* stores under: it separates rendered statements and field-security profiles, so a slot never
|
|
5998
|
+
* serves one caller rows shaped for another. The returned rows must be the statement's full
|
|
5999
|
+
* output; the caller's withheld columns are dropped from them after the hit.
|
|
4547
6000
|
*/
|
|
4548
|
-
async checkQueryCache(_query, _params, _appliedParameters) {
|
|
6001
|
+
async checkQueryCache(_query, _params, _appliedParameters, _slotKey) {
|
|
4549
6002
|
return null;
|
|
4550
6003
|
}
|
|
4551
6004
|
/**
|
|
4552
6005
|
* Checks the paged cache for a specific page of query results.
|
|
4553
6006
|
* Returns a full RunQueryResult on hit, null on miss.
|
|
4554
6007
|
* Currently always returns null (query caching is not active).
|
|
6008
|
+
*
|
|
6009
|
+
* An override must look the page up by `slotKey` alone: it names the rendered statement, the
|
|
6010
|
+
* caller's field-security profile and the page, so a page cached for a restricted caller is
|
|
6011
|
+
* never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
|
|
6012
|
+
* from the returned rows after the hit.
|
|
4555
6013
|
*/
|
|
4556
|
-
async checkPagedQueryCache(_query, _params, _appliedParameters) {
|
|
6014
|
+
async checkPagedQueryCache(_query, _params, _appliedParameters, _slotKey) {
|
|
4557
6015
|
return null;
|
|
4558
6016
|
}
|
|
4559
6017
|
/**
|
|
@@ -4665,13 +6123,47 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4665
6123
|
/**
|
|
4666
6124
|
* Caches query results if caching is enabled for the query.
|
|
4667
6125
|
* Currently a no-op (query caching is not active).
|
|
6126
|
+
*
|
|
6127
|
+
* `results` is the statement's full output, before the caller's withheld columns are dropped.
|
|
6128
|
+
* An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
|
|
4668
6129
|
*/
|
|
4669
|
-
async cacheQueryResults(_query, _parameters, _results) {
|
|
6130
|
+
async cacheQueryResults(_query, _parameters, _results, _slotKey) {
|
|
4670
6131
|
// No-op: query caching has been removed
|
|
4671
6132
|
}
|
|
4672
6133
|
/**************************************************************************/
|
|
4673
6134
|
// Load — Shared Implementation
|
|
4674
6135
|
/**************************************************************************/
|
|
6136
|
+
/**
|
|
6137
|
+
* The `WHERE` predicate that selects one record by its composite key, using dialect-neutral
|
|
6138
|
+
* quoting. Quoted key values have embedded single quotes escaped: a key value can contain
|
|
6139
|
+
* apostrophes (an object-valued soft key whose JSON carries free text), and an unescaped quote
|
|
6140
|
+
* both breaks the statement and is an injection vector.
|
|
6141
|
+
*/
|
|
6142
|
+
BuildPrimaryKeyWhereClause(entityInfo, compositeKey) {
|
|
6143
|
+
return compositeKey.KeyValuePairs.map(val => {
|
|
6144
|
+
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
6145
|
+
if (!pk)
|
|
6146
|
+
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
6147
|
+
const quotes = pk.NeedsQuotes ? "'" : '';
|
|
6148
|
+
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
6149
|
+
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
6150
|
+
}).join(' AND ');
|
|
6151
|
+
}
|
|
6152
|
+
/**
|
|
6153
|
+
* Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
|
|
6154
|
+
* Server and PostgreSQL), in place, and returns the row.
|
|
6155
|
+
*/
|
|
6156
|
+
TrimFixedWidthValues(entityInfo, row) {
|
|
6157
|
+
for (const field of entityInfo.Fields) {
|
|
6158
|
+
const isFixedWidth = field.FixedWidthColumn ?? (field.TSType === EntityFieldTSType.String && (field.Type.trim().toLowerCase() === 'char' || field.Type.trim().toLowerCase() === 'nchar'));
|
|
6159
|
+
if (isFixedWidth) {
|
|
6160
|
+
const val = row[field.Name];
|
|
6161
|
+
if (typeof val === 'string')
|
|
6162
|
+
row[field.Name] = val.trimEnd();
|
|
6163
|
+
}
|
|
6164
|
+
}
|
|
6165
|
+
return row;
|
|
6166
|
+
}
|
|
4675
6167
|
/**
|
|
4676
6168
|
* Loads a single entity record by composite key, with optional relationship loading.
|
|
4677
6169
|
* Uses dialect-neutral quoting for all SQL construction.
|
|
@@ -4702,17 +6194,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4702
6194
|
return null;
|
|
4703
6195
|
}
|
|
4704
6196
|
// 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 ');
|
|
6197
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, compositeKey);
|
|
4716
6198
|
// Append Read row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
4717
6199
|
let fullWhere = where;
|
|
4718
6200
|
if (user) {
|
|
@@ -4735,16 +6217,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4735
6217
|
const rawData = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4736
6218
|
const d = await this.PostProcessRows(rawData, entityInfo, user);
|
|
4737
6219
|
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
|
-
}
|
|
6220
|
+
const ret = this.TrimFixedWidthValues(entityInfo, d[0]);
|
|
4748
6221
|
// Load entity relationships if requested
|
|
4749
6222
|
if (entityRelationshipsToLoad && entityRelationshipsToLoad.length > 0) {
|
|
4750
6223
|
for (const rel of entityRelationshipsToLoad) {
|
|
@@ -5027,8 +6500,67 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5027
6500
|
if (!entity.GetUserPermisions(contextUser)?.CanRead) {
|
|
5028
6501
|
return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
|
|
5029
6502
|
}
|
|
6503
|
+
const fieldSecurityRefusal = this.datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser);
|
|
6504
|
+
if (fieldSecurityRefusal) {
|
|
6505
|
+
return { Filter: filter, RowFilter: '', Refusal: fieldSecurityRefusal };
|
|
6506
|
+
}
|
|
5030
6507
|
return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
|
|
5031
6508
|
}
|
|
6509
|
+
/**
|
|
6510
|
+
* Why a caller's ItemFilter is refused by the field-level security gate — the same gate every
|
|
6511
|
+
* RunView filter passes — or null when it may run. The item's stored WhereClause is
|
|
6512
|
+
* administrator-defined dataset metadata, not a predicate the caller chose, so it is not checked.
|
|
6513
|
+
*/
|
|
6514
|
+
datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser) {
|
|
6515
|
+
try {
|
|
6516
|
+
this.AssertClausesRespectFieldSecurityForEntity(entity, [clientFilter], contextUser);
|
|
6517
|
+
return null;
|
|
6518
|
+
}
|
|
6519
|
+
catch (e) {
|
|
6520
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
6521
|
+
return e.message;
|
|
6522
|
+
}
|
|
6523
|
+
throw e;
|
|
6524
|
+
}
|
|
6525
|
+
}
|
|
6526
|
+
/**
|
|
6527
|
+
* The fields of a dataset item's entity the caller may not read, lowercased; empty when none,
|
|
6528
|
+
* when there is no caller, or for MJ_Metadata, which every principal loads to learn the schema.
|
|
6529
|
+
*/
|
|
6530
|
+
datasetItemDeniedFields(datasetName, entity, contextUser) {
|
|
6531
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName || !entity.FieldLevelSecurityApplies) {
|
|
6532
|
+
return new Set();
|
|
6533
|
+
}
|
|
6534
|
+
return entity.GetDeniedReadFields(contextUser);
|
|
6535
|
+
}
|
|
6536
|
+
/**
|
|
6537
|
+
* The error a failed dataset batch reports to the caller. When the caller is denied fields on
|
|
6538
|
+
* an item's entity and the database rejected a column that does not exist, every item reports
|
|
6539
|
+
* the field-security error a denied column gets instead, so the two cannot be told apart.
|
|
6540
|
+
*/
|
|
6541
|
+
datasetBatchErrorForCaller(batchError, items, datasetName, contextUser) {
|
|
6542
|
+
if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6543
|
+
return batchError;
|
|
6544
|
+
}
|
|
6545
|
+
for (const item of items) {
|
|
6546
|
+
const converted = FieldSecuritySQLGate.ErrorForInvalidColumn(batchError, this.EntityByName(String(item['Entity'])), contextUser);
|
|
6547
|
+
if (converted)
|
|
6548
|
+
return converted.message;
|
|
6549
|
+
}
|
|
6550
|
+
return batchError;
|
|
6551
|
+
}
|
|
6552
|
+
/**
|
|
6553
|
+
* Dataset item rows as the caller may see them: denied columns removed, and Record Changes
|
|
6554
|
+
* payloads narrowed. Cached rows are shared and full width, so this always builds new rows
|
|
6555
|
+
* rather than narrowing the cached ones. MJ_Metadata is exempt for the reason given on
|
|
6556
|
+
* {@link datasetItemDeniedFields}.
|
|
6557
|
+
*/
|
|
6558
|
+
projectDatasetRowsForCaller(datasetName, entity, rows, contextUser) {
|
|
6559
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6560
|
+
return rows;
|
|
6561
|
+
}
|
|
6562
|
+
return ProjectEntityValueRowsForUser(this, entity, rows, contextUser) ?? rows;
|
|
6563
|
+
}
|
|
5032
6564
|
/**
|
|
5033
6565
|
* The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
|
|
5034
6566
|
* item's filter sits two parentheses deep because a client ItemFilter is screened inside one
|
|
@@ -5091,6 +6623,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5091
6623
|
const uncachedFingerprints = [];
|
|
5092
6624
|
let cacheHitCount = 0;
|
|
5093
6625
|
let cacheMissCount = 0;
|
|
6626
|
+
const preparedItems = [];
|
|
5094
6627
|
for (const item of items) {
|
|
5095
6628
|
const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
|
|
5096
6629
|
const entityBaseView = String(item['EntityBaseView']);
|
|
@@ -5130,28 +6663,120 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5130
6663
|
}
|
|
5131
6664
|
// The row filter keys the slot, so one user's filtered rows are never served to another.
|
|
5132
6665
|
const rowFilterKey = scope.RowFilter || undefined;
|
|
5133
|
-
|
|
5134
|
-
|
|
5135
|
-
|
|
5136
|
-
|
|
6666
|
+
const fingerprint = cacheAvailable
|
|
6667
|
+
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
|
|
6668
|
+
: '';
|
|
6669
|
+
const cached = cacheAvailable && fingerprint
|
|
6670
|
+
? await cache.GetRunViewResult(fingerprint)
|
|
6671
|
+
: null;
|
|
6672
|
+
preparedItems.push({
|
|
6673
|
+
item,
|
|
6674
|
+
entitySchemaName,
|
|
6675
|
+
entityBaseView,
|
|
6676
|
+
code,
|
|
6677
|
+
entityName,
|
|
6678
|
+
entityID,
|
|
6679
|
+
itemEntity,
|
|
6680
|
+
scope,
|
|
6681
|
+
rowFilterKey,
|
|
6682
|
+
fingerprint,
|
|
6683
|
+
cached,
|
|
6684
|
+
});
|
|
6685
|
+
}
|
|
6686
|
+
// Reconcile cached dataset slots against live SQL status (GetDatasetStatusByName)
|
|
6687
|
+
// when status was recently fetched, when GetDatasetStatusByName is overridden/spied,
|
|
6688
|
+
// or when any cached item's verification TTL (ServerCacheVerificationTTLMs) has elapsed.
|
|
6689
|
+
let liveStatus;
|
|
6690
|
+
if (cacheAvailable && preparedItems.some(p => p.cached !== null)) {
|
|
6691
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
6692
|
+
const recorded = provider._lastDatasetStatusByName.get(statusKey) ?? this._lastDatasetStatusByName.get(statusKey);
|
|
6693
|
+
const isStatusMethodOverridden = this.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName ||
|
|
6694
|
+
provider.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName;
|
|
6695
|
+
const anyCachedExpired = preparedItems.some(p => {
|
|
6696
|
+
if (!p.cached)
|
|
6697
|
+
return false;
|
|
6698
|
+
const verifiedAt = p.cached.lastVerifiedAt ?? p.cached.cachedAt;
|
|
6699
|
+
return (this.ServerCacheVerificationTTLMs <= 0 ||
|
|
6700
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs));
|
|
6701
|
+
});
|
|
6702
|
+
if (isStatusMethodOverridden ||
|
|
6703
|
+
(anyCachedExpired && (!recorded || (Date.now() - recorded.timestamp) > this.ServerCacheVerificationTTLMs))) {
|
|
6704
|
+
try {
|
|
6705
|
+
const fetched = await provider.GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse);
|
|
6706
|
+
if (fetched?.Success) {
|
|
6707
|
+
liveStatus = fetched;
|
|
6708
|
+
}
|
|
6709
|
+
}
|
|
6710
|
+
catch (statusErr) {
|
|
6711
|
+
LogError(`GetDatasetByName("${datasetName}"): status verification failed: ${statusErr instanceof Error ? statusErr.message : String(statusErr)}`);
|
|
6712
|
+
}
|
|
6713
|
+
}
|
|
6714
|
+
else if (recorded?.status?.Success) {
|
|
6715
|
+
liveStatus = recorded.status;
|
|
6716
|
+
}
|
|
6717
|
+
}
|
|
6718
|
+
const statusByEntityID = liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)
|
|
6719
|
+
? IndexByUUID(liveStatus.EntityUpdateDates.filter(e => Boolean(e.EntityID)), e => e.EntityID)
|
|
6720
|
+
: null;
|
|
6721
|
+
const statusByEntityName = new Map();
|
|
6722
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6723
|
+
for (const e of liveStatus.EntityUpdateDates) {
|
|
6724
|
+
if (e.EntityName) {
|
|
6725
|
+
statusByEntityName.set(e.EntityName.trim().toLowerCase(), e);
|
|
6726
|
+
}
|
|
6727
|
+
}
|
|
6728
|
+
}
|
|
6729
|
+
for (const prepared of preparedItems) {
|
|
6730
|
+
const { item, entitySchemaName, entityBaseView, code, entityName, entityID, itemEntity, scope, fingerprint } = prepared;
|
|
6731
|
+
let cached = prepared.cached;
|
|
6732
|
+
if (cached) {
|
|
6733
|
+
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
6734
|
+
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
6735
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6736
|
+
const statusEntry = (entityID ? statusByEntityID?.Get(entityID) : undefined)
|
|
6737
|
+
?? statusByEntityName.get(entityName.trim().toLowerCase());
|
|
6738
|
+
if (statusEntry) {
|
|
6739
|
+
const rowCountMatches = cached.results.length === statusEntry.RowCount;
|
|
6740
|
+
const cachedMaxDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
6741
|
+
const effectiveCachedTime = Math.max(latestUpdateDate ? new Date(latestUpdateDate).getTime() : 0, cachedMaxDate ? cachedMaxDate.getTime() : 0);
|
|
6742
|
+
const statusTime = statusEntry.UpdateDate ? new Date(statusEntry.UpdateDate).getTime() : 0;
|
|
6743
|
+
const timestampMatches = isNaN(statusTime) ||
|
|
6744
|
+
statusTime <= 0 ||
|
|
6745
|
+
effectiveCachedTime <= 0 ||
|
|
6746
|
+
Math.abs(statusTime - effectiveCachedTime) < 1000;
|
|
6747
|
+
if (!rowCountMatches || !timestampMatches) {
|
|
6748
|
+
LogStatusEx({
|
|
6749
|
+
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`,
|
|
6750
|
+
verboseOnly: true,
|
|
6751
|
+
});
|
|
6752
|
+
await cache.InvalidateRunViewResult(fingerprint);
|
|
6753
|
+
cached = null;
|
|
6754
|
+
}
|
|
6755
|
+
else {
|
|
6756
|
+
cache.TouchRunViewResultVerifiedAt(fingerprint);
|
|
6757
|
+
}
|
|
6758
|
+
}
|
|
6759
|
+
}
|
|
5137
6760
|
if (cached) {
|
|
5138
6761
|
cacheHitCount++;
|
|
5139
|
-
const
|
|
5140
|
-
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
6762
|
+
const materializedDatasetRows = await provider.MaterializeCachedRowsForCaller(cached.results, itemEntity, contextUser, false);
|
|
5141
6763
|
cachedResults.push({
|
|
5142
6764
|
EntityID: entityID,
|
|
5143
6765
|
EntityName: entityName,
|
|
5144
6766
|
Code: code,
|
|
5145
|
-
Results:
|
|
6767
|
+
Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, materializedDatasetRows, contextUser),
|
|
5146
6768
|
LatestUpdateDate: latestUpdateDate,
|
|
5147
6769
|
Success: true,
|
|
5148
6770
|
});
|
|
5149
6771
|
continue; // Skip SQL for this item
|
|
5150
6772
|
}
|
|
5151
6773
|
}
|
|
5152
|
-
// Cache miss — validate columns and build SQL
|
|
6774
|
+
// Cache miss (or invalidated stale slot) — validate columns and build SQL
|
|
5153
6775
|
cacheMissCount++;
|
|
5154
|
-
|
|
6776
|
+
// A caller denied fields never has them selected; such a narrowed read is not written to
|
|
6777
|
+
// the shared slot, which holds full-width rows for every caller.
|
|
6778
|
+
const deniedFields = this.datasetItemDeniedFields(datasetName, itemEntity, contextUser);
|
|
6779
|
+
const columns = provider.getColumnsForDatasetItem(item, datasetName, deniedFields);
|
|
5155
6780
|
if (!columns) {
|
|
5156
6781
|
errorResults.push({
|
|
5157
6782
|
EntityID: entityID,
|
|
@@ -5168,11 +6793,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5168
6793
|
const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
|
|
5169
6794
|
uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
|
|
5170
6795
|
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);
|
|
6796
|
+
// A narrowed read (the caller is denied fields) is never written to the shared slot.
|
|
6797
|
+
uncachedFingerprints.push(deniedFields.size === 0 ? fingerprint : '');
|
|
5176
6798
|
}
|
|
5177
6799
|
// Phase 2: Execute SQL only for cache misses
|
|
5178
6800
|
let batchResults = [];
|
|
@@ -5191,6 +6813,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5191
6813
|
catch (err) {
|
|
5192
6814
|
batchError = err instanceof Error ? err.message : String(err);
|
|
5193
6815
|
LogError(`GetDatasetByName("${datasetName}"): Batch execution failed: ${batchError}`);
|
|
6816
|
+
batchError = this.datasetBatchErrorForCaller(batchError, uncachedItems, datasetName, contextUser);
|
|
5194
6817
|
}
|
|
5195
6818
|
}
|
|
5196
6819
|
// Phase 3: Process SQL results and write-through to cache
|
|
@@ -5245,13 +6868,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5245
6868
|
// item.Results — these very arrays — to every engine subclass), so those slots
|
|
5246
6869
|
// must stay under the defensive deep-freeze like any RunView result.
|
|
5247
6870
|
const isMetadataScaffolding = datasetName === ProviderBase._mjMetadataDatasetName;
|
|
5248
|
-
|
|
6871
|
+
const rowsForCache = isMetadataScaffolding
|
|
6872
|
+
? itemData
|
|
6873
|
+
: provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName));
|
|
6874
|
+
await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, rowsForCache, maxUpdatedAt, undefined, undefined, this, undefined, isMetadataScaffolding ? { ProviderInternalScaffolding: true } : undefined);
|
|
5249
6875
|
}
|
|
5250
6876
|
sqlResults.push({
|
|
5251
6877
|
EntityID: entityID,
|
|
5252
6878
|
EntityName: entityName,
|
|
5253
6879
|
Code: code,
|
|
5254
|
-
Results: itemData,
|
|
6880
|
+
Results: this.projectDatasetRowsForCaller(datasetName, provider.EntityByName(entityName), itemData, contextUser),
|
|
5255
6881
|
LatestUpdateDate: latestUpdateDate,
|
|
5256
6882
|
Success: itemData !== null && itemData !== undefined,
|
|
5257
6883
|
});
|
|
@@ -5414,7 +7040,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5414
7040
|
EntityUpdateDates: [],
|
|
5415
7041
|
};
|
|
5416
7042
|
}
|
|
5417
|
-
|
|
7043
|
+
const statusResult = {
|
|
5418
7044
|
DatasetID: String(items[0]['DatasetID']),
|
|
5419
7045
|
DatasetName: datasetName,
|
|
5420
7046
|
Success: true,
|
|
@@ -5422,6 +7048,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5422
7048
|
LatestUpdateDate: overallLatestDate,
|
|
5423
7049
|
EntityUpdateDates: updateDates,
|
|
5424
7050
|
};
|
|
7051
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
7052
|
+
const now = Date.now();
|
|
7053
|
+
this._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
7054
|
+
provider._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
7055
|
+
return statusResult;
|
|
7056
|
+
}
|
|
7057
|
+
/**
|
|
7058
|
+
* Builds the lookup key for {@link _lastDatasetStatusByName} from dataset name and item filters.
|
|
7059
|
+
*/
|
|
7060
|
+
buildDatasetStatusCacheKey(datasetName, itemFilters) {
|
|
7061
|
+
return `${datasetName}::${this.ConvertItemFiltersToUniqueKey(itemFilters ?? [])}`;
|
|
5425
7062
|
}
|
|
5426
7063
|
/**************************************************************************/
|
|
5427
7064
|
// getColumnsForDatasetItem — Column Validation
|
|
@@ -5435,41 +7072,53 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5435
7072
|
* binary column can still be named explicitly. When the entity's metadata is not loaded yet —
|
|
5436
7073
|
* the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
|
|
5437
7074
|
* are converted to base64 by the caller.
|
|
7075
|
+
*
|
|
7076
|
+
* `deniedFields` (lowercased) are the columns the caller may not read. They are never
|
|
7077
|
+
* selected: a named one is dropped, and an item that names none selects every readable column.
|
|
5438
7078
|
*/
|
|
5439
|
-
getColumnsForDatasetItem(item, datasetName) {
|
|
7079
|
+
getColumnsForDatasetItem(item, datasetName, deniedFields) {
|
|
5440
7080
|
const specifiedColumns = item['Columns'] ? String(item['Columns']).split(',').map(col => col.trim()) : [];
|
|
7081
|
+
const entity = this.EntityByID(item['EntityID']);
|
|
7082
|
+
const denied = deniedFields ?? new Set();
|
|
5441
7083
|
if (specifiedColumns.length === 0) {
|
|
5442
|
-
|
|
7084
|
+
if (entity && denied.size > 0) {
|
|
7085
|
+
return this.readableDatasetColumns(entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => f.Name), entity, denied);
|
|
7086
|
+
}
|
|
5443
7087
|
if (entity?.HasBinaryFields) {
|
|
5444
7088
|
return entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => this.QuoteIdentifier(f.Name)).join(',');
|
|
5445
7089
|
}
|
|
7090
|
+
return '*';
|
|
7091
|
+
}
|
|
7092
|
+
if (!entity && this.Entities.length > 0) {
|
|
7093
|
+
LogError(`Entity not found for dataset item ${item['Code']} in dataset ${datasetName}`);
|
|
7094
|
+
return null;
|
|
5446
7095
|
}
|
|
5447
|
-
if (
|
|
5448
|
-
const
|
|
5449
|
-
if (
|
|
5450
|
-
LogError(`
|
|
7096
|
+
if (entity) {
|
|
7097
|
+
const invalidColumns = specifiedColumns.filter(col => !entity.FieldByName(col));
|
|
7098
|
+
if (invalidColumns.length > 0) {
|
|
7099
|
+
LogError(`Invalid columns specified for dataset item ${item['Code']} in dataset ${datasetName}: ${invalidColumns.join(', ')}`);
|
|
5451
7100
|
return null;
|
|
5452
7101
|
}
|
|
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
7102
|
}
|
|
5472
|
-
|
|
7103
|
+
// Ensure DateFieldToCheck is included
|
|
7104
|
+
const dateField = item['DateFieldToCheck'] ? String(item['DateFieldToCheck']).trim() : '';
|
|
7105
|
+
if (dateField.length > 0 && specifiedColumns.indexOf(dateField) === -1) {
|
|
7106
|
+
if (!entity || entity.FieldByName(dateField))
|
|
7107
|
+
specifiedColumns.push(dateField);
|
|
7108
|
+
}
|
|
7109
|
+
if (entity && denied.size > 0) {
|
|
7110
|
+
return this.readableDatasetColumns(specifiedColumns, entity, denied);
|
|
7111
|
+
}
|
|
7112
|
+
return specifiedColumns.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
7113
|
+
}
|
|
7114
|
+
/**
|
|
7115
|
+
* `columns` without the denied ones, quoted and joined. When every one is denied, the primary
|
|
7116
|
+
* key columns are selected instead, which are never denied, so the read still has a shape.
|
|
7117
|
+
*/
|
|
7118
|
+
readableDatasetColumns(columns, entity, denied) {
|
|
7119
|
+
const readable = columns.filter(col => !denied.has(col.trim().toLowerCase()));
|
|
7120
|
+
const selected = readable.length > 0 ? readable : entity.PrimaryKeys.map(pk => pk.Name);
|
|
7121
|
+
return selected.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
5473
7122
|
}
|
|
5474
7123
|
/**************************************************************************/
|
|
5475
7124
|
// Dataset Cache Helpers
|
|
@@ -5551,7 +7200,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5551
7200
|
* `AIEngine.Models` to recover the driver class / APIName and call
|
|
5552
7201
|
* `EmbedText(model, text)` directly. If the EntityDocument does not specify
|
|
5553
7202
|
* a model (or the model isn't loaded) we fall back to
|
|
5554
|
-
* `EmbedTextLocal` (
|
|
7203
|
+
* `EmbedTextLocal` (the default local model) only as a last resort. The search
|
|
7204
|
+
* text is embedded as a query (`inputType: 'query'`). The index's
|
|
7205
|
+
* `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
|
|
7206
|
+
* the model's native size.
|
|
5555
7207
|
*
|
|
5556
7208
|
* Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
|
|
5557
7209
|
* which rehydrates the vector pool for `entityDocumentId` from
|
|
@@ -5578,15 +7230,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5578
7230
|
LogError(`searchEntitiesSemanticPass: EntityDocument AIModelID="${embeddingAIModelId}" not found in AIEngine.Models. Index/query model mismatch is likely — refusing to fall back silently.`);
|
|
5579
7231
|
return [];
|
|
5580
7232
|
}
|
|
5581
|
-
const result = await AIEngine.Instance.EmbedText(model, searchText);
|
|
7233
|
+
const result = await AIEngine.Instance.EmbedText(model, searchText, undefined, { inputType: 'query' });
|
|
5582
7234
|
queryVector = result?.vector ?? null;
|
|
5583
7235
|
}
|
|
5584
7236
|
else {
|
|
5585
7237
|
// No model on the EntityDocument — last-resort fallback to the
|
|
5586
7238
|
// highest-power local embedder. Logged because this path means
|
|
5587
7239
|
// indexing-time and query-time models can diverge.
|
|
5588
|
-
LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to
|
|
5589
|
-
const embed = await AIEngine.Instance.EmbedTextLocal(searchText);
|
|
7240
|
+
LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to the default local embedding model. Index/query mismatch possible.`);
|
|
7241
|
+
const embed = await AIEngine.Instance.EmbedTextLocal(searchText, { inputType: 'query' });
|
|
5590
7242
|
queryVector = embed?.result?.vector ?? null;
|
|
5591
7243
|
}
|
|
5592
7244
|
}
|