@memberjunction/generic-database-provider 6.2.0-edge.4 → 6.2.0-edge.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -1
- package/dist/GenericDatabaseProvider.d.ts +516 -49
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +1869 -329
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.d.ts +43 -0
- package/dist/SqlLogger.d.ts.map +1 -1
- package/dist/SqlLogger.js +165 -35
- package/dist/SqlLogger.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +284 -0
- package/dist/clientClauseScreen.d.ts.map +1 -0
- package/dist/clientClauseScreen.js +637 -0
- package/dist/clientClauseScreen.js.map +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/recordChangeSnapshot.d.ts +43 -0
- package/dist/recordChangeSnapshot.d.ts.map +1 -0
- package/dist/recordChangeSnapshot.js +85 -0
- package/dist/recordChangeSnapshot.js.map +1 -0
- package/dist/renderPipeline.d.ts +27 -0
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +45 -3
- package/dist/renderPipeline.js.map +1 -1
- package/dist/saveTypes.d.ts +41 -4
- package/dist/saveTypes.d.ts.map +1 -1
- package/dist/systemUserFieldAccess.d.ts +16 -1
- package/dist/systemUserFieldAccess.d.ts.map +1 -1
- package/dist/systemUserFieldAccess.js +39 -8
- package/dist/systemUserFieldAccess.js.map +1 -1
- package/dist/types.d.ts +59 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -15,19 +15,19 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
18
|
-
import { 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, 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
|
-
import { SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
24
|
+
import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
25
25
|
import { GetDialect } from '@memberjunction/sql-dialect';
|
|
26
|
-
import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression } from '@memberjunction/sql-parser';
|
|
26
|
+
import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
27
27
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
28
28
|
import { RenderPipeline } from './renderPipeline.js';
|
|
29
29
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
30
|
-
import { QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
30
|
+
import { GetQueryApprovalStateAsync, QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
31
31
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
32
32
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
33
33
|
import { QueueManager } from '@memberjunction/queue';
|
|
@@ -36,6 +36,9 @@ import { BuildEntityChangeContext } from '@memberjunction/actions-base';
|
|
|
36
36
|
import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
37
37
|
import { TransactionAffinity } from './TransactionAffinity.js';
|
|
38
38
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
39
|
+
import { ClientClauseScreen } from './clientClauseScreen.js';
|
|
40
|
+
import { IsSystemUser } from './systemUser.js';
|
|
41
|
+
import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
|
|
39
42
|
import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
|
|
40
43
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
41
44
|
/**
|
|
@@ -70,8 +73,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
70
73
|
constructor() {
|
|
71
74
|
// Composition engine is now owned by RenderPipeline
|
|
72
75
|
super(...arguments);
|
|
76
|
+
/**
|
|
77
|
+
* Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
|
|
78
|
+
* and Dataset slots. Within this window after a slot was written or last verified against
|
|
79
|
+
* SQL, `RunViewsWithCacheCheck` and `GetDatasetByName` can trust the in-memory slot with
|
|
80
|
+
* zero DB hits. Once this window elapses, the next check performs a lightweight batched
|
|
81
|
+
* SQL status probe (`COUNT(*)` + `MAX(__mj_UpdatedAt)`) to auto-reconcile any out-of-band
|
|
82
|
+
* SQL mutations (e.g., migrations, `mj sync push`, external scripts) without requiring a
|
|
83
|
+
* server restart.
|
|
84
|
+
*/
|
|
85
|
+
this.ServerCacheVerificationTTLMs = 5000;
|
|
86
|
+
/**
|
|
87
|
+
* Most recent authoritative SQL status result per dataset key (`datasetName + filterKey`),
|
|
88
|
+
* populated by `GetDatasetStatusByName` and consumed by `GetDatasetByName` to reconcile
|
|
89
|
+
* cached dataset item slots against live SQL row counts and timestamps.
|
|
90
|
+
*/
|
|
91
|
+
this._lastDatasetStatusByName = new Map();
|
|
73
92
|
/** Per transaction-group counts so the same hash twice in one batch gets `_hash_2`. */
|
|
74
93
|
this._saveCallSuffixCounts = new WeakMap();
|
|
94
|
+
/**
|
|
95
|
+
* Connections a save's SQL is being generated for, by entity object: the transaction a
|
|
96
|
+
* transaction group runs its items on. Set only for the duration of
|
|
97
|
+
* {@link GenerateSaveSQLReadingOn}.
|
|
98
|
+
*/
|
|
99
|
+
this._snapshotConnections = new WeakMap();
|
|
100
|
+
/** Full-width delete snapshots captured by {@link Delete}, consumed by `GenerateDeleteSQL`. */
|
|
101
|
+
this._deleteSnapshots = new WeakMap();
|
|
102
|
+
this._requestFLSKeys = new WeakMap();
|
|
75
103
|
// ─── Nested transactions ─────────────────────────────────────────
|
|
76
104
|
//
|
|
77
105
|
// Depth 1 = physical BEGIN. Depth 2+ = a dialect savepoint on that same
|
|
@@ -167,22 +195,43 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
167
195
|
}
|
|
168
196
|
return super.Config(data, providerToUse);
|
|
169
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Public accessor for {@link ServerCacheVerificationTTLMs}.
|
|
200
|
+
* Set to `0` to force SQL status verification on every cache check.
|
|
201
|
+
*/
|
|
202
|
+
get ServerCacheVerificationTTL() {
|
|
203
|
+
return this.ServerCacheVerificationTTLMs;
|
|
204
|
+
}
|
|
205
|
+
set ServerCacheVerificationTTL(value) {
|
|
206
|
+
this.ServerCacheVerificationTTLMs = Math.max(0, value);
|
|
207
|
+
}
|
|
170
208
|
/**************************************************************************/
|
|
171
209
|
// SQL Logging — Session Management & Statement Logging
|
|
172
210
|
/**************************************************************************/
|
|
173
211
|
static { this._sqlLoggingSessionsKey = 'MJ_GenericDatabaseProvider_SqlLoggingSessions'; }
|
|
212
|
+
static { this._cachedSqlLoggingSessions = null; }
|
|
174
213
|
get _sqlLoggingSessions() {
|
|
214
|
+
if (GenericDatabaseProvider._cachedSqlLoggingSessions) {
|
|
215
|
+
return GenericDatabaseProvider._cachedSqlLoggingSessions;
|
|
216
|
+
}
|
|
175
217
|
const g = MJGlobal.Instance.GetGlobalObjectStore();
|
|
176
218
|
if (g) {
|
|
177
219
|
if (!g[GenericDatabaseProvider._sqlLoggingSessionsKey]) {
|
|
178
220
|
g[GenericDatabaseProvider._sqlLoggingSessionsKey] = new Map();
|
|
179
221
|
}
|
|
180
|
-
|
|
222
|
+
GenericDatabaseProvider._cachedSqlLoggingSessions = g[GenericDatabaseProvider._sqlLoggingSessionsKey];
|
|
223
|
+
return GenericDatabaseProvider._cachedSqlLoggingSessions;
|
|
181
224
|
}
|
|
182
225
|
else {
|
|
183
226
|
throw new Error('No global object store available for SQL logging session');
|
|
184
227
|
}
|
|
185
228
|
}
|
|
229
|
+
/**
|
|
230
|
+
* Fast O(1) check for whether any SQL logging sessions are currently active.
|
|
231
|
+
*/
|
|
232
|
+
get HasActiveSqlLoggingSessions() {
|
|
233
|
+
return this._sqlLoggingSessions.size > 0;
|
|
234
|
+
}
|
|
186
235
|
/**
|
|
187
236
|
* Creates a new SQL logging session that will capture all SQL operations to a file.
|
|
188
237
|
* Returns a disposable session object that must be disposed to stop logging.
|
|
@@ -299,7 +348,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
299
348
|
const hasVerboseSession = allSessions.some(s => s.options.verboseOutput === true);
|
|
300
349
|
if (hasVerboseSession) {
|
|
301
350
|
console.log('=== SQL LOGGING DEBUG ===');
|
|
302
|
-
console.log(`Query to log: ${query.substring(0, 100)}...`);
|
|
351
|
+
console.log(`Query to log: ${ApplyStatementTransforms(query, allSessions).substring(0, 100)}...`);
|
|
303
352
|
console.log(`Context user email: ${contextUser?.Email || 'NOT_PROVIDED'}`);
|
|
304
353
|
console.log(`Active sessions count: ${this._sqlLoggingSessions.size}`);
|
|
305
354
|
console.log(`All sessions:`, allSessions.map(s => ({
|
|
@@ -389,6 +438,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
389
438
|
* save succeeds is not a durability improvement, it is a different feature.
|
|
390
439
|
*/
|
|
391
440
|
async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs) {
|
|
441
|
+
const engine = EntityActionEngineServer.Instance;
|
|
442
|
+
if (engine.Loaded && engine.GetActionsByEntityName(entity.EntityInfo.Name, 'Active').length === 0) {
|
|
443
|
+
return [];
|
|
444
|
+
}
|
|
392
445
|
// FIRST STATEMENT, and deliberately before the first `await`. After-hooks are dispatched
|
|
393
446
|
// fire-and-forget, and the moment this method yields, the save completes and `finalizeSave()`
|
|
394
447
|
// reloads the entity — resetting every field's OldValue to its new value. A change context
|
|
@@ -400,8 +453,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
400
453
|
// rolled-back save never fires it (see RunAfterCommit).
|
|
401
454
|
const postCommitToken = this.CapturePostCommitToken();
|
|
402
455
|
try {
|
|
403
|
-
|
|
404
|
-
|
|
456
|
+
if (!engine.Loaded) {
|
|
457
|
+
await engine.Config(false, user);
|
|
458
|
+
}
|
|
405
459
|
const newRecord = entityChange.IsCreate;
|
|
406
460
|
const baseTypeType = baseType === 'save' ? (newRecord ? 'Create' : 'Update') : 'Delete';
|
|
407
461
|
const invocationType = baseType === 'validate' ? 'Validate' : before ? 'Before' + baseTypeType : 'After' + baseTypeType;
|
|
@@ -470,10 +524,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
470
524
|
try {
|
|
471
525
|
if (baseType === 'delete')
|
|
472
526
|
return; // delete not yet supported for AI actions
|
|
473
|
-
|
|
527
|
+
const ai = AIEngine.Instance;
|
|
528
|
+
if (!ai.Loaded) {
|
|
529
|
+
await ai.Config(false, user);
|
|
530
|
+
}
|
|
474
531
|
const actions = this.GetEntityAIActions(entity.EntityInfo, before);
|
|
475
532
|
if (actions && actions.length > 0) {
|
|
476
|
-
const ai = AIEngine.Instance;
|
|
477
533
|
for (let i = 0; i < actions.length; i++) {
|
|
478
534
|
const a = actions[i];
|
|
479
535
|
if ((a.TriggerEvent === 'before save' && before) || (a.TriggerEvent === 'after save' && !before)) {
|
|
@@ -678,8 +734,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
678
734
|
if (datetimeFields.length > 0 && !entityInfo.ExternalDataSourceID) {
|
|
679
735
|
processedRows = await this.AdjustDatetimeFields(processedRows, datetimeFields, entityInfo);
|
|
680
736
|
}
|
|
681
|
-
// Step 2: Encryption decryption
|
|
682
|
-
const encryptedFields =
|
|
737
|
+
// Step 2: Encryption decryption — memoized per EntityInfo (like DatetimeFields/BinaryFields)
|
|
738
|
+
const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
|
|
683
739
|
if (encryptedFields.length === 0)
|
|
684
740
|
return processedRows;
|
|
685
741
|
const encryptionEngine = EncryptionEngine.Instance;
|
|
@@ -712,6 +768,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
712
768
|
return processedRow;
|
|
713
769
|
}));
|
|
714
770
|
}
|
|
771
|
+
static { this._encryptedFieldsCache = new WeakMap(); }
|
|
772
|
+
static getEncryptedFields(entityInfo) {
|
|
773
|
+
let entry = GenericDatabaseProvider._encryptedFieldsCache.get(entityInfo);
|
|
774
|
+
if (!entry || entry.fieldCount !== entityInfo.Fields.length) {
|
|
775
|
+
entry = {
|
|
776
|
+
fieldCount: entityInfo.Fields.length,
|
|
777
|
+
fields: entityInfo.Fields.filter((field) => field.Encrypt && field.EncryptionKeyID),
|
|
778
|
+
};
|
|
779
|
+
GenericDatabaseProvider._encryptedFieldsCache.set(entityInfo, entry);
|
|
780
|
+
}
|
|
781
|
+
return entry.fields;
|
|
782
|
+
}
|
|
715
783
|
/**
|
|
716
784
|
* Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
|
|
717
785
|
* own read paths but returns entity rows — the transaction groups. Every row a provider hands
|
|
@@ -1042,6 +1110,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1042
1110
|
const pkValues = entity.PrimaryKey?.KeyValuePairs?.map((p) => p.Value) ?? [];
|
|
1043
1111
|
return this.allocateSaveCallSuffixForPk(entity.TransactionGroup, entity.EntityInfo.SchemaName, entity.EntityInfo.BaseTable, pkValues);
|
|
1044
1112
|
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Builds the dialect-quoted, comma-separated column list for {@link EntityInfo.DatestampReturnFields}
|
|
1115
|
+
* (primary key column(s) followed by `__mj_CreatedAt` and `__mj_UpdatedAt`) using {@link QuoteIdentifier}.
|
|
1116
|
+
*
|
|
1117
|
+
* Examples:
|
|
1118
|
+
* - SQL Server: `[ID], [__mj_CreatedAt], [__mj_UpdatedAt]`
|
|
1119
|
+
* - PostgreSQL: `"ID", "__mj_CreatedAt", "__mj_UpdatedAt"`
|
|
1120
|
+
*/
|
|
1121
|
+
GetDatestampSelectColumnsSQL(entityInfo) {
|
|
1122
|
+
const fields = entityInfo.DatestampReturnFields ?? entityInfo.PrimaryKeys ?? [];
|
|
1123
|
+
return fields.map((f) => this.QuoteIdentifier(f.Name)).join(', ');
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Resolves the compile-time vs. effective runtime {@link SaveReturnContext} for a save operation.
|
|
1127
|
+
*
|
|
1128
|
+
* Centralizes the `SaveReturnMode` decision logic in `GenericDatabaseProvider` so dialect providers
|
|
1129
|
+
* (`SQLServerDataProvider`, `PostgreSQLDataProvider`, and future providers) never duplicate the
|
|
1130
|
+
* rules for:
|
|
1131
|
+
* - `spReturnMode`: the return shape compiled into the stored procedure / function (`EntityInfo.SaveReturnMode`).
|
|
1132
|
+
* - `effectiveReturnMode`: the return shape requested for this call (`options?.SaveReturnMode ?? spReturnMode`).
|
|
1133
|
+
* - `needsDatestampProjection`: `true` when the compiled routine returns the full row (`spReturnMode === 'full'`)
|
|
1134
|
+
* but the caller requested `'datestamps_only'` at runtime, requiring the provider to project the result down
|
|
1135
|
+
* to `datestampSelectColumnsSQL` before wire transmission.
|
|
1136
|
+
*/
|
|
1137
|
+
ResolveSaveReturnContext(entity, options) {
|
|
1138
|
+
const spReturnMode = entity.EntityInfo.SaveReturnMode ?? 'full';
|
|
1139
|
+
const effectiveReturnMode = options?.SaveReturnMode ?? spReturnMode;
|
|
1140
|
+
const spReturnsDatestampsOnly = spReturnMode === 'datestamps_only';
|
|
1141
|
+
const needsDatestampProjection = !spReturnsDatestampsOnly && effectiveReturnMode === 'datestamps_only';
|
|
1142
|
+
const datestampSelectColumnsSQL = this.GetDatestampSelectColumnsSQL(entity.EntityInfo);
|
|
1143
|
+
const routineSelectColumnsSQL = needsDatestampProjection ? datestampSelectColumnsSQL : '*';
|
|
1144
|
+
const finalSelectColumnsSQL = effectiveReturnMode === 'datestamps_only' ? datestampSelectColumnsSQL : '*';
|
|
1145
|
+
return {
|
|
1146
|
+
spReturnMode,
|
|
1147
|
+
effectiveReturnMode,
|
|
1148
|
+
spReturnsDatestampsOnly,
|
|
1149
|
+
needsDatestampProjection,
|
|
1150
|
+
datestampSelectColumnsSQL,
|
|
1151
|
+
routineSelectColumnsSQL,
|
|
1152
|
+
finalSelectColumnsSQL,
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1045
1155
|
/**
|
|
1046
1156
|
* Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
|
|
1047
1157
|
* record saves for migration replay (SQL Server's Metadata_Sync migrations) override
|
|
@@ -1065,10 +1175,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1065
1175
|
return undefined;
|
|
1066
1176
|
}
|
|
1067
1177
|
/** The entries of a save's parameter map whose fields this save actually changed. */
|
|
1068
|
-
changedFieldValues(entity, fieldValues) {
|
|
1178
|
+
changedFieldValues(entity, fieldValues, dirtyFields) {
|
|
1069
1179
|
const changed = new Map();
|
|
1070
1180
|
for (const [f, value] of fieldValues) {
|
|
1071
|
-
|
|
1181
|
+
const isDirty = dirtyFields ? dirtyFields.has(f) : !!entity.GetFieldByName(f.Name)?.Dirty;
|
|
1182
|
+
if (isDirty)
|
|
1072
1183
|
changed.set(f, value);
|
|
1073
1184
|
}
|
|
1074
1185
|
return changed;
|
|
@@ -1088,6 +1199,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1088
1199
|
const spName = this.GetCreateUpdateSPName(entity, isNew);
|
|
1089
1200
|
// 1. Iterate fields, apply IsSPParameter + PK rules, coerce values.
|
|
1090
1201
|
const fieldValueMap = new Map();
|
|
1202
|
+
const dirtyFields = isUpdate ? new Set() : undefined;
|
|
1091
1203
|
for (const f of entity.EntityInfo.Fields) {
|
|
1092
1204
|
if (!f.IsSPParameter(isUpdate))
|
|
1093
1205
|
continue;
|
|
@@ -1125,16 +1237,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1125
1237
|
if (coerced.kind === 'skip')
|
|
1126
1238
|
continue;
|
|
1127
1239
|
fieldValueMap.set(f, coerced.value);
|
|
1240
|
+
if (dirtyFields && theField?.Dirty) {
|
|
1241
|
+
dirtyFields.add(f);
|
|
1242
|
+
}
|
|
1128
1243
|
}
|
|
1129
1244
|
// 2. Encrypt — between coercion and rendering, mutates the map in place.
|
|
1130
1245
|
await this.EncryptFieldValuesForSave(entity, fieldValueMap, user);
|
|
1131
1246
|
// 3. Render the provider-specific binding.
|
|
1132
1247
|
const binding = this.RenderSaveCallBinding(entity, fieldValueMap, isUpdate, spName);
|
|
1133
|
-
// 4.
|
|
1134
|
-
//
|
|
1135
|
-
//
|
|
1136
|
-
//
|
|
1137
|
-
|
|
1248
|
+
// 4. Resolve SaveReturnContext and wrap with result capture.
|
|
1249
|
+
// `unprojectedSaveSQL` is the bare SP/function call (kept for `simpleSQL` fallback so
|
|
1250
|
+
// SQL logging / migration replay never gets polluted with runtime datestamp projection wrappers).
|
|
1251
|
+
// When `returnContext.needsDatestampProjection` is true, `ProjectSaveCallToDatestamps`
|
|
1252
|
+
// projects the executed result down to `datestampSelectColumnsSQL`.
|
|
1253
|
+
const returnContext = this.ResolveSaveReturnContext(entity, options);
|
|
1254
|
+
const unprojectedSaveSQL = this.WrapSaveCallForResult(binding, entity, spName, undefined, {
|
|
1255
|
+
...returnContext,
|
|
1256
|
+
effectiveReturnMode: returnContext.spReturnMode,
|
|
1257
|
+
needsDatestampProjection: false,
|
|
1258
|
+
routineSelectColumnsSQL: '*',
|
|
1259
|
+
finalSelectColumnsSQL: returnContext.spReturnsDatestampsOnly ? returnContext.datestampSelectColumnsSQL : '*',
|
|
1260
|
+
});
|
|
1261
|
+
const baseSaveSQL = returnContext.needsDatestampProjection
|
|
1262
|
+
? this.ProjectSaveCallToDatestamps(binding, entity, spName, returnContext)
|
|
1263
|
+
: unprojectedSaveSQL;
|
|
1138
1264
|
let saveSQL = baseSaveSQL;
|
|
1139
1265
|
// A CREATE's logged form is guarded on the primary key so a migration replay of
|
|
1140
1266
|
// the recording converges on a database that already holds the row (#4503). An
|
|
@@ -1142,45 +1268,181 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1142
1268
|
// resets the target's other columns. A forced save (IgnoreDirtyState, e.g. MetadataSync's
|
|
1143
1269
|
// `alwaysPush`) asked to re-impose the whole row, so it keeps the full-row form. Dialects
|
|
1144
1270
|
// without a replay form log the plain save SQL.
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1271
|
+
// Computed lazily and memoized so saves with SQL logging off skip replay/literal rendering.
|
|
1272
|
+
let cachedSimpleSQL;
|
|
1273
|
+
const computeSimpleSQL = () => {
|
|
1274
|
+
if (cachedSimpleSQL === undefined) {
|
|
1275
|
+
const replaySQL = isNew
|
|
1276
|
+
? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
|
|
1277
|
+
: options?.IgnoreDirtyState
|
|
1278
|
+
? undefined
|
|
1279
|
+
: this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap, dirtyFields));
|
|
1280
|
+
// A statement that runs with parameters is logged in its literal form, which replays alone.
|
|
1281
|
+
cachedSimpleSQL = replaySQL ?? unprojectedSaveSQL.literalSQL ?? unprojectedSaveSQL.sql;
|
|
1282
|
+
}
|
|
1283
|
+
return cachedSimpleSQL;
|
|
1284
|
+
};
|
|
1151
1285
|
// 5. Optionally wrap with record-change emission.
|
|
1152
1286
|
let overlappingChangeData;
|
|
1153
1287
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
1154
1288
|
// audit row for ITS writes only — the entity keeps TrackRecordChanges for everyone else.
|
|
1155
1289
|
if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
|
|
1156
|
-
const newData =
|
|
1157
|
-
const
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
if (diffChanges && Object.keys(diffChanges).length > 0) {
|
|
1290
|
+
const { NewData: newData, OldData: oldData } = await this.BuildRecordChangeSnapshots(entity, isUpdate, user);
|
|
1291
|
+
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
|
|
1292
|
+
if (payload) {
|
|
1293
|
+
// ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
|
|
1294
|
+
// for SS subtype propagation without running DiffObjects + JSON.stringify twice.
|
|
1295
|
+
if (isUpdate && oldData && payload.changesJSON) {
|
|
1163
1296
|
overlappingChangeData = {
|
|
1164
|
-
changesJSON:
|
|
1165
|
-
changesDescription:
|
|
1297
|
+
changesJSON: payload.changesJSON,
|
|
1298
|
+
changesDescription: payload.changesDescription,
|
|
1166
1299
|
};
|
|
1167
1300
|
}
|
|
1168
|
-
|
|
1169
|
-
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
|
|
1170
|
-
if (payload) {
|
|
1171
|
-
saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity);
|
|
1301
|
+
saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity, options, returnContext);
|
|
1172
1302
|
}
|
|
1173
1303
|
}
|
|
1174
1304
|
const result = {
|
|
1175
1305
|
fullSQL: saveSQL.sql,
|
|
1176
|
-
simpleSQL
|
|
1306
|
+
get simpleSQL() {
|
|
1307
|
+
return computeSimpleSQL();
|
|
1308
|
+
},
|
|
1177
1309
|
parameters: saveSQL.parameters ?? null,
|
|
1178
1310
|
};
|
|
1311
|
+
if ('literalSQL' in saveSQL) {
|
|
1312
|
+
Object.defineProperty(result, 'literalSQL', {
|
|
1313
|
+
enumerable: true,
|
|
1314
|
+
configurable: true,
|
|
1315
|
+
get() {
|
|
1316
|
+
return saveSQL.literalSQL;
|
|
1317
|
+
},
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1179
1320
|
if (overlappingChangeData) {
|
|
1180
1321
|
result.extraData = { overlappingChangeData };
|
|
1181
1322
|
}
|
|
1182
1323
|
return result;
|
|
1183
1324
|
}
|
|
1325
|
+
/**
|
|
1326
|
+
* The old and new snapshots a save's Record Change is built from. The audit trail stores
|
|
1327
|
+
* whole payloads and projects them per reader, so both snapshots describe the whole record
|
|
1328
|
+
* whoever saves it.
|
|
1329
|
+
*
|
|
1330
|
+
* - **A user denied nothing** (unrestricted and system-user saves): the object's own values.
|
|
1331
|
+
* No query, even when the object was loaded without some columns.
|
|
1332
|
+
* - **A restricted user's update** (their object never holds the fields they cannot read):
|
|
1333
|
+
* the stored values of those fields are read once and the snapshots are widened with them.
|
|
1334
|
+
* The diff is unchanged, because a field the object never held has the same stored value
|
|
1335
|
+
* on both sides.
|
|
1336
|
+
* - **Create**: there is no stored row yet. A field the INSERT omits because the user may
|
|
1337
|
+
* not supply it is left out rather than recorded with a value the record never got.
|
|
1338
|
+
*
|
|
1339
|
+
* The read runs on the save's connection: inside an open transaction it reads that
|
|
1340
|
+
* transaction's state. A save queued in a transaction group is generated when `Save()` is
|
|
1341
|
+
* called, so its snapshot reflects the row as of then — the same moment the object's own
|
|
1342
|
+
* old values describe.
|
|
1343
|
+
*/
|
|
1344
|
+
async BuildRecordChangeSnapshots(entity, isUpdate, user) {
|
|
1345
|
+
if (!isUpdate) {
|
|
1346
|
+
return CreateSnapshots(entity);
|
|
1347
|
+
}
|
|
1348
|
+
const narrow = { NewData: entity.GetAll(false), OldData: entity.GetAll(true) };
|
|
1349
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1350
|
+
if (lacking.size === 0) {
|
|
1351
|
+
return narrow;
|
|
1352
|
+
}
|
|
1353
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1354
|
+
return storedRow ? WidenUpdateSnapshots(entity, narrow, storedRow, lacking) : narrow;
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Generates a save's SQL with any stored-row read its Record Change snapshot needs run on
|
|
1358
|
+
* `connectionSource`. A transaction group that regenerates an item's SQL while its own
|
|
1359
|
+
* transaction is open passes that transaction, so the read sees the group's earlier writes and
|
|
1360
|
+
* never waits on the locks the group itself holds.
|
|
1361
|
+
*/
|
|
1362
|
+
async GenerateSaveSQLReadingOn(entity, isNew, user, connectionSource) {
|
|
1363
|
+
if (!connectionSource) {
|
|
1364
|
+
return this.GenerateSaveSQL(entity, isNew, user);
|
|
1365
|
+
}
|
|
1366
|
+
this._snapshotConnections.set(entity, connectionSource);
|
|
1367
|
+
try {
|
|
1368
|
+
return await this.GenerateSaveSQL(entity, isNew, user);
|
|
1369
|
+
}
|
|
1370
|
+
finally {
|
|
1371
|
+
this._snapshotConnections.delete(entity);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Deletes a record. Before the shared orchestration runs, a restricted user's delete reads the
|
|
1376
|
+
* stored values of the fields their object never held, so the delete's `FullRecordJSON` — the
|
|
1377
|
+
* snapshot a deleted record is restored from — is full width. `GenerateDeleteSQL` is
|
|
1378
|
+
* synchronous, so the snapshot is captured here and handed to it through
|
|
1379
|
+
* {@link RecordChangeDeleteSnapshot}. A user denied nothing costs no extra query.
|
|
1380
|
+
*/
|
|
1381
|
+
async Delete(entity, options, user) {
|
|
1382
|
+
const captured = await this.captureDeleteSnapshot(entity, options, user);
|
|
1383
|
+
try {
|
|
1384
|
+
return await super.Delete(entity, options, user);
|
|
1385
|
+
}
|
|
1386
|
+
finally {
|
|
1387
|
+
if (captured)
|
|
1388
|
+
this._deleteSnapshots.delete(entity);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
/** Reads and stores the full-width delete snapshot when one is needed; true when it stored one. */
|
|
1392
|
+
async captureDeleteSnapshot(entity, options, user) {
|
|
1393
|
+
if (!this.ShouldTrackRecordChanges(entity.EntityInfo) || options?.SkipRecordChanges === true || options?.ReplayOnly === true) {
|
|
1394
|
+
return false;
|
|
1395
|
+
}
|
|
1396
|
+
if (!entity.IsSaved || entity.EntityInfo.ExternalDataSourceID) {
|
|
1397
|
+
return false; // the orchestration refuses these; nothing to snapshot
|
|
1398
|
+
}
|
|
1399
|
+
const lacking = FieldsLackingStoredValue(entity, user);
|
|
1400
|
+
if (lacking.size === 0) {
|
|
1401
|
+
return false;
|
|
1402
|
+
}
|
|
1403
|
+
const storedRow = await this.ReadStoredRowForRecordChange(entity, user, lacking);
|
|
1404
|
+
if (!storedRow) {
|
|
1405
|
+
return false;
|
|
1406
|
+
}
|
|
1407
|
+
this._deleteSnapshots.set(entity, WidenDeleteSnapshot(entity, entity.GetAll(true), storedRow, lacking));
|
|
1408
|
+
return true;
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* The record snapshot a delete's Record Change carries: the full-width snapshot {@link Delete}
|
|
1412
|
+
* captured, else `narrow` (the object's own values, which are already full width whenever no
|
|
1413
|
+
* snapshot was needed).
|
|
1414
|
+
*/
|
|
1415
|
+
RecordChangeDeleteSnapshot(entity, narrow) {
|
|
1416
|
+
// Optional chaining: a provider built without running its constructor (a test host made
|
|
1417
|
+
// with Object.create) has no snapshot map, and then there is nothing captured.
|
|
1418
|
+
return this._deleteSnapshots?.get(entity) ?? narrow;
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Reads the stored values of `columns` — the fields a snapshot lacks — for a Record Change
|
|
1422
|
+
* snapshot. Provider-internal: no row-level filter and no field-security check, because the
|
|
1423
|
+
* payload is stored unprojected and projected for each reader. The row gets the same
|
|
1424
|
+
* post-processing as a `Load` (binary to base64, datetime adjustment, decryption,
|
|
1425
|
+
* fixed-width trimming). Runs on the connection the save is generated for when one was named
|
|
1426
|
+
* ({@link GenerateSaveSQLReadingOn}), else on the save's usual connection. Kept out of the SQL
|
|
1427
|
+
* log, which records the save itself.
|
|
1428
|
+
*/
|
|
1429
|
+
async ReadStoredRowForRecordChange(entity, user, columns) {
|
|
1430
|
+
const entityInfo = entity.EntityInfo;
|
|
1431
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, entity.PrimaryKey);
|
|
1432
|
+
const selectList = [...columns].map(name => this.QuoteIdentifier(name)).join(', ');
|
|
1433
|
+
const sql = `SELECT ${selectList} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${where}`;
|
|
1434
|
+
const options = {
|
|
1435
|
+
description: `Record Change snapshot of ${entityInfo.Name}`,
|
|
1436
|
+
ignoreLogging: true,
|
|
1437
|
+
connectionSource: this._snapshotConnections?.get(entity),
|
|
1438
|
+
};
|
|
1439
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, options, user);
|
|
1440
|
+
const rows = await this.PostProcessRows(rawRows, entityInfo, user);
|
|
1441
|
+
if (!rows || rows.length === 0) {
|
|
1442
|
+
return null;
|
|
1443
|
+
}
|
|
1444
|
+
return this.TrimFixedWidthValues(entityInfo, rows[0]);
|
|
1445
|
+
}
|
|
1184
1446
|
/**
|
|
1185
1447
|
* Builds a platform-specific TOP/LIMIT clause for non-paginated row limits.
|
|
1186
1448
|
* SQL Server: `TOP N`; PostgreSQL returns empty (uses LIMIT via BuildPaginationSQL).
|
|
@@ -1221,30 +1483,39 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1221
1483
|
* `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
|
|
1222
1484
|
* Server — both preserve case.
|
|
1223
1485
|
*/
|
|
1224
|
-
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride) {
|
|
1486
|
+
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride, schemaNameOverride) {
|
|
1225
1487
|
const rowsAreLimited = usingPagination || maxRowsForQuery > 0;
|
|
1226
1488
|
if (!rowsAreLimited)
|
|
1227
1489
|
return null;
|
|
1228
|
-
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1490
|
+
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, baseViewOverride ?? entityInfo.BaseView)}`;
|
|
1229
1491
|
}
|
|
1230
1492
|
/**
|
|
1231
|
-
* Resolves the
|
|
1232
|
-
*
|
|
1233
|
-
*
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
*
|
|
1240
|
-
*
|
|
1241
|
-
*
|
|
1242
|
-
* wrong: the minted entity's CodeName need not match the query-derived view name.)
|
|
1243
|
-
*
|
|
1244
|
-
* Convention-based for the base-view case: if the entity has no such materialization the wrapper view
|
|
1245
|
-
* won't exist and the read will error — opting into `'Materialized'` asserts the snapshot exists.
|
|
1493
|
+
* Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
|
|
1494
|
+
* optional loaded `MJUserViewEntityExtended`. An explicit empty string (`""`) on
|
|
1495
|
+
* `params.AlternateBaseView` overrides any saved view pin back to `BaseView` (`undefined`).
|
|
1496
|
+
*/
|
|
1497
|
+
resolveEffectiveAbvNameFromParams(params, viewEntity) {
|
|
1498
|
+
return GetEffectiveAlternateBaseViewName(params, viewEntity);
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* Resolves the view a RunView reads from: an explicit or pinned `AlternateBaseView` when present,
|
|
1502
|
+
* the entity's materialized wrapper view when `DataSource: 'Materialized'`, or the entity's live
|
|
1503
|
+
* `BaseView` by default.
|
|
1246
1504
|
*/
|
|
1247
|
-
GetEffectiveBaseView(entityInfo, params) {
|
|
1505
|
+
GetEffectiveBaseView(entityInfo, params, viewEntity, suppressDeprecationWarning = false) {
|
|
1506
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1507
|
+
if (effectiveAbvName) {
|
|
1508
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1509
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1510
|
+
}
|
|
1511
|
+
const resolution = ResolveAlternateBaseView({
|
|
1512
|
+
entity: entityInfo,
|
|
1513
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1514
|
+
suppressDeprecationWarning,
|
|
1515
|
+
callerName: 'GetEffectiveBaseView',
|
|
1516
|
+
});
|
|
1517
|
+
return resolution.effectiveViewName;
|
|
1518
|
+
}
|
|
1248
1519
|
// Case-INSENSITIVE prefix test (matches the sibling guard in providerBase.IsServerCacheAllowedForEntity):
|
|
1249
1520
|
// a BaseView returned with non-lowercase casing (e.g. 'Materialized_vwFoo' from a case-insensitive SQL
|
|
1250
1521
|
// Server, or a hand-authored entity) is still an already-materialized view — a case-sensitive check
|
|
@@ -1256,18 +1527,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1256
1527
|
}
|
|
1257
1528
|
/**
|
|
1258
1529
|
* Async status-aware wrapper around {@link GetEffectiveBaseView} for the BASE-VIEW materialization case.
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
* cache-invalidation event), so a cached status could otherwise be stale. Non-materialized reads and minted
|
|
1266
|
-
* query virtual entities (BaseView already `materialized_vw…`) skip the lookup entirely (no extra query).
|
|
1267
|
-
*/
|
|
1268
|
-
async resolveEffectiveBaseView(entityInfo, params, contextUser) {
|
|
1530
|
+
*/
|
|
1531
|
+
async resolveEffectiveBaseView(entityInfo, params, contextUser, viewEntity) {
|
|
1532
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, viewEntity);
|
|
1533
|
+
if (effectiveAbvName) {
|
|
1534
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1535
|
+
}
|
|
1269
1536
|
if (!IsMaterializedDataSource(params.DataSource) || entityInfo.BaseView?.toLowerCase().startsWith('materialized_vw')) {
|
|
1270
|
-
return this.GetEffectiveBaseView(entityInfo, params);
|
|
1537
|
+
return this.GetEffectiveBaseView(entityInfo, params, viewEntity);
|
|
1271
1538
|
}
|
|
1272
1539
|
const rv = new RunView(this);
|
|
1273
1540
|
const res = await rv.RunView({
|
|
@@ -1295,6 +1562,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1295
1562
|
// base-view materialization always mints into the source entity's own schema.)
|
|
1296
1563
|
return row.ViewName?.trim() || `materialized_vw${entityInfo.CodeName}`;
|
|
1297
1564
|
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Resolves both the effective `{ schemaName, viewName }` for a RunView call, honoring:
|
|
1567
|
+
* 1. Explicit `params.AlternateBaseView` (including `""` to force `BaseView` over a saved view pin)
|
|
1568
|
+
* 2. Saved `UserView.DisplayState.alternateBaseView` (from `viewEntity`, `params.ViewEntity`, or loaded by `ViewID`/`ViewName`)
|
|
1569
|
+
* 3. `DataSource: 'Materialized'`
|
|
1570
|
+
* 4. `entityInfo.BaseView`
|
|
1571
|
+
*/
|
|
1572
|
+
async resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity) {
|
|
1573
|
+
let resolvedViewEntity = viewEntity ?? params?.ViewEntity ?? null;
|
|
1574
|
+
if (!resolvedViewEntity && typeof params?.AlternateBaseView !== 'string') {
|
|
1575
|
+
try {
|
|
1576
|
+
if (params?.ViewID && params.ViewID.length > 0) {
|
|
1577
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntity(params.ViewID, contextUser)) ?? null;
|
|
1578
|
+
}
|
|
1579
|
+
else if (params?.ViewName && params.ViewName.length > 0) {
|
|
1580
|
+
resolvedViewEntity = (await ViewInfo.GetViewEntityByName(params.ViewName, contextUser)) ?? null;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
catch (e) {
|
|
1584
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1585
|
+
LogError(`GenericDatabaseProvider.resolveEffectiveBaseViewTarget: failed to load User View (${params?.ViewID || params?.ViewName}) on entity "${entityInfo.Name}": ${msg}`);
|
|
1586
|
+
throw e;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
const effectiveAbvName = this.resolveEffectiveAbvNameFromParams(params, resolvedViewEntity);
|
|
1590
|
+
if (effectiveAbvName) {
|
|
1591
|
+
if (IsMaterializedDataSource(params?.DataSource)) {
|
|
1592
|
+
throw new Error(`AlternateBaseView '${effectiveAbvName}' on entity '${entityInfo.Name}' cannot be combined with DataSource: 'Materialized'.`);
|
|
1593
|
+
}
|
|
1594
|
+
const resolution = ResolveAlternateBaseView({
|
|
1595
|
+
entity: entityInfo,
|
|
1596
|
+
alternateBaseViewName: effectiveAbvName,
|
|
1597
|
+
contextUser,
|
|
1598
|
+
callerName: 'resolveEffectiveBaseViewTarget',
|
|
1599
|
+
});
|
|
1600
|
+
return { schemaName: resolution.effectiveSchemaName, viewName: resolution.effectiveViewName };
|
|
1601
|
+
}
|
|
1602
|
+
const viewName = await this.resolveEffectiveBaseView(entityInfo, params, contextUser, resolvedViewEntity);
|
|
1603
|
+
return { schemaName: entityInfo.SchemaName, viewName };
|
|
1604
|
+
}
|
|
1298
1605
|
/**
|
|
1299
1606
|
* Reports whether a materialization-metadata `RunView` FAILED, logging the failure when it did.
|
|
1300
1607
|
*
|
|
@@ -1465,14 +1772,74 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1465
1772
|
TransformExternalSQLClause(clause, _entityInfo) {
|
|
1466
1773
|
return clause;
|
|
1467
1774
|
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
|
|
1777
|
+
* WhereClause) stays inside the parentheses this provider puts around it, read with this
|
|
1778
|
+
* provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
|
|
1779
|
+
* security, which also carries API-key row filters and guest scope; a piece that closes its
|
|
1780
|
+
* parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
|
|
1781
|
+
* caller controls.
|
|
1782
|
+
*/
|
|
1783
|
+
AssertClauseBalanced(clause, label, options) {
|
|
1784
|
+
const check = IsBalancedSQLFragment(clause, this.Dialect, options);
|
|
1785
|
+
if (!check.IsBalanced) {
|
|
1786
|
+
throw new Error(`Invalid ${label}: ${check.Reason}`);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
/**
|
|
1790
|
+
* Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
|
|
1791
|
+
* {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
|
|
1792
|
+
* top-level AND terms, each term is transformed, checked and parenthesized on its own. A
|
|
1793
|
+
* PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
|
|
1794
|
+
* runs before this transform, so a rewrite that changes the caller's term cannot reach the
|
|
1795
|
+
* hook's term.
|
|
1796
|
+
*/
|
|
1797
|
+
PrepareExtraFilterSQL(extraFilter, entityInfo) {
|
|
1798
|
+
if (!extraFilter)
|
|
1799
|
+
return '';
|
|
1800
|
+
const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
|
|
1801
|
+
const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
|
|
1802
|
+
if (!terms || terms.length < 2) {
|
|
1803
|
+
this.AssertClauseBalanced(transformed, 'ExtraFilter');
|
|
1804
|
+
return transformed;
|
|
1805
|
+
}
|
|
1806
|
+
return terms
|
|
1807
|
+
.map((term) => {
|
|
1808
|
+
const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
|
|
1809
|
+
this.AssertClauseBalanced(termSQL, 'ExtraFilter');
|
|
1810
|
+
return `(${termSQL})`;
|
|
1811
|
+
})
|
|
1812
|
+
.join(' AND ');
|
|
1813
|
+
}
|
|
1468
1814
|
/**
|
|
1469
1815
|
* Optionally wraps a view query with user view run logging.
|
|
1470
1816
|
* SQL Server overrides to use spCreateUserViewRunWithDetail.
|
|
1471
1817
|
* Default: returns null (no view run logging).
|
|
1472
1818
|
*/
|
|
1473
|
-
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user) {
|
|
1819
|
+
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride) {
|
|
1474
1820
|
return null;
|
|
1475
1821
|
}
|
|
1822
|
+
/**
|
|
1823
|
+
* Maximum number of concurrent database view executions allowed within a single
|
|
1824
|
+
* {@link InternalRunViews} batch. Prevents large `RunViews` batches from exhausting
|
|
1825
|
+
* the connection pool in a single tick. Set to 0 or Infinity to disable the cap.
|
|
1826
|
+
* Default: 8.
|
|
1827
|
+
*/
|
|
1828
|
+
static { this.MaxConcurrentViewsPerBatch = 8; }
|
|
1829
|
+
/**
|
|
1830
|
+
* Process-wide single-flight coalescing registry for in-flight read-only RunView executions.
|
|
1831
|
+
* When multiple concurrent requests (across any per-request provider instance on the same
|
|
1832
|
+
* server process) execute an identical non-transactional RunView simultaneously, only the
|
|
1833
|
+
* first caller queries the database; joiners await the same promise and receive a shallow-cloned
|
|
1834
|
+
* result object and Results array.
|
|
1835
|
+
*/
|
|
1836
|
+
static { this._inFlightRunViews = new Map(); }
|
|
1837
|
+
/**
|
|
1838
|
+
* Number of currently in-flight coalesced RunView executions across this process.
|
|
1839
|
+
*/
|
|
1840
|
+
static get InFlightRunViewCount() {
|
|
1841
|
+
return GenericDatabaseProvider._inFlightRunViews.size;
|
|
1842
|
+
}
|
|
1476
1843
|
/**
|
|
1477
1844
|
* Shared InternalRunView implementation.
|
|
1478
1845
|
* Handles: view resolution, permissions, field selection, WHERE clause building
|
|
@@ -1482,6 +1849,117 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1482
1849
|
async InternalRunView(params, contextUser) {
|
|
1483
1850
|
return this.RunViewCore(params, contextUser);
|
|
1484
1851
|
}
|
|
1852
|
+
/**
|
|
1853
|
+
* Determines whether a RunView invocation is eligible for process-wide single-flight
|
|
1854
|
+
* coalescing across concurrent requests.
|
|
1855
|
+
*/
|
|
1856
|
+
canCoalesceRunViewInFlight(params, countExecutor) {
|
|
1857
|
+
if (!params || countExecutor) {
|
|
1858
|
+
return false;
|
|
1859
|
+
}
|
|
1860
|
+
if (params.ResultType && params.ResultType !== 'simple' && params.ResultType !== 'count_only') {
|
|
1861
|
+
return false;
|
|
1862
|
+
}
|
|
1863
|
+
if (params.SaveViewResults || params.ForceAuditLog) {
|
|
1864
|
+
return false;
|
|
1865
|
+
}
|
|
1866
|
+
if (this.IsCallerInAmbientTransaction() || this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction) {
|
|
1867
|
+
return false;
|
|
1868
|
+
}
|
|
1869
|
+
return true;
|
|
1870
|
+
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Builds the deterministic single-flight key for an in-flight RunView execution.
|
|
1873
|
+
* Includes connection string, entity/view identity, filter, orderBy, fields, resultType,
|
|
1874
|
+
* pagination/keyset cursor, aggregates, and effective user role/row-filter security context.
|
|
1875
|
+
*/
|
|
1876
|
+
buildSingleFlightRunViewKey(params, contextUser) {
|
|
1877
|
+
try {
|
|
1878
|
+
const user = contextUser ?? this.CurrentUser;
|
|
1879
|
+
if (!user) {
|
|
1880
|
+
return null;
|
|
1881
|
+
}
|
|
1882
|
+
const entityInfo = params.EntityName ? this.EntityByName(params.EntityName) : undefined;
|
|
1883
|
+
if (entityInfo?.AuditViewRuns && (params.ViewID || params.ViewName || params.ViewEntity)) {
|
|
1884
|
+
return null;
|
|
1885
|
+
}
|
|
1886
|
+
const baseFingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString);
|
|
1887
|
+
const fieldsKey = params.Fields && params.Fields.length > 0
|
|
1888
|
+
? [...params.Fields].map(f => f.trim().toLowerCase()).sort().join(',')
|
|
1889
|
+
: '*';
|
|
1890
|
+
const rlsClause = entityInfo && typeof entityInfo.GetEffectiveRowFilterWhereClause === 'function'
|
|
1891
|
+
? entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '')
|
|
1892
|
+
: `user:${user.ID ?? ''}`;
|
|
1893
|
+
const roleKey = user.UserRoles && user.UserRoles.length > 0
|
|
1894
|
+
? user.UserRoles.map(r => (r.RoleID ?? '').trim().toLowerCase()).sort().join(',')
|
|
1895
|
+
: `user:${user.ID ?? ''}`;
|
|
1896
|
+
const aggregatesKey = params.Aggregates && params.Aggregates.length > 0
|
|
1897
|
+
? JSON.stringify(params.Aggregates)
|
|
1898
|
+
: '';
|
|
1899
|
+
const afterKey = params.AfterKey ? params.AfterKey.ToConcatenatedString() : '';
|
|
1900
|
+
const ve = params.ViewEntity;
|
|
1901
|
+
const viewEntityKey = ve
|
|
1902
|
+
? `${ve.ID ?? ''}:${ve.WhereClause ?? ''}:${ve.SmartFilterWhereClause ?? ''}:${ve.AlternateBaseView ?? ''}`
|
|
1903
|
+
: '';
|
|
1904
|
+
const abvKey = IsExplicitBaseViewOverride(params)
|
|
1905
|
+
? '__base_override__'
|
|
1906
|
+
: (NormalizeAlternateBaseViewName(GetEffectiveAlternateBaseViewName(params)) ?? '');
|
|
1907
|
+
return [
|
|
1908
|
+
baseFingerprint,
|
|
1909
|
+
`f:${fieldsKey}`,
|
|
1910
|
+
`rt:${params.ResultType || 'simple'}`,
|
|
1911
|
+
`uss:${params.UserSearchString ?? ''}`,
|
|
1912
|
+
`vid:${params.ViewID ?? ''}`,
|
|
1913
|
+
`vn:${params.ViewName ?? ''}`,
|
|
1914
|
+
`ve:${viewEntityKey}`,
|
|
1915
|
+
`exRun:${params.ExcludeUserViewRunID ?? ''}`,
|
|
1916
|
+
`exAll:${params.ExcludeDataFromAllPriorViewRuns ? '1' : '0'}`,
|
|
1917
|
+
`ovEx:${params.OverrideExcludeFilter ?? ''}`,
|
|
1918
|
+
`igMax:${params.IgnoreMaxRows ? '1' : '0'}`,
|
|
1919
|
+
`max:${params.MaxRows ?? ''}`,
|
|
1920
|
+
`start:${params.StartRow ?? ''}`,
|
|
1921
|
+
`after:${afterKey}`,
|
|
1922
|
+
`ds:${params.DataSource ?? ''}`,
|
|
1923
|
+
`abv:${abvKey}`,
|
|
1924
|
+
`agg:${aggregatesKey}`,
|
|
1925
|
+
`roles:${roleKey}`,
|
|
1926
|
+
`rls:${rlsClause}`,
|
|
1927
|
+
].join('|');
|
|
1928
|
+
}
|
|
1929
|
+
catch {
|
|
1930
|
+
return null;
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Shallow-clones a shared single-flight RunViewResult and its row objects so concurrent
|
|
1935
|
+
* callers cannot mutate each other's result arrays or row properties in place.
|
|
1936
|
+
*/
|
|
1937
|
+
cloneSingleFlightRunViewResult(result) {
|
|
1938
|
+
if (!result) {
|
|
1939
|
+
return result;
|
|
1940
|
+
}
|
|
1941
|
+
return {
|
|
1942
|
+
...result,
|
|
1943
|
+
Results: Array.isArray(result.Results)
|
|
1944
|
+
? result.Results.map(row => (row && typeof row === 'object' ? { ...row } : row))
|
|
1945
|
+
: [],
|
|
1946
|
+
AggregateResults: result.AggregateResults
|
|
1947
|
+
? result.AggregateResults.map(a => ({ ...a }))
|
|
1948
|
+
: undefined,
|
|
1949
|
+
};
|
|
1950
|
+
}
|
|
1951
|
+
/**
|
|
1952
|
+
* Returns true when an identical read-only RunView is already in flight in the process-wide
|
|
1953
|
+
* single-flight registry. Used by {@link InternalRunViews} so duplicate views in a batch can
|
|
1954
|
+
* join an active query immediately without consuming a concurrency slot.
|
|
1955
|
+
*/
|
|
1956
|
+
hasInFlightSingleFlightView(params, contextUser) {
|
|
1957
|
+
if (!this.canCoalesceRunViewInFlight(params)) {
|
|
1958
|
+
return false;
|
|
1959
|
+
}
|
|
1960
|
+
const key = this.buildSingleFlightRunViewKey(params, contextUser);
|
|
1961
|
+
return !!key && GenericDatabaseProvider._inFlightRunViews.has(key);
|
|
1962
|
+
}
|
|
1485
1963
|
/**
|
|
1486
1964
|
* The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
|
|
1487
1965
|
* direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
|
|
@@ -1489,10 +1967,43 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1489
1967
|
* Everything before that step — permissions, RLS, filter screening — is unchanged.
|
|
1490
1968
|
*/
|
|
1491
1969
|
async RunViewCore(params, contextUser, countExecutor) {
|
|
1970
|
+
const singleFlightKey = this.canCoalesceRunViewInFlight(params, countExecutor)
|
|
1971
|
+
? this.buildSingleFlightRunViewKey(params, contextUser)
|
|
1972
|
+
: null;
|
|
1973
|
+
if (singleFlightKey) {
|
|
1974
|
+
const existing = GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey);
|
|
1975
|
+
if (existing) {
|
|
1976
|
+
existing.hasJoiners = true;
|
|
1977
|
+
const shared = await existing.promise;
|
|
1978
|
+
return this.cloneSingleFlightRunViewResult(shared);
|
|
1979
|
+
}
|
|
1980
|
+
const entry = {
|
|
1981
|
+
promise: null,
|
|
1982
|
+
hasJoiners: false,
|
|
1983
|
+
};
|
|
1984
|
+
const executionPromise = this.executeRunViewCore(params, contextUser, countExecutor)
|
|
1985
|
+
.finally(() => {
|
|
1986
|
+
if (GenericDatabaseProvider._inFlightRunViews.get(singleFlightKey) === entry) {
|
|
1987
|
+
GenericDatabaseProvider._inFlightRunViews.delete(singleFlightKey);
|
|
1988
|
+
}
|
|
1989
|
+
});
|
|
1990
|
+
entry.promise = executionPromise;
|
|
1991
|
+
GenericDatabaseProvider._inFlightRunViews.set(singleFlightKey, entry);
|
|
1992
|
+
const result = await executionPromise;
|
|
1993
|
+
return entry.hasJoiners
|
|
1994
|
+
? this.cloneSingleFlightRunViewResult(result)
|
|
1995
|
+
: result;
|
|
1996
|
+
}
|
|
1997
|
+
return this.executeRunViewCore(params, contextUser, countExecutor);
|
|
1998
|
+
}
|
|
1999
|
+
async executeRunViewCore(params, contextUser, countExecutor) {
|
|
1492
2000
|
if (params?.Aggregates?.length) {
|
|
1493
2001
|
LogStatus(`[GenericDatabaseProvider] InternalRunView received aggregates: entityName=${params.EntityName}, viewID=${params.ViewID}, viewName=${params.ViewName}, aggregateCount=${params.Aggregates.length}`);
|
|
1494
2002
|
}
|
|
1495
2003
|
const startTime = new Date();
|
|
2004
|
+
// The entity the view reads, once resolved — the catch below needs it to tell a restricted
|
|
2005
|
+
// caller's "no such column" apart from any other failure.
|
|
2006
|
+
let resolvedEntity = null;
|
|
1496
2007
|
try {
|
|
1497
2008
|
if (!params)
|
|
1498
2009
|
return null;
|
|
@@ -1502,12 +2013,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1502
2013
|
// ── View / Entity resolution ──
|
|
1503
2014
|
let viewEntity = null;
|
|
1504
2015
|
let entityInfo = null;
|
|
1505
|
-
|
|
1506
|
-
viewEntity = params.ViewEntity;
|
|
1507
|
-
else if (params.ViewID && params.ViewID.length > 0)
|
|
1508
|
-
viewEntity = await ViewInfo.GetViewEntity(params.ViewID, contextUser) ?? null;
|
|
1509
|
-
else if (params.ViewName && params.ViewName.length > 0)
|
|
1510
|
-
viewEntity = await ViewInfo.GetViewEntityByName(params.ViewName, contextUser) ?? null;
|
|
2016
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
1511
2017
|
if (!viewEntity) {
|
|
1512
2018
|
if (!params.EntityName || params.EntityName.length === 0)
|
|
1513
2019
|
throw new Error('EntityName is required when ViewID or ViewName is not provided');
|
|
@@ -1521,6 +2027,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1521
2027
|
throw new Error(`Entity ID: ${viewEntity.EntityID} not found in metadata`);
|
|
1522
2028
|
}
|
|
1523
2029
|
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2030
|
+
resolvedEntity = entityInfo;
|
|
2031
|
+
// A stored view's properties: refused here (Success:false, naming the property) before any SQL runs.
|
|
2032
|
+
const propertyFilter = this.BuildViewPropertyFilter(viewEntity, entityInfo, params, user);
|
|
1524
2033
|
// ── External data source dispatch ──
|
|
1525
2034
|
// Entities backed by an external data source are proxied live through a
|
|
1526
2035
|
// driver and have no view/sproc in the MJ DB, so delegate before any SQL
|
|
@@ -1531,11 +2040,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1531
2040
|
this.assertExternalReadAllowedUnderRLS(entityInfo, user);
|
|
1532
2041
|
// Refuse params we can't honor remotely rather than silently dropping them — most
|
|
1533
2042
|
// importantly AfterKey, which would otherwise return the same page on every call.
|
|
1534
|
-
this.assertExternalRunViewParamsSupported(params, entityInfo.Name);
|
|
2043
|
+
this.assertExternalRunViewParamsSupported(params, entityInfo.Name, viewEntity);
|
|
2044
|
+
if (propertyFilter) {
|
|
2045
|
+
throw new Error(`View properties are not supported for external-data-source entity '${entityInfo.Name}'.`);
|
|
2046
|
+
}
|
|
1535
2047
|
// A saved view's stored WhereClause/OrderBy live on viewEntity, not params, and the
|
|
1536
2048
|
// normal SQL path that applies them runs below this early return — so fold them in
|
|
1537
2049
|
// here, else a UserView over an external entity silently returns unfiltered rows.
|
|
1538
2050
|
const externalParams = await this.mergeExternalViewParams(params, viewEntity, user);
|
|
2051
|
+
this.assertExternalClausesRespectFieldSecurity(entityInfo, externalParams, user);
|
|
1539
2052
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Entity '${entityInfo.Name}'`);
|
|
1540
2053
|
const externalResult = await externalRouter.RunViewExternal(entityInfo, externalParams, user, this);
|
|
1541
2054
|
// Apply the same row post-processing MJ-DB reads get (field decryption + datetime
|
|
@@ -1544,16 +2057,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1544
2057
|
// Generic-erasure boundary: PostProcessRows operates on Record<string,unknown>[]
|
|
1545
2058
|
// but Results is typed T[]; the double-cast bridges that erasure (not a lazy `any`).
|
|
1546
2059
|
const rows = externalResult.Results;
|
|
1547
|
-
|
|
2060
|
+
const processed = (await this.PostProcessRows(rows, entityInfo, user));
|
|
2061
|
+
externalResult.Results = this.projectExternalRowsForCaller(processed, entityInfo, externalParams, user);
|
|
1548
2062
|
}
|
|
1549
2063
|
return externalResult;
|
|
1550
2064
|
}
|
|
1551
2065
|
// ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
|
|
1552
|
-
const extraFilter = this.
|
|
2066
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
|
|
1553
2067
|
const userSearchString = params.UserSearchString ?? '';
|
|
1554
2068
|
const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
|
|
1555
2069
|
const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
|
|
1556
2070
|
const saveViewResults = params.SaveViewResults ?? false;
|
|
2071
|
+
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
2072
|
+
this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
2073
|
+
// Field-level security on the clauses as this provider runs them, now that a ViewID- or
|
|
2074
|
+
// ViewName-only request has an entity. Before any SQL, like every other screen here.
|
|
2075
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [
|
|
2076
|
+
extraFilter,
|
|
2077
|
+
overrideExcludeFilter,
|
|
2078
|
+
...(params.Aggregates ?? []).map(a => a?.expression),
|
|
2079
|
+
], user);
|
|
1557
2080
|
// ── TOP / pagination mode ──
|
|
1558
2081
|
// Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
|
|
1559
2082
|
// and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
|
|
@@ -1598,34 +2121,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1598
2121
|
const fields = this.getRunTimeViewFieldString(params, viewEntity, user);
|
|
1599
2122
|
// ── Build SELECT and COUNT SQL ──
|
|
1600
2123
|
// DataSource:'Materialized' routes the read to the entity's materialized wrapper view
|
|
1601
|
-
// (same shape, so RLS/paging/fields all apply identically);
|
|
1602
|
-
|
|
2124
|
+
// (same shape, so RLS/paging/fields all apply identically); AlternateBaseView routes to
|
|
2125
|
+
// a registered alternate base view (which may also live in a custom schema); default stays the live base view.
|
|
2126
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser, viewEntity);
|
|
2127
|
+
const effectiveBaseView = effectiveTarget.viewName;
|
|
2128
|
+
const effectiveSchemaName = effectiveTarget.schemaName;
|
|
1603
2129
|
const topFragment = topSQL ? topSQL + ' ' : '';
|
|
1604
|
-
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(
|
|
2130
|
+
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`;
|
|
1605
2131
|
// count_only ALWAYS needs the count query — BuildTotalRowCountSQL only emits
|
|
1606
2132
|
// it when rows are limited (its pagination purpose), which previously left
|
|
1607
2133
|
// count_only with no COUNT at all (silently returned TotalRowCount 0).
|
|
1608
2134
|
let countSQL = params.ResultType === 'count_only'
|
|
1609
|
-
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(
|
|
1610
|
-
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView);
|
|
2135
|
+
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`
|
|
2136
|
+
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName);
|
|
1611
2137
|
// ── WHERE clause assembly ──
|
|
1612
2138
|
let whereSQL = '';
|
|
1613
2139
|
let bHasWhere = false;
|
|
1614
2140
|
// 1. View where clause
|
|
1615
2141
|
if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
|
|
1616
2142
|
const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
|
|
1617
|
-
// SECURITY: a stored view WhereClause originates from a client save, so
|
|
1618
|
-
//
|
|
1619
|
-
//
|
|
1620
|
-
//
|
|
1621
|
-
//
|
|
1622
|
-
//
|
|
1623
|
-
//
|
|
1624
|
-
//
|
|
2143
|
+
// SECURITY: a stored view WhereClause originates from a client save, so the rendered
|
|
2144
|
+
// clause passes the full client-clause screen (ScreenStoredViewWhereClause) and the
|
|
2145
|
+
// keyword denylist ExtraFilter gets. The one exemption is CustomWhereClause views:
|
|
2146
|
+
// those are admin-authored (MJUserViewEntityServer's save gate restricts setting/
|
|
2147
|
+
// changing them to Owner-type users) and may legitimately contain constructs the
|
|
2148
|
+
// screens block. Auto-generated clauses (FilterState / SmartFilter / nested
|
|
2149
|
+
// {%UserView%} templates) are written against entity base views, which the screens
|
|
2150
|
+
// permit when the running user reads each of those entities unscoped.
|
|
2151
|
+
this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
|
|
2152
|
+
// Field-level security covers CustomWhereClause views too: their clause is
|
|
2153
|
+
// admin-written, but it still runs as the acting user and could read a column
|
|
2154
|
+
// that user is denied.
|
|
2155
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [renderedWhere], user);
|
|
1625
2156
|
const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
|
|
1626
2157
|
if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
|
|
1627
2158
|
throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
|
|
1628
2159
|
}
|
|
2160
|
+
// CustomWhereClause views too: an unbalanced clause would take row-level security
|
|
2161
|
+
// out of force for everyone who runs the view. Only their admin-written text may
|
|
2162
|
+
// carry comments.
|
|
2163
|
+
this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
|
|
2164
|
+
AllowComments: isCustomWhereClause,
|
|
2165
|
+
});
|
|
1629
2166
|
whereSQL = `(${renderedWhere})`;
|
|
1630
2167
|
bHasWhere = true;
|
|
1631
2168
|
}
|
|
@@ -1636,6 +2173,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1636
2173
|
whereSQL = bHasWhere ? `${whereSQL} AND (${extraFilter})` : `(${extraFilter})`;
|
|
1637
2174
|
bHasWhere = true;
|
|
1638
2175
|
}
|
|
2176
|
+
// 2b. View properties: one typed predicate per property with a value, after the view's
|
|
2177
|
+
// own clause and ExtraFilter. Row-level security is still ANDed on below.
|
|
2178
|
+
if (propertyFilter.length > 0) {
|
|
2179
|
+
whereSQL = bHasWhere ? `${whereSQL} AND (${propertyFilter})` : `(${propertyFilter})`;
|
|
2180
|
+
bHasWhere = true;
|
|
2181
|
+
}
|
|
1639
2182
|
// 3. User search string
|
|
1640
2183
|
//
|
|
1641
2184
|
// 🚨 NOT screened by ValidateUserProvidedSQLClause (#4392). That denylist exists for
|
|
@@ -1655,7 +2198,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1655
2198
|
// in a literal: it is what keeps the text inside the quotes, where no keyword it
|
|
1656
2199
|
// contains can mean anything to the parser.
|
|
1657
2200
|
if (userSearchString.length > 0) {
|
|
1658
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user);
|
|
2201
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
1659
2202
|
if (sUserSearchSQL.length > 0) {
|
|
1660
2203
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
1661
2204
|
bHasWhere = true;
|
|
@@ -1670,8 +2213,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1670
2213
|
// first column's value with a prior run — refuse rather than return the wrong rows.
|
|
1671
2214
|
this.assertSingleColumnPrimaryKey(entityInfo, 'ExcludeUserViewRunID / ExcludeDataFromAllPriorViewRuns');
|
|
1672
2215
|
let sExcludeSQL = `${this.QuoteIdentifier(entityInfo.FirstPrimaryKey.Name)} NOT IN (SELECT RecordID FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwUserViewRunDetails')} WHERE EntityID='${viewEntity?.EntityID}' AND`; // first-pk-ok: guarded above — view-run RecordID is a single bare key value, PrimaryKeys.length === 1 enforced
|
|
1673
|
-
if (params.ExcludeDataFromAllPriorViewRuns === true)
|
|
2216
|
+
if (params.ExcludeDataFromAllPriorViewRuns === true) {
|
|
2217
|
+
// SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
|
|
2218
|
+
if (!IsValidUUID(String(viewEntity?.ID ?? '')))
|
|
2219
|
+
throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
|
|
1674
2220
|
sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
|
|
2221
|
+
}
|
|
1675
2222
|
else {
|
|
1676
2223
|
// SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
|
|
1677
2224
|
// interpolated directly into SQL here. Unlike ExtraFilter/OrderBy/
|
|
@@ -1687,6 +2234,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1687
2234
|
if (overrideExcludeFilter.length > 0) {
|
|
1688
2235
|
if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
|
|
1689
2236
|
throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
|
|
2237
|
+
this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
1690
2238
|
sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
|
|
1691
2239
|
}
|
|
1692
2240
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
|
|
@@ -1749,13 +2297,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1749
2297
|
const orderBy = rawOrderBy.length > 0
|
|
1750
2298
|
? (usingKeyset || orderByIsPkFallback ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
|
|
1751
2299
|
: '';
|
|
2300
|
+
if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
|
|
2301
|
+
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
2302
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [orderBy], user);
|
|
2303
|
+
// No caller OrderBy means the sort came from the saved view's stored sort state.
|
|
2304
|
+
if (!params.OrderBy && viewEntity)
|
|
2305
|
+
this.ScreenStoredViewOrderBy(orderBy, user);
|
|
2306
|
+
}
|
|
1752
2307
|
// View run logging (SQL Server-specific, others return null)
|
|
1753
2308
|
let userViewRunID = '';
|
|
1754
2309
|
if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
|
|
1755
2310
|
// Pass entityInfo + effectiveBaseView so the logged read honors DataSource:'Materialized'
|
|
1756
2311
|
// (reads the snapshot). effectiveBaseView === entityInfo.BaseView on the default live path,
|
|
1757
2312
|
// so non-materialized reads are unchanged.
|
|
1758
|
-
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user);
|
|
2313
|
+
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName);
|
|
1759
2314
|
if (logResult) {
|
|
1760
2315
|
viewSQL = logResult.executeViewSQL;
|
|
1761
2316
|
userViewRunID = logResult.runID;
|
|
@@ -1796,33 +2351,59 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1796
2351
|
if (params.Aggregates && params.Aggregates.length > 0) {
|
|
1797
2352
|
// Aggregate over the SAME source the rows/count came from — effectiveBaseView, so a caller
|
|
1798
2353
|
// asking for DataSource:'Materialized' gets aggregates over the snapshot, not the live view.
|
|
1799
|
-
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo,
|
|
2354
|
+
const aggregateBuild = this.BuildAggregateSQL(params.Aggregates, entityInfo, effectiveSchemaName, effectiveBaseView, whereSQL);
|
|
1800
2355
|
aggregateSQL = aggregateBuild.aggregateSQL;
|
|
1801
2356
|
aggregateValidationErrors = aggregateBuild.validationErrors;
|
|
2357
|
+
this.assertAggregateRefusalsAreNotColumnProbes(aggregateValidationErrors, entityInfo, user);
|
|
1802
2358
|
}
|
|
1803
|
-
// ── Execute queries
|
|
1804
|
-
const
|
|
1805
|
-
const
|
|
2359
|
+
// ── Execute queries (single TDS batch via ExecuteSQLBatch when multiple SQL statements are needed) ──
|
|
2360
|
+
const sqlQueries = [];
|
|
2361
|
+
const sqlQueryKeys = [];
|
|
2362
|
+
let countExecutorPromise = null;
|
|
1806
2363
|
if (params.ResultType !== 'count_only') {
|
|
1807
|
-
|
|
1808
|
-
|
|
2364
|
+
sqlQueries.push(viewSQL);
|
|
2365
|
+
sqlQueryKeys.push('data');
|
|
1809
2366
|
}
|
|
1810
2367
|
const maxRowsUsed = params.MaxRows || entityInfo.UserViewMaxRows;
|
|
1811
|
-
|
|
2368
|
+
// SkipTotalRowCount is an explicit caller opt-out of the count (see RunViewParams);
|
|
2369
|
+
// count_only still counts — that result IS the count, the flag cannot mean anything there.
|
|
2370
|
+
const skipCount = params.SkipTotalRowCount === true && params.ResultType !== 'count_only';
|
|
2371
|
+
const willNeedCount = countSQL && ((usingPagination && !skipCount) || params.ResultType === 'count_only');
|
|
1812
2372
|
if (willNeedCount) {
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
2373
|
+
if (countExecutor && params.ResultType === 'count_only') {
|
|
2374
|
+
countExecutorPromise = countExecutor(countSQL);
|
|
2375
|
+
}
|
|
2376
|
+
else {
|
|
2377
|
+
sqlQueries.push(countSQL);
|
|
2378
|
+
sqlQueryKeys.push('count');
|
|
2379
|
+
}
|
|
1817
2380
|
}
|
|
1818
2381
|
const aggregateStartTime = Date.now();
|
|
1819
2382
|
if (aggregateSQL) {
|
|
1820
|
-
|
|
1821
|
-
|
|
2383
|
+
sqlQueries.push(aggregateSQL);
|
|
2384
|
+
sqlQueryKeys.push('aggregate');
|
|
1822
2385
|
}
|
|
1823
|
-
const results = await Promise.all(queries);
|
|
1824
2386
|
const resultMap = {};
|
|
1825
|
-
|
|
2387
|
+
if (sqlQueries.length === 1 && !countExecutorPromise) {
|
|
2388
|
+
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser);
|
|
2389
|
+
}
|
|
2390
|
+
else if (sqlQueries.length > 0 && countExecutorPromise) {
|
|
2391
|
+
const [batchResults, countRes] = await Promise.all([
|
|
2392
|
+
sqlQueries.length === 1
|
|
2393
|
+
? this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser).then(r => [r])
|
|
2394
|
+
: this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser),
|
|
2395
|
+
countExecutorPromise,
|
|
2396
|
+
]);
|
|
2397
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2398
|
+
resultMap['count'] = countRes;
|
|
2399
|
+
}
|
|
2400
|
+
else if (sqlQueries.length > 1) {
|
|
2401
|
+
const batchResults = await this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser);
|
|
2402
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2403
|
+
}
|
|
2404
|
+
else if (countExecutorPromise) {
|
|
2405
|
+
resultMap['count'] = await countExecutorPromise;
|
|
2406
|
+
}
|
|
1826
2407
|
// ── Process data rows ──
|
|
1827
2408
|
let retData = resultMap['data'] || [];
|
|
1828
2409
|
if (retData.length > 0 && params.ResultType !== 'count_only') {
|
|
@@ -1835,7 +2416,34 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1835
2416
|
if (countResult && countResult.length > 0)
|
|
1836
2417
|
rowCount = countResult[0].TotalRowCount;
|
|
1837
2418
|
}
|
|
1838
|
-
else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed) {
|
|
2419
|
+
else if (countSQL && maxRowsUsed && maxRowsUsed > 1 && retData.length === maxRowsUsed && !skipCount) {
|
|
2420
|
+
// A row-limited read that came back FULL may have been truncated, so the total is
|
|
2421
|
+
// worth a second round trip: this is what makes Explorer's "100 of 299" correct.
|
|
2422
|
+
// `maxRowsUsed > 1` carves out the ONE case where it cannot be: a `MaxRows:1`
|
|
2423
|
+
// probe. Those callers ask "does a row exist / give me the one row" — a
|
|
2424
|
+
// record-map lookup, a single-key resolve — and never read TotalRowCount. The
|
|
2425
|
+
// count they triggered was pure cost, and SEQUENTIAL cost: it runs after the data
|
|
2426
|
+
// query has already resolved, so it is a full extra round trip on the critical
|
|
2427
|
+
// path, not a parallel one.
|
|
2428
|
+
//
|
|
2429
|
+
// Measured on a live tenant over a 120-second census: 1,000 record-map lookups
|
|
2430
|
+
// fired 721 of these counts and 800 row lookups fired 600 — 1,321 extra round
|
|
2431
|
+
// trips totalling 9,760 ms, 11.4% of ALL SQL time in the window. Nothing read a
|
|
2432
|
+
// single one of the results.
|
|
2433
|
+
//
|
|
2434
|
+
// Everything with `maxRowsUsed > 1` is untouched, so the "100 of 299" behaviour
|
|
2435
|
+
// is preserved exactly; only the degenerate single-row probe changes.
|
|
2436
|
+
//
|
|
2437
|
+
// What DOES change for `MaxRows:1`, stated plainly: with no `rowCount`, the return
|
|
2438
|
+
// below falls back to `rowCount ?? retData.length`, so a hit now reports
|
|
2439
|
+
// `TotalRowCount: 1` instead of the whole view's row count. That is the entire
|
|
2440
|
+
// observable difference, and it is confined to a limit of exactly one row — a shape
|
|
2441
|
+
// no caller asks for in order to learn a total, because a total is the one thing a
|
|
2442
|
+
// single-row limit cannot tell it anything about.
|
|
2443
|
+
//
|
|
2444
|
+
// `!skipCount`: a caller that never reads TotalRowCount can also opt out of this count
|
|
2445
|
+
// on a full multi-row page (RunViewParams.SkipTotalRowCount); the pagination count
|
|
2446
|
+
// above honours the same flag.
|
|
1839
2447
|
const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
|
|
1840
2448
|
if (countResult && countResult.length > 0)
|
|
1841
2449
|
rowCount = countResult[0].TotalRowCount;
|
|
@@ -1895,6 +2503,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1895
2503
|
if (this.isConnectionError(e)) {
|
|
1896
2504
|
throw e;
|
|
1897
2505
|
}
|
|
2506
|
+
// A field-security refusal throws, as the provider's pre-cache gate does, and a
|
|
2507
|
+
// restricted caller's "no such column" becomes the same refusal — so a denied column
|
|
2508
|
+
// and a missing one look identical however the request reached this point.
|
|
2509
|
+
const fieldSecurityError = this.fieldSecurityErrorFor(e, resolvedEntity, contextUser ?? this.CurrentUser);
|
|
2510
|
+
if (fieldSecurityError) {
|
|
2511
|
+
throw fieldSecurityError;
|
|
2512
|
+
}
|
|
1898
2513
|
const exceptionStopTime = new Date();
|
|
1899
2514
|
LogError(e);
|
|
1900
2515
|
return {
|
|
@@ -1908,12 +2523,155 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1908
2523
|
};
|
|
1909
2524
|
}
|
|
1910
2525
|
}
|
|
2526
|
+
/** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
|
|
2527
|
+
async LoadRunViewEntity(params, contextUser) {
|
|
2528
|
+
if (params.ViewEntity)
|
|
2529
|
+
return params.ViewEntity;
|
|
2530
|
+
if (params.ViewID && params.ViewID.length > 0)
|
|
2531
|
+
return await ViewInfo.GetViewEntity(params.ViewID, contextUser) ?? null;
|
|
2532
|
+
if (params.ViewName && params.ViewName.length > 0)
|
|
2533
|
+
return await ViewInfo.GetViewEntityByName(params.ViewName, contextUser) ?? null;
|
|
2534
|
+
return null;
|
|
2535
|
+
}
|
|
2536
|
+
/**
|
|
2537
|
+
* Works out a stored view's property values before the cache lookup (see
|
|
2538
|
+
* {@link ProviderBase.PrepareRunViewProperties}). The resolved values, token defaults included,
|
|
2539
|
+
* replace `Properties` and `ServerProperties`, so the fingerprint keys on what the run will use,
|
|
2540
|
+
* and RunViewCore resolving them again yields the same predicates. A run that would be refused
|
|
2541
|
+
* is left as it is and kept out of the cache; RunViewCore refuses it with its message. A view
|
|
2542
|
+
* that cannot be loaded is left to RunViewCore too, which reports it as it always has.
|
|
2543
|
+
*/
|
|
2544
|
+
async PrepareRunViewProperties(params, contextUser) {
|
|
2545
|
+
if (!params.ViewEntity && !params.ViewID && !params.ViewName) {
|
|
2546
|
+
return; // an entity run: RunViewCore refuses any properties it carries
|
|
2547
|
+
}
|
|
2548
|
+
let viewEntity;
|
|
2549
|
+
try {
|
|
2550
|
+
viewEntity = await this.LoadRunViewEntity(params, contextUser);
|
|
2551
|
+
}
|
|
2552
|
+
catch {
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
const entityInfo = viewEntity ? this.EntityByID(viewEntity.EntityID) : undefined;
|
|
2556
|
+
const user = contextUser ?? this.CurrentUser;
|
|
2557
|
+
if (!viewEntity || !entityInfo || !user) {
|
|
2558
|
+
return;
|
|
2559
|
+
}
|
|
2560
|
+
try {
|
|
2561
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2562
|
+
if (resolved) {
|
|
2563
|
+
params.ServerProperties = resolved.Values;
|
|
2564
|
+
delete params.Properties;
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
catch {
|
|
2568
|
+
params.BypassCache = true;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
/**
|
|
2572
|
+
* Checks a stored view's declared properties and works out each one's value for this run.
|
|
2573
|
+
* @returns null when the view declares none and the run sends none
|
|
2574
|
+
* @throws on a malformed definition, any refusal {@link ResolveViewPropertyValues} makes, or a
|
|
2575
|
+
* property with a value whose target field the user cannot read
|
|
2576
|
+
*/
|
|
2577
|
+
ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user) {
|
|
2578
|
+
const declared = viewEntity?.PropertiesObject ?? [];
|
|
2579
|
+
const sent = params.Properties !== undefined || params.ServerProperties !== undefined;
|
|
2580
|
+
if (!viewEntity) {
|
|
2581
|
+
if (sent)
|
|
2582
|
+
throw new Error('Properties apply only to a stored view: run it by ViewID, ViewName or ViewEntity.');
|
|
2583
|
+
return null;
|
|
2584
|
+
}
|
|
2585
|
+
if (declared.length === 0 && !sent) {
|
|
2586
|
+
return null;
|
|
2587
|
+
}
|
|
2588
|
+
const definitionErrors = ValidateUserViewProperties(declared, entityInfo.Fields.map(f => f.Name));
|
|
2589
|
+
if (definitionErrors.length > 0) {
|
|
2590
|
+
throw new Error(`View '${viewEntity.Name ?? viewEntity.ID}' has invalid properties: ${definitionErrors.join(' ')}`);
|
|
2591
|
+
}
|
|
2592
|
+
const values = ResolveViewPropertyValues(declared, params.Properties, params.ServerProperties, { User: user, TimeZone: params.TimeZone });
|
|
2593
|
+
this.assertViewPropertyFieldsReadable(declared, values, entityInfo, user);
|
|
2594
|
+
return { Declared: declared, Values: values };
|
|
2595
|
+
}
|
|
2596
|
+
/**
|
|
2597
|
+
* The WHERE clause a stored view's properties add to this run: '' when there are none.
|
|
2598
|
+
* Screened like any caller clause, though it is built only from typed literals.
|
|
2599
|
+
*/
|
|
2600
|
+
BuildViewPropertyFilter(viewEntity, entityInfo, params, user) {
|
|
2601
|
+
const resolved = this.ResolveRunViewPropertyValues(viewEntity, entityInfo, params, user);
|
|
2602
|
+
if (!resolved) {
|
|
2603
|
+
return '';
|
|
2604
|
+
}
|
|
2605
|
+
const filter = BuildViewPropertyFilter(resolved.Declared, resolved.Values, entityInfo.Fields.map(f => f.Name), this.Dialect);
|
|
2606
|
+
if (filter.length > 0 && !this.ValidateUserProvidedSQLClause(filter)) {
|
|
2607
|
+
throw new Error(`Invalid view property filter: contains one or more forbidden keywords`);
|
|
2608
|
+
}
|
|
2609
|
+
return filter;
|
|
2610
|
+
}
|
|
2611
|
+
/** The field-security check other predicates get: a property with a value may not filter a field the user cannot read. */
|
|
2612
|
+
assertViewPropertyFieldsReadable(declared, values, entityInfo, user) {
|
|
2613
|
+
if (!entityInfo.FieldLevelSecurityApplies) {
|
|
2614
|
+
return;
|
|
2615
|
+
}
|
|
2616
|
+
const denied = entityInfo.GetDeniedReadFields(user);
|
|
2617
|
+
for (const property of declared) {
|
|
2618
|
+
if (values[property.Name] !== null && denied.has(property.Target.Field.trim().toLowerCase())) {
|
|
2619
|
+
throw new FieldSecurityError(property.Target.Field, entityInfo.Name);
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
1911
2623
|
async InternalRunViews(params, contextUser) {
|
|
1912
2624
|
if (IsCoalescibleCountBatch(params)) {
|
|
1913
2625
|
return this.RunCoalescedCountBatch(params, contextUser);
|
|
1914
2626
|
}
|
|
1915
|
-
|
|
1916
|
-
|
|
2627
|
+
if (params.length === 0) {
|
|
2628
|
+
return [];
|
|
2629
|
+
}
|
|
2630
|
+
const limit = GenericDatabaseProvider.MaxConcurrentViewsPerBatch;
|
|
2631
|
+
if (!limit || !Number.isFinite(limit) || limit <= 0 || params.length <= limit) {
|
|
2632
|
+
const promises = params.map((p) => this.runBatchedView(p, contextUser));
|
|
2633
|
+
return Promise.all(promises);
|
|
2634
|
+
}
|
|
2635
|
+
const results = new Array(params.length);
|
|
2636
|
+
const started = new Array(params.length).fill(false);
|
|
2637
|
+
const joinerPromises = [];
|
|
2638
|
+
let cursor = 0;
|
|
2639
|
+
const attachInFlightDuplicates = (fromIndex) => {
|
|
2640
|
+
if (typeof this.hasInFlightSingleFlightView !== 'function') {
|
|
2641
|
+
return;
|
|
2642
|
+
}
|
|
2643
|
+
for (let j = fromIndex; j < params.length; j++) {
|
|
2644
|
+
if (!started[j] && this.hasInFlightSingleFlightView(params[j], contextUser)) {
|
|
2645
|
+
started[j] = true;
|
|
2646
|
+
const joinIdx = j;
|
|
2647
|
+
joinerPromises.push(this.runBatchedView(params[joinIdx], contextUser).then((res) => {
|
|
2648
|
+
results[joinIdx] = res;
|
|
2649
|
+
}));
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
};
|
|
2653
|
+
const runWorker = async () => {
|
|
2654
|
+
while (cursor < params.length) {
|
|
2655
|
+
const idx = cursor++;
|
|
2656
|
+
if (started[idx]) {
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
started[idx] = true;
|
|
2660
|
+
const viewPromise = this.runBatchedView(params[idx], contextUser);
|
|
2661
|
+
attachInFlightDuplicates(idx + 1);
|
|
2662
|
+
results[idx] = await viewPromise;
|
|
2663
|
+
}
|
|
2664
|
+
};
|
|
2665
|
+
const workerCount = Math.min(limit, params.length);
|
|
2666
|
+
const workers = [];
|
|
2667
|
+
for (let w = 0; w < workerCount; w++) {
|
|
2668
|
+
workers.push(runWorker());
|
|
2669
|
+
}
|
|
2670
|
+
await Promise.all(workers);
|
|
2671
|
+
if (joinerPromises.length > 0) {
|
|
2672
|
+
await Promise.all(joinerPromises);
|
|
2673
|
+
}
|
|
2674
|
+
return results;
|
|
1917
2675
|
}
|
|
1918
2676
|
/**
|
|
1919
2677
|
* All-`count_only` batch: every view runs the normal per-view path (so every
|
|
@@ -1925,8 +2683,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1925
2683
|
async RunCoalescedCountBatch(params, contextUser) {
|
|
1926
2684
|
const batch = new CountOnlyBatchCoalescer(params.length, (sql) => this.ExecuteSQL(sql, undefined, undefined, contextUser), (name) => this.QuoteIdentifier(name), (error) => this.isConnectionError(error));
|
|
1927
2685
|
return Promise.all(params.map((p, index) => this.RunViewCore(p, contextUser, (countSQL) => batch.Execute(index, countSQL))
|
|
2686
|
+
.catch((error) => GenericDatabaseProvider.fieldSecurityRefusalAsResult(error))
|
|
1928
2687
|
.finally(() => batch.MarkSettled(index))));
|
|
1929
2688
|
}
|
|
2689
|
+
/**
|
|
2690
|
+
* One view of a `RunViews` batch. A field-security refusal of this view becomes this view's
|
|
2691
|
+
* `Success: false` result, carrying the refusal's message, so it does not fail the views
|
|
2692
|
+
* batched with it. Any other error is thrown, as a single RunView throws it.
|
|
2693
|
+
*/
|
|
2694
|
+
async runBatchedView(params, contextUser) {
|
|
2695
|
+
try {
|
|
2696
|
+
return await this.InternalRunView(params, contextUser);
|
|
2697
|
+
}
|
|
2698
|
+
catch (error) {
|
|
2699
|
+
return GenericDatabaseProvider.fieldSecurityRefusalAsResult(error);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
1930
2702
|
/**************************************************************************/
|
|
1931
2703
|
// InternalRunView Helpers
|
|
1932
2704
|
/**************************************************************************/
|
|
@@ -1975,7 +2747,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1975
2747
|
* column list here buys the same protection without touching either.
|
|
1976
2748
|
*/
|
|
1977
2749
|
buildFieldSecuritySelectList(entityInfo, user) {
|
|
1978
|
-
if (!user || !entityInfo.
|
|
2750
|
+
if (!user || !entityInfo.FieldLevelSecurityApplies) {
|
|
1979
2751
|
return '*'; // the overwhelmingly common case — one boolean, unchanged SQL
|
|
1980
2752
|
}
|
|
1981
2753
|
const denied = entityInfo.GetDeniedReadFields(user);
|
|
@@ -2033,9 +2805,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2033
2805
|
// Binary columns are omitted from every implicit field list (saved-view columns and
|
|
2034
2806
|
// the no-Fields wildcard) unless requested; an explicit params.Fields entry is honoured.
|
|
2035
2807
|
const includeBinary = params.IncludeBinaryFields === true;
|
|
2808
|
+
// The request's own denied set, shared with its cache key (ResolveRequestDeniedReadFields),
|
|
2809
|
+
// so the slot this fill lands in is keyed for the columns it actually selects.
|
|
2036
2810
|
const flsUser = contextUser ?? this.CurrentUser;
|
|
2037
|
-
const denied = params.ResultType !== 'entity_object'
|
|
2038
|
-
?
|
|
2811
|
+
const denied = params.ResultType !== 'entity_object'
|
|
2812
|
+
? this.ResolveRequestDeniedReadFields(params, entityInfo, flsUser)
|
|
2039
2813
|
: new Set();
|
|
2040
2814
|
if (params.Fields) {
|
|
2041
2815
|
for (const ef of entityInfo.PrimaryKeys) {
|
|
@@ -2101,8 +2875,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2101
2875
|
* - escapes LIKE metacharacters (%, _, [, ]) in user input with ESCAPE '\\',
|
|
2102
2876
|
* - skips fields that are not sensible text-search targets (non-text types,
|
|
2103
2877
|
* unbounded text columns when FTX is off).
|
|
2878
|
+
*
|
|
2879
|
+
* @param deniedFields - The request's denied set (see ResolveRequestDeniedReadFields), so the
|
|
2880
|
+
* searched columns match the ones its cache key and SELECT list were built from. Read from
|
|
2881
|
+
* the entity for `contextUser` when omitted.
|
|
2104
2882
|
*/
|
|
2105
|
-
createViewUserSearchSQL(entityInfo, userSearchString, contextUser) {
|
|
2883
|
+
createViewUserSearchSQL(entityInfo, userSearchString, contextUser, deniedFields) {
|
|
2106
2884
|
let sUserSearchSQL = '';
|
|
2107
2885
|
const safeUserSearchString = userSearchString.replace(/'/g, "''");
|
|
2108
2886
|
// Field-level security: never search fields the user cannot read. Matching against a
|
|
@@ -2112,15 +2890,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2112
2890
|
// fields are simply excluded from the searched set. Computed once per call, never per
|
|
2113
2891
|
// field (the per-request precompute contract).
|
|
2114
2892
|
const user = contextUser ?? this.CurrentUser;
|
|
2115
|
-
const deniedSearchFields =
|
|
2116
|
-
? entityInfo.GetDeniedReadFields(user)
|
|
2117
|
-
: new Set();
|
|
2893
|
+
const deniedSearchFields = deniedFields
|
|
2894
|
+
?? (entityInfo.FieldLevelSecurityApplies && user ? entityInfo.GetDeniedReadFields(user) : new Set());
|
|
2118
2895
|
// The full-text index spans its indexed columns as one unit — a denied FTS-indexed
|
|
2119
2896
|
// column cannot be excluded from the index function. When (and only when) a denied
|
|
2120
2897
|
// field is FTS-indexed, fall back to the per-field LIKE path, which CAN exclude it.
|
|
2121
2898
|
const ftsCoversDeniedField = deniedSearchFields.size > 0 &&
|
|
2122
2899
|
entityInfo.Fields.some(f => f.FullTextSearchEnabled && deniedSearchFields.has(f.Name.trim().toLowerCase()));
|
|
2123
|
-
|
|
2900
|
+
// `FullTextSearchEnabled` alone is NOT enough to take this branch: the branch names
|
|
2901
|
+
// `FullTextSearchFunction` and, when that is null or blank, the `?? ''` below emitted
|
|
2902
|
+
// `... FROM "schema".""('term')` — a syntax error, thrown on EVERY user search of such an
|
|
2903
|
+
// entity, with no fallback. The two columns are independent (the flag can be set by hand
|
|
2904
|
+
// or by a metadata sync before CodeGen has minted the function), so the name has to be
|
|
2905
|
+
// checked, not assumed. A blank name now falls through to the per-field LIKE path, which
|
|
2906
|
+
// needs no database object and returns results.
|
|
2907
|
+
//
|
|
2908
|
+
// Composed with, not substituted for, the field-security condition above — both have to
|
|
2909
|
+
// hold to search through the index.
|
|
2910
|
+
const ftsFunctionName = entityInfo.FullTextSearchFunction;
|
|
2911
|
+
const hasFTSFunction = typeof ftsFunctionName === 'string' && ftsFunctionName.trim().length > 0;
|
|
2912
|
+
if (entityInfo.FullTextSearchEnabled && hasFTSFunction && !ftsCoversDeniedField) {
|
|
2124
2913
|
let u = safeUserSearchString;
|
|
2125
2914
|
const uUpper = u.toUpperCase();
|
|
2126
2915
|
// WORD-boundary tests, not substring tests (#4392). As substrings, `OR` matches
|
|
@@ -2162,9 +2951,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2162
2951
|
// Note this restores the pre-#4392 screen for this path; it does not close the
|
|
2163
2952
|
// unquoted-format hole, which the denylist never covered (`1) OR 1=1` carries no
|
|
2164
2953
|
// forbidden keyword). Quoting `{0}` in the format is what actually closes that.
|
|
2165
|
-
|
|
2954
|
+
//
|
|
2955
|
+
// The screen reads the quote-doubled term, because that is the text `{0}` becomes.
|
|
2956
|
+
const termIsSQL = this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields);
|
|
2957
|
+
if (termIsSQL && user) {
|
|
2958
|
+
// Spliced in unquoted, the term is a predicate the caller wrote, so it gets the
|
|
2959
|
+
// field-security gate every other caller predicate gets.
|
|
2960
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [safeUserSearchString], user);
|
|
2961
|
+
}
|
|
2962
|
+
if (termIsSQL && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
|
|
2166
2963
|
throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
|
|
2167
|
-
`which splices the term directly into SQL, and the term contains
|
|
2964
|
+
`which splices the term directly into SQL, and the term is not allowed there: it contains ` +
|
|
2965
|
+
`a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
|
|
2966
|
+
`tokens, such as an unbalanced quote or bracket.`);
|
|
2168
2967
|
}
|
|
2169
2968
|
const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
|
|
2170
2969
|
for (const field of entityInfo.Fields) {
|
|
@@ -2196,6 +2995,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2196
2995
|
sUserSearchSQL = '(1=0)';
|
|
2197
2996
|
}
|
|
2198
2997
|
}
|
|
2998
|
+
// A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
|
|
2999
|
+
this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
|
|
2199
3000
|
return sUserSearchSQL;
|
|
2200
3001
|
}
|
|
2201
3002
|
/**
|
|
@@ -2295,6 +3096,81 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2295
3096
|
return true;
|
|
2296
3097
|
}
|
|
2297
3098
|
/**************************************************************************/
|
|
3099
|
+
// Client clause screening
|
|
3100
|
+
/**************************************************************************/
|
|
3101
|
+
/**
|
|
3102
|
+
* SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
|
|
3103
|
+
* Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
|
|
3104
|
+
* fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
|
|
3105
|
+
*/
|
|
3106
|
+
AssertClauseFragmentIsSingleStatement(clause, label) {
|
|
3107
|
+
ClientClauseScreen.AssertSingleStatementFragment(clause, label, this.Dialect);
|
|
3108
|
+
}
|
|
3109
|
+
/**
|
|
3110
|
+
* SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
|
|
3111
|
+
* against this provider's entities and dialect, with `contextUser` as the acting user. With
|
|
3112
|
+
* `entityInfo`, the clause is screened in the form this provider runs a client clause for that
|
|
3113
|
+
* entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
|
|
3114
|
+
* outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
|
|
3115
|
+
* saved-view save gate (`MJUserViewEntityServer`).
|
|
3116
|
+
*/
|
|
3117
|
+
ScreenClientClause(clause, label, contextUser, entityInfo) {
|
|
3118
|
+
const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
|
|
3119
|
+
ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
|
|
3120
|
+
}
|
|
3121
|
+
/**
|
|
3122
|
+
* The field-security error a failed RunView must raise, or null to report the failure as
|
|
3123
|
+
* usual: a {@link FieldSecurityError} raised along the way, or — for a caller denied fields on
|
|
3124
|
+
* `entity` — a database "no such column" rejection, rewritten into the error a denied column
|
|
3125
|
+
* gets ({@link FieldSecuritySQLGate.ErrorForInvalidColumn}).
|
|
3126
|
+
*/
|
|
3127
|
+
fieldSecurityErrorFor(error, entity, user) {
|
|
3128
|
+
if (error instanceof Error && (error instanceof FieldSecurityError || error.name === FieldSecurityError.ErrorName)) {
|
|
3129
|
+
return error;
|
|
3130
|
+
}
|
|
3131
|
+
return FieldSecuritySQLGate.ErrorForInvalidColumn(error, entity, user);
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* For a caller denied fields on `entity`, throws the field-security error when an aggregate was
|
|
3135
|
+
* refused because it names a column the entity does not have. A denied column in an aggregate is
|
|
3136
|
+
* refused by the gate with that error, so an unknown one must not answer differently.
|
|
3137
|
+
*/
|
|
3138
|
+
assertAggregateRefusalsAreNotColumnProbes(errors, entity, user) {
|
|
3139
|
+
if (errors.length === 0 || !FieldSecuritySQLGate.UserCarriesDenials([entity], user)) {
|
|
3140
|
+
return;
|
|
3141
|
+
}
|
|
3142
|
+
for (const refused of errors) {
|
|
3143
|
+
const match = /references "((?:[^"]|"")*)", which (?:is not a column|matches more than one column) of this entity/.exec(refused.error ?? '');
|
|
3144
|
+
if (match) {
|
|
3145
|
+
// Named the way the gate names a denied column in the same expression, so the two
|
|
3146
|
+
// refusals read the same whatever case the caller typed.
|
|
3147
|
+
const column = FieldSecuritySQLGate.ReportedColumnName(refused.expression, match[1].replace(/""/g, '"'), this.PlatformKey);
|
|
3148
|
+
throw new FieldSecurityError(column, entity.Name);
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
/**
|
|
3153
|
+
* SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
|
|
3154
|
+
* Any user who can save a view can write its WhereClause, directly or through FilterState or a
|
|
3155
|
+
* Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
|
|
3156
|
+
* can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
|
|
3157
|
+
* request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
|
|
3158
|
+
* `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
|
|
3159
|
+
*/
|
|
3160
|
+
ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
|
|
3161
|
+
if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
|
|
3162
|
+
return; // truthy — the DB may hand back true or 1
|
|
3163
|
+
this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
|
|
3164
|
+
this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
|
|
3165
|
+
}
|
|
3166
|
+
/**
|
|
3167
|
+
* SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
|
|
3168
|
+
* the full client-clause screen. Any user who can save a view can write those.
|
|
3169
|
+
*/
|
|
3170
|
+
ScreenStoredViewOrderBy(orderBy, user) {
|
|
3171
|
+
this.ScreenClientClause(orderBy, 'OrderBy', user);
|
|
3172
|
+
}
|
|
3173
|
+
/**************************************************************************/
|
|
2298
3174
|
// RenderViewWhereClause — View Template Rendering
|
|
2299
3175
|
/**************************************************************************/
|
|
2300
3176
|
/**
|
|
@@ -2330,7 +3206,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2330
3206
|
// takes a one-column subquery — an entity with a composite key has no single column to return.
|
|
2331
3207
|
const innerEntityInfo = innerViewEntity.ViewEntityInfo;
|
|
2332
3208
|
this.assertSingleColumnPrimaryKey(innerEntityInfo, `The {%UserView%} template variable ${match}`);
|
|
2333
|
-
const
|
|
3209
|
+
const innerTarget = await this.resolveEffectiveBaseViewTarget(innerEntityInfo, { EntityName: innerEntityInfo.Name, ViewEntity: innerViewEntity }, user, innerViewEntity);
|
|
3210
|
+
const innerSQL = `SELECT ${this.QuoteIdentifier(innerEntityInfo.FirstPrimaryKey.Name)} FROM ${this.QuoteSchemaAndView(innerTarget.schemaName, innerTarget.viewName)} WHERE (${innerWhere})`; // first-pk-ok: guarded above — IN (subquery) takes one column, PrimaryKeys.length === 1 enforced
|
|
2334
3211
|
// Function replacement — `innerSQL` is generated SQL that can
|
|
2335
3212
|
// legitimately contain `$`. See issue #3171.
|
|
2336
3213
|
sWhere = sWhere.replace(match, () => innerSQL);
|
|
@@ -2444,6 +3321,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2444
3321
|
}
|
|
2445
3322
|
return items;
|
|
2446
3323
|
}
|
|
3324
|
+
/**
|
|
3325
|
+
* The field-security key of one request, built once per request (`params` object) and user.
|
|
3326
|
+
* A smart-cache-check item asks for it from each leg — its browser freshness check, the
|
|
3327
|
+
* server-cache lookup and the cache write — and the answer cannot change within the request:
|
|
3328
|
+
* the denied set it is built from is already resolved once per request.
|
|
3329
|
+
*/
|
|
3330
|
+
ComputeRunViewFLSFingerprintKey(params, contextUser) {
|
|
3331
|
+
const user = contextUser ?? this.CurrentUser;
|
|
3332
|
+
const memo = this._requestFLSKeys?.get(params);
|
|
3333
|
+
if (memo && memo.User === user && memo.Target === GenericDatabaseProvider.flsKeyTarget(params)) {
|
|
3334
|
+
return memo.Key;
|
|
3335
|
+
}
|
|
3336
|
+
const key = super.ComputeRunViewFLSFingerprintKey(params, user);
|
|
3337
|
+
this._requestFLSKeys?.set(params, { User: user, Target: GenericDatabaseProvider.flsKeyTarget(params), Key: key });
|
|
3338
|
+
return key;
|
|
3339
|
+
}
|
|
3340
|
+
/** What a request's field-security key is about: its entity, or the saved view it names. */
|
|
3341
|
+
static flsKeyTarget(params) {
|
|
3342
|
+
return `${params.EntityName ?? ''}|${params.ViewID ?? ''}|${params.ViewName ?? ''}|${params.ViewEntity ? 'loaded' : ''}`;
|
|
3343
|
+
}
|
|
3344
|
+
/** The message refusing `user` Read on `entityInfo`, or null when the user may read it. */
|
|
3345
|
+
readPermissionError(entityInfo, user) {
|
|
3346
|
+
try {
|
|
3347
|
+
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
3348
|
+
return null;
|
|
3349
|
+
}
|
|
3350
|
+
catch (e) {
|
|
3351
|
+
return e instanceof Error ? e.message : String(e);
|
|
3352
|
+
}
|
|
3353
|
+
}
|
|
2447
3354
|
/**
|
|
2448
3355
|
* Smart cache validation for batch RunViews.
|
|
2449
3356
|
* For each view request, if cacheStatus is provided, checks if the cache is current
|
|
@@ -2459,9 +3366,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2459
3366
|
}
|
|
2460
3367
|
// ── Superset/projection contract (same as the ProviderBase pipeline) ──
|
|
2461
3368
|
// For every cache-eligible item: widen Fields to ALL entity fields so any
|
|
2462
|
-
// cache write stores the
|
|
2463
|
-
//
|
|
2464
|
-
//
|
|
3369
|
+
// cache write stores every column the user's permission class may read (the
|
|
3370
|
+
// slot is keyed by that class), and remember the caller's requested shape
|
|
3371
|
+
// (∪ primary keys — platform contract) so every serve leg projects back down
|
|
3372
|
+
// before returning rows to the client. This path
|
|
2465
3373
|
// previously cached narrow rows under the Fields-agnostic fingerprint and
|
|
2466
3374
|
// served cached rows unprojected — one client's shape poisoned the slot
|
|
2467
3375
|
// for every subsequent caller.
|
|
@@ -2505,15 +3413,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2505
3413
|
const requested = p.Fields && p.Fields.length > 0
|
|
2506
3414
|
? p.Fields.map(f => f.trim().toLowerCase())
|
|
2507
3415
|
: null;
|
|
2508
|
-
// ALL fields, for every user:
|
|
2509
|
-
//
|
|
2510
|
-
//
|
|
3416
|
+
// ALL fields requested, for every user: the SELECT built from this list leaves
|
|
3417
|
+
// out the columns this user may not read, and the slot is keyed by the user's
|
|
3418
|
+
// permission class, so a slot holds only what its class may read.
|
|
3419
|
+
// ApplyFieldSecurityProjection still runs on every serve as a backstop.
|
|
2511
3420
|
this.ResolveIncludeBinaryFields(p, widenEntity);
|
|
2512
3421
|
p.Fields = this.ComputeRunViewFetchFields(widenEntity, p);
|
|
2513
3422
|
if (requested) {
|
|
2514
3423
|
callerFieldsByIndex.set(i, ProviderBase.UnionFieldsWithPrimaryKeys(requested, widenEntity));
|
|
2515
3424
|
}
|
|
2516
3425
|
}
|
|
3426
|
+
// A status the browser computed for other columns than this user may read now
|
|
3427
|
+
// describes a slot with the wrong columns, even if no row changed. Dropping it sends
|
|
3428
|
+
// the item down the "nothing cached" path, which answers with fresh rows.
|
|
3429
|
+
if (this.cacheStatusFieldSecurityDiffers(params[i].cacheStatus, p, user)) {
|
|
3430
|
+
params[i].cacheStatus = undefined;
|
|
3431
|
+
}
|
|
2517
3432
|
}
|
|
2518
3433
|
/** Projects rows down to the caller's requested shape for a given item index. */
|
|
2519
3434
|
const projectForCaller = (index, rows) => {
|
|
@@ -2535,6 +3450,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2535
3450
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: gateRejection });
|
|
2536
3451
|
continue;
|
|
2537
3452
|
}
|
|
3453
|
+
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
3454
|
+
// Read-permission gate for EVERY item whose entity is known, before any leg can answer:
|
|
3455
|
+
// an item with no cache status, and an external entity, are served from the server cache
|
|
3456
|
+
// on a hit WITHOUT re-entering InternalRunView, so a CanRead check that lived only on the
|
|
3457
|
+
// cache-miss path would let a user lacking permission receive rows another user warmed.
|
|
3458
|
+
if (entityInfo) {
|
|
3459
|
+
const permissionError = this.readPermissionError(entityInfo, user);
|
|
3460
|
+
if (permissionError !== null) {
|
|
3461
|
+
errorResults.push({ viewIndex: i, status: 'error', errorMessage: permissionError });
|
|
3462
|
+
continue;
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
2538
3465
|
// Keyset queries bypass the cache entirely (per the AfterKey API contract):
|
|
2539
3466
|
// each call uses a different seek key, so cached entries would never be
|
|
2540
3467
|
// reusable. Route directly to standard execution path.
|
|
@@ -2542,22 +3469,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2542
3469
|
itemsWithoutCacheCheck.push({ index: i, item });
|
|
2543
3470
|
continue;
|
|
2544
3471
|
}
|
|
2545
|
-
const entityInfo = item.params.EntityName ? this.EntityByName(item.params.EntityName) : undefined;
|
|
2546
3472
|
if (!entityInfo) {
|
|
2547
3473
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: `Entity ${item.params.EntityName} not found in metadata` });
|
|
2548
3474
|
continue;
|
|
2549
3475
|
}
|
|
2550
|
-
// Read-permission gate for EVERY entity (external + local) up front. This must run before
|
|
2551
|
-
// the external routing below: external entities are served from the server cache on a hit
|
|
2552
|
-
// WITHOUT re-entering InternalRunView, so if the CanRead check only lived on the cache-miss
|
|
2553
|
-
// path a user lacking permission could receive rows another user warmed into the cache.
|
|
2554
|
-
try {
|
|
2555
|
-
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2556
|
-
}
|
|
2557
|
-
catch (e) {
|
|
2558
|
-
errorResults.push({ viewIndex: i, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
2559
|
-
continue;
|
|
2560
|
-
}
|
|
2561
3476
|
// External-data-source entities can't participate in DB-side cache validation
|
|
2562
3477
|
// (no MJ base view / __mj_UpdatedAt to COUNT/MAX against). Route them to the
|
|
2563
3478
|
// standard execution path, which dispatches to the external driver and TTL-caches
|
|
@@ -2568,7 +3483,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2568
3483
|
}
|
|
2569
3484
|
itemsNeedingValidation.push({ index: i, item, entityInfo });
|
|
2570
3485
|
}
|
|
2571
|
-
// Phase 1: Check server's LocalCacheManager first (zero DB hits)
|
|
3486
|
+
// Phase 1: Check server's LocalCacheManager first (zero DB hits when within freshness window)
|
|
2572
3487
|
const currentResults = [];
|
|
2573
3488
|
const serverCacheStaleItems = [];
|
|
2574
3489
|
const serverCacheMissItems = [];
|
|
@@ -2579,6 +3494,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2579
3494
|
if (resolved.status === 'current') {
|
|
2580
3495
|
currentResults.push(resolved.result);
|
|
2581
3496
|
}
|
|
3497
|
+
else if (resolved.status === 'needs_verification') {
|
|
3498
|
+
serverCacheMissItems.push({
|
|
3499
|
+
index,
|
|
3500
|
+
item,
|
|
3501
|
+
entityInfo,
|
|
3502
|
+
serverCached: resolved.serverCached,
|
|
3503
|
+
fingerprint: resolved.fingerprint,
|
|
3504
|
+
});
|
|
3505
|
+
}
|
|
2582
3506
|
else {
|
|
2583
3507
|
serverCacheStaleItems.push({ index, item, entityInfo, serverCached: resolved.serverCached });
|
|
2584
3508
|
}
|
|
@@ -2587,29 +3511,63 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2587
3511
|
serverCacheMissItems.push({ index, item, entityInfo });
|
|
2588
3512
|
}
|
|
2589
3513
|
}
|
|
2590
|
-
// Phase 2: For server cache misses,
|
|
3514
|
+
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
2591
3515
|
const differentialItems = [];
|
|
2592
3516
|
const staleItemsNoTracking = [];
|
|
2593
3517
|
if (serverCacheMissItems.length > 0) {
|
|
2594
|
-
// Build WHERE clauses and run batched DB status check only for cache misses
|
|
3518
|
+
// Build WHERE clauses and run batched DB status check only for cache misses / TTL-expired slots
|
|
2595
3519
|
const itemsForDBCheck = [];
|
|
2596
|
-
for (const { index, item, entityInfo } of serverCacheMissItems) {
|
|
3520
|
+
for (const { index, item, entityInfo, serverCached, fingerprint } of serverCacheMissItems) {
|
|
2597
3521
|
try {
|
|
2598
3522
|
const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user);
|
|
2599
|
-
itemsForDBCheck.push({ index, item, entityInfo, whereSQL });
|
|
3523
|
+
itemsForDBCheck.push({ index, item, entityInfo, whereSQL, serverCached, fingerprint });
|
|
2600
3524
|
}
|
|
2601
3525
|
catch (e) {
|
|
2602
3526
|
errorResults.push({ viewIndex: index, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
2603
3527
|
}
|
|
2604
3528
|
}
|
|
2605
3529
|
const cacheStatusResults = await this.getBatchedServerCacheStatus(itemsForDBCheck, contextUser);
|
|
2606
|
-
for (const { index, item, entityInfo, whereSQL } of itemsForDBCheck) {
|
|
3530
|
+
for (const { index, item, entityInfo, whereSQL, serverCached, fingerprint } of itemsForDBCheck) {
|
|
2607
3531
|
const serverStatus = cacheStatusResults.get(index);
|
|
2608
3532
|
if (!serverStatus || !serverStatus.success) {
|
|
2609
|
-
|
|
3533
|
+
const statusError = serverStatus?.errorMessage || 'Failed to get cache status';
|
|
3534
|
+
const fieldSecurityError = FieldSecuritySQLGate.ErrorForInvalidColumn(statusError, entityInfo, user);
|
|
3535
|
+
errorResults.push({ viewIndex: index, status: 'error', errorMessage: fieldSecurityError?.message ?? statusError });
|
|
2610
3536
|
continue;
|
|
2611
3537
|
}
|
|
2612
|
-
const entityLabel = item.params.EntityName || 'unknown';
|
|
3538
|
+
const entityLabel = item.params.EntityName || 'unknown';
|
|
3539
|
+
if (serverCached && fingerprint) {
|
|
3540
|
+
const cachedSlotStatus = {
|
|
3541
|
+
maxUpdatedAt: serverCached.maxUpdatedAt,
|
|
3542
|
+
rowCount: serverCached.totalRowCount ?? serverCached.rowCount,
|
|
3543
|
+
};
|
|
3544
|
+
if (this.isCacheCurrent(cachedSlotStatus, serverStatus)) {
|
|
3545
|
+
// Server cache slot is confirmed current against SQL — refresh its verification timestamp in O(1)
|
|
3546
|
+
LocalCacheManager.Instance.TouchRunViewResultVerifiedAt(fingerprint);
|
|
3547
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3548
|
+
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
3549
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3550
|
+
}
|
|
3551
|
+
else {
|
|
3552
|
+
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
|
|
3553
|
+
serverCacheStaleItems.push({ index, item, entityInfo, serverCached });
|
|
3554
|
+
}
|
|
3555
|
+
continue;
|
|
3556
|
+
}
|
|
3557
|
+
else {
|
|
3558
|
+
// Out-of-band SQL mutation or missed invalidation occurred!
|
|
3559
|
+
// Evict the stale server slot and refresh from DB so LocalCacheManager and the client self-heal.
|
|
3560
|
+
LogStatusEx({ message: ` ♻️ [SmartCache RECONCILE-EVICT] "${entityLabel}" — server cache slot disagreed with DB status; invalidating and refreshing from DB`, verboseOnly: true });
|
|
3561
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
3562
|
+
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3563
|
+
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3564
|
+
}
|
|
3565
|
+
else {
|
|
3566
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
3567
|
+
}
|
|
3568
|
+
continue;
|
|
3569
|
+
}
|
|
3570
|
+
}
|
|
2613
3571
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
2614
3572
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches DB (server cache miss)`, verboseOnly: true });
|
|
2615
3573
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
@@ -2633,22 +3591,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2633
3591
|
const noCacheStatusServedFromCache = [];
|
|
2634
3592
|
const noCacheStatusNeedsDB = [];
|
|
2635
3593
|
for (const entry of itemsWithoutCacheCheck) {
|
|
2636
|
-
// A param carrying BypassCache
|
|
3594
|
+
// A param carrying BypassCache (or any cache-ineligible request such as an AlternateBaseView
|
|
3595
|
+
// with CachePolicy === 'Bypass', an unknown/disabled AlternateBaseView, or a view-only request
|
|
3596
|
+
// denied by the read-permission gate) lands here because it is ineligible for a cache status,
|
|
2637
3597
|
// NOT because the caller has nothing cached — and those two must not be treated alike.
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
// !param.BypassCache); this is the matching read-side gate.
|
|
2643
|
-
if (entry.item.params.BypassCache) {
|
|
2644
|
-
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — BypassCache requested, going to the database`, verboseOnly: true });
|
|
3598
|
+
if (entry.item.params.BypassCache ||
|
|
3599
|
+
!this.runViewCacheEligible(entry.item.params) ||
|
|
3600
|
+
this.cacheDeniedForViewOnlyRequest(entry.item.params, contextUser)) {
|
|
3601
|
+
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — cache ineligible or BypassCache requested, going to the database`, verboseOnly: true });
|
|
2645
3602
|
noCacheStatusNeedsDB.push(entry);
|
|
2646
3603
|
continue;
|
|
2647
3604
|
}
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
const fingerprint =
|
|
3605
|
+
// A saved-view request without an entity name had no Read check above; only the
|
|
3606
|
+
// database leg resolves its entity and checks it, so it never reads the cache here.
|
|
3607
|
+
if (LocalCacheManager.Instance.IsInitialized && !this.cacheDeniedForViewOnlyRequest(entry.item.params, user)) {
|
|
3608
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(entry.item.params, user);
|
|
2652
3609
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
2653
3610
|
if (cached) {
|
|
2654
3611
|
const entityLabel = entry.item.params.EntityName || 'unknown';
|
|
@@ -2661,7 +3618,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2661
3618
|
}
|
|
2662
3619
|
// Phase 4: Run queries in parallel for items needing data.
|
|
2663
3620
|
// Every leg that returns rows projects them down to the caller's requested
|
|
2664
|
-
// shape (callerFieldsByIndex) — the cache
|
|
3621
|
+
// shape (callerFieldsByIndex) — the cache holds every field the slot's
|
|
3622
|
+
// permission class may read.
|
|
2665
3623
|
const queryPromises = [
|
|
2666
3624
|
// Items without cache check — served from server cache
|
|
2667
3625
|
...noCacheStatusServedFromCache.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
@@ -2700,8 +3658,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2700
3658
|
// BOTH projections, in this order — they are siblings, not alternatives, and
|
|
2701
3659
|
// `PostRunView` calls them as a pair at all four of its projection points. Applying
|
|
2702
3660
|
// only the first leaves the audit trail leaking: `ApplyFieldSecurityProjection`
|
|
2703
|
-
// short-circuits
|
|
2704
|
-
// `MJ: Record Changes` has
|
|
3661
|
+
// short-circuits when field security does not apply to the RunView entity, and
|
|
3662
|
+
// `MJ: Record Changes` has field security OFF by design, so it is a no-op on exactly the
|
|
2705
3663
|
// rows that matter. The denied values there are INSIDE the `ChangesJSON` /
|
|
2706
3664
|
// `FullRecordJSON` payload columns, which no amount of column stripping reaches —
|
|
2707
3665
|
// `ApplyRecordChangeFieldSecurityProjection` is what projects them against the entity
|
|
@@ -2764,7 +3722,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2764
3722
|
async buildWhereClauseForCacheCheck(params, entityInfo, user) {
|
|
2765
3723
|
let whereSQL = '';
|
|
2766
3724
|
let bHasWhere = false;
|
|
2767
|
-
|
|
3725
|
+
// PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
|
|
3726
|
+
// check then runs on the result, as on the main view path.
|
|
3727
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
|
|
3728
|
+
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
2768
3729
|
if (extraFilter.length > 0) {
|
|
2769
3730
|
if (!this.ValidateUserProvidedSQLClause(extraFilter))
|
|
2770
3731
|
throw new Error(`Invalid Extra Filter: ${extraFilter}`);
|
|
@@ -2774,7 +3735,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2774
3735
|
// Free text, not a SQL fragment — deliberately NOT run through
|
|
2775
3736
|
// ValidateUserProvidedSQLClause. See the equivalent note on the view path above (#4392).
|
|
2776
3737
|
if (params.UserSearchString && params.UserSearchString.length > 0) {
|
|
2777
|
-
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user);
|
|
3738
|
+
const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString, user, this.ResolveRequestDeniedReadFields(params, entityInfo, user));
|
|
2778
3739
|
if (sUserSearchSQL.length > 0) {
|
|
2779
3740
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sUserSearchSQL})` : `(${sUserSearchSQL})`;
|
|
2780
3741
|
bHasWhere = true;
|
|
@@ -2792,8 +3753,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2792
3753
|
* entity whose view does not carry it, instead of comparing by count alone the way
|
|
2793
3754
|
* `BaseEngine.SweepAgainstDatabase` documents.
|
|
2794
3755
|
*/
|
|
2795
|
-
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
|
|
2796
|
-
const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
3756
|
+
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL, schemaNameOverride) {
|
|
3757
|
+
const from = `FROM ${this.QuoteSchemaAndView(schemaNameOverride ?? entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
2797
3758
|
const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
|
|
2798
3759
|
// `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
|
|
2799
3760
|
// throwing: a freshness check must not be the thing that breaks a sweep.
|
|
@@ -2819,8 +3780,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2819
3780
|
// snapshot cache against an unrelated source, yielding a meaningless current/stale verdict.
|
|
2820
3781
|
// (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
|
|
2821
3782
|
// matches the SQL Server override and is defense-in-depth on the PG/default path.)
|
|
2822
|
-
const
|
|
2823
|
-
const statusSQL = this.BuildCacheStatusSQL(entityInfo,
|
|
3783
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
|
|
3784
|
+
const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveTarget.viewName, whereSQL, effectiveTarget.schemaName);
|
|
2824
3785
|
const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
|
|
2825
3786
|
if (rows && rows.length > 0) {
|
|
2826
3787
|
const row = rows[0];
|
|
@@ -2845,7 +3806,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2845
3806
|
* Runs a full view query and returns results with cache metadata.
|
|
2846
3807
|
*/
|
|
2847
3808
|
async runFullQueryAndReturn(params, viewIndex, contextUser) {
|
|
2848
|
-
|
|
3809
|
+
let result;
|
|
3810
|
+
try {
|
|
3811
|
+
result = await this.InternalRunView(params, contextUser);
|
|
3812
|
+
}
|
|
3813
|
+
catch (e) {
|
|
3814
|
+
// A field-security refusal fails this item only, as the up-front gate does on this path.
|
|
3815
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
3816
|
+
return { viewIndex, status: 'error', errorMessage: e.message };
|
|
3817
|
+
}
|
|
3818
|
+
throw e;
|
|
3819
|
+
}
|
|
2849
3820
|
if (!result.Success) {
|
|
2850
3821
|
return { viewIndex, status: 'error', errorMessage: result.ErrorMessage || 'Unknown error executing view' };
|
|
2851
3822
|
}
|
|
@@ -2874,9 +3845,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2874
3845
|
// external source has caching disabled — skip the write to avoid stale data.
|
|
2875
3846
|
const ttlMs = await this.resolveExternalCacheTTLMs(params, contextUser);
|
|
2876
3847
|
if (ttlMs !== 0) {
|
|
2877
|
-
const
|
|
2878
|
-
const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(params);
|
|
2879
|
-
const fingerprint = LocalCacheManager.Instance.GenerateRunViewFingerprint(params, this.InstanceConnectionString, rlsWhereClause, undefined, flsFieldsKey);
|
|
3848
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(params, contextUser);
|
|
2880
3849
|
const maxUpdatedAt = result.maxUpdatedAt || new Date().toISOString();
|
|
2881
3850
|
// Pass the aggregates (B38-family omission #4). This slot is ALSO written by
|
|
2882
3851
|
// InternalRunView's normal PostRunView path WITH aggregates — two writers,
|
|
@@ -2952,7 +3921,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2952
3921
|
* infinite loop / duplicate processing in deep-pagination jobs. Aggregates and a non-empty
|
|
2953
3922
|
* UserSearchString likewise can't be evaluated remotely. Throws a clear error naming the param.
|
|
2954
3923
|
*/
|
|
2955
|
-
assertExternalRunViewParamsSupported(params, entityName) {
|
|
3924
|
+
assertExternalRunViewParamsSupported(params, entityName, viewEntity) {
|
|
3925
|
+
if (this.resolveEffectiveAbvNameFromParams(params, viewEntity)) {
|
|
3926
|
+
throw new Error(`AlternateBaseView is not supported for external-data-source entity '${entityName}'.`);
|
|
3927
|
+
}
|
|
2956
3928
|
if (params.AfterKey) {
|
|
2957
3929
|
throw new Error(`Keyset pagination (AfterKey) is not supported for external-data-source entity '${entityName}'. Use StartRow/MaxRows offset paging instead.`);
|
|
2958
3930
|
}
|
|
@@ -2978,6 +3950,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2978
3950
|
throw new Error(`Invalid OrderBy clause for external-data-source entity '${entityName}': contains one or more forbidden keywords.`);
|
|
2979
3951
|
}
|
|
2980
3952
|
}
|
|
3953
|
+
/**
|
|
3954
|
+
* Field-level security on the clauses an external-data-source read hands its driver: the
|
|
3955
|
+
* caller's own, merged with a saved view's stored ones. The same gates the SQL path applies to
|
|
3956
|
+
* the clauses it runs; the external dispatch returns before that path, and the driver runs
|
|
3957
|
+
* the clauses remotely, where nothing else checks them.
|
|
3958
|
+
*/
|
|
3959
|
+
assertExternalClausesRespectFieldSecurity(entityInfo, params, user) {
|
|
3960
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [params.ExtraFilter, params.OverrideExcludeFilter], user);
|
|
3961
|
+
this.AssertSortRespectsFieldSecurityForEntity(entityInfo, [params.OrderBy], user);
|
|
3962
|
+
}
|
|
3963
|
+
/**
|
|
3964
|
+
* An external driver's rows without the columns `user` may not read. The driver returns the
|
|
3965
|
+
* entity's columns at full width, and the result-path projection resolves the entity only from
|
|
3966
|
+
* an `EntityName` or a loaded `ViewEntity`, so a request naming only a `ViewID` would keep
|
|
3967
|
+
* them: the entity resolved here is named explicitly.
|
|
3968
|
+
*/
|
|
3969
|
+
projectExternalRowsForCaller(rows, entityInfo, params, user) {
|
|
3970
|
+
return this.ApplyFieldSecurityProjection(rows, { ...params, EntityName: entityInfo.Name }, user);
|
|
3971
|
+
}
|
|
2981
3972
|
/**
|
|
2982
3973
|
* Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
|
|
2983
3974
|
* external dispatch. The external branch returns before the normal SQL path that applies
|
|
@@ -3013,21 +4004,68 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3013
4004
|
}
|
|
3014
4005
|
return merged;
|
|
3015
4006
|
}
|
|
4007
|
+
/**
|
|
4008
|
+
* True when a browser's cache status carries a field-security key (see
|
|
4009
|
+
* `ProviderBase.ComputeFieldSecurityCacheStatusKey`) other than the one this server computes
|
|
4010
|
+
* for `user` and `params`: the browser's slot was filled for a different set of columns, so
|
|
4011
|
+
* its row count and newest timestamp say nothing about whether it is current. False when the
|
|
4012
|
+
* status carries no key.
|
|
4013
|
+
*/
|
|
4014
|
+
cacheStatusFieldSecurityDiffers(status, params, user) {
|
|
4015
|
+
if (status?.fieldSecurityKey == null) {
|
|
4016
|
+
return false; // an older client: no key, no check
|
|
4017
|
+
}
|
|
4018
|
+
return status.fieldSecurityKey !== this.ComputeFieldSecurityCacheStatusKey(params, user);
|
|
4019
|
+
}
|
|
3016
4020
|
/**
|
|
3017
4021
|
* Checks the server's LocalCacheManager for cached data matching the client's request.
|
|
3018
|
-
* Returns the resolution if found (
|
|
3019
|
-
*
|
|
4022
|
+
* Returns the resolution if found ('current', 'stale' server-cached data to serve, or
|
|
4023
|
+
* 'needs_verification' when the server slot's freshness window has elapsed),
|
|
4024
|
+
* or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
|
|
3020
4025
|
*/
|
|
3021
4026
|
async resolveFromServerCache(item, index, entityLabel, contextUser) {
|
|
3022
4027
|
if (!LocalCacheManager.Instance.IsInitialized)
|
|
3023
4028
|
return null;
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
4029
|
+
if (!this.runViewCacheEligible(item.params) || this.cacheDeniedForViewOnlyRequest(item.params, contextUser)) {
|
|
4030
|
+
return null;
|
|
4031
|
+
}
|
|
4032
|
+
const fingerprint = this.ComputeRunViewCacheFingerprint(item.params, contextUser);
|
|
3027
4033
|
const cached = await LocalCacheManager.Instance.GetRunViewResult(fingerprint);
|
|
3028
4034
|
if (!cached)
|
|
3029
4035
|
return null;
|
|
3030
|
-
|
|
4036
|
+
// 1. Client Monotonicity Guard:
|
|
4037
|
+
// If the client's cacheStatus has a timestamp newer than the server's cached slot,
|
|
4038
|
+
// the server slot is provably stale (e.g., client received a newer write from another
|
|
4039
|
+
// replica or after an out-of-band update). Never serve stale rows backward in time:
|
|
4040
|
+
// evict the server slot immediately and route to Phase 2 DB validation.
|
|
4041
|
+
const clientDate = this.parseClientTimestamp(item.cacheStatus.maxUpdatedAt);
|
|
4042
|
+
const serverCachedDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
4043
|
+
const serverCachedRowCount = cached.totalRowCount ?? cached.rowCount;
|
|
4044
|
+
if (clientDate &&
|
|
4045
|
+
serverCachedDate &&
|
|
4046
|
+
((clientDate.getTime() - serverCachedDate.getTime()) >= 1000 ||
|
|
4047
|
+
(clientDate.getTime() > serverCachedDate.getTime() && item.cacheStatus.rowCount !== serverCachedRowCount))) {
|
|
4048
|
+
LogStatusEx({
|
|
4049
|
+
message: ` ⚠️ [SmartCache MONOTONICITY-EVICT] "${entityLabel}" — client timestamp (${item.cacheStatus.maxUpdatedAt}) is newer than server cache (${cached.maxUpdatedAt}); evicting stale server slot`,
|
|
4050
|
+
verboseOnly: true,
|
|
4051
|
+
});
|
|
4052
|
+
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
4053
|
+
return null;
|
|
4054
|
+
}
|
|
4055
|
+
// 2. Bounded Server-Slot Freshness Window:
|
|
4056
|
+
// If the server slot has not been verified against SQL within ServerCacheVerificationTTLMs,
|
|
4057
|
+
// route to Phase 2's batched SQL status check before trusting it.
|
|
4058
|
+
const verifiedAt = cached.lastVerifiedAt ?? cached.cachedAt;
|
|
4059
|
+
const needsVerification = this.ServerCacheVerificationTTLMs <= 0 ||
|
|
4060
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs);
|
|
4061
|
+
if (needsVerification) {
|
|
4062
|
+
LogStatusEx({
|
|
4063
|
+
message: ` ⏱️ [SmartCache VERIFY-TTL] "${entityLabel}" — server cache slot verification TTL expired, routing to batched DB status check`,
|
|
4064
|
+
verboseOnly: true,
|
|
4065
|
+
});
|
|
4066
|
+
return { status: 'needs_verification', serverCached: cached, fingerprint };
|
|
4067
|
+
}
|
|
4068
|
+
const serverStatus = { maxUpdatedAt: cached.maxUpdatedAt, rowCount: serverCachedRowCount };
|
|
3031
4069
|
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3032
4070
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches server cache, no DB hit`, verboseOnly: true });
|
|
3033
4071
|
return { status: 'current', result: { viewIndex: index, status: 'current' } };
|
|
@@ -3040,8 +4078,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3040
4078
|
* Packages server-cached data as a RunViewWithCacheCheckResult for return to the client.
|
|
3041
4079
|
*/
|
|
3042
4080
|
async serveFromServerCache(viewIndex, serverCached, callerFields = null) {
|
|
3043
|
-
// The server cache stores the
|
|
3044
|
-
// caller's requested fields (∪ PK) before returning, exactly like the
|
|
4081
|
+
// The server cache stores every field the slot's permission class may read —
|
|
4082
|
+
// project down to the caller's requested fields (∪ PK) before returning, exactly like the
|
|
3045
4083
|
// ProviderBase hit path. Serving unprojected rows here previously leaked
|
|
3046
4084
|
// whatever shape happened to be cached to every subsequent caller.
|
|
3047
4085
|
//
|
|
@@ -3172,11 +4210,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3172
4210
|
const fields = params.Fields && params.Fields.length > 0
|
|
3173
4211
|
? params.Fields.map(f => this.QuoteIdentifier(f)).join(', ')
|
|
3174
4212
|
: '*';
|
|
3175
|
-
|
|
4213
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, params, contextUser);
|
|
4214
|
+
let sql = `SELECT ${fields} FROM ${this.QuoteSchemaAndView(effectiveTarget.schemaName, effectiveTarget.viewName)} WHERE ${combinedWhere}`;
|
|
3176
4215
|
const orderBy = this.TransformExternalSQLClause(params.OrderBy || '', entityInfo);
|
|
3177
4216
|
if (orderBy.length > 0) {
|
|
3178
4217
|
if (!this.ValidateUserProvidedSQLClause(orderBy))
|
|
3179
4218
|
throw new Error(`Invalid OrderBy clause: ${orderBy}`);
|
|
4219
|
+
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
3180
4220
|
sql += ` ORDER BY ${orderBy}`;
|
|
3181
4221
|
}
|
|
3182
4222
|
return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
@@ -3206,6 +4246,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3206
4246
|
const itemsWithoutValidationSQL = [];
|
|
3207
4247
|
const firstFetchWithValidation = [];
|
|
3208
4248
|
const errorResults = [];
|
|
4249
|
+
const definitionHashes = new Map();
|
|
3209
4250
|
for (let i = 0; i < params.length; i++) {
|
|
3210
4251
|
const item = params[i];
|
|
3211
4252
|
const query = this.resolveQuery(item.params);
|
|
@@ -3213,15 +4254,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3213
4254
|
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: `Query not found: ${item.params.QueryID || item.params.QueryName}` });
|
|
3214
4255
|
continue;
|
|
3215
4256
|
}
|
|
3216
|
-
const
|
|
4257
|
+
const definition = this.QueryDefinitionSignatureFor(query);
|
|
4258
|
+
const runCheck = this.authorizeCacheCheckedQuery(query, item, definition, user);
|
|
3217
4259
|
if (!runCheck.canRun) {
|
|
3218
4260
|
const deniedMsg = runCheck.deniedEntities.length > 0
|
|
3219
4261
|
? ` Denied entities: ${runCheck.deniedEntities.join(', ')}.`
|
|
3220
4262
|
: '';
|
|
3221
|
-
|
|
4263
|
+
const errorMessage = runCheck.renderError ?? `User does not have permission to run query: ${query.Name}.${deniedMsg}`;
|
|
4264
|
+
errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage });
|
|
3222
4265
|
continue;
|
|
3223
4266
|
}
|
|
3224
|
-
if (
|
|
4267
|
+
if (definition) {
|
|
4268
|
+
definitionHashes.set(i, definition.Hash);
|
|
4269
|
+
}
|
|
4270
|
+
if (!item.cacheStatus || this.clientSlotDefinitionDiffers(item.cacheStatus, definition)) {
|
|
4271
|
+
// No slot, or the client's slot holds rows of another definition of the query:
|
|
4272
|
+
// whatever CacheValidationSQL says about the data, those rows came from other SQL.
|
|
3225
4273
|
if (query.CacheValidationSQL) {
|
|
3226
4274
|
// First fetch for a validated query — run the validation status
|
|
3227
4275
|
// anyway so the fresh response is STAMPED with the validation
|
|
@@ -3267,7 +4315,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3267
4315
|
...staleItems.map(({ index, params: queryParams, query }) => this.runFullQueryAndReturnForQuery(queryParams, index, 'stale', contextUser, query.ID, cacheStatusResults.get(index))),
|
|
3268
4316
|
];
|
|
3269
4317
|
const fullQueryResults = await Promise.all(fullQueryPromises);
|
|
3270
|
-
const allResults = [...errorResults, ...currentResults, ...fullQueryResults]
|
|
4318
|
+
const allResults = [...errorResults, ...currentResults, ...fullQueryResults]
|
|
4319
|
+
.map(result => result.status === 'error' || !definitionHashes.has(result.queryIndex)
|
|
4320
|
+
? result
|
|
4321
|
+
: { ...result, definitionHash: definitionHashes.get(result.queryIndex) });
|
|
3271
4322
|
allResults.sort((a, b) => a.queryIndex - b.queryIndex);
|
|
3272
4323
|
return { success: true, results: allResults };
|
|
3273
4324
|
}
|
|
@@ -3276,6 +4327,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3276
4327
|
return { success: false, results: [], errorMessage: e instanceof Error ? e.message : String(e) };
|
|
3277
4328
|
}
|
|
3278
4329
|
}
|
|
4330
|
+
/**
|
|
4331
|
+
* The authorization of one {@link RunQueriesWithCacheCheck} item before it is routed. An item
|
|
4332
|
+
* that may be answered "current" without running — it carries a cache status for this
|
|
4333
|
+
* definition and the query has validation SQL — is checked in full on its rendering here. Every
|
|
4334
|
+
* other item runs, and the run checks the rendering it executes, so only the render-free part
|
|
4335
|
+
* is checked here rather than rendering the query twice.
|
|
4336
|
+
*/
|
|
4337
|
+
authorizeCacheCheckedQuery(query, item, definition, user) {
|
|
4338
|
+
const mayAnswerWithoutRunning = !!item.cacheStatus
|
|
4339
|
+
&& !this.clientSlotDefinitionDiffers(item.cacheStatus, definition)
|
|
4340
|
+
&& !!query.CacheValidationSQL;
|
|
4341
|
+
return mayAnswerWithoutRunning ? this.authorizeQueryRun(query, item.params.Parameters, user) : query.UserCanRun(user);
|
|
4342
|
+
}
|
|
3279
4343
|
/**
|
|
3280
4344
|
* B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
|
|
3281
4345
|
* cache HIT that the miss path enforces. Resolution uses `resolveQuery()` (QueryEngine as
|
|
@@ -3285,6 +4349,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3285
4349
|
* applies before a real execution. The base's roles-only check would let a user read cached
|
|
3286
4350
|
* rows of a query whose underlying entities they cannot read.
|
|
3287
4351
|
*
|
|
4352
|
+
* The run-time checks (`UserCanRunRenderedSQL`: entities read by the SQL itself, and field-level
|
|
4353
|
+
* security) run against the query rendered with the request's own parameters: the SQL the miss
|
|
4354
|
+
* path would check and execute for this slot, since the slot's fingerprint carries those
|
|
4355
|
+
* parameters and its definition hash the query's SQL. A user the miss path would refuse is never
|
|
4356
|
+
* served the slot; a rendering that fails is treated as not authorized, so the request falls
|
|
4357
|
+
* through to execution and gets that path's error.
|
|
4358
|
+
*
|
|
3288
4359
|
* Non-throwing by contract: any resolution error degrades to `resolvable: false`, which the
|
|
3289
4360
|
* gate treats as "fall through to authorized execution" — one extra query run, never an
|
|
3290
4361
|
* unauthorized serve and never a crashed cache path.
|
|
@@ -3297,9 +4368,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3297
4368
|
}
|
|
3298
4369
|
return {
|
|
3299
4370
|
resolvable: true,
|
|
3300
|
-
authorized: !user || query.
|
|
4371
|
+
authorized: !user || this.authorizeQueryRun(query, params.Parameters, user).canRun,
|
|
3301
4372
|
categoryPath: query.CategoryPath,
|
|
3302
|
-
queryName: query.Name
|
|
4373
|
+
queryName: query.Name,
|
|
4374
|
+
contextTokens: this.queryContextTokens(query),
|
|
4375
|
+
queryId: query.ID,
|
|
4376
|
+
definition: this.QueryDefinitionSignatureFor(query)
|
|
3303
4377
|
};
|
|
3304
4378
|
}
|
|
3305
4379
|
catch (e) {
|
|
@@ -3307,6 +4381,31 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3307
4381
|
return { resolvable: false, authorized: false };
|
|
3308
4382
|
}
|
|
3309
4383
|
}
|
|
4384
|
+
/**
|
|
4385
|
+
* The definition signature of `query` on this provider's platform: what a RunQuery cache slot
|
|
4386
|
+
* of the query must have been written under to be served. Computed by `QueryEngine` from the
|
|
4387
|
+
* same metadata this provider executes. Undefined when the engine cannot compute it, which
|
|
4388
|
+
* disables the definition check for that read rather than failing it.
|
|
4389
|
+
*/
|
|
4390
|
+
QueryDefinitionSignatureFor(query) {
|
|
4391
|
+
try {
|
|
4392
|
+
return QueryEngine.Instance.GetDefinitionSignature(query.ID, this.PlatformKey);
|
|
4393
|
+
}
|
|
4394
|
+
catch (e) {
|
|
4395
|
+
LogStatusEx({ message: `QueryDefinitionSignatureFor: could not compute the definition of query '${query.Name}' (${e instanceof Error ? e.message : String(e)}) — skipping the definition check.`, verboseOnly: true });
|
|
4396
|
+
return undefined;
|
|
4397
|
+
}
|
|
4398
|
+
}
|
|
4399
|
+
/**
|
|
4400
|
+
* True when a client sent the definition hash its slot was written under and it is not this
|
|
4401
|
+
* server's. A client that sends none (a release before the hash existed) gets no definition check.
|
|
4402
|
+
*/
|
|
4403
|
+
clientSlotDefinitionDiffers(cacheStatus, definition) {
|
|
4404
|
+
if (cacheStatus.definitionHash == null || !definition) {
|
|
4405
|
+
return false;
|
|
4406
|
+
}
|
|
4407
|
+
return cacheStatus.definitionHash !== definition.Hash;
|
|
4408
|
+
}
|
|
3310
4409
|
/**
|
|
3311
4410
|
* Resolves a query from RunQueryParams (by ID or Name+CategoryPath).
|
|
3312
4411
|
* Uses QueryEngine as the single source of truth for query metadata.
|
|
@@ -3360,16 +4459,128 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3360
4459
|
if (user) {
|
|
3361
4460
|
const result = query.UserCanRun(user);
|
|
3362
4461
|
if (!result.canRun) {
|
|
3363
|
-
|
|
3364
|
-
? ` Denied entities: ${result.deniedEntities.join(', ')}.`
|
|
3365
|
-
: '';
|
|
3366
|
-
throw new Error(`User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`);
|
|
4462
|
+
throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
|
|
3367
4463
|
}
|
|
3368
4464
|
}
|
|
3369
4465
|
if (query.Status !== 'Approved') {
|
|
3370
4466
|
LogStatus(`WARNING: Executing query '${query.Name}' (ID: ${query.ID}) with status '${query.Status}'. Query has not been approved.`);
|
|
3371
4467
|
}
|
|
3372
4468
|
}
|
|
4469
|
+
/**
|
|
4470
|
+
* For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
|
|
4471
|
+
* current approval — status Approved and a stored fingerprint equal to the fingerprint of the
|
|
4472
|
+
* definition this run executes. The fingerprint is worked out here, from the same
|
|
4473
|
+
* `QueryEngine` metadata the run renders, never from a caller's value.
|
|
4474
|
+
*
|
|
4475
|
+
* @throws Error naming the first query whose approval is not current
|
|
4476
|
+
*/
|
|
4477
|
+
async ValidateQueryApprovalAsync(query, render) {
|
|
4478
|
+
if (RenderPipeline.HasCompositionTokens(query.GetPlatformSQL(this.PlatformKey)) && !render.HasCompositions) {
|
|
4479
|
+
throw new Error(`Query '${query.Name}' (ID: ${query.ID}) composes other queries, which requires a context user so every composed query's approval can be verified.`);
|
|
4480
|
+
}
|
|
4481
|
+
const engine = QueryEngine.Instance;
|
|
4482
|
+
const depsByQueryID = GroupByUUID(engine.Dependencies, d => d.QueryID);
|
|
4483
|
+
const queriesByID = IndexByUUID(engine.Queries);
|
|
4484
|
+
const composedIDs = new UUIDSet(render.CTEs.map(c => c.QueryID));
|
|
4485
|
+
const queue = [query.ID, ...render.CTEs.map(c => c.QueryID)];
|
|
4486
|
+
while (queue.length > 0) {
|
|
4487
|
+
const currentID = queue.shift();
|
|
4488
|
+
for (const dep of depsByQueryID.Get(currentID) ?? []) {
|
|
4489
|
+
if (dep.DependsOnQueryID && !composedIDs.Has(dep.DependsOnQueryID) && !UUIDsEqual(dep.DependsOnQueryID, query.ID)) {
|
|
4490
|
+
composedIDs.Add(dep.DependsOnQueryID);
|
|
4491
|
+
queue.push(dep.DependsOnQueryID);
|
|
4492
|
+
}
|
|
4493
|
+
}
|
|
4494
|
+
}
|
|
4495
|
+
const toVerify = [query];
|
|
4496
|
+
for (const cte of render.CTEs) {
|
|
4497
|
+
const found = queriesByID.Get(cte.QueryID);
|
|
4498
|
+
if (!found) {
|
|
4499
|
+
throw new Error(`Query '${cte.QueryName || cte.QueryID}' composed by '${query.Name}' is not a saved query in QueryEngine, so its approval cannot be verified.`);
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
for (const depID of composedIDs) {
|
|
4503
|
+
const found = queriesByID.Get(depID);
|
|
4504
|
+
if (!found) {
|
|
4505
|
+
throw new Error(`Query dependency (ID: ${depID}) composed by '${query.Name}' is not found in QueryEngine, so its approval cannot be verified.`);
|
|
4506
|
+
}
|
|
4507
|
+
toVerify.push(found);
|
|
4508
|
+
}
|
|
4509
|
+
for (const q of toVerify) {
|
|
4510
|
+
const state = await GetQueryApprovalStateAsync(q);
|
|
4511
|
+
if (state !== 'Current') {
|
|
4512
|
+
const reason = state === 'NotApproved'
|
|
4513
|
+
? `its status is '${q.Status}'`
|
|
4514
|
+
: 'its definition changed after it was approved (or it was approved before approvals were fingerprinted)';
|
|
4515
|
+
throw new Error(`Query '${q.Name}' (ID: ${q.ID}) is not approved in its current form: ${reason}. The run requires an approved query.`);
|
|
4516
|
+
}
|
|
4517
|
+
}
|
|
4518
|
+
}
|
|
4519
|
+
/** The context tokens a query reads, with every query it composes, as the `QueryEngine` holds them. */
|
|
4520
|
+
queryContextTokens(query) {
|
|
4521
|
+
const engine = QueryEngine.Instance;
|
|
4522
|
+
return FindQueryContextTokens(query.ID, id => [engine.Queries.find(q => UUIDsEqual(q.ID, id))?.SQL, ...engine.QuerySQLs.filter(s => UUIDsEqual(s.QueryID, id)).map(s => s.SQL)], id => engine.Dependencies.filter(d => UUIDsEqual(d.QueryID, id)).map(d => d.DependsOnQueryID));
|
|
4523
|
+
}
|
|
4524
|
+
/**
|
|
4525
|
+
* SECURITY — authorizes a saved query against the SQL the run will execute (fully composed and
|
|
4526
|
+
* rendered), after {@link ValidateQueryForExecution} has passed: the entities that SQL reads,
|
|
4527
|
+
* and field-level security on every column it references. A template that injects an
|
|
4528
|
+
* identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
|
|
4529
|
+
* render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
|
|
4530
|
+
* The refusal does not say which field or clause caused it.
|
|
4531
|
+
*
|
|
4532
|
+
* @throws Error when the user may not run this rendering of the query
|
|
4533
|
+
*/
|
|
4534
|
+
ValidateRenderedQueryForExecution(query, renderedSQL, contextUser) {
|
|
4535
|
+
const user = contextUser || this.CurrentUser;
|
|
4536
|
+
if (!user) {
|
|
4537
|
+
return;
|
|
4538
|
+
}
|
|
4539
|
+
const result = this.checkRenderedQuery(query, renderedSQL, user);
|
|
4540
|
+
if (!result.canRun) {
|
|
4541
|
+
throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
/** The refusal for a user who may not run `query`; names entities the user cannot read, never a field. */
|
|
4545
|
+
queryRunRefusalMessage(query, deniedEntities) {
|
|
4546
|
+
const deniedMsg = deniedEntities.length > 0 ? ` Denied entities: ${deniedEntities.join(', ')}.` : '';
|
|
4547
|
+
return `User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`;
|
|
4548
|
+
}
|
|
4549
|
+
/** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
|
|
4550
|
+
checkRenderedQuery(query, renderedSQL, user) {
|
|
4551
|
+
const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey);
|
|
4552
|
+
if (result.fieldSecurityViolation) {
|
|
4553
|
+
const v = result.fieldSecurityViolation;
|
|
4554
|
+
LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}' by field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''}).`, verboseOnly: true });
|
|
4555
|
+
}
|
|
4556
|
+
return result;
|
|
4557
|
+
}
|
|
4558
|
+
/**
|
|
4559
|
+
* The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
|
|
4560
|
+
* and the run-time checks on the query rendered with `parameters`. A rendering that fails
|
|
4561
|
+
* refuses, carrying the rendering's error.
|
|
4562
|
+
*/
|
|
4563
|
+
authorizeQueryRun(query, parameters, user) {
|
|
4564
|
+
const base = query.UserCanRun(user);
|
|
4565
|
+
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
4566
|
+
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
4567
|
+
// already confirmed the user holds one of its roles: nothing to render.
|
|
4568
|
+
return base;
|
|
4569
|
+
}
|
|
4570
|
+
let renderedSQL;
|
|
4571
|
+
try {
|
|
4572
|
+
renderedSQL = this.processQueryParameters(query, parameters, user).finalSQL;
|
|
4573
|
+
}
|
|
4574
|
+
catch (e) {
|
|
4575
|
+
return { canRun: false, deniedEntities: [], renderError: e instanceof Error ? e.message : String(e) };
|
|
4576
|
+
}
|
|
4577
|
+
return this.checkRenderedQuery(query, renderedSQL, user);
|
|
4578
|
+
}
|
|
4579
|
+
/** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
|
|
4580
|
+
static roleListGrants(query) {
|
|
4581
|
+
const permissions = query.QueryPermissions;
|
|
4582
|
+
return !!permissions && permissions.length > 0;
|
|
4583
|
+
}
|
|
3373
4584
|
/**
|
|
3374
4585
|
* Resolves a category path string to a QueryCategoryInfo ID.
|
|
3375
4586
|
*/
|
|
@@ -3399,22 +4610,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3399
4610
|
const promises = items.map(async ({ index, query }) => {
|
|
3400
4611
|
try {
|
|
3401
4612
|
const rows = await this.ExecuteSQL(query.CacheValidationSQL, undefined, undefined, contextUser);
|
|
3402
|
-
|
|
3403
|
-
const row = rows[0];
|
|
3404
|
-
results.set(index, {
|
|
3405
|
-
success: true,
|
|
3406
|
-
// Both spellings accepted. The shipped `CacheValidationSQL` field description tells authors
|
|
3407
|
-
// to return `TotalRows`, while this has only ever read `RowCount` — so a query written
|
|
3408
|
-
// from the documentation yields `Number(undefined)` = NaN, `NaN !== NaN` makes the slot
|
|
3409
|
-
// never validate, and NaN is then written back into the client's cache entry where `??`
|
|
3410
|
-
// cannot clear it. Silent, permanent degradation to always-refetch, with no error.
|
|
3411
|
-
rowCount: Number(row['RowCount'] ?? row['TotalRows']),
|
|
3412
|
-
maxUpdatedAt: row['MaxUpdatedAt'] ? new Date(String(row['MaxUpdatedAt'])).toISOString() : undefined,
|
|
3413
|
-
});
|
|
3414
|
-
}
|
|
3415
|
-
else {
|
|
3416
|
-
results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
|
|
3417
|
-
}
|
|
4613
|
+
results.set(index, this.QueryCacheStatusFromRow(rows?.[0]));
|
|
3418
4614
|
}
|
|
3419
4615
|
catch (e) {
|
|
3420
4616
|
results.set(index, { success: false, errorMessage: e instanceof Error ? e.message : String(e) });
|
|
@@ -3423,6 +4619,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3423
4619
|
await Promise.all(promises);
|
|
3424
4620
|
return results;
|
|
3425
4621
|
}
|
|
4622
|
+
/**
|
|
4623
|
+
* Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
|
|
4624
|
+
* an empty result: zero rows, no timestamp.
|
|
4625
|
+
*
|
|
4626
|
+
* Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
|
|
4627
|
+
* tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
|
|
4628
|
+
* of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
|
|
4629
|
+
* validate, and NaN is then written back into the client's cache entry where `??` cannot clear
|
|
4630
|
+
* it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
|
|
4631
|
+
* batch the validation SQL read their rows through this too.
|
|
4632
|
+
*/
|
|
4633
|
+
QueryCacheStatusFromRow(row) {
|
|
4634
|
+
if (!row) {
|
|
4635
|
+
return { success: true, rowCount: 0, maxUpdatedAt: undefined };
|
|
4636
|
+
}
|
|
4637
|
+
const maxUpdatedAt = row['MaxUpdatedAt'];
|
|
4638
|
+
return {
|
|
4639
|
+
success: true,
|
|
4640
|
+
rowCount: Number(row['RowCount'] ?? row['TotalRows']),
|
|
4641
|
+
maxUpdatedAt: maxUpdatedAt
|
|
4642
|
+
? (maxUpdatedAt instanceof Date ? maxUpdatedAt : new Date(String(maxUpdatedAt))).toISOString()
|
|
4643
|
+
: undefined,
|
|
4644
|
+
};
|
|
4645
|
+
}
|
|
3426
4646
|
/**
|
|
3427
4647
|
* Runs a full query and returns results with cache metadata.
|
|
3428
4648
|
*/
|
|
@@ -3639,9 +4859,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3639
4859
|
* the live query (serving live is always correct — this is a transparent optimization, never a
|
|
3640
4860
|
* correctness dependency).
|
|
3641
4861
|
*/
|
|
3642
|
-
async tryBuildMaterializedQueryPlan(query, params, contextUser) {
|
|
4862
|
+
async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues) {
|
|
3643
4863
|
if (!IsMaterializedDataSource(params.DataSource))
|
|
3644
4864
|
return null; // not opted in → live
|
|
4865
|
+
// A snapshot is shared by every caller and was built without this caller's Context (user, date), so a
|
|
4866
|
+
// run whose template read Context is served live: its rows depend on who runs it and when.
|
|
4867
|
+
if (contextValues && Object.keys(contextValues).length > 0)
|
|
4868
|
+
return null;
|
|
3645
4869
|
if (query.ExternalDataSourceID)
|
|
3646
4870
|
return null; // external source → materialized table is local; live
|
|
3647
4871
|
// The query<->materialization link lives in the MaterializedResultQuery join table — there is no
|
|
@@ -3736,7 +4960,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3736
4960
|
schemaName: mat.SchemaName,
|
|
3737
4961
|
viewName: mat.ViewName,
|
|
3738
4962
|
spec,
|
|
3739
|
-
|
|
4963
|
+
// Server-set parameters take their values from ServerParameters (a caller value for one was
|
|
4964
|
+
// already refused when the template rendered), so the row filter sees both.
|
|
4965
|
+
paramValues: params.ServerParameters ? { ...params.Parameters, ...params.ServerParameters } : params.Parameters,
|
|
3740
4966
|
paramTypes,
|
|
3741
4967
|
isPostgres: this.PlatformKey === 'postgresql',
|
|
3742
4968
|
});
|
|
@@ -3744,6 +4970,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3744
4970
|
async InternalRunQuery(params, contextUser) {
|
|
3745
4971
|
// Route ad-hoc SQL queries to dedicated handler
|
|
3746
4972
|
if (params.SQL) {
|
|
4973
|
+
if (params.RequireApproved) {
|
|
4974
|
+
return {
|
|
4975
|
+
Success: false,
|
|
4976
|
+
QueryID: '',
|
|
4977
|
+
QueryName: 'Ad-Hoc Query',
|
|
4978
|
+
Results: [],
|
|
4979
|
+
RowCount: 0,
|
|
4980
|
+
TotalRowCount: 0,
|
|
4981
|
+
ExecutionTime: 0,
|
|
4982
|
+
ErrorMessage: 'Ad-hoc SQL has no approved query definition and cannot run when RequireApproved is set.',
|
|
4983
|
+
};
|
|
4984
|
+
}
|
|
3747
4985
|
return this.ExecuteAdhocQuery(params, contextUser);
|
|
3748
4986
|
}
|
|
3749
4987
|
let finalSQL;
|
|
@@ -3751,15 +4989,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3751
4989
|
// Find and validate query
|
|
3752
4990
|
const query = this.findAndValidateQuery(params, contextUser);
|
|
3753
4991
|
// Process parameters (composition + Nunjucks templates)
|
|
3754
|
-
const resolved = this.processQueryParameters(query, params.Parameters, contextUser);
|
|
4992
|
+
const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params);
|
|
3755
4993
|
finalSQL = resolved.finalSQL;
|
|
3756
4994
|
const appliedParameters = resolved.appliedParameters;
|
|
4995
|
+
// Opt-in: the approval must be current for the definition about to run
|
|
4996
|
+
if (params.RequireApproved) {
|
|
4997
|
+
await this.ValidateQueryApprovalAsync(query, resolved.renderResult);
|
|
4998
|
+
}
|
|
4999
|
+
// Authorize what will actually run, before any cache, materialized or external read.
|
|
5000
|
+
this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser);
|
|
3757
5001
|
// ── Phase 2: materialized read redirect (plan §5) ──
|
|
3758
5002
|
// If the caller opted into DataSource:'Materialized' and this query has a fresh, Active
|
|
3759
5003
|
// RowFilterBroad materialization, serve from the materialized table with the row-filter params
|
|
3760
5004
|
// injected as BOUND predicates. On ANY uncertainty tryBuildMaterializedQueryPlan returns null and
|
|
3761
5005
|
// we fall through to the live execution below — a materialized read can never diverge from live.
|
|
3762
|
-
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser);
|
|
5006
|
+
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues);
|
|
3763
5007
|
if (matPlan) {
|
|
3764
5008
|
// Use a LOCAL for the materialized SQL — never overwrite `finalSQL` (which stays the
|
|
3765
5009
|
// live-rendered SQL), so a fallback below runs the live path unchanged.
|
|
@@ -3846,7 +5090,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3846
5090
|
// credential should be least-privilege). Do not assume EDS RLS covers the Query path.
|
|
3847
5091
|
if (query.ExternalDataSourceID) {
|
|
3848
5092
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
|
|
3849
|
-
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser);
|
|
5093
|
+
return await this.runExternalQueryWithCache(query, finalSQL, params, externalRouter, contextUser, resolved.renderResult.ContextValues);
|
|
3850
5094
|
}
|
|
3851
5095
|
// Execute query — use SQL-level paging when requested, else fetch all rows
|
|
3852
5096
|
const useSQLPaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
|
|
@@ -3953,7 +5197,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3953
5197
|
async ExecuteAdhocQuery(params, contextUser) {
|
|
3954
5198
|
try {
|
|
3955
5199
|
const validator = SQLExpressionValidator.Instance;
|
|
3956
|
-
const validation = validator.
|
|
5200
|
+
const validation = validator.ValidateFullQuery(params.SQL, this.PlatformKey);
|
|
3957
5201
|
const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
|
|
3958
5202
|
if (!validation.valid || !statementCheck.IsReadOnly) {
|
|
3959
5203
|
return {
|
|
@@ -4012,6 +5256,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4012
5256
|
RequireReadStatement: true,
|
|
4013
5257
|
...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
|
|
4014
5258
|
});
|
|
5259
|
+
this.AssertAdhocReadAllowed(rendered.Trace.AfterTemplates, contextUser);
|
|
4015
5260
|
const options = this.adhocSQLOptions(params);
|
|
4016
5261
|
if (!usePaging) {
|
|
4017
5262
|
const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
|
|
@@ -4026,6 +5271,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4026
5271
|
const rows = dataResult ?? [];
|
|
4027
5272
|
return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
|
|
4028
5273
|
}
|
|
5274
|
+
/**
|
|
5275
|
+
* SECURITY — what ad-hoc SQL may read, checked in the provider so that every in-process caller
|
|
5276
|
+
* (agents, data contexts, actions) is covered, not only the API's resolvers. `sql` is the
|
|
5277
|
+
* rendered statement, before the server's own paging wrap. Every table it reads must be an
|
|
5278
|
+
* entity base view the caller can read unscoped: CanRead with no row-level filter and no denied
|
|
5279
|
+
* field, because raw SQL applies neither ({@link ClientClauseScreen.AssertStatementReadsUnscopedEntityViews}).
|
|
5280
|
+
* The system user runs the server's own SQL and is not checked, but only when passed
|
|
5281
|
+
* explicitly: no user at all refuses, rather than falling back to the provider's own user,
|
|
5282
|
+
* which on a server is the system user.
|
|
5283
|
+
*
|
|
5284
|
+
* @throws Error when the caller may not run `sql`
|
|
5285
|
+
*/
|
|
5286
|
+
AssertAdhocReadAllowed(sql, contextUser) {
|
|
5287
|
+
if (!contextUser) {
|
|
5288
|
+
throw new Error('Invalid ad-hoc SQL: no acting user was passed — refusing');
|
|
5289
|
+
}
|
|
5290
|
+
if (IsSystemUser(contextUser)) {
|
|
5291
|
+
return;
|
|
5292
|
+
}
|
|
5293
|
+
ClientClauseScreen.AssertStatementReadsUnscopedEntityViews(sql, this.Entities, ClientClauseScreen.DialectFor(this), contextUser, 'ad-hoc SQL');
|
|
5294
|
+
}
|
|
4029
5295
|
/**
|
|
4030
5296
|
* The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
|
|
4031
5297
|
* fails does not fail the run: some queries page fine but cannot be counted (duplicate column
|
|
@@ -4092,11 +5358,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4092
5358
|
* Delegates to {@link RenderPipeline.Run} for the composition → template
|
|
4093
5359
|
* pipeline. Paging is handled separately by the caller (InternalRunQuery).
|
|
4094
5360
|
*/
|
|
4095
|
-
processQueryParameters(query, parameters, contextUser) {
|
|
5361
|
+
processQueryParameters(query, parameters, contextUser, serverSet) {
|
|
4096
5362
|
const result = RenderPipeline.Run(query.GetPlatformSQL(this.PlatformKey), {
|
|
4097
5363
|
Platform: this.PlatformKey,
|
|
4098
|
-
ContextUser: contextUser,
|
|
5364
|
+
ContextUser: contextUser ?? this.CurrentUser,
|
|
4099
5365
|
Parameters: parameters,
|
|
5366
|
+
ServerParameters: serverSet?.ServerParameters,
|
|
5367
|
+
TimeZone: serverSet?.TimeZone,
|
|
4100
5368
|
UsesTemplate: query.UsesTemplate ?? false,
|
|
4101
5369
|
QueryInfo: {
|
|
4102
5370
|
SQL: query.SQL ?? '',
|
|
@@ -4131,11 +5399,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4131
5399
|
* truth (a TTL of <= 0 disables caching for the source); field-drift warnings still apply to
|
|
4132
5400
|
* freshly-fetched rows. Ad-hoc SQL (params.SQL) is never cached.
|
|
4133
5401
|
*/
|
|
4134
|
-
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser) {
|
|
5402
|
+
async runExternalQueryWithCache(query, finalSQL, params, router, contextUser, contextValues) {
|
|
4135
5403
|
const externalDataSourceID = query.ExternalDataSourceID;
|
|
4136
5404
|
const ttlSeconds = await router.GetCacheTTLSeconds(externalDataSourceID, contextUser, this);
|
|
4137
|
-
|
|
5405
|
+
// A result that read Context.Now depends on the instant it ran and is never reused.
|
|
5406
|
+
const cacheable = !params.SQL && ttlSeconds > 0 && LocalCacheManager.Instance.IsInitialized && !(contextValues && 'Now' in contextValues);
|
|
4138
5407
|
let fingerprint;
|
|
5408
|
+
let definition;
|
|
4139
5409
|
if (cacheable) {
|
|
4140
5410
|
// MaxRows/StartRow shape the result set, and the data source ID disambiguates slots.
|
|
4141
5411
|
const fingerprintParams = {
|
|
@@ -4143,9 +5413,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4143
5413
|
__maxRows: params.MaxRows ?? -1,
|
|
4144
5414
|
__startRow: params.StartRow ?? 0,
|
|
4145
5415
|
__eds: externalDataSourceID,
|
|
5416
|
+
// What the server set shapes the result too, so one user's slot never answers another's.
|
|
5417
|
+
...this.serverSetFingerprintSegment(params, contextValues),
|
|
4146
5418
|
};
|
|
4147
5419
|
fingerprint = LocalCacheManager.Instance.GenerateRunQueryFingerprint(query.ID, query.Name, fingerprintParams, this.InstanceConnectionString, query.CategoryPath);
|
|
4148
|
-
|
|
5420
|
+
definition = this.QueryDefinitionSignatureFor(query);
|
|
5421
|
+
// TTL-enforced, and a miss when the slot was written under another definition of the query.
|
|
5422
|
+
const cached = await LocalCacheManager.Instance.GetRunQueryResult(fingerprint, definition);
|
|
4149
5423
|
if (cached) {
|
|
4150
5424
|
return {
|
|
4151
5425
|
QueryID: cached.queryId ?? query.ID,
|
|
@@ -4176,10 +5450,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4176
5450
|
const { paginatedResult, totalRowCount } = this.applyQueryPagination(checked.Results, params);
|
|
4177
5451
|
if (cacheable && fingerprint) {
|
|
4178
5452
|
// Fire-and-forget store with the data source's TTL (ms).
|
|
4179
|
-
LocalCacheManager.Instance.SetRunQueryResult(fingerprint, query.Name, paginatedResult, '', totalRowCount, query.ID, ttlSeconds * 1000).catch(e => LogError(`External RunQuery cache write failed: ${e}`));
|
|
5453
|
+
LocalCacheManager.Instance.SetRunQueryResult(fingerprint, query.Name, paginatedResult, '', totalRowCount, query.ID, ttlSeconds * 1000, undefined, definition).catch(e => LogError(`External RunQuery cache write failed: ${e}`));
|
|
4180
5454
|
}
|
|
4181
5455
|
return { ...checked, Results: paginatedResult, RowCount: paginatedResult.length, TotalRowCount: totalRowCount };
|
|
4182
5456
|
}
|
|
5457
|
+
/**
|
|
5458
|
+
* The result-cache fingerprint segment for what the server set on a run: its `ServerParameters`
|
|
5459
|
+
* and the `Context` values the template read. Empty when there are neither, so the fingerprint
|
|
5460
|
+
* is exactly what it was before either existed.
|
|
5461
|
+
*/
|
|
5462
|
+
serverSetFingerprintSegment(params, contextValues) {
|
|
5463
|
+
const segment = {};
|
|
5464
|
+
if (params.ServerParameters && Object.keys(params.ServerParameters).length > 0) {
|
|
5465
|
+
segment.__serverParameters = params.ServerParameters;
|
|
5466
|
+
}
|
|
5467
|
+
if (contextValues && Object.keys(contextValues).length > 0) {
|
|
5468
|
+
segment.__context = contextValues;
|
|
5469
|
+
}
|
|
5470
|
+
return segment;
|
|
5471
|
+
}
|
|
4183
5472
|
warnIfExternalQueryFieldsMissing(query, result) {
|
|
4184
5473
|
if (!result.Success || !result.Results || result.Results.length === 0) {
|
|
4185
5474
|
return result;
|
|
@@ -4215,6 +5504,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4215
5504
|
try {
|
|
4216
5505
|
const resolved = this.resolveSpecParameters(spec, contextUser);
|
|
4217
5506
|
finalSQL = resolved.finalSQL;
|
|
5507
|
+
// Checked on this rendering, the one that runs: a check a caller made on its own
|
|
5508
|
+
// rendering of the same input is not proof of what this one reads.
|
|
5509
|
+
this.AssertAdhocReadAllowed(resolved.renderResult.Trace.AfterTemplates, contextUser);
|
|
4218
5510
|
// Execute
|
|
4219
5511
|
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
|
|
4220
5512
|
return {
|
|
@@ -4405,6 +5697,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4405
5697
|
/**************************************************************************/
|
|
4406
5698
|
// Load — Shared Implementation
|
|
4407
5699
|
/**************************************************************************/
|
|
5700
|
+
/**
|
|
5701
|
+
* The `WHERE` predicate that selects one record by its composite key, using dialect-neutral
|
|
5702
|
+
* quoting. Quoted key values have embedded single quotes escaped: a key value can contain
|
|
5703
|
+
* apostrophes (an object-valued soft key whose JSON carries free text), and an unescaped quote
|
|
5704
|
+
* both breaks the statement and is an injection vector.
|
|
5705
|
+
*/
|
|
5706
|
+
BuildPrimaryKeyWhereClause(entityInfo, compositeKey) {
|
|
5707
|
+
return compositeKey.KeyValuePairs.map(val => {
|
|
5708
|
+
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
5709
|
+
if (!pk)
|
|
5710
|
+
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
5711
|
+
const quotes = pk.NeedsQuotes ? "'" : '';
|
|
5712
|
+
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
5713
|
+
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
5714
|
+
}).join(' AND ');
|
|
5715
|
+
}
|
|
5716
|
+
/**
|
|
5717
|
+
* Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
|
|
5718
|
+
* Server and PostgreSQL), in place, and returns the row.
|
|
5719
|
+
*/
|
|
5720
|
+
TrimFixedWidthValues(entityInfo, row) {
|
|
5721
|
+
for (const field of entityInfo.Fields) {
|
|
5722
|
+
const isFixedWidth = field.FixedWidthColumn ?? (field.TSType === EntityFieldTSType.String && (field.Type.trim().toLowerCase() === 'char' || field.Type.trim().toLowerCase() === 'nchar'));
|
|
5723
|
+
if (isFixedWidth) {
|
|
5724
|
+
const val = row[field.Name];
|
|
5725
|
+
if (typeof val === 'string')
|
|
5726
|
+
row[field.Name] = val.trimEnd();
|
|
5727
|
+
}
|
|
5728
|
+
}
|
|
5729
|
+
return row;
|
|
5730
|
+
}
|
|
4408
5731
|
/**
|
|
4409
5732
|
* Loads a single entity record by composite key, with optional relationship loading.
|
|
4410
5733
|
* Uses dialect-neutral quoting for all SQL construction.
|
|
@@ -4435,17 +5758,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4435
5758
|
return null;
|
|
4436
5759
|
}
|
|
4437
5760
|
// Build WHERE from composite key
|
|
4438
|
-
const where =
|
|
4439
|
-
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
4440
|
-
if (!pk)
|
|
4441
|
-
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
4442
|
-
const quotes = pk.NeedsQuotes ? "'" : '';
|
|
4443
|
-
// Escape embedded single quotes when the value is wrapped in quotes. A PK value can
|
|
4444
|
-
// legitimately contain apostrophes (e.g. an object-valued soft key whose JSON carries
|
|
4445
|
-
// free-text), and an unescaped quote both breaks the SQL string and is an injection vector.
|
|
4446
|
-
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
4447
|
-
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
4448
|
-
}).join(' AND ');
|
|
5761
|
+
const where = this.BuildPrimaryKeyWhereClause(entityInfo, compositeKey);
|
|
4449
5762
|
// Append Read row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
4450
5763
|
let fullWhere = where;
|
|
4451
5764
|
if (user) {
|
|
@@ -4468,17 +5781,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4468
5781
|
const rawData = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4469
5782
|
const d = await this.PostProcessRows(rawData, entityInfo, user);
|
|
4470
5783
|
if (d && d.length > 0) {
|
|
4471
|
-
const ret = d[0];
|
|
4472
|
-
// Trim trailing spaces for fixed-width char fields (char/nchar pad with spaces on both SQL Server and PG)
|
|
4473
|
-
for (const field of entityInfo.Fields) {
|
|
4474
|
-
if (field.TSType === EntityFieldTSType.String &&
|
|
4475
|
-
field.Type.toLowerCase().includes('char') &&
|
|
4476
|
-
!field.Type.toLowerCase().includes('varchar')) {
|
|
4477
|
-
const val = ret[field.Name];
|
|
4478
|
-
if (typeof val === 'string')
|
|
4479
|
-
ret[field.Name] = val.trimEnd();
|
|
4480
|
-
}
|
|
4481
|
-
}
|
|
5784
|
+
const ret = this.TrimFixedWidthValues(entityInfo, d[0]);
|
|
4482
5785
|
// Load entity relationships if requested
|
|
4483
5786
|
if (entityRelationshipsToLoad && entityRelationshipsToLoad.length > 0) {
|
|
4484
5787
|
for (const rel of entityRelationshipsToLoad) {
|
|
@@ -4551,6 +5854,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4551
5854
|
/**
|
|
4552
5855
|
* Checks whether a new record's field values pass the Create RLS filter.
|
|
4553
5856
|
* Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
|
|
5857
|
+
* Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
|
|
5858
|
+
* filter that references a column the new row leaves NULL evaluates instead of failing to bind.
|
|
5859
|
+
* The row is what the caller sends: a column the database fills on insert (a non-literal default
|
|
5860
|
+
* or a trigger) is seen as NULL here.
|
|
4554
5861
|
*/
|
|
4555
5862
|
async CheckCreateRLS(entity, user) {
|
|
4556
5863
|
const entityInfo = entity.EntityInfo;
|
|
@@ -4558,7 +5865,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4558
5865
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
4559
5866
|
return true;
|
|
4560
5867
|
}
|
|
4561
|
-
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo
|
|
5868
|
+
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
|
|
4562
5869
|
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
|
|
4563
5870
|
const result = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4564
5871
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
@@ -4591,7 +5898,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4591
5898
|
return true; // pre-image check already passed and no filter-referenced column changed
|
|
4592
5899
|
}
|
|
4593
5900
|
}
|
|
4594
|
-
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo
|
|
5901
|
+
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
|
|
4595
5902
|
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
|
|
4596
5903
|
const result = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4597
5904
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
@@ -4627,22 +5934,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4627
5934
|
* Builds field projections for an RLS synthetic-row subquery (Create post-image and
|
|
4628
5935
|
* Update post-image checks).
|
|
4629
5936
|
*
|
|
4630
|
-
*
|
|
4631
|
-
*
|
|
4632
|
-
*
|
|
4633
|
-
* differently from a real row, so nulls are emitted as
|
|
4634
|
-
* the field's metadata-resolved type. An unresolvable
|
|
4635
|
-
* rather than emitting an untyped NULL.
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
BuildRLSSyntheticRowProjections(entity, entityInfo, includeNulls) {
|
|
5937
|
+
* Every non-virtual field is projected, null fields included: a filter referencing a
|
|
5938
|
+
* column the row leaves NULL must see SQL NULL, not a missing column (which fails to
|
|
5939
|
+
* bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
|
|
5940
|
+
* untyped and can evaluate differently from a real row, so nulls are emitted as
|
|
5941
|
+
* `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
|
|
5942
|
+
* type fails the save (throw) rather than emitting an untyped NULL.
|
|
5943
|
+
*/
|
|
5944
|
+
BuildRLSSyntheticRowProjections(entity, entityInfo) {
|
|
4639
5945
|
const parts = [];
|
|
4640
5946
|
for (const field of entityInfo.Fields) {
|
|
4641
5947
|
if (field.IsVirtual)
|
|
4642
5948
|
continue;
|
|
4643
5949
|
const val = entity.Get(field.Name);
|
|
4644
|
-
if (val == null && !includeNulls)
|
|
4645
|
-
continue;
|
|
4646
5950
|
parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
4647
5951
|
}
|
|
4648
5952
|
return parts.join(', ');
|
|
@@ -4671,7 +5975,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4671
5975
|
// spot check and still emits `CAST(NULL AS nvarchar(50))` on the very next field.
|
|
4672
5976
|
const baseType = field.Type;
|
|
4673
5977
|
if (!baseType || baseType.trim().length === 0) {
|
|
4674
|
-
throw new Error(`Cannot build RLS
|
|
5978
|
+
throw new Error(`Cannot build RLS row projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
|
|
4675
5979
|
}
|
|
4676
5980
|
// `field.Length` is the SYSTEM (byte) length from `sys.columns`, but
|
|
4677
5981
|
// `MapDataTypeToString` takes a CHARACTER count — `RuntimeSchemaManager` calls it as
|
|
@@ -4683,8 +5987,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4683
5987
|
// the CAST becomes illegal and the RLS post-image gate throws on SQL SERVER: the exact
|
|
4684
5988
|
// failure this change set out to remove from PostgreSQL, relocated to the primary
|
|
4685
5989
|
// platform. `MaxLength` does the halving, but flattens the `-1` MAX sentinel to 0, so
|
|
4686
|
-
// the sentinel is passed through explicitly.
|
|
4687
|
-
|
|
5990
|
+
// the sentinel is passed through explicitly. `MaxLength` is also 0 for `binary`/`varbinary`,
|
|
5991
|
+
// whose length is a byte count, and SQL Server rejects `VARBINARY(0)`, so those keep
|
|
5992
|
+
// `field.Length`.
|
|
5993
|
+
const isBinary = /^(var)?binary$/i.test(baseType.trim());
|
|
5994
|
+
const charLength = field.Length === -1 || isBinary ? field.Length : field.MaxLength;
|
|
4688
5995
|
// `getDialect()` is nullable on this base. Falling back to `SQLFullType` — the exact
|
|
4689
5996
|
// string this used to emit — keeps SQL Server, whose vocabulary that already is,
|
|
4690
5997
|
// byte-identical to its previous behaviour.
|
|
@@ -4731,12 +6038,115 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4731
6038
|
BuildParameterPlaceholder(index) {
|
|
4732
6039
|
return `$${index + 1}`;
|
|
4733
6040
|
}
|
|
6041
|
+
/**
|
|
6042
|
+
* Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
|
|
6043
|
+
* denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
|
|
6044
|
+
* that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
|
|
6045
|
+
* user checks: every authenticated client loads it to learn the schema, including principals
|
|
6046
|
+
* (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
|
|
6047
|
+
*/
|
|
6048
|
+
resolveDatasetItemScope(datasetName, item, itemFilters, contextUser) {
|
|
6049
|
+
const code = String(item['Code']);
|
|
6050
|
+
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
6051
|
+
const clientFilter = itemFilters?.find(f => f?.ItemCode === code)?.Filter ?? '';
|
|
6052
|
+
if (clientFilter && !this.ValidateUserProvidedSQLClause(clientFilter)) {
|
|
6053
|
+
return { Filter: '', RowFilter: '', Refusal: `Invalid ItemFilter for dataset item '${code}': contains one or more forbidden keywords` };
|
|
6054
|
+
}
|
|
6055
|
+
const filter = whereClause && clientFilter ? `${whereClause} AND (${clientFilter})` : (whereClause || clientFilter);
|
|
6056
|
+
if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6057
|
+
return { Filter: filter, RowFilter: '', Refusal: null };
|
|
6058
|
+
}
|
|
6059
|
+
const entityName = String(item['Entity']);
|
|
6060
|
+
const entity = this.EntityByName(entityName);
|
|
6061
|
+
if (!entity) {
|
|
6062
|
+
return { Filter: filter, RowFilter: '', Refusal: `Entity '${entityName}' of dataset item '${code}' not found in metadata` };
|
|
6063
|
+
}
|
|
6064
|
+
if (!entity.GetUserPermisions(contextUser)?.CanRead) {
|
|
6065
|
+
return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
|
|
6066
|
+
}
|
|
6067
|
+
const fieldSecurityRefusal = this.datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser);
|
|
6068
|
+
if (fieldSecurityRefusal) {
|
|
6069
|
+
return { Filter: filter, RowFilter: '', Refusal: fieldSecurityRefusal };
|
|
6070
|
+
}
|
|
6071
|
+
return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
|
|
6072
|
+
}
|
|
6073
|
+
/**
|
|
6074
|
+
* Why a caller's ItemFilter is refused by the field-level security gate — the same gate every
|
|
6075
|
+
* RunView filter passes — or null when it may run. The item's stored WhereClause is
|
|
6076
|
+
* administrator-defined dataset metadata, not a predicate the caller chose, so it is not checked.
|
|
6077
|
+
*/
|
|
6078
|
+
datasetItemFilterFieldSecurityRefusal(entity, clientFilter, contextUser) {
|
|
6079
|
+
try {
|
|
6080
|
+
this.AssertClausesRespectFieldSecurityForEntity(entity, [clientFilter], contextUser);
|
|
6081
|
+
return null;
|
|
6082
|
+
}
|
|
6083
|
+
catch (e) {
|
|
6084
|
+
if (e instanceof Error && e.name === FieldSecurityError.ErrorName) {
|
|
6085
|
+
return e.message;
|
|
6086
|
+
}
|
|
6087
|
+
throw e;
|
|
6088
|
+
}
|
|
6089
|
+
}
|
|
6090
|
+
/**
|
|
6091
|
+
* The fields of a dataset item's entity the caller may not read, lowercased; empty when none,
|
|
6092
|
+
* when there is no caller, or for MJ_Metadata, which every principal loads to learn the schema.
|
|
6093
|
+
*/
|
|
6094
|
+
datasetItemDeniedFields(datasetName, entity, contextUser) {
|
|
6095
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName || !entity.FieldLevelSecurityApplies) {
|
|
6096
|
+
return new Set();
|
|
6097
|
+
}
|
|
6098
|
+
return entity.GetDeniedReadFields(contextUser);
|
|
6099
|
+
}
|
|
6100
|
+
/**
|
|
6101
|
+
* The error a failed dataset batch reports to the caller. When the caller is denied fields on
|
|
6102
|
+
* an item's entity and the database rejected a column that does not exist, every item reports
|
|
6103
|
+
* the field-security error a denied column gets instead, so the two cannot be told apart.
|
|
6104
|
+
*/
|
|
6105
|
+
datasetBatchErrorForCaller(batchError, items, datasetName, contextUser) {
|
|
6106
|
+
if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6107
|
+
return batchError;
|
|
6108
|
+
}
|
|
6109
|
+
for (const item of items) {
|
|
6110
|
+
const converted = FieldSecuritySQLGate.ErrorForInvalidColumn(batchError, this.EntityByName(String(item['Entity'])), contextUser);
|
|
6111
|
+
if (converted)
|
|
6112
|
+
return converted.message;
|
|
6113
|
+
}
|
|
6114
|
+
return batchError;
|
|
6115
|
+
}
|
|
6116
|
+
/**
|
|
6117
|
+
* Dataset item rows as the caller may see them: denied columns removed, and Record Changes
|
|
6118
|
+
* payloads narrowed. Cached rows are shared and full width, so this always builds new rows
|
|
6119
|
+
* rather than narrowing the cached ones. MJ_Metadata is exempt for the reason given on
|
|
6120
|
+
* {@link datasetItemDeniedFields}.
|
|
6121
|
+
*/
|
|
6122
|
+
projectDatasetRowsForCaller(datasetName, entity, rows, contextUser) {
|
|
6123
|
+
if (!entity || !contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
6124
|
+
return rows;
|
|
6125
|
+
}
|
|
6126
|
+
return ProjectEntityValueRowsForUser(this, entity, rows, contextUser) ?? rows;
|
|
6127
|
+
}
|
|
6128
|
+
/**
|
|
6129
|
+
* The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
|
|
6130
|
+
* item's filter sits two parentheses deep because a client ItemFilter is screened inside one
|
|
6131
|
+
* level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
|
|
6132
|
+
*/
|
|
6133
|
+
datasetItemWhereClause(scope) {
|
|
6134
|
+
if (!scope.RowFilter)
|
|
6135
|
+
return scope.Filter;
|
|
6136
|
+
if (!scope.Filter)
|
|
6137
|
+
return scope.RowFilter;
|
|
6138
|
+
return `(${scope.RowFilter}) AND ((${scope.Filter}))`;
|
|
6139
|
+
}
|
|
4734
6140
|
/**
|
|
4735
6141
|
* Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
|
|
4736
6142
|
* and aggregating results. Uses dialect-neutral quoting for all SQL construction.
|
|
4737
6143
|
*
|
|
4738
6144
|
* ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
|
|
4739
6145
|
* while PG (and the default) use parallel individual queries.
|
|
6146
|
+
*
|
|
6147
|
+
* An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
|
|
6148
|
+
* CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
|
|
6149
|
+
* item runs no SQL and fails the dataset.
|
|
4740
6150
|
*/
|
|
4741
6151
|
async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
|
|
4742
6152
|
const provider = (providerToUse ?? this);
|
|
@@ -4777,13 +6187,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4777
6187
|
const uncachedFingerprints = [];
|
|
4778
6188
|
let cacheHitCount = 0;
|
|
4779
6189
|
let cacheMissCount = 0;
|
|
6190
|
+
const preparedItems = [];
|
|
4780
6191
|
for (const item of items) {
|
|
4781
6192
|
const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
|
|
4782
6193
|
const entityBaseView = String(item['EntityBaseView']);
|
|
4783
6194
|
const code = String(item['Code']);
|
|
4784
6195
|
const entityName = String(item['Entity']);
|
|
4785
6196
|
const entityID = String(item['EntityID']);
|
|
4786
|
-
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
4787
6197
|
// External-data-source entities have no MJ base view — their data is proxied live and
|
|
4788
6198
|
// can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
|
|
4789
6199
|
// rather than silently querying a non-existent (or wrongly same-named) local view.
|
|
@@ -4800,38 +6210,136 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4800
6210
|
});
|
|
4801
6211
|
continue;
|
|
4802
6212
|
}
|
|
4803
|
-
//
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
|
|
4810
|
-
|
|
6213
|
+
// The item's filter and the caller's row filter, or why it is refused. A refused item
|
|
6214
|
+
// never reaches the cache or the database.
|
|
6215
|
+
const scope = provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser);
|
|
6216
|
+
if (scope.Refusal) {
|
|
6217
|
+
errorResults.push({
|
|
6218
|
+
EntityID: entityID,
|
|
6219
|
+
EntityName: entityName,
|
|
6220
|
+
Code: code,
|
|
6221
|
+
Results: [],
|
|
6222
|
+
LatestUpdateDate: undefined,
|
|
6223
|
+
Status: scope.Refusal,
|
|
6224
|
+
Success: false,
|
|
6225
|
+
});
|
|
6226
|
+
continue;
|
|
6227
|
+
}
|
|
6228
|
+
// The row filter keys the slot, so one user's filtered rows are never served to another.
|
|
6229
|
+
const rowFilterKey = scope.RowFilter || undefined;
|
|
6230
|
+
const fingerprint = cacheAvailable
|
|
6231
|
+
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
|
|
6232
|
+
: '';
|
|
6233
|
+
const cached = cacheAvailable && fingerprint
|
|
6234
|
+
? await cache.GetRunViewResult(fingerprint)
|
|
6235
|
+
: null;
|
|
6236
|
+
preparedItems.push({
|
|
6237
|
+
item,
|
|
6238
|
+
entitySchemaName,
|
|
6239
|
+
entityBaseView,
|
|
6240
|
+
code,
|
|
6241
|
+
entityName,
|
|
6242
|
+
entityID,
|
|
6243
|
+
itemEntity,
|
|
6244
|
+
scope,
|
|
6245
|
+
rowFilterKey,
|
|
6246
|
+
fingerprint,
|
|
6247
|
+
cached,
|
|
6248
|
+
});
|
|
6249
|
+
}
|
|
6250
|
+
// Reconcile cached dataset slots against live SQL status (GetDatasetStatusByName)
|
|
6251
|
+
// when status was recently fetched, when GetDatasetStatusByName is overridden/spied,
|
|
6252
|
+
// or when any cached item's verification TTL (ServerCacheVerificationTTLMs) has elapsed.
|
|
6253
|
+
let liveStatus;
|
|
6254
|
+
if (cacheAvailable && preparedItems.some(p => p.cached !== null)) {
|
|
6255
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
6256
|
+
const recorded = provider._lastDatasetStatusByName.get(statusKey) ?? this._lastDatasetStatusByName.get(statusKey);
|
|
6257
|
+
const isStatusMethodOverridden = this.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName ||
|
|
6258
|
+
provider.GetDatasetStatusByName !== GenericDatabaseProvider.prototype.GetDatasetStatusByName;
|
|
6259
|
+
const anyCachedExpired = preparedItems.some(p => {
|
|
6260
|
+
if (!p.cached)
|
|
6261
|
+
return false;
|
|
6262
|
+
const verifiedAt = p.cached.lastVerifiedAt ?? p.cached.cachedAt;
|
|
6263
|
+
return (this.ServerCacheVerificationTTLMs <= 0 ||
|
|
6264
|
+
(verifiedAt !== undefined && (Date.now() - verifiedAt) > this.ServerCacheVerificationTTLMs));
|
|
6265
|
+
});
|
|
6266
|
+
if (isStatusMethodOverridden ||
|
|
6267
|
+
(anyCachedExpired && (!recorded || (Date.now() - recorded.timestamp) > this.ServerCacheVerificationTTLMs))) {
|
|
6268
|
+
try {
|
|
6269
|
+
const fetched = await provider.GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse);
|
|
6270
|
+
if (fetched?.Success) {
|
|
6271
|
+
liveStatus = fetched;
|
|
6272
|
+
}
|
|
6273
|
+
}
|
|
6274
|
+
catch (statusErr) {
|
|
6275
|
+
LogError(`GetDatasetByName("${datasetName}"): status verification failed: ${statusErr instanceof Error ? statusErr.message : String(statusErr)}`);
|
|
6276
|
+
}
|
|
6277
|
+
}
|
|
6278
|
+
else if (recorded?.status?.Success) {
|
|
6279
|
+
liveStatus = recorded.status;
|
|
6280
|
+
}
|
|
6281
|
+
}
|
|
6282
|
+
const statusByEntityID = liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)
|
|
6283
|
+
? IndexByUUID(liveStatus.EntityUpdateDates.filter(e => Boolean(e.EntityID)), e => e.EntityID)
|
|
6284
|
+
: null;
|
|
6285
|
+
const statusByEntityName = new Map();
|
|
6286
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6287
|
+
for (const e of liveStatus.EntityUpdateDates) {
|
|
6288
|
+
if (e.EntityName) {
|
|
6289
|
+
statusByEntityName.set(e.EntityName.trim().toLowerCase(), e);
|
|
4811
6290
|
}
|
|
4812
6291
|
}
|
|
4813
|
-
|
|
4814
|
-
|
|
4815
|
-
|
|
4816
|
-
|
|
6292
|
+
}
|
|
6293
|
+
for (const prepared of preparedItems) {
|
|
6294
|
+
const { item, entitySchemaName, entityBaseView, code, entityName, entityID, itemEntity, scope, fingerprint } = prepared;
|
|
6295
|
+
let cached = prepared.cached;
|
|
6296
|
+
if (cached) {
|
|
6297
|
+
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
6298
|
+
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
6299
|
+
if (liveStatus?.Success && Array.isArray(liveStatus.EntityUpdateDates)) {
|
|
6300
|
+
const statusEntry = (entityID ? statusByEntityID?.Get(entityID) : undefined)
|
|
6301
|
+
?? statusByEntityName.get(entityName.trim().toLowerCase());
|
|
6302
|
+
if (statusEntry) {
|
|
6303
|
+
const rowCountMatches = cached.results.length === statusEntry.RowCount;
|
|
6304
|
+
const cachedMaxDate = this.parseClientTimestamp(cached.maxUpdatedAt);
|
|
6305
|
+
const effectiveCachedTime = Math.max(latestUpdateDate ? new Date(latestUpdateDate).getTime() : 0, cachedMaxDate ? cachedMaxDate.getTime() : 0);
|
|
6306
|
+
const statusTime = statusEntry.UpdateDate ? new Date(statusEntry.UpdateDate).getTime() : 0;
|
|
6307
|
+
const timestampMatches = isNaN(statusTime) ||
|
|
6308
|
+
statusTime <= 0 ||
|
|
6309
|
+
effectiveCachedTime <= 0 ||
|
|
6310
|
+
Math.abs(statusTime - effectiveCachedTime) < 1000;
|
|
6311
|
+
if (!rowCountMatches || !timestampMatches) {
|
|
6312
|
+
LogStatusEx({
|
|
6313
|
+
message: ` ♻️ [Dataset RECONCILE-EVICT] "${datasetName}/${code}" (${entityName}) — cached slot (rows=${cached.results.length}) disagreed with SQL status (rows=${statusEntry.RowCount}); invalidating and re-fetching from SQL`,
|
|
6314
|
+
verboseOnly: true,
|
|
6315
|
+
});
|
|
6316
|
+
await cache.InvalidateRunViewResult(fingerprint);
|
|
6317
|
+
cached = null;
|
|
6318
|
+
}
|
|
6319
|
+
else {
|
|
6320
|
+
cache.TouchRunViewResultVerifiedAt(fingerprint);
|
|
6321
|
+
}
|
|
6322
|
+
}
|
|
6323
|
+
}
|
|
4817
6324
|
if (cached) {
|
|
4818
6325
|
cacheHitCount++;
|
|
4819
|
-
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
4820
|
-
const latestUpdateDate = this.computeLatestUpdateDate(cached.results, dateFieldToCheck, item);
|
|
4821
6326
|
cachedResults.push({
|
|
4822
6327
|
EntityID: entityID,
|
|
4823
6328
|
EntityName: entityName,
|
|
4824
6329
|
Code: code,
|
|
4825
|
-
Results: cached.results,
|
|
6330
|
+
Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, cached.results, contextUser),
|
|
4826
6331
|
LatestUpdateDate: latestUpdateDate,
|
|
4827
6332
|
Success: true,
|
|
4828
6333
|
});
|
|
4829
6334
|
continue; // Skip SQL for this item
|
|
4830
6335
|
}
|
|
4831
6336
|
}
|
|
4832
|
-
// Cache miss — validate columns and build SQL
|
|
6337
|
+
// Cache miss (or invalidated stale slot) — validate columns and build SQL
|
|
4833
6338
|
cacheMissCount++;
|
|
4834
|
-
|
|
6339
|
+
// A caller denied fields never has them selected; such a narrowed read is not written to
|
|
6340
|
+
// the shared slot, which holds full-width rows for every caller.
|
|
6341
|
+
const deniedFields = this.datasetItemDeniedFields(datasetName, itemEntity, contextUser);
|
|
6342
|
+
const columns = provider.getColumnsForDatasetItem(item, datasetName, deniedFields);
|
|
4835
6343
|
if (!columns) {
|
|
4836
6344
|
errorResults.push({
|
|
4837
6345
|
EntityID: entityID,
|
|
@@ -4844,14 +6352,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4844
6352
|
});
|
|
4845
6353
|
continue;
|
|
4846
6354
|
}
|
|
4847
|
-
const
|
|
6355
|
+
const whereSQL = this.datasetItemWhereClause(scope);
|
|
6356
|
+
const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
|
|
4848
6357
|
uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
|
|
4849
6358
|
uncachedItems.push(item);
|
|
4850
|
-
//
|
|
4851
|
-
|
|
4852
|
-
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString, undefined, this.datasetCacheSegment(datasetName, code))
|
|
4853
|
-
: '';
|
|
4854
|
-
uncachedFingerprints.push(fp);
|
|
6359
|
+
// A narrowed read (the caller is denied fields) is never written to the shared slot.
|
|
6360
|
+
uncachedFingerprints.push(deniedFields.size === 0 ? fingerprint : '');
|
|
4855
6361
|
}
|
|
4856
6362
|
// Phase 2: Execute SQL only for cache misses
|
|
4857
6363
|
let batchResults = [];
|
|
@@ -4870,6 +6376,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4870
6376
|
catch (err) {
|
|
4871
6377
|
batchError = err instanceof Error ? err.message : String(err);
|
|
4872
6378
|
LogError(`GetDatasetByName("${datasetName}"): Batch execution failed: ${batchError}`);
|
|
6379
|
+
batchError = this.datasetBatchErrorForCaller(batchError, uncachedItems, datasetName, contextUser);
|
|
4873
6380
|
}
|
|
4874
6381
|
}
|
|
4875
6382
|
// Phase 3: Process SQL results and write-through to cache
|
|
@@ -4930,7 +6437,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4930
6437
|
EntityID: entityID,
|
|
4931
6438
|
EntityName: entityName,
|
|
4932
6439
|
Code: code,
|
|
4933
|
-
Results: itemData,
|
|
6440
|
+
Results: this.projectDatasetRowsForCaller(datasetName, provider.EntityByName(entityName), itemData, contextUser),
|
|
4934
6441
|
LatestUpdateDate: latestUpdateDate,
|
|
4935
6442
|
Success: itemData !== null && itemData !== undefined,
|
|
4936
6443
|
});
|
|
@@ -4977,6 +6484,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4977
6484
|
/**
|
|
4978
6485
|
* Retrieves status information for a dataset by name: per-entity row count and
|
|
4979
6486
|
* latest update date. Uses ExecuteSQLBatch for per-item status queries.
|
|
6487
|
+
*
|
|
6488
|
+
* Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
|
|
6489
|
+
* status fails with the refusal and no status SQL runs.
|
|
4980
6490
|
*/
|
|
4981
6491
|
async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
|
|
4982
6492
|
const overallStart = performance.now();
|
|
@@ -5015,33 +6525,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5015
6525
|
// in GetDatasetByName.
|
|
5016
6526
|
const updateDates = [];
|
|
5017
6527
|
let overallLatestDate = new Date(1900, 1, 1);
|
|
6528
|
+
// Same scope as GetDatasetByName's data read — the stored item WhereClause, the caller's
|
|
6529
|
+
// ItemFilter and the caller's row filter — so status and data describe the same row set.
|
|
6530
|
+
// (Every shipped MJ_Metadata item has a NULL WhereClause and no row filter, so for
|
|
6531
|
+
// metadata this is an unfiltered aggregate.)
|
|
6532
|
+
const scopes = items.map(item => provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser));
|
|
6533
|
+
const refusal = scopes.find(scope => scope.Refusal)?.Refusal;
|
|
6534
|
+
if (refusal) {
|
|
6535
|
+
return {
|
|
6536
|
+
DatasetID: String(items[0]['DatasetID']),
|
|
6537
|
+
DatasetName: datasetName,
|
|
6538
|
+
Success: false,
|
|
6539
|
+
Status: refusal,
|
|
6540
|
+
LatestUpdateDate: new Date(0),
|
|
6541
|
+
EntityUpdateDates: [],
|
|
6542
|
+
};
|
|
6543
|
+
}
|
|
5018
6544
|
const itemMeta = [];
|
|
5019
|
-
const queries = items.map((item) => {
|
|
6545
|
+
const queries = items.map((item, index) => {
|
|
5020
6546
|
const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
|
|
5021
6547
|
const entityBaseView = String(item['EntityBaseView']);
|
|
5022
|
-
const code = String(item['Code']);
|
|
5023
6548
|
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
5024
|
-
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
5025
6549
|
itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
|
|
5026
6550
|
// The floor for the reported timestamp: an edit to the dataset DEFINITION itself
|
|
5027
6551
|
// (item added, filter changed) must read as a change even when no entity row moved.
|
|
5028
6552
|
const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
|
|
5029
6553
|
const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
|
|
5030
6554
|
const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
|
|
5031
|
-
|
|
5032
|
-
|
|
5033
|
-
// row set. (Every shipped MJ_Metadata item has a NULL WhereClause, so for metadata
|
|
5034
|
-
// this is identical to an unfiltered aggregate.)
|
|
5035
|
-
let effectiveFilter = whereClause;
|
|
5036
|
-
if (itemFilters && itemFilters.length > 0) {
|
|
5037
|
-
const filter = itemFilters.find(f => f.ItemCode === code);
|
|
5038
|
-
if (filter) {
|
|
5039
|
-
effectiveFilter = whereClause
|
|
5040
|
-
? `${whereClause} AND (${filter.Filter})`
|
|
5041
|
-
: filter.Filter;
|
|
5042
|
-
}
|
|
5043
|
-
}
|
|
5044
|
-
const filterSQL = effectiveFilter ? ' WHERE ' + effectiveFilter : '';
|
|
6555
|
+
const whereSQL = this.datasetItemWhereClause(scopes[index]);
|
|
6556
|
+
const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
|
|
5045
6557
|
return `SELECT ` +
|
|
5046
6558
|
`CASE ` +
|
|
5047
6559
|
`WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
|
|
@@ -5088,7 +6600,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5088
6600
|
EntityUpdateDates: [],
|
|
5089
6601
|
};
|
|
5090
6602
|
}
|
|
5091
|
-
|
|
6603
|
+
const statusResult = {
|
|
5092
6604
|
DatasetID: String(items[0]['DatasetID']),
|
|
5093
6605
|
DatasetName: datasetName,
|
|
5094
6606
|
Success: true,
|
|
@@ -5096,6 +6608,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5096
6608
|
LatestUpdateDate: overallLatestDate,
|
|
5097
6609
|
EntityUpdateDates: updateDates,
|
|
5098
6610
|
};
|
|
6611
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
6612
|
+
const now = Date.now();
|
|
6613
|
+
this._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
6614
|
+
provider._lastDatasetStatusByName.set(statusKey, { status: statusResult, timestamp: now });
|
|
6615
|
+
return statusResult;
|
|
6616
|
+
}
|
|
6617
|
+
/**
|
|
6618
|
+
* Builds the lookup key for {@link _lastDatasetStatusByName} from dataset name and item filters.
|
|
6619
|
+
*/
|
|
6620
|
+
buildDatasetStatusCacheKey(datasetName, itemFilters) {
|
|
6621
|
+
return `${datasetName}::${this.ConvertItemFiltersToUniqueKey(itemFilters ?? [])}`;
|
|
5099
6622
|
}
|
|
5100
6623
|
/**************************************************************************/
|
|
5101
6624
|
// getColumnsForDatasetItem — Column Validation
|
|
@@ -5109,41 +6632,53 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5109
6632
|
* binary column can still be named explicitly. When the entity's metadata is not loaded yet —
|
|
5110
6633
|
* the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
|
|
5111
6634
|
* are converted to base64 by the caller.
|
|
6635
|
+
*
|
|
6636
|
+
* `deniedFields` (lowercased) are the columns the caller may not read. They are never
|
|
6637
|
+
* selected: a named one is dropped, and an item that names none selects every readable column.
|
|
5112
6638
|
*/
|
|
5113
|
-
getColumnsForDatasetItem(item, datasetName) {
|
|
6639
|
+
getColumnsForDatasetItem(item, datasetName, deniedFields) {
|
|
5114
6640
|
const specifiedColumns = item['Columns'] ? String(item['Columns']).split(',').map(col => col.trim()) : [];
|
|
6641
|
+
const entity = this.EntityByID(item['EntityID']);
|
|
6642
|
+
const denied = deniedFields ?? new Set();
|
|
5115
6643
|
if (specifiedColumns.length === 0) {
|
|
5116
|
-
|
|
6644
|
+
if (entity && denied.size > 0) {
|
|
6645
|
+
return this.readableDatasetColumns(entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => f.Name), entity, denied);
|
|
6646
|
+
}
|
|
5117
6647
|
if (entity?.HasBinaryFields) {
|
|
5118
6648
|
return entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => this.QuoteIdentifier(f.Name)).join(',');
|
|
5119
6649
|
}
|
|
6650
|
+
return '*';
|
|
6651
|
+
}
|
|
6652
|
+
if (!entity && this.Entities.length > 0) {
|
|
6653
|
+
LogError(`Entity not found for dataset item ${item['Code']} in dataset ${datasetName}`);
|
|
6654
|
+
return null;
|
|
5120
6655
|
}
|
|
5121
|
-
if (
|
|
5122
|
-
const
|
|
5123
|
-
if (
|
|
5124
|
-
LogError(`
|
|
6656
|
+
if (entity) {
|
|
6657
|
+
const invalidColumns = specifiedColumns.filter(col => !entity.FieldByName(col));
|
|
6658
|
+
if (invalidColumns.length > 0) {
|
|
6659
|
+
LogError(`Invalid columns specified for dataset item ${item['Code']} in dataset ${datasetName}: ${invalidColumns.join(', ')}`);
|
|
5125
6660
|
return null;
|
|
5126
6661
|
}
|
|
5127
|
-
if (entity) {
|
|
5128
|
-
const invalidColumns = [];
|
|
5129
|
-
specifiedColumns.forEach(col => {
|
|
5130
|
-
if (!entity.FieldByName(col)) {
|
|
5131
|
-
invalidColumns.push(col);
|
|
5132
|
-
}
|
|
5133
|
-
});
|
|
5134
|
-
if (invalidColumns.length > 0) {
|
|
5135
|
-
LogError(`Invalid columns specified for dataset item ${item['Code']} in dataset ${datasetName}: ${invalidColumns.join(', ')}`);
|
|
5136
|
-
return null;
|
|
5137
|
-
}
|
|
5138
|
-
}
|
|
5139
|
-
// Ensure DateFieldToCheck is included
|
|
5140
|
-
const dateField = item['DateFieldToCheck'] ? String(item['DateFieldToCheck']).trim() : '';
|
|
5141
|
-
if (dateField.length > 0 && specifiedColumns.indexOf(dateField) === -1) {
|
|
5142
|
-
if (!entity || entity.FieldByName(dateField))
|
|
5143
|
-
specifiedColumns.push(dateField);
|
|
5144
|
-
}
|
|
5145
6662
|
}
|
|
5146
|
-
|
|
6663
|
+
// Ensure DateFieldToCheck is included
|
|
6664
|
+
const dateField = item['DateFieldToCheck'] ? String(item['DateFieldToCheck']).trim() : '';
|
|
6665
|
+
if (dateField.length > 0 && specifiedColumns.indexOf(dateField) === -1) {
|
|
6666
|
+
if (!entity || entity.FieldByName(dateField))
|
|
6667
|
+
specifiedColumns.push(dateField);
|
|
6668
|
+
}
|
|
6669
|
+
if (entity && denied.size > 0) {
|
|
6670
|
+
return this.readableDatasetColumns(specifiedColumns, entity, denied);
|
|
6671
|
+
}
|
|
6672
|
+
return specifiedColumns.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
6673
|
+
}
|
|
6674
|
+
/**
|
|
6675
|
+
* `columns` without the denied ones, quoted and joined. When every one is denied, the primary
|
|
6676
|
+
* key columns are selected instead, which are never denied, so the read still has a shape.
|
|
6677
|
+
*/
|
|
6678
|
+
readableDatasetColumns(columns, entity, denied) {
|
|
6679
|
+
const readable = columns.filter(col => !denied.has(col.trim().toLowerCase()));
|
|
6680
|
+
const selected = readable.length > 0 ? readable : entity.PrimaryKeys.map(pk => pk.Name);
|
|
6681
|
+
return selected.map(col => this.QuoteIdentifier(col.trim())).join(',');
|
|
5147
6682
|
}
|
|
5148
6683
|
/**************************************************************************/
|
|
5149
6684
|
// Dataset Cache Helpers
|
|
@@ -5277,10 +6812,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5277
6812
|
const data = result.data;
|
|
5278
6813
|
const matches = data?.matches ?? [];
|
|
5279
6814
|
const out = [];
|
|
6815
|
+
const seenRecordIds = new Set();
|
|
5280
6816
|
for (const m of matches) {
|
|
5281
6817
|
const recordId = String(m.metadata?.['RecordID'] ?? '');
|
|
5282
6818
|
if (!recordId)
|
|
5283
6819
|
continue;
|
|
6820
|
+
const normalizedKey = recordId.toLowerCase();
|
|
6821
|
+
if (seenRecordIds.has(normalizedKey))
|
|
6822
|
+
continue;
|
|
6823
|
+
seenRecordIds.add(normalizedKey);
|
|
5284
6824
|
out.push({
|
|
5285
6825
|
ID: recordId,
|
|
5286
6826
|
Score: m.score,
|