@memberjunction/generic-database-provider 6.2.0-edge.6 → 6.2.0-edge.8
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 +150 -0
- package/dist/GenericDatabaseProvider.d.ts +329 -41
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +864 -238
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +16 -72
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +34 -278
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/composition/compositionAssembler.d.ts +33 -0
- package/dist/composition/compositionAssembler.d.ts.map +1 -0
- package/dist/composition/compositionAssembler.js +270 -0
- package/dist/composition/compositionAssembler.js.map +1 -0
- package/dist/composition/compositionInfo.d.ts +7 -0
- package/dist/composition/compositionInfo.d.ts.map +1 -0
- package/dist/composition/compositionInfo.js +31 -0
- package/dist/composition/compositionInfo.js.map +1 -0
- package/dist/composition/compositionLookup.d.ts +44 -0
- package/dist/composition/compositionLookup.d.ts.map +1 -0
- package/dist/composition/compositionLookup.js +122 -0
- package/dist/composition/compositionLookup.js.map +1 -0
- package/dist/composition/compositionRender.d.ts +136 -0
- package/dist/composition/compositionRender.d.ts.map +1 -0
- package/dist/composition/compositionRender.js +264 -0
- package/dist/composition/compositionRender.js.map +1 -0
- package/dist/composition/compositionTypes.d.ts +40 -0
- package/dist/composition/compositionTypes.d.ts.map +1 -0
- package/dist/composition/compositionTypes.js +2 -0
- package/dist/composition/compositionTypes.js.map +1 -0
- package/dist/composition/quotedTagRefusal.d.ts +44 -0
- package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
- package/dist/composition/quotedTagRefusal.js +132 -0
- package/dist/composition/quotedTagRefusal.js.map +1 -0
- package/dist/composition/renderSteps.d.ts +16 -0
- package/dist/composition/renderSteps.d.ts.map +1 -0
- package/dist/composition/renderSteps.js +42 -0
- package/dist/composition/renderSteps.js.map +1 -0
- package/dist/composition/safetyGate.d.ts +46 -0
- package/dist/composition/safetyGate.d.ts.map +1 -0
- package/dist/composition/safetyGate.js +61 -0
- package/dist/composition/safetyGate.js.map +1 -0
- package/dist/composition/templateUnit.d.ts +95 -0
- package/dist/composition/templateUnit.d.ts.map +1 -0
- package/dist/composition/templateUnit.js +189 -0
- package/dist/composition/templateUnit.js.map +1 -0
- package/dist/describeStatement.d.ts +51 -0
- package/dist/describeStatement.d.ts.map +1 -0
- package/dist/describeStatement.js +19 -0
- package/dist/describeStatement.js.map +1 -0
- package/dist/fieldSecurity/projectionStars.d.ts +15 -0
- package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
- package/dist/fieldSecurity/projectionStars.js +116 -0
- package/dist/fieldSecurity/projectionStars.js.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
- package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
- package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
- package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/pagingLayout.d.ts +68 -0
- package/dist/pagingLayout.d.ts.map +1 -0
- package/dist/pagingLayout.js +190 -0
- package/dist/pagingLayout.js.map +1 -0
- package/dist/queryCompositionEngine.d.ts +22 -222
- package/dist/queryCompositionEngine.d.ts.map +1 -1
- package/dist/queryCompositionEngine.js +35 -729
- package/dist/queryCompositionEngine.js.map +1 -1
- package/dist/queryPagingEngine.d.ts +26 -5
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +51 -15
- package/dist/queryPagingEngine.js.map +1 -1
- package/dist/renderPipeline.d.ts +77 -85
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +70 -220
- package/dist/renderPipeline.js.map +1 -1
- package/dist/statementMemo.d.ts +29 -0
- package/dist/statementMemo.d.ts.map +1 -0
- package/dist/statementMemo.js +61 -0
- package/dist/statementMemo.js.map +1 -0
- package/dist/typedQueryParameter.d.ts +55 -0
- package/dist/typedQueryParameter.d.ts.map +1 -0
- package/dist/typedQueryParameter.js +122 -0
- package/dist/typedQueryParameter.js.map +1 -0
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
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';
|
|
18
|
+
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProjectEntityValueRowsForUser, FieldSecurityError, FieldSecuritySQLGate, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride, NormalizeAlternateBaseViewName, ResolveAlternateBaseView, LocalCacheManager, LogError, LogStatus, LogStatusEx, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, } from '@memberjunction/core';
|
|
19
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
|
|
@@ -23,7 +23,12 @@ import { createHash } from 'node:crypto';
|
|
|
23
23
|
import { v4 as uuidv4 } from 'uuid';
|
|
24
24
|
import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
25
25
|
import { GetDialect } from '@memberjunction/sql-dialect';
|
|
26
|
-
import {
|
|
26
|
+
import { SqlDocument, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
27
|
+
import { DescribeStatementFailure } from './describeStatement.js';
|
|
28
|
+
import { NamedQueryParameter, TypedBindValue, TypedQueryParameter } from './typedQueryParameter.js';
|
|
29
|
+
import { StatementMemo } from './statementMemo.js';
|
|
30
|
+
import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
|
|
31
|
+
import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './fieldSecurity/queryColumnSecurity.js';
|
|
27
32
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
28
33
|
import { RenderPipeline } from './renderPipeline.js';
|
|
29
34
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
@@ -32,7 +37,7 @@ import { AIEngine } from '@memberjunction/aiengine';
|
|
|
32
37
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
33
38
|
import { QueueManager } from '@memberjunction/queue';
|
|
34
39
|
import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
|
|
35
|
-
import { BuildEntityChangeContext } from '@memberjunction/actions-base';
|
|
40
|
+
import { BuildEntityChangeContext, DurableEntityActionRegistry } from '@memberjunction/actions-base';
|
|
36
41
|
import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
37
42
|
import { TransactionAffinity } from './TransactionAffinity.js';
|
|
38
43
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
@@ -69,9 +74,89 @@ export class DoomedTransactionError extends Error {
|
|
|
69
74
|
}
|
|
70
75
|
}
|
|
71
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Builds a safe parameter summary list for SQL error messages and diagnostic observations.
|
|
79
|
+
* When `includeReadValues` is false (e.g., mutations or error strings), only parameter names,
|
|
80
|
+
* types, and byte lengths are included — never raw parameter values.
|
|
81
|
+
*/
|
|
82
|
+
export function SummarizeSqlParameters(parameters, includeReadValues = false) {
|
|
83
|
+
if (!parameters) {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
const summaries = [];
|
|
87
|
+
const describeValue = (name, rawVal) => {
|
|
88
|
+
const unwrapped = rawVal != null && typeof rawVal === 'object' && 'value' in rawVal
|
|
89
|
+
? rawVal.value
|
|
90
|
+
: rawVal;
|
|
91
|
+
if (unwrapped === null || unwrapped === undefined) {
|
|
92
|
+
return { name, type: unwrapped === null ? 'null' : 'undefined', byteLength: 0, value: includeReadValues ? null : undefined };
|
|
93
|
+
}
|
|
94
|
+
if (Buffer.isBuffer(unwrapped) || unwrapped instanceof Uint8Array) {
|
|
95
|
+
return { name, type: 'binary', byteLength: unwrapped.byteLength };
|
|
96
|
+
}
|
|
97
|
+
if (unwrapped instanceof Date) {
|
|
98
|
+
const iso = unwrapped.toISOString();
|
|
99
|
+
return {
|
|
100
|
+
name,
|
|
101
|
+
type: 'Date',
|
|
102
|
+
byteLength: iso.length,
|
|
103
|
+
value: includeReadValues ? iso : undefined,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
const t = typeof unwrapped;
|
|
107
|
+
if (t === 'string') {
|
|
108
|
+
const s = unwrapped;
|
|
109
|
+
const byteLen = Buffer.byteLength(s, 'utf8');
|
|
110
|
+
return {
|
|
111
|
+
name,
|
|
112
|
+
type: 'string',
|
|
113
|
+
byteLength: byteLen,
|
|
114
|
+
value: includeReadValues ? (s.length > 256 ? `${s.slice(0, 256)}…` : s) : undefined,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
if (t === 'number' || t === 'boolean') {
|
|
118
|
+
return {
|
|
119
|
+
name,
|
|
120
|
+
type: t,
|
|
121
|
+
byteLength: String(unwrapped).length,
|
|
122
|
+
value: includeReadValues ? unwrapped : undefined,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return { name, type: t };
|
|
126
|
+
};
|
|
127
|
+
if (Array.isArray(parameters)) {
|
|
128
|
+
for (let i = 0; i < parameters.length; i++) {
|
|
129
|
+
const item = parameters[i];
|
|
130
|
+
if (item != null && typeof item === 'object' && 'name' in item) {
|
|
131
|
+
const named = item;
|
|
132
|
+
summaries.push(describeValue(String(named.name), named.value));
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
summaries.push(describeValue(`@p${i}`, item));
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
else if (typeof parameters === 'object') {
|
|
140
|
+
for (const [k, v] of Object.entries(parameters)) {
|
|
141
|
+
summaries.push(describeValue(k, v));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return summaries;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Formats parameter summaries into a compact `name:type(bytes)` string for safe error messages.
|
|
148
|
+
*/
|
|
149
|
+
export function FormatSqlParameterTypesForError(parameters) {
|
|
150
|
+
const summaries = SummarizeSqlParameters(parameters, false);
|
|
151
|
+
if (summaries.length === 0) {
|
|
152
|
+
return 'none';
|
|
153
|
+
}
|
|
154
|
+
return summaries
|
|
155
|
+
.map(s => `${s.name}:${s.type}${s.byteLength !== undefined ? `(${s.byteLength}B)` : ''}`)
|
|
156
|
+
.join(', ');
|
|
157
|
+
}
|
|
72
158
|
export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
73
159
|
constructor() {
|
|
74
|
-
// Composition engine is now owned by RenderPipeline
|
|
75
160
|
super(...arguments);
|
|
76
161
|
/**
|
|
77
162
|
* Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
|
|
@@ -144,6 +229,92 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
144
229
|
*/
|
|
145
230
|
this._openBatchLevels = 0;
|
|
146
231
|
}
|
|
232
|
+
static { this._sqlObserversGlobalKey = '___MJ_SQL_OBSERVERS___'; }
|
|
233
|
+
static { this._fallbackSqlObservers = new Set(); }
|
|
234
|
+
static get _sqlObservers() {
|
|
235
|
+
const g = MJGlobal.Instance.GetGlobalObjectStore();
|
|
236
|
+
if (!g) {
|
|
237
|
+
return GenericDatabaseProvider._fallbackSqlObservers;
|
|
238
|
+
}
|
|
239
|
+
let set = g[GenericDatabaseProvider._sqlObserversGlobalKey];
|
|
240
|
+
if (!set) {
|
|
241
|
+
set = new Set();
|
|
242
|
+
g[GenericDatabaseProvider._sqlObserversGlobalKey] = set;
|
|
243
|
+
}
|
|
244
|
+
return set;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Registers a global SQL observer that receives timing and metadata for all SQL executions
|
|
248
|
+
* across provider instances (including per-request providers and pool shims).
|
|
249
|
+
* Returns an unsubscribe function.
|
|
250
|
+
*/
|
|
251
|
+
static RegisterSqlObserver(observer) {
|
|
252
|
+
const normalized = typeof observer === 'function' ? { onSqlExecuted: observer } : observer;
|
|
253
|
+
GenericDatabaseProvider._sqlObservers.add(normalized);
|
|
254
|
+
return () => {
|
|
255
|
+
GenericDatabaseProvider._sqlObservers.delete(normalized);
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Returns the live connection pool counts, or `null` when this provider has no pool to measure.
|
|
260
|
+
* Providers that own a pool override this.
|
|
261
|
+
*/
|
|
262
|
+
GetPoolStats() {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Instance convenience alias for {@link GenericDatabaseProvider.RegisterSqlObserver}.
|
|
267
|
+
*/
|
|
268
|
+
RegisterSqlObserver(observer) {
|
|
269
|
+
return GenericDatabaseProvider.RegisterSqlObserver(observer);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Returns true when at least one SQL observer is registered and capture is not suppressed.
|
|
273
|
+
*/
|
|
274
|
+
static HasSqlObservers() {
|
|
275
|
+
return GenericDatabaseProvider._sqlObservers.size > 0 && !IsDiagnosticCaptureSuppressed();
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Dispatches a SQL execution observation to all registered observers unless `ignoreLogging`
|
|
279
|
+
* or `WithoutDiagnosticCapture` is active. Automatically enriches with ambient `DiagnosticContext`.
|
|
280
|
+
*/
|
|
281
|
+
static NotifySqlObservers(observation) {
|
|
282
|
+
if (observation.ignoreLogging ||
|
|
283
|
+
GenericDatabaseProvider._sqlObservers.size === 0 ||
|
|
284
|
+
IsDiagnosticCaptureSuppressed()) {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const ctx = observation.diagnosticContext ?? GetDiagnosticContext();
|
|
288
|
+
const parameterTypes = observation.parameterTypes ??
|
|
289
|
+
(observation.parameterSummaries
|
|
290
|
+
? observation.parameterSummaries.map((s) => ({
|
|
291
|
+
name: s.name,
|
|
292
|
+
sqlType: s.type,
|
|
293
|
+
byteLength: s.byteLength ?? 0,
|
|
294
|
+
}))
|
|
295
|
+
: []);
|
|
296
|
+
const enriched = {
|
|
297
|
+
...observation,
|
|
298
|
+
diagnosticContext: ctx,
|
|
299
|
+
errorMessage: observation.errorMessage ?? observation.error?.message,
|
|
300
|
+
parameterTypes,
|
|
301
|
+
...(ctx
|
|
302
|
+
? {
|
|
303
|
+
sessionId: observation.sessionId ?? ctx.sessionId ?? ctx.SessionID,
|
|
304
|
+
traceId: observation.traceId ?? ctx.traceId ?? ctx.TraceID,
|
|
305
|
+
spanId: observation.spanId ?? ctx.spanId ?? ctx.SpanID,
|
|
306
|
+
}
|
|
307
|
+
: {}),
|
|
308
|
+
};
|
|
309
|
+
for (const observer of GenericDatabaseProvider._sqlObservers) {
|
|
310
|
+
try {
|
|
311
|
+
observer.onSqlExecuted(enriched);
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
// Observer errors must never affect SQL execution
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
147
318
|
/**
|
|
148
319
|
* Returns the active local storage provider, lazily creating an
|
|
149
320
|
* {@link InMemoryLocalStorageProvider} if none has been set.
|
|
@@ -205,6 +376,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
205
376
|
set ServerCacheVerificationTTL(value) {
|
|
206
377
|
this.ServerCacheVerificationTTLMs = Math.max(0, value);
|
|
207
378
|
}
|
|
379
|
+
invalidateInflightViewsForEntity(lowerEntityName) {
|
|
380
|
+
super.invalidateInflightViewsForEntity(lowerEntityName);
|
|
381
|
+
this._lastDatasetStatusByName.clear();
|
|
382
|
+
}
|
|
383
|
+
async ClearDatasetCache(datasetName, itemFilters) {
|
|
384
|
+
const statusKey = this.buildDatasetStatusCacheKey(datasetName, itemFilters);
|
|
385
|
+
this._lastDatasetStatusByName.delete(statusKey);
|
|
386
|
+
await super.ClearDatasetCache(datasetName, itemFilters);
|
|
387
|
+
}
|
|
208
388
|
/**************************************************************************/
|
|
209
389
|
// SQL Logging — Session Management & Statement Logging
|
|
210
390
|
/**************************************************************************/
|
|
@@ -437,7 +617,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
437
617
|
* `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
|
|
438
618
|
* save succeeds is not a durability improvement, it is a different feature.
|
|
439
619
|
*/
|
|
440
|
-
async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs) {
|
|
620
|
+
async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs, runModeFilter) {
|
|
441
621
|
const engine = EntityActionEngineServer.Instance;
|
|
442
622
|
if (engine.Loaded && engine.GetActionsByEntityName(entity.EntityInfo.Name, 'Active').length === 0) {
|
|
443
623
|
return [];
|
|
@@ -470,6 +650,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
470
650
|
const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
|
|
471
651
|
const results = [];
|
|
472
652
|
for (const a of activeActions) {
|
|
653
|
+
if (runModeFilter === 'DurableOnly' && a.RunMode !== 'Durable') {
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
if (runModeFilter === 'NonDurableOnly' && a.RunMode === 'Durable') {
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
473
659
|
if (guarded && originatingEntityActionIDs?.some((id) => UUIDsEqual(id, a.ID))) {
|
|
474
660
|
// The caller declared this save IS this action's write-back. Used by work that
|
|
475
661
|
// detached from the async context the guard tracks — see
|
|
@@ -610,11 +796,38 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
610
796
|
}
|
|
611
797
|
}
|
|
612
798
|
}
|
|
613
|
-
|
|
799
|
+
async ShouldEnlistSaveInTransaction(entity, user, options, isNewRecord) {
|
|
800
|
+
if (options.SkipEntityActions === true || options.ReplayOnly === true) {
|
|
801
|
+
return false;
|
|
802
|
+
}
|
|
803
|
+
if (DurableEntityActionRegistry.Instance.Submitter === null) {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
const engine = EntityActionEngineServer.Instance;
|
|
807
|
+
if (!engine.Loaded) {
|
|
808
|
+
await engine.Config(false, user);
|
|
809
|
+
}
|
|
810
|
+
const invocationType = isNewRecord ? 'AfterCreate' : 'AfterUpdate';
|
|
811
|
+
const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
|
|
812
|
+
const originatingSet = options.OriginatingEntityActionIDs && options.OriginatingEntityActionIDs.length > 0
|
|
813
|
+
? new UUIDSet(options.OriginatingEntityActionIDs)
|
|
814
|
+
: null;
|
|
815
|
+
return activeActions.some((a) => a.RunMode === 'Durable' && !originatingSet?.Has(a.ID));
|
|
816
|
+
}
|
|
817
|
+
async OnDurableAfterSaveExecute(entity, user, options, context) {
|
|
818
|
+
if (options.SkipEntityActions === true) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
context.State['durableActionsEnlistedInTx'] = true;
|
|
822
|
+
await this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, 'DurableOnly');
|
|
823
|
+
}
|
|
824
|
+
OnAfterSaveExecute(entity, user, options, context) {
|
|
614
825
|
if (options.SkipEntityAIActions !== true)
|
|
615
826
|
this.HandleEntityAIActions(entity, 'save', false, user); // NO AWAIT INTENTIONALLY
|
|
616
|
-
if (options.SkipEntityActions !== true)
|
|
617
|
-
|
|
827
|
+
if (options.SkipEntityActions !== true) {
|
|
828
|
+
const filter = context.State['durableActionsEnlistedInTx'] === true ? 'NonDurableOnly' : undefined;
|
|
829
|
+
this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, filter); // NO AWAIT INTENTIONALLY
|
|
830
|
+
}
|
|
618
831
|
}
|
|
619
832
|
async OnSaveCompleted(entity, saveSQLResult, user, options, context) {
|
|
620
833
|
const superPatches = await super.OnSaveCompleted(entity, saveSQLResult, user, options, context);
|
|
@@ -708,6 +921,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
708
921
|
/**************************************************************************/
|
|
709
922
|
// PostProcessRows — Datetime Adjustment + Encryption Decryption
|
|
710
923
|
/**************************************************************************/
|
|
924
|
+
/**
|
|
925
|
+
* Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
|
|
926
|
+
* preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
|
|
927
|
+
* Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
|
|
928
|
+
*/
|
|
929
|
+
static { this._preDecryptionRowsByResult = new WeakMap(); }
|
|
711
930
|
/**
|
|
712
931
|
* Post-processes rows: first applies platform-specific datetime adjustments
|
|
713
932
|
* via the virtual `AdjustDatetimeFields` hook, then handles field-level
|
|
@@ -716,7 +935,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
716
935
|
* Subclasses should NOT override this method. Instead, override
|
|
717
936
|
* `AdjustDatetimeFields` for platform-specific datetime corrections.
|
|
718
937
|
*/
|
|
719
|
-
async PostProcessRows(rows, entityInfo, user) {
|
|
938
|
+
async PostProcessRows(rows, entityInfo, user, options) {
|
|
720
939
|
if (!rows || rows.length === 0)
|
|
721
940
|
return rows;
|
|
722
941
|
// Step 0: binary columns → base64. Drivers return varbinary/bytea as byte arrays (Node
|
|
@@ -738,11 +957,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
738
957
|
const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
|
|
739
958
|
if (encryptedFields.length === 0)
|
|
740
959
|
return processedRows;
|
|
960
|
+
// Preserve ciphertext-bearing normalized rows for cache storage BEFORE decrypting any fields.
|
|
961
|
+
const ciphertextRowsForCache = processedRows.map(r => ({ ...r }));
|
|
962
|
+
const decryptedRows = await this.decryptRowsForConsumer(processedRows, entityInfo, encryptedFields, user, Boolean(options?.preserveRestrictedApiCiphertext));
|
|
963
|
+
GenericDatabaseProvider._preDecryptionRowsByResult.set(decryptedRows, ciphertextRowsForCache);
|
|
964
|
+
return decryptedRows;
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
|
|
968
|
+
* When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
|
|
969
|
+
* remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
|
|
970
|
+
* needlessly decrypt values destined for sentinel redaction.
|
|
971
|
+
*/
|
|
972
|
+
async decryptRowsForConsumer(rows, entityInfo, encryptedFields, user, preserveRestrictedApiCiphertext) {
|
|
973
|
+
if (!rows || rows.length === 0 || encryptedFields.length === 0) {
|
|
974
|
+
return rows;
|
|
975
|
+
}
|
|
976
|
+
const fieldsToDecrypt = preserveRestrictedApiCiphertext
|
|
977
|
+
? encryptedFields.filter(f => f.AllowDecryptInAPI)
|
|
978
|
+
: encryptedFields;
|
|
979
|
+
if (fieldsToDecrypt.length === 0) {
|
|
980
|
+
return rows.map(r => ({ ...r }));
|
|
981
|
+
}
|
|
741
982
|
const encryptionEngine = EncryptionEngine.Instance;
|
|
742
983
|
await encryptionEngine.Config(false, user);
|
|
743
|
-
return Promise.all(
|
|
984
|
+
return Promise.all(rows.map(async (row) => {
|
|
744
985
|
const processedRow = { ...row };
|
|
745
|
-
for (const field of
|
|
986
|
+
for (const field of fieldsToDecrypt) {
|
|
746
987
|
const fieldValue = processedRow[field.Name];
|
|
747
988
|
if (fieldValue === null || fieldValue === undefined || fieldValue === '')
|
|
748
989
|
continue;
|
|
@@ -768,6 +1009,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
768
1009
|
return processedRow;
|
|
769
1010
|
}));
|
|
770
1011
|
}
|
|
1012
|
+
PrepareRowsForCacheStorage(rows, entityInfo) {
|
|
1013
|
+
if (!rows || rows.length === 0)
|
|
1014
|
+
return rows;
|
|
1015
|
+
const preDecrypted = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
|
|
1016
|
+
if (preDecrypted) {
|
|
1017
|
+
return preDecrypted;
|
|
1018
|
+
}
|
|
1019
|
+
if (entityInfo && GenericDatabaseProvider.getEncryptedFields(entityInfo).length > 0) {
|
|
1020
|
+
// Rows passed directly without PostProcessRows: returned as-is (LocalCacheManager's
|
|
1021
|
+
// server write gate rejects any row carrying plaintext on an encrypted column).
|
|
1022
|
+
return rows;
|
|
1023
|
+
}
|
|
1024
|
+
return rows;
|
|
1025
|
+
}
|
|
1026
|
+
async MaterializeCachedRowsForCaller(rows, entityInfo, contextUser, preserveRestrictedApiCiphertext) {
|
|
1027
|
+
if (!rows || rows.length === 0 || !entityInfo) {
|
|
1028
|
+
return rows;
|
|
1029
|
+
}
|
|
1030
|
+
const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
|
|
1031
|
+
if (encryptedFields.length === 0) {
|
|
1032
|
+
return rows;
|
|
1033
|
+
}
|
|
1034
|
+
return this.decryptRowsForConsumer(rows, entityInfo, encryptedFields, contextUser ?? this.CurrentUser, Boolean(preserveRestrictedApiCiphertext));
|
|
1035
|
+
}
|
|
771
1036
|
static { this._encryptedFieldsCache = new WeakMap(); }
|
|
772
1037
|
static getEncryptedFields(entityInfo) {
|
|
773
1038
|
let entry = GenericDatabaseProvider._encryptedFieldsCache.get(entityInfo);
|
|
@@ -1543,6 +1808,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1543
1808
|
Fields: ['Status', 'ViewName'],
|
|
1544
1809
|
ResultType: 'simple',
|
|
1545
1810
|
MaxRows: 1,
|
|
1811
|
+
SkipTotalRowCount: true,
|
|
1546
1812
|
BypassCache: true,
|
|
1547
1813
|
}, contextUser);
|
|
1548
1814
|
// A FAILED lookup must not masquerade as "no materialization exists" — see MaterializationLookupFailed
|
|
@@ -2057,7 +2323,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2057
2323
|
// Generic-erasure boundary: PostProcessRows operates on Record<string,unknown>[]
|
|
2058
2324
|
// but Results is typed T[]; the double-cast bridges that erasure (not a lazy `any`).
|
|
2059
2325
|
const rows = externalResult.Results;
|
|
2060
|
-
const processed = (await this.PostProcessRows(rows, entityInfo, user
|
|
2326
|
+
const processed = (await this.PostProcessRows(rows, entityInfo, user, {
|
|
2327
|
+
preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
|
|
2328
|
+
}));
|
|
2061
2329
|
externalResult.Results = this.projectExternalRowsForCaller(processed, entityInfo, externalParams, user);
|
|
2062
2330
|
}
|
|
2063
2331
|
return externalResult;
|
|
@@ -2157,13 +2425,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2157
2425
|
if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
|
|
2158
2426
|
throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
|
|
2159
2427
|
}
|
|
2428
|
+
// The filter builder saves WhereClauses in SQL Server syntax (`[Field] LIKE ...`), so the
|
|
2429
|
+
// rendered clause gets the same platform rewrite as ExtraFilter. Without it PostgreSQL
|
|
2430
|
+
// rejects every filtered saved view run here: `syntax error at or near "["`.
|
|
2431
|
+
const viewWhereSQL = this.TransformExternalSQLClause(renderedWhere, entityInfo);
|
|
2160
2432
|
// CustomWhereClause views too: an unbalanced clause would take row-level security
|
|
2161
2433
|
// out of force for everyone who runs the view. Only their admin-written text may
|
|
2162
|
-
// carry comments.
|
|
2163
|
-
this.AssertClauseBalanced(
|
|
2434
|
+
// carry comments. Checked after the rewrite, since that is the text that runs.
|
|
2435
|
+
this.AssertClauseBalanced(viewWhereSQL, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
|
|
2164
2436
|
AllowComments: isCustomWhereClause,
|
|
2165
2437
|
});
|
|
2166
|
-
whereSQL = `(${
|
|
2438
|
+
whereSQL = `(${viewWhereSQL})`;
|
|
2167
2439
|
bHasWhere = true;
|
|
2168
2440
|
}
|
|
2169
2441
|
// 2. ExtraFilter
|
|
@@ -2407,7 +2679,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2407
2679
|
// ── Process data rows ──
|
|
2408
2680
|
let retData = resultMap['data'] || [];
|
|
2409
2681
|
if (retData.length > 0 && params.ResultType !== 'count_only') {
|
|
2410
|
-
retData = await this.PostProcessRows(retData, entityInfo, user
|
|
2682
|
+
retData = await this.PostProcessRows(retData, entityInfo, user, {
|
|
2683
|
+
preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
|
|
2684
|
+
});
|
|
2411
2685
|
}
|
|
2412
2686
|
// ── Process count ──
|
|
2413
2687
|
let rowCount = null;
|
|
@@ -2416,34 +2690,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2416
2690
|
if (countResult && countResult.length > 0)
|
|
2417
2691
|
rowCount = countResult[0].TotalRowCount;
|
|
2418
2692
|
}
|
|
2419
|
-
else if (countSQL && maxRowsUsed &&
|
|
2693
|
+
else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed && !skipCount) {
|
|
2420
2694
|
// A row-limited read that came back FULL may have been truncated, so the total is
|
|
2421
2695
|
// 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
2696
|
//
|
|
2437
|
-
//
|
|
2438
|
-
//
|
|
2439
|
-
//
|
|
2440
|
-
//
|
|
2441
|
-
//
|
|
2442
|
-
//
|
|
2443
|
-
//
|
|
2444
|
-
//
|
|
2445
|
-
// on a full multi-row page (RunViewParams.SkipTotalRowCount); the pagination count
|
|
2446
|
-
// above honours the same flag.
|
|
2697
|
+
// That round trip is SEQUENTIAL: it runs after the data query has already resolved,
|
|
2698
|
+
// so it is a full extra trip on the critical path, not a parallel one. For a
|
|
2699
|
+
// single-row probe it fires on every hit. Measured on a live tenant over a
|
|
2700
|
+
// 120-second census: 1,000 record-map lookups fired 721 of these counts and 800 row
|
|
2701
|
+
// lookups fired 600 — 1,321 extra round trips totalling 9,760 ms, 11.4% of ALL SQL
|
|
2702
|
+
// time in the window, with nothing reading a single result. Callers that only read
|
|
2703
|
+
// `Results` opt out explicitly with RunViewParams.SkipTotalRowCount; the provider
|
|
2704
|
+
// never infers that from the value of MaxRows.
|
|
2447
2705
|
const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
|
|
2448
2706
|
if (countResult && countResult.length > 0)
|
|
2449
2707
|
rowCount = countResult[0].TotalRowCount;
|
|
@@ -2486,7 +2744,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2486
2744
|
}
|
|
2487
2745
|
return {
|
|
2488
2746
|
RowCount: params.ResultType === 'count_only' ? rowCount : retData.length,
|
|
2489
|
-
TotalRowCount: rowCount ?? retData.length,
|
|
2747
|
+
TotalRowCount: skipCount ? undefined : rowCount ?? retData.length,
|
|
2490
2748
|
Results: retData,
|
|
2491
2749
|
UserViewRunID: userViewRunID,
|
|
2492
2750
|
ExecutionTime: stopTime.getTime() - startTime.getTime(),
|
|
@@ -3503,7 +3761,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3503
3761
|
fingerprint: resolved.fingerprint,
|
|
3504
3762
|
});
|
|
3505
3763
|
}
|
|
3764
|
+
else if (entityInfo.TrackRecordChanges) {
|
|
3765
|
+
// The client's copy is older and the entity tracks record changes: Phase 2 reads
|
|
3766
|
+
// the DB status and sends only the changed rows, not the full cached copy.
|
|
3767
|
+
serverCacheMissItems.push({ index, item, entityInfo });
|
|
3768
|
+
}
|
|
3506
3769
|
else {
|
|
3770
|
+
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${resolved.serverCached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
3507
3771
|
serverCacheStaleItems.push({ index, item, entityInfo, serverCached: resolved.serverCached });
|
|
3508
3772
|
}
|
|
3509
3773
|
}
|
|
@@ -3514,6 +3778,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3514
3778
|
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
3515
3779
|
const differentialItems = [];
|
|
3516
3780
|
const staleItemsNoTracking = [];
|
|
3781
|
+
/** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
|
|
3782
|
+
const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus) => {
|
|
3783
|
+
LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
|
|
3784
|
+
differentialItems.push({
|
|
3785
|
+
index, params: item.params, entityInfo, whereSQL,
|
|
3786
|
+
clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
|
|
3787
|
+
clientRowCount: item.cacheStatus.rowCount,
|
|
3788
|
+
serverStatus,
|
|
3789
|
+
});
|
|
3790
|
+
};
|
|
3517
3791
|
if (serverCacheMissItems.length > 0) {
|
|
3518
3792
|
// Build WHERE clauses and run batched DB status check only for cache misses / TTL-expired slots
|
|
3519
3793
|
const itemsForDBCheck = [];
|
|
@@ -3548,6 +3822,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3548
3822
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
3549
3823
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3550
3824
|
}
|
|
3825
|
+
else if (entityInfo.TrackRecordChanges) {
|
|
3826
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
3827
|
+
}
|
|
3551
3828
|
else {
|
|
3552
3829
|
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
|
|
3553
3830
|
serverCacheStaleItems.push({ index, item, entityInfo, serverCached });
|
|
@@ -3573,13 +3850,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3573
3850
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3574
3851
|
}
|
|
3575
3852
|
else if (entityInfo.TrackRecordChanges) {
|
|
3576
|
-
|
|
3577
|
-
differentialItems.push({
|
|
3578
|
-
index, params: item.params, entityInfo, whereSQL,
|
|
3579
|
-
clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
|
|
3580
|
-
clientRowCount: item.cacheStatus.rowCount,
|
|
3581
|
-
serverStatus,
|
|
3582
|
-
});
|
|
3853
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
3583
3854
|
}
|
|
3584
3855
|
else {
|
|
3585
3856
|
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
|
|
@@ -3610,7 +3881,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3610
3881
|
if (cached) {
|
|
3611
3882
|
const entityLabel = entry.item.params.EntityName || 'unknown';
|
|
3612
3883
|
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — client has no cache, serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
3613
|
-
noCacheStatusServedFromCache.push({ index: entry.index, serverCached: cached });
|
|
3884
|
+
noCacheStatusServedFromCache.push({ index: entry.index, params: entry.item.params, serverCached: cached });
|
|
3614
3885
|
continue;
|
|
3615
3886
|
}
|
|
3616
3887
|
}
|
|
@@ -3622,11 +3893,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3622
3893
|
// permission class may read.
|
|
3623
3894
|
const queryPromises = [
|
|
3624
3895
|
// Items without cache check — served from server cache
|
|
3625
|
-
...noCacheStatusServedFromCache.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
3896
|
+
...noCacheStatusServedFromCache.map(({ index, params: viewParams, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, viewParams, user)),
|
|
3626
3897
|
// Items without cache check — server cache miss, must hit DB
|
|
3627
3898
|
...noCacheStatusNeedsDB.map(({ index, item }) => this.runFullQueryAndCacheResult(item.params, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
3628
|
-
// Server cache
|
|
3629
|
-
...serverCacheStaleItems.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
|
|
3899
|
+
// Server cache newer than the client, no change tracking — serve from server's cached data (zero DB)
|
|
3900
|
+
...serverCacheStaleItems.map(({ index, item, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, item.params, user)),
|
|
3630
3901
|
// DB-validated stale items (no change tracking)
|
|
3631
3902
|
...staleItemsNoTracking.map(({ index, params: viewParams }) => this.runFullQueryAndCacheResult(viewParams, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
3632
3903
|
// DB-validated differential items
|
|
@@ -3808,7 +4079,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3808
4079
|
async runFullQueryAndReturn(params, viewIndex, contextUser) {
|
|
3809
4080
|
let result;
|
|
3810
4081
|
try {
|
|
3811
|
-
result = await this.InternalRunView(params, contextUser);
|
|
4082
|
+
result = await this.InternalRunView({ ...params, PreserveRestrictedApiCiphertext: true }, contextUser);
|
|
3812
4083
|
}
|
|
3813
4084
|
catch (e) {
|
|
3814
4085
|
// A field-security refusal fails this item only, as the up-front gate does on this path.
|
|
@@ -3847,13 +4118,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3847
4118
|
if (ttlMs !== 0) {
|
|
3848
4119
|
const fingerprint = this.ComputeRunViewCacheFingerprint(params, contextUser);
|
|
3849
4120
|
const maxUpdatedAt = result.maxUpdatedAt || new Date().toISOString();
|
|
4121
|
+
const cacheEntity = this.resolveEntityForRunViewParams(params);
|
|
3850
4122
|
// Pass the aggregates (B38-family omission #4). This slot is ALSO written by
|
|
3851
4123
|
// InternalRunView's normal PostRunView path WITH aggregates — two writers,
|
|
3852
4124
|
// one slot, and this one dropped them. Whichever write landed last won, so a
|
|
3853
4125
|
// later server-cache hit served rows with or without aggregates depending on
|
|
3854
4126
|
// a write race. That is exactly the standalone-passes / aggregator-fails
|
|
3855
4127
|
// flake client-cache C13 exhibited.
|
|
3856
|
-
await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, result.results, maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
|
|
4128
|
+
await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, this.PrepareRowsForCacheStorage(result.results, cacheEntity), maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
|
|
3857
4129
|
}
|
|
3858
4130
|
}
|
|
3859
4131
|
// Project the response down to the caller's requested shape AFTER the
|
|
@@ -3967,7 +4239,23 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3967
4239
|
* them: the entity resolved here is named explicitly.
|
|
3968
4240
|
*/
|
|
3969
4241
|
projectExternalRowsForCaller(rows, entityInfo, params, user) {
|
|
3970
|
-
|
|
4242
|
+
const entityParams = { ...params, EntityName: entityInfo.Name };
|
|
4243
|
+
const projected = this.ApplyFieldSecurityProjection(rows, entityParams, user);
|
|
4244
|
+
this.carryCiphertextRowsForCache(rows, projected, entityParams, user);
|
|
4245
|
+
return projected;
|
|
4246
|
+
}
|
|
4247
|
+
/**
|
|
4248
|
+
* Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
|
|
4249
|
+
* narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
|
|
4250
|
+
* caller's width instead of finding no copy and falling back to the decrypted rows.
|
|
4251
|
+
*/
|
|
4252
|
+
carryCiphertextRowsForCache(rows, projected, params, user) {
|
|
4253
|
+
if (projected === rows)
|
|
4254
|
+
return;
|
|
4255
|
+
const ciphertextRows = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
|
|
4256
|
+
if (ciphertextRows) {
|
|
4257
|
+
GenericDatabaseProvider._preDecryptionRowsByResult.set(projected, this.ApplyFieldSecurityProjection(ciphertextRows, params, user));
|
|
4258
|
+
}
|
|
3971
4259
|
}
|
|
3972
4260
|
/**
|
|
3973
4261
|
* Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
|
|
@@ -4019,7 +4307,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4019
4307
|
}
|
|
4020
4308
|
/**
|
|
4021
4309
|
* Checks the server's LocalCacheManager for cached data matching the client's request.
|
|
4022
|
-
* Returns the resolution if found ('current', 'stale' server
|
|
4310
|
+
* Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
|
|
4023
4311
|
* 'needs_verification' when the server slot's freshness window has elapsed),
|
|
4024
4312
|
* or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
|
|
4025
4313
|
*/
|
|
@@ -4070,24 +4358,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4070
4358
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches server cache, no DB hit`, verboseOnly: true });
|
|
4071
4359
|
return { status: 'current', result: { viewIndex: index, status: 'current' } };
|
|
4072
4360
|
}
|
|
4073
|
-
// Server has newer data than client
|
|
4074
|
-
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
|
|
4361
|
+
// Server has newer data than the client; the caller decides between the cached copy and a differential
|
|
4075
4362
|
return { status: 'stale', serverCached: cached };
|
|
4076
4363
|
}
|
|
4077
4364
|
/**
|
|
4078
4365
|
* Packages server-cached data as a RunViewWithCacheCheckResult for return to the client.
|
|
4079
4366
|
*/
|
|
4080
|
-
async serveFromServerCache(viewIndex, serverCached, callerFields = null) {
|
|
4081
|
-
// The server cache stores every field the slot's permission class may read
|
|
4367
|
+
async serveFromServerCache(viewIndex, serverCached, callerFields = null, viewParams, contextUser) {
|
|
4368
|
+
// The server cache stores every field the slot's permission class may read (with encrypted
|
|
4369
|
+
// fields stored as ciphertext at rest). Materialize allowed API decryptions first, then
|
|
4082
4370
|
// project down to the caller's requested fields (∪ PK) before returning, exactly like the
|
|
4083
|
-
// ProviderBase hit path.
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
// `serverCached.results` are the cache's shared, deep-frozen rows — the runtime freeze
|
|
4087
|
-
// is what actually protects the cache. See ProviderBase's hit path.
|
|
4371
|
+
// ProviderBase hit path.
|
|
4372
|
+
const cacheEntity = viewParams ? this.resolveEntityForRunViewParams(viewParams) : undefined;
|
|
4373
|
+
const materialized = await this.MaterializeCachedRowsForCaller(serverCached.results, cacheEntity, contextUser, true);
|
|
4088
4374
|
const results = callerFields
|
|
4089
|
-
? ProjectRowsToFields(
|
|
4090
|
-
:
|
|
4375
|
+
? ProjectRowsToFields(materialized, callerFields)
|
|
4376
|
+
: materialized;
|
|
4091
4377
|
return {
|
|
4092
4378
|
viewIndex,
|
|
4093
4379
|
status: 'stale',
|
|
@@ -4104,19 +4390,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4104
4390
|
/**
|
|
4105
4391
|
* Runs a differential query and returns only changes since the client's cached state.
|
|
4106
4392
|
* Includes updated/created rows and deleted record IDs.
|
|
4107
|
-
* Falls back to full query if hidden deletes are detected.
|
|
4393
|
+
* Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
|
|
4108
4394
|
*/
|
|
4109
4395
|
async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null) {
|
|
4110
4396
|
try {
|
|
4111
|
-
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, clientMaxUpdatedAt, whereSQL, contextUser);
|
|
4112
|
-
const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, clientMaxUpdatedAt, contextUser);
|
|
4113
|
-
// Validation: detect hidden deletes not tracked in RecordChanges
|
|
4114
4397
|
const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
|
|
4115
4398
|
if (!clientMaxUpdatedDate) {
|
|
4116
4399
|
// Unparseable client timestamp — can't trust the differential math; fall
|
|
4117
4400
|
// back to a full refresh (cached wide + projected, like every other leg).
|
|
4118
4401
|
return this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
|
|
4119
4402
|
}
|
|
4403
|
+
const since = clientMaxUpdatedDate.toISOString();
|
|
4404
|
+
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser);
|
|
4405
|
+
const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, since, contextUser);
|
|
4406
|
+
// Validation: detect hidden deletes not tracked in RecordChanges
|
|
4120
4407
|
const newInserts = updatedRows.filter(row => {
|
|
4121
4408
|
const createdAt = row['__mj_CreatedAt'];
|
|
4122
4409
|
if (!createdAt)
|
|
@@ -4182,13 +4469,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4182
4469
|
return { viewIndex, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) };
|
|
4183
4470
|
}
|
|
4184
4471
|
}
|
|
4472
|
+
/**
|
|
4473
|
+
* Formats a client timestamp as ISO 8601 for a SQL literal.
|
|
4474
|
+
* Throws when the value is not a date.
|
|
4475
|
+
*/
|
|
4476
|
+
toSQLTimestamp(raw) {
|
|
4477
|
+
const date = this.parseClientTimestamp(raw);
|
|
4478
|
+
if (!date)
|
|
4479
|
+
throw new Error('Client timestamp is not a valid date');
|
|
4480
|
+
return date.toISOString();
|
|
4481
|
+
}
|
|
4185
4482
|
/**
|
|
4186
4483
|
* Gets IDs of records deleted since a given timestamp.
|
|
4187
|
-
* Uses dialect-neutral quoting
|
|
4484
|
+
* Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
|
|
4485
|
+
* Subclasses can override for parameterized queries.
|
|
4188
4486
|
*/
|
|
4189
4487
|
async getDeletedRecordIDsSince(entityID, sinceTimestamp, contextUser) {
|
|
4190
4488
|
try {
|
|
4191
|
-
const
|
|
4489
|
+
const since = this.toSQLTimestamp(sinceTimestamp);
|
|
4490
|
+
const sql = `SELECT DISTINCT ${this.QuoteIdentifier('RecordID')} FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwRecordChanges')} WHERE ${this.QuoteIdentifier('EntityID')} = '${entityID}' AND ${this.QuoteIdentifier('Type')} = 'Delete' AND (${this.QuoteIdentifier('ChangedAt')} > '${since}')`;
|
|
4192
4491
|
const results = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
4193
4492
|
return results.map(r => String(r['RecordID']));
|
|
4194
4493
|
}
|
|
@@ -4199,11 +4498,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4199
4498
|
}
|
|
4200
4499
|
/**
|
|
4201
4500
|
* Gets rows updated/created since a given timestamp.
|
|
4202
|
-
* Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy
|
|
4501
|
+
* Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
|
|
4502
|
+
* timestamp in ISO 8601 form as its own predicate group.
|
|
4203
4503
|
*/
|
|
4204
4504
|
async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser) {
|
|
4205
4505
|
try {
|
|
4206
|
-
const timestampFilter =
|
|
4506
|
+
const timestampFilter = `(${this.QuoteIdentifier('__mj_UpdatedAt')} > '${this.toSQLTimestamp(sinceTimestamp)}')`;
|
|
4207
4507
|
const combinedWhere = whereSQL
|
|
4208
4508
|
? `(${whereSQL}) AND ${timestampFilter}`
|
|
4209
4509
|
: timestampFilter;
|
|
@@ -4219,7 +4519,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4219
4519
|
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
4220
4520
|
sql += ` ORDER BY ${orderBy}`;
|
|
4221
4521
|
}
|
|
4222
|
-
|
|
4522
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
4523
|
+
const processed = await this.PostProcessRows(rawRows, entityInfo, (contextUser ?? this.CurrentUser), { preserveRestrictedApiCiphertext: true });
|
|
4524
|
+
return processed;
|
|
4223
4525
|
}
|
|
4224
4526
|
catch (e) {
|
|
4225
4527
|
LogError(e);
|
|
@@ -4251,16 +4553,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4251
4553
|
const item = params[i];
|
|
4252
4554
|
const query = this.resolveQuery(item.params);
|
|
4253
4555
|
if (!query) {
|
|
4254
|
-
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage:
|
|
4556
|
+
errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params)) });
|
|
4255
4557
|
continue;
|
|
4256
4558
|
}
|
|
4257
4559
|
const definition = this.QueryDefinitionSignatureFor(query);
|
|
4258
4560
|
const runCheck = this.authorizeCacheCheckedQuery(query, item, definition, user);
|
|
4259
4561
|
if (!runCheck.canRun) {
|
|
4260
|
-
const
|
|
4261
|
-
? ` Denied entities: ${runCheck.deniedEntities.join(', ')}.`
|
|
4262
|
-
: '';
|
|
4263
|
-
const errorMessage = runCheck.renderError ?? `User does not have permission to run query: ${query.Name}.${deniedMsg}`;
|
|
4562
|
+
const errorMessage = runCheck.renderError ?? this.queryRunRefusalMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params));
|
|
4264
4563
|
errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage });
|
|
4265
4564
|
continue;
|
|
4266
4565
|
}
|
|
@@ -4338,7 +4637,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4338
4637
|
const mayAnswerWithoutRunning = !!item.cacheStatus
|
|
4339
4638
|
&& !this.clientSlotDefinitionDiffers(item.cacheStatus, definition)
|
|
4340
4639
|
&& !!query.CacheValidationSQL;
|
|
4341
|
-
|
|
4640
|
+
if (mayAnswerWithoutRunning) {
|
|
4641
|
+
return this.authorizeQueryRun(query, item.params.Parameters, user);
|
|
4642
|
+
}
|
|
4643
|
+
const result = query.UserCanRun(user);
|
|
4644
|
+
if (!result.canRun) {
|
|
4645
|
+
// RunQueriesWithCacheCheck short-circuits on !canRun before reaching
|
|
4646
|
+
// runFullQueryAndReturnForQuery, so this refusal would otherwise never log.
|
|
4647
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4648
|
+
}
|
|
4649
|
+
return result;
|
|
4342
4650
|
}
|
|
4343
4651
|
/**
|
|
4344
4652
|
* B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
|
|
@@ -4366,9 +4674,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4366
4674
|
if (!query) {
|
|
4367
4675
|
return { resolvable: false, authorized: false };
|
|
4368
4676
|
}
|
|
4677
|
+
// Pre-cache probe: a denial here falls through to execution, which logs at its own
|
|
4678
|
+
// gate, so this probe does not log (no duplicate refusal lines on cached runs).
|
|
4679
|
+
const run = user ? this.authorizeQueryRun(query, params.Parameters, user, false) : null;
|
|
4369
4680
|
return {
|
|
4370
4681
|
resolvable: true,
|
|
4371
|
-
authorized: !
|
|
4682
|
+
authorized: !run || run.canRun,
|
|
4683
|
+
// A run that drops denied columns returns rows shaped by the user's denials, so its
|
|
4684
|
+
// slot is the user's field-security segment's alone.
|
|
4685
|
+
fieldSecurityKey: user && run?.needsColumnFiltering ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : undefined,
|
|
4372
4686
|
categoryPath: query.CategoryPath,
|
|
4373
4687
|
queryName: query.Name,
|
|
4374
4688
|
contextTokens: this.queryContextTokens(query),
|
|
@@ -4452,14 +4766,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4452
4766
|
*
|
|
4453
4767
|
* @param query - The resolved MJQueryEntityExtended to validate
|
|
4454
4768
|
* @param contextUser - The user attempting to execute the query
|
|
4769
|
+
* @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
|
|
4770
|
+
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
4455
4771
|
* @throws Error if the user does not have permission to run the query
|
|
4456
4772
|
*/
|
|
4457
|
-
ValidateQueryForExecution(query, contextUser) {
|
|
4773
|
+
ValidateQueryForExecution(query, contextUser, requestedLabel = query.ID) {
|
|
4458
4774
|
const user = contextUser || this.CurrentUser;
|
|
4459
4775
|
if (user) {
|
|
4460
4776
|
const result = query.UserCanRun(user);
|
|
4461
4777
|
if (!result.canRun) {
|
|
4462
|
-
|
|
4778
|
+
// This gate, not the rendered-SQL one, is where a role-list denial lands: it
|
|
4779
|
+
// short-circuits before any SQL is rendered.
|
|
4780
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4781
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
4463
4782
|
}
|
|
4464
4783
|
}
|
|
4465
4784
|
if (query.Status !== 'Approved') {
|
|
@@ -4527,44 +4846,130 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4527
4846
|
* and field-level security on every column it references. A template that injects an
|
|
4528
4847
|
* identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
|
|
4529
4848
|
* 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
4849
|
*
|
|
4850
|
+
* A refusal reads exactly like the message for a query that does not exist
|
|
4851
|
+
* ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
|
|
4852
|
+
*
|
|
4853
|
+
* @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
|
|
4854
|
+
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
4855
|
+
* @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
|
|
4856
|
+
* `alias.*` that reaches only the output reads an entity the user is denied a field on.
|
|
4532
4857
|
* @throws Error when the user may not run this rendering of the query
|
|
4533
4858
|
*/
|
|
4534
|
-
ValidateRenderedQueryForExecution(query, renderedSQL, contextUser) {
|
|
4859
|
+
ValidateRenderedQueryForExecution(query, renderedSQL, contextUser, requestedLabel = query.ID) {
|
|
4535
4860
|
const user = contextUser || this.CurrentUser;
|
|
4536
4861
|
if (!user) {
|
|
4537
|
-
return;
|
|
4862
|
+
return { NeedsColumnFiltering: false };
|
|
4538
4863
|
}
|
|
4539
4864
|
const result = this.checkRenderedQuery(query, renderedSQL, user);
|
|
4540
4865
|
if (!result.canRun) {
|
|
4541
|
-
throw new Error(this.queryRunRefusalMessage(
|
|
4866
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
4867
|
+
}
|
|
4868
|
+
return { NeedsColumnFiltering: result.needsColumnFiltering === true };
|
|
4869
|
+
}
|
|
4870
|
+
/**
|
|
4871
|
+
* The message for a saved query that does not exist or that the caller may not run. The two
|
|
4872
|
+
* are worded identically, so a refusal does not confirm that the query, or anything it reads,
|
|
4873
|
+
* exists.
|
|
4874
|
+
*
|
|
4875
|
+
* It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
|
|
4876
|
+
* looked up from the resolved query: a refusal of a request by ID that named the query would
|
|
4877
|
+
* both differ from that request's not-found message and disclose the query's name.
|
|
4878
|
+
*
|
|
4879
|
+
* @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
|
|
4880
|
+
*/
|
|
4881
|
+
static QueryUnavailableMessage(label) {
|
|
4882
|
+
return `Query '${label}' does not exist or you do not have permission to run it.`;
|
|
4883
|
+
}
|
|
4884
|
+
/**
|
|
4885
|
+
* The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
|
|
4886
|
+
* name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
|
|
4887
|
+
*/
|
|
4888
|
+
static RequestedQueryLabel(params) {
|
|
4889
|
+
if (params.QueryName) {
|
|
4890
|
+
const path = (params.CategoryPath ?? '').split('/').map(s => s.trim()).filter(s => s.length > 0).join('/');
|
|
4891
|
+
return path ? `${path}/${params.QueryName}` : params.QueryName;
|
|
4542
4892
|
}
|
|
4893
|
+
return params.QueryID ?? '';
|
|
4543
4894
|
}
|
|
4544
|
-
/** The refusal for a
|
|
4545
|
-
queryRunRefusalMessage(
|
|
4546
|
-
|
|
4547
|
-
return `User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`;
|
|
4895
|
+
/** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
|
|
4896
|
+
queryRunRefusalMessage(requestedLabel) {
|
|
4897
|
+
return GenericDatabaseProvider.QueryUnavailableMessage(requestedLabel);
|
|
4548
4898
|
}
|
|
4549
|
-
/**
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
|
|
4553
|
-
|
|
4554
|
-
|
|
4899
|
+
/**
|
|
4900
|
+
* The OPERATOR's record of why a run was refused. The refusal returned to the caller is
|
|
4901
|
+
* {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
|
|
4902
|
+
* that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
|
|
4903
|
+
*
|
|
4904
|
+
* Without it a refusal is unattributable: the query's own role list, SQL the field-security
|
|
4905
|
+
* gate could not read, and a field-security violation all end in the same caller message.
|
|
4906
|
+
*
|
|
4907
|
+
* Previously only the field-security case logged anything, and only at `verboseOnly`, which
|
|
4908
|
+
* CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
|
|
4909
|
+
* bundles refusing together) could not be diagnosed from the logs at all. Called from every
|
|
4910
|
+
* refusal gate, so no path is silent.
|
|
4911
|
+
*
|
|
4912
|
+
* The loaded-role count is here because an empty or undefined `UserRoles` denies every
|
|
4913
|
+
* permission-bearing query at once — exactly the all-or-nothing signature those runs show.
|
|
4914
|
+
* Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
|
|
4915
|
+
* to ask and it costs one integer.
|
|
4916
|
+
*/
|
|
4917
|
+
logQueryRunRefusal(query, user, result) {
|
|
4918
|
+
const v = result.fieldSecurityViolation;
|
|
4919
|
+
const queryRoles = (query.QueryPermissions ?? []).map(p => p.Role).join(', ');
|
|
4920
|
+
const reason = v
|
|
4921
|
+
? `field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''})`
|
|
4922
|
+
: result.deniedEntities.length > 0
|
|
4923
|
+
? `unreadable entities (${result.deniedEntities.join(', ')})`
|
|
4924
|
+
: `the query's own role list (MJ: Query Permissions: [${queryRoles}])`;
|
|
4925
|
+
const userRoles = user.UserRoles
|
|
4926
|
+
? `${user.UserRoles.length} ([${user.UserRoles.map(r => r.Role).join(', ')}])`
|
|
4927
|
+
: 'undefined';
|
|
4928
|
+
LogStatus(`RunQuery: query '${query.Name}' (${query.ID}) refused for user '${user.Email}' by ${reason}. ` +
|
|
4929
|
+
`Roles loaded for this user: ${userRoles}.`);
|
|
4930
|
+
}
|
|
4931
|
+
/**
|
|
4932
|
+
* The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
|
|
4933
|
+
* refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
|
|
4934
|
+
* projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
|
|
4935
|
+
* its denied columns dropped instead of being refused.
|
|
4936
|
+
*/
|
|
4937
|
+
checkRenderedQuery(query, renderedSQL, user, logRefusal = true) {
|
|
4938
|
+
const stars = this.projectionStarOffsets(renderedSQL, user);
|
|
4939
|
+
const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey, stars ? { ProjectionStarOffsets: stars } : undefined);
|
|
4940
|
+
if (!result.canRun && logRefusal) {
|
|
4941
|
+
this.logQueryRunRefusal(query, user, result);
|
|
4555
4942
|
}
|
|
4556
4943
|
return result;
|
|
4557
4944
|
}
|
|
4945
|
+
/** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
|
|
4946
|
+
static { this.projectionStarMemo = new StatementMemo(500); }
|
|
4947
|
+
/**
|
|
4948
|
+
* The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
|
|
4949
|
+
* denied a field on some entity and only when the text holds a `*`; undefined otherwise.
|
|
4950
|
+
*/
|
|
4951
|
+
projectionStarOffsets(renderedSQL, user) {
|
|
4952
|
+
if (!renderedSQL.includes('*') || !FieldSecuritySQLGate.CatalogHasDenialsForUser(this.Entities, user)) {
|
|
4953
|
+
return undefined;
|
|
4954
|
+
}
|
|
4955
|
+
const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
|
|
4956
|
+
return GenericDatabaseProvider.projectionStarMemo.GetOrCompute(key, () => FindProjectionStars(renderedSQL, this.Dialect));
|
|
4957
|
+
}
|
|
4558
4958
|
/**
|
|
4559
4959
|
* The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
|
|
4560
4960
|
* and the run-time checks on the query rendered with `parameters`. A rendering that fails
|
|
4561
4961
|
* refuses, carrying the rendering's error.
|
|
4562
4962
|
*/
|
|
4563
|
-
authorizeQueryRun(query, parameters, user) {
|
|
4963
|
+
authorizeQueryRun(query, parameters, user, logRefusal = true) {
|
|
4564
4964
|
const base = query.UserCanRun(user);
|
|
4565
4965
|
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
4566
4966
|
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
4567
4967
|
// already confirmed the user holds one of its roles: nothing to render.
|
|
4968
|
+
if (!base.canRun && logRefusal) {
|
|
4969
|
+
// The batch/cache-checked path returns rather than throws, so this refusal would
|
|
4970
|
+
// otherwise never reach a log at all.
|
|
4971
|
+
this.logQueryRunRefusal(query, user, base);
|
|
4972
|
+
}
|
|
4568
4973
|
return base;
|
|
4569
4974
|
}
|
|
4570
4975
|
let renderedSQL;
|
|
@@ -4574,7 +4979,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4574
4979
|
catch (e) {
|
|
4575
4980
|
return { canRun: false, deniedEntities: [], renderError: e instanceof Error ? e.message : String(e) };
|
|
4576
4981
|
}
|
|
4577
|
-
return this.checkRenderedQuery(query, renderedSQL, user);
|
|
4982
|
+
return this.checkRenderedQuery(query, renderedSQL, user, logRefusal);
|
|
4578
4983
|
}
|
|
4579
4984
|
/** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
|
|
4580
4985
|
static roleListGrants(query) {
|
|
@@ -4698,102 +5103,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4698
5103
|
* {@link buildMaterializedReadQuery}).
|
|
4699
5104
|
*/
|
|
4700
5105
|
static { this.MATERIALIZED_SURROGATE_ORDER_COLUMN = '__mj_MaterializedRowID'; }
|
|
4701
|
-
/** Quotes a SQL identifier for the target engine (SQL Server `[x]`, PostgreSQL `"x"`), escaping the closer. */
|
|
4702
|
-
static quoteMaterializedIdentifier(name, isPostgres) {
|
|
4703
|
-
return isPostgres ? `"${name.replace(/"/g, '""')}"` : `[${name.replace(/]/g, ']]')}]`;
|
|
4704
|
-
}
|
|
4705
5106
|
/**
|
|
4706
5107
|
* PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
|
|
4707
5108
|
* output columns, the materialized view (schema + name), the persisted read-filter spec, the caller's
|
|
4708
|
-
* parameter values, and the
|
|
4709
|
-
* predicate as `column <op> <placeholder>` with the value **bound**
|
|
4710
|
-
*
|
|
5109
|
+
* parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
|
|
5110
|
+
* predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
|
|
5111
|
+
* value (SQL-injection-safe by construction).
|
|
5112
|
+
*
|
|
5113
|
+
* With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
|
|
5114
|
+
* a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
|
|
5115
|
+
* placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
|
|
5116
|
+
* varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
|
|
5117
|
+
* Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
|
|
5118
|
+
* ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
|
|
5119
|
+
* dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
|
|
4711
5120
|
*
|
|
4712
5121
|
* Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
|
|
4713
5122
|
* the caller falls back to running live (always correct): an operator outside the safe set, a spec
|
|
4714
5123
|
* parameter the caller did not supply (the live query would apply the param's default), a null value,
|
|
4715
|
-
*
|
|
5124
|
+
* an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
|
|
5125
|
+
* known type or a value its type cannot hold. No IO — fully unit-testable.
|
|
4716
5126
|
*/
|
|
4717
|
-
/**
|
|
4718
|
-
* True if `sql`'s top-level SELECT carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
|
|
4719
|
-
* {@link buildMaterializedReadQuery} emits no ORDER BY and the snapshot is built with the source's top-level
|
|
4720
|
-
* ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and therefore its
|
|
4721
|
-
* pagination under StartRow/MaxRows — is preserved) rather than from the unordered snapshot. Parse failure or
|
|
4722
|
-
* an un-reasoned statement shape returns `true` (refuse-to-live: treat unknown as ordered rather than risk
|
|
4723
|
-
* serving mis-ordered pages). Mirrors MaterializationRefresher.stripTopLevelOrderBy's AST detection.
|
|
4724
|
-
*
|
|
4725
|
-
* @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
|
|
4726
|
-
* `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
|
|
4727
|
-
*/
|
|
4728
|
-
static queryHasTopLevelOrderBy(sql, platformKey) {
|
|
4729
|
-
if (!sql || sql.trim().length === 0)
|
|
4730
|
-
return false;
|
|
4731
|
-
try {
|
|
4732
|
-
const parsed = SQLParser.Astify(sql, GetDialect(platformKey ?? 'sqlserver'));
|
|
4733
|
-
if (!parsed.astParsed || parsed.ast == null)
|
|
4734
|
-
return true; // unparseable → refuse to live
|
|
4735
|
-
const stmtNode = Array.isArray(parsed.ast) ? (parsed.ast.length === 1 ? parsed.ast[0] : null) : parsed.ast;
|
|
4736
|
-
if (stmtNode == null || typeof stmtNode !== 'object')
|
|
4737
|
-
return true;
|
|
4738
|
-
const s = stmtNode;
|
|
4739
|
-
if (s.type !== 'select')
|
|
4740
|
-
return true; // not a simple SELECT we can reason about → refuse to live
|
|
4741
|
-
return s.orderby != null;
|
|
4742
|
-
}
|
|
4743
|
-
catch {
|
|
4744
|
-
return true; // parser threw → refuse to live (safe: served correctly by the live path)
|
|
4745
|
-
}
|
|
4746
|
-
}
|
|
4747
5127
|
static buildMaterializedReadQuery(opts) {
|
|
4748
|
-
const { outputColumns, schemaName, viewName, spec
|
|
5128
|
+
const { outputColumns, schemaName, viewName, spec } = opts;
|
|
4749
5129
|
if (!outputColumns || outputColumns.length === 0)
|
|
4750
5130
|
return null;
|
|
4751
5131
|
if (!spec || spec.length === 0)
|
|
4752
5132
|
return null;
|
|
4753
|
-
const
|
|
4754
|
-
const
|
|
5133
|
+
const dialect = opts.dialect ?? GetDialect(opts.isPostgres ? 'postgresql' : 'sqlserver');
|
|
5134
|
+
const binder = GenericDatabaseProvider.materializedBinder(opts, dialect);
|
|
5135
|
+
// A typed binding converts the value itself, so it takes native forms (a boolean, a UTC ISO date with
|
|
5136
|
+
// its 'Z'); so does an untyped one whose driver binds booleans natively (PostgreSQL). SQL Server's
|
|
5137
|
+
// untyped binding takes BIT 1/0 and a zone-less ISO string.
|
|
5138
|
+
const nativeForms = binder.Typed || (opts.dialect ? typeof dialect.Binding.BooleanParameterValue(true) === 'boolean' : opts.isPostgres === true);
|
|
4755
5139
|
const predicates = [];
|
|
4756
|
-
// Placeholder for the NEXT bound value: SQL Server uses positional `?`; PostgreSQL uses `$n` (1-based,
|
|
4757
|
-
// computed BEFORE the value is pushed so the index aligns with the array position).
|
|
4758
|
-
const nextPlaceholder = () => (isPostgres ? `$${parameters.length + 1}` : '?');
|
|
4759
5140
|
for (const e of spec) {
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
// (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
|
|
4763
|
-
if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
|
|
5141
|
+
const predicate = GenericDatabaseProvider.materializedPredicate(e, opts, dialect, binder, nativeForms);
|
|
5142
|
+
if (predicate === null)
|
|
4764
5143
|
return null;
|
|
4765
|
-
|
|
4766
|
-
return null;
|
|
4767
|
-
const val = paramValues ? paramValues[e.paramName] : undefined;
|
|
4768
|
-
if (val === undefined || val === null)
|
|
4769
|
-
return null; // caller omitted it → live applies the default
|
|
4770
|
-
const col = q(e.column);
|
|
4771
|
-
const isListOp = e.operator === 'IN' || e.operator === 'NOT IN';
|
|
4772
|
-
if (isListOp) {
|
|
4773
|
-
if (!Array.isArray(val) || val.length === 0)
|
|
4774
|
-
return null; // empty/non-array IN → live
|
|
4775
|
-
const phs = val.map((item) => {
|
|
4776
|
-
const ph = nextPlaceholder();
|
|
4777
|
-
parameters.push(item); // list elements bound as-is (array element type is not declared)
|
|
4778
|
-
return ph;
|
|
4779
|
-
});
|
|
4780
|
-
predicates.push(`${col} ${e.operator} (${phs.join(', ')})`);
|
|
4781
|
-
}
|
|
4782
|
-
else {
|
|
4783
|
-
// Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
|
|
4784
|
-
// Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
|
|
4785
|
-
// which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
|
|
4786
|
-
// than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
|
|
4787
|
-
// aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
|
|
4788
|
-
const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, paramTypes?.[e.paramName], isPostgres);
|
|
4789
|
-
if (!coerced.ok)
|
|
4790
|
-
return null;
|
|
4791
|
-
const ph = nextPlaceholder();
|
|
4792
|
-
parameters.push(coerced.value);
|
|
4793
|
-
predicates.push(`${col} ${e.operator} ${ph}`);
|
|
4794
|
-
}
|
|
5144
|
+
predicates.push(predicate);
|
|
4795
5145
|
}
|
|
4796
|
-
const
|
|
5146
|
+
const q = (name) => dialect.Writer.QuoteIdentifier(name);
|
|
5147
|
+
const cols = outputColumns.map(c => q(c)).join(', ');
|
|
4797
5148
|
// Deterministic page order. A materialized read carries no user ORDER BY (an ordered source query falls
|
|
4798
5149
|
// back to live), so without an explicit order the paging engine would append `ORDER BY (SELECT NULL)` and
|
|
4799
5150
|
// successive pages could skip or duplicate rows whenever the execution plan differs between calls. The
|
|
@@ -4802,7 +5153,90 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4802
5153
|
// buildDataSQL detects this ORDER BY and pages against it instead of the dialect default.
|
|
4803
5154
|
const orderBy = q(GenericDatabaseProvider.MATERIALIZED_SURROGATE_ORDER_COLUMN);
|
|
4804
5155
|
const sql = `SELECT ${cols} FROM ${q(schemaName)}.${q(viewName)} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`;
|
|
4805
|
-
return { sql, parameters };
|
|
5156
|
+
return { sql, parameters: binder.Parameters };
|
|
5157
|
+
}
|
|
5158
|
+
/**
|
|
5159
|
+
* The parameter list one materialized read builds, and how a value joins it: typed by the filtered
|
|
5160
|
+
* column when the snapshot's column types are known, otherwise untyped (the deprecated form).
|
|
5161
|
+
*/
|
|
5162
|
+
static materializedBinder(opts, dialect) {
|
|
5163
|
+
const parameters = [];
|
|
5164
|
+
const types = opts.columnTypes
|
|
5165
|
+
? new Map(Object.entries(opts.columnTypes).map(([name, type]) => [name.toLowerCase(), type]))
|
|
5166
|
+
: null;
|
|
5167
|
+
const untypedPlaceholder = (index) => (opts.isPostgres ? `$${index + 1}` : '?');
|
|
5168
|
+
return {
|
|
5169
|
+
Parameters: parameters,
|
|
5170
|
+
Typed: types !== null,
|
|
5171
|
+
Bind(column, value) {
|
|
5172
|
+
if (types === null && opts.dialect) {
|
|
5173
|
+
return GenericDatabaseProvider.bindNamedParameter(parameters, dialect, value);
|
|
5174
|
+
}
|
|
5175
|
+
if (types === null) {
|
|
5176
|
+
parameters.push(value);
|
|
5177
|
+
return untypedPlaceholder(parameters.length - 1);
|
|
5178
|
+
}
|
|
5179
|
+
const sqlType = types.get(column.toLowerCase());
|
|
5180
|
+
const bound = sqlType === undefined ? undefined : TypedBindValue(value, sqlType);
|
|
5181
|
+
if (sqlType === undefined || bound === undefined)
|
|
5182
|
+
return null;
|
|
5183
|
+
const reference = dialect.Binding.TypedParameter(parameters.length, sqlType);
|
|
5184
|
+
parameters.push(new TypedQueryParameter(reference.Name, sqlType, bound));
|
|
5185
|
+
return reference.Placeholder;
|
|
5186
|
+
},
|
|
5187
|
+
};
|
|
5188
|
+
}
|
|
5189
|
+
/**
|
|
5190
|
+
* Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
|
|
5191
|
+
* it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
|
|
5192
|
+
* provider from rewriting `?` in the statement text, which the legacy positional array form does
|
|
5193
|
+
* everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
|
|
5194
|
+
*/
|
|
5195
|
+
static bindNamedParameter(parameters, dialect, value) {
|
|
5196
|
+
const bound = GenericDatabaseProvider.namedParameterValue(value);
|
|
5197
|
+
if (bound === undefined)
|
|
5198
|
+
return null;
|
|
5199
|
+
const placeholder = dialect.Binding.ParameterPlaceholder(parameters.length);
|
|
5200
|
+
parameters.push(new NamedQueryParameter(placeholder.startsWith('@') ? placeholder.slice(1) : placeholder, bound));
|
|
5201
|
+
return placeholder;
|
|
5202
|
+
}
|
|
5203
|
+
/** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
|
|
5204
|
+
static namedParameterValue(value) {
|
|
5205
|
+
if (value === null || value instanceof Date)
|
|
5206
|
+
return value;
|
|
5207
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
|
|
5208
|
+
return value;
|
|
5209
|
+
return undefined;
|
|
5210
|
+
}
|
|
5211
|
+
/** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
|
|
5212
|
+
static materializedPredicate(e, opts, dialect, binder, nativeForms) {
|
|
5213
|
+
// Defensive: the spec is parsed from a persisted JSON string, so validate each element's shape
|
|
5214
|
+
// before use — a malformed element (missing/non-string column/operator/paramName) returns null
|
|
5215
|
+
// (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
|
|
5216
|
+
if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
|
|
5217
|
+
return null;
|
|
5218
|
+
if (!GenericDatabaseProvider.RUNTIME_SAFE_READ_FILTER_OPERATORS.has(e.operator))
|
|
5219
|
+
return null;
|
|
5220
|
+
const val = opts.paramValues ? opts.paramValues[e.paramName] : undefined;
|
|
5221
|
+
if (val === undefined || val === null)
|
|
5222
|
+
return null; // caller omitted it → live applies the default
|
|
5223
|
+
const col = dialect.Writer.QuoteIdentifier(e.column);
|
|
5224
|
+
if (e.operator === 'IN' || e.operator === 'NOT IN') {
|
|
5225
|
+
if (!Array.isArray(val) || val.length === 0)
|
|
5226
|
+
return null; // empty/non-array IN → live
|
|
5227
|
+
const placeholders = val.map(item => binder.Bind(e.column, item));
|
|
5228
|
+
return placeholders.some(p => p === null) ? null : `${col} ${e.operator} (${placeholders.join(', ')})`;
|
|
5229
|
+
}
|
|
5230
|
+
// Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
|
|
5231
|
+
// Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
|
|
5232
|
+
// which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
|
|
5233
|
+
// than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
|
|
5234
|
+
// aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
|
|
5235
|
+
const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, opts.paramTypes?.[e.paramName], nativeForms);
|
|
5236
|
+
if (!coerced.ok)
|
|
5237
|
+
return null;
|
|
5238
|
+
const placeholder = binder.Bind(e.column, coerced.value);
|
|
5239
|
+
return placeholder === null ? null : `${col} ${e.operator} ${placeholder}`;
|
|
4806
5240
|
}
|
|
4807
5241
|
/**
|
|
4808
5242
|
* Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
|
|
@@ -4818,13 +5252,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4818
5252
|
* the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
|
|
4819
5253
|
* - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
|
|
4820
5254
|
* - `boolean` → live truthiness: ONLY 'true' (case-insensitive) or a real boolean `true` is true; everything
|
|
4821
|
-
* else is false (live never refuses a boolean).
|
|
5255
|
+
* else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
|
|
4822
5256
|
* - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
|
|
4823
5257
|
* the naive input string: live applies the local→UTC shift, so binding the raw string would
|
|
4824
|
-
* diverge for any timed value. Invalid date → refuse.
|
|
5258
|
+
* diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
|
|
5259
|
+
* suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
|
|
5260
|
+
* (error 241); the zone-less string is the same UTC wall-clock.
|
|
4825
5261
|
* - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
|
|
5262
|
+
*
|
|
5263
|
+
* @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
|
|
4826
5264
|
*/
|
|
4827
|
-
static coerceMaterializedScalarValue(value, type,
|
|
5265
|
+
static coerceMaterializedScalarValue(value, type, nativeForms) {
|
|
4828
5266
|
switch (type) {
|
|
4829
5267
|
case 'number': {
|
|
4830
5268
|
const n = Number(typeof value === 'string' ? value.trim() : value);
|
|
@@ -4832,19 +5270,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4832
5270
|
}
|
|
4833
5271
|
case 'boolean': {
|
|
4834
5272
|
const b = typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true';
|
|
4835
|
-
return { ok: true, value:
|
|
5273
|
+
return { ok: true, value: nativeForms ? b : b ? 1 : 0 };
|
|
4836
5274
|
}
|
|
4837
5275
|
case 'date': {
|
|
4838
5276
|
const d = value instanceof Date ? value : new Date(String(value));
|
|
4839
5277
|
if (Number.isNaN(d.getTime()))
|
|
4840
5278
|
return { ok: false };
|
|
4841
5279
|
const iso = d.toISOString();
|
|
4842
|
-
|
|
4843
|
-
// for datetimeoffset), so binding it would throw and force a fallback to live. Strip it for SS: the
|
|
4844
|
-
// value is already the UTC moment and a zone-less ISO string binds as that same datetime2 wall-clock,
|
|
4845
|
-
// matching the live path's rendered literal (no row divergence). PostgreSQL's timestamptz accepts
|
|
4846
|
-
// 'Z', so keep it there.
|
|
4847
|
-
return { ok: true, value: isPostgres ? iso : iso.replace(/Z$/, '') };
|
|
5280
|
+
return { ok: true, value: nativeForms ? iso : iso.replace(/Z$/, '') };
|
|
4848
5281
|
}
|
|
4849
5282
|
case 'string':
|
|
4850
5283
|
return { ok: true, value: String(value) };
|
|
@@ -4852,14 +5285,70 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4852
5285
|
return { ok: true, value };
|
|
4853
5286
|
}
|
|
4854
5287
|
}
|
|
5288
|
+
/**
|
|
5289
|
+
* The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
|
|
5290
|
+
* describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
|
|
5291
|
+
* the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
|
|
5292
|
+
* be described (→ live).
|
|
5293
|
+
*/
|
|
5294
|
+
async materializedColumnTypes(mat, contextUser) {
|
|
5295
|
+
const refreshed = mat.LastRefreshedAt instanceof Date ? mat.LastRefreshedAt.toISOString() : String(mat.LastRefreshedAt ?? '');
|
|
5296
|
+
const key = StatementMemo.KeyOf(`${NormalizeUUID(mat.ID)}|${refreshed}|${mat.SchemaName}.${mat.ViewName}`, this.Dialect.Key);
|
|
5297
|
+
const kept = GenericDatabaseProvider.materializedColumnTypeMemo.Get(key);
|
|
5298
|
+
if (kept)
|
|
5299
|
+
return kept;
|
|
5300
|
+
const writer = this.Dialect.Writer;
|
|
5301
|
+
const described = await this.DescribeStatement(`SELECT * FROM ${writer.QuoteIdentifier(mat.SchemaName)}.${writer.QuoteIdentifier(mat.ViewName)}`, contextUser);
|
|
5302
|
+
if (!described.Success) {
|
|
5303
|
+
LogStatusEx({ message: `Materialized read: the column types of ${mat.SchemaName}.${mat.ViewName} could not be read (${described.Diagnostics.join('; ')}) — serving live.`, verboseOnly: true });
|
|
5304
|
+
return null;
|
|
5305
|
+
}
|
|
5306
|
+
const types = {};
|
|
5307
|
+
for (const c of described.Columns)
|
|
5308
|
+
types[c.Name.toLowerCase()] = c.SQLFullType;
|
|
5309
|
+
GenericDatabaseProvider.materializedColumnTypeMemo.Set(key, types);
|
|
5310
|
+
return types;
|
|
5311
|
+
}
|
|
5312
|
+
/** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
|
|
5313
|
+
static { this.materializedColumnTypeMemo = new StatementMemo(500); }
|
|
5314
|
+
/** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
|
|
5315
|
+
static { this.topLevelOrderByMemo = new StatementMemo(1000); }
|
|
5316
|
+
/**
|
|
5317
|
+
* True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
|
|
5318
|
+
* {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
|
|
5319
|
+
* source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
|
|
5320
|
+
* therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
|
|
5321
|
+
* `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
|
|
5322
|
+
* (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
|
|
5323
|
+
* (SQL, dialect) in a bounded memo.
|
|
5324
|
+
*
|
|
5325
|
+
* @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
|
|
5326
|
+
* `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
|
|
5327
|
+
*/
|
|
5328
|
+
static queryHasTopLevelOrderBy(sql, platformKey) {
|
|
5329
|
+
if (!sql || sql.trim().length === 0)
|
|
5330
|
+
return false;
|
|
5331
|
+
const dialect = GetDialect(platformKey ?? 'sqlserver');
|
|
5332
|
+
return GenericDatabaseProvider.topLevelOrderByMemo.GetOrCompute(StatementMemo.KeyOf(sql, dialect.Key), () => {
|
|
5333
|
+
const doc = SqlDocument.Parse(sql, dialect);
|
|
5334
|
+
if (doc.TopLevelQuery() === null || doc.HasStackedStatements().Value)
|
|
5335
|
+
return true;
|
|
5336
|
+
const orderBy = doc.TopLevelOrderBy();
|
|
5337
|
+
return !orderBy.Complete || orderBy.Value !== null;
|
|
5338
|
+
});
|
|
5339
|
+
}
|
|
4855
5340
|
/**
|
|
4856
5341
|
* Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
|
|
4857
5342
|
* `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
|
|
4858
5343
|
* persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
|
|
4859
5344
|
* the live query (serving live is always correct — this is a transparent optimization, never a
|
|
4860
5345
|
* correctness dependency).
|
|
5346
|
+
*
|
|
5347
|
+
* @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
|
|
5348
|
+
* check reads it; without it the check reads the platform SQL, where template syntax makes any
|
|
5349
|
+
* template query read as ordered (→ live).
|
|
4861
5350
|
*/
|
|
4862
|
-
async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues) {
|
|
5351
|
+
async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues, renderedSQL) {
|
|
4863
5352
|
if (!IsMaterializedDataSource(params.DataSource))
|
|
4864
5353
|
return null; // not opted in → live
|
|
4865
5354
|
// A snapshot is shared by every caller and was built without this caller's Context (user, date), so a
|
|
@@ -4879,6 +5368,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4879
5368
|
Fields: ['MaterializedResultID'],
|
|
4880
5369
|
ResultType: 'simple',
|
|
4881
5370
|
MaxRows: 1,
|
|
5371
|
+
SkipTotalRowCount: true,
|
|
4882
5372
|
}, contextUser);
|
|
4883
5373
|
// Same failure-vs-absence distinction as the base-view path: a permission/query failure here would
|
|
4884
5374
|
// otherwise be indistinguishable from "this query is not materialized", silently pinning the caller to
|
|
@@ -4894,10 +5384,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4894
5384
|
// source's top-level ORDER BY stripped (it has no inherent order). A query that carries a top-level ORDER
|
|
4895
5385
|
// BY would therefore page differently from the live query. Refuse → live (which preserves the ordering)
|
|
4896
5386
|
// rather than serve a divergent page order — consistent with this method's "any uncertainty → live".
|
|
4897
|
-
// Check the
|
|
4898
|
-
//
|
|
5387
|
+
// Check the SQL the live path executes: the rendered statement when the caller has it (a template decides
|
|
5388
|
+
// its ORDER BY only when it renders, and the structural reader does not read template syntax, so the
|
|
5389
|
+
// template text of every template query would read as ordered), otherwise the PLATFORM-resolved SQL — not
|
|
5390
|
+
// the base query.SQL: a per-platform QuerySQL variant (e.g. a PostgreSQL variant) may add a top-level
|
|
4899
5391
|
// ORDER BY the base SQL lacks, and parsing the base SQL would miss it and serve mis-ordered snapshot pages.
|
|
4900
|
-
|
|
5392
|
+
const orderingSQL = renderedSQL ?? query.GetPlatformSQL(this.PlatformKey) ?? '';
|
|
5393
|
+
if (GenericDatabaseProvider.queryHasTopLevelOrderBy(orderingSQL, this.PlatformKey))
|
|
4901
5394
|
return null;
|
|
4902
5395
|
// Load the materialization metadata. matId is our own UUID (from committed metadata), so it is safe
|
|
4903
5396
|
// to interpolate into ExtraFilter — it never carries caller input.
|
|
@@ -4910,9 +5403,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4910
5403
|
const res = await rv.RunView({
|
|
4911
5404
|
EntityName: 'MJ: Materialized Results',
|
|
4912
5405
|
ExtraFilter: `ID='${matId}'`,
|
|
4913
|
-
Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName'],
|
|
5406
|
+
Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName', 'LastRefreshedAt'],
|
|
4914
5407
|
ResultType: 'simple',
|
|
4915
5408
|
MaxRows: 1,
|
|
5409
|
+
SkipTotalRowCount: true,
|
|
4916
5410
|
BypassCache: true,
|
|
4917
5411
|
}, contextUser);
|
|
4918
5412
|
if (this.MaterializationLookupFailed(res, `query "${query.Name}" (materialization metadata)`))
|
|
@@ -4955,6 +5449,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4955
5449
|
const paramTypes = {};
|
|
4956
5450
|
for (const p of query.QueryParameters ?? [])
|
|
4957
5451
|
paramTypes[p.Name] = p.Type;
|
|
5452
|
+
// Each value binds with the type of the snapshot column it is compared with (read once per refresh;
|
|
5453
|
+
// the status read above stays uncached). Unknown types → live.
|
|
5454
|
+
const columnTypes = await this.materializedColumnTypes({ ID: matId, SchemaName: mat.SchemaName, ViewName: mat.ViewName, LastRefreshedAt: mat.LastRefreshedAt ?? null }, contextUser);
|
|
5455
|
+
if (!columnTypes)
|
|
5456
|
+
return null;
|
|
4958
5457
|
return GenericDatabaseProvider.buildMaterializedReadQuery({
|
|
4959
5458
|
outputColumns,
|
|
4960
5459
|
schemaName: mat.SchemaName,
|
|
@@ -4964,7 +5463,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4964
5463
|
// already refused when the template rendered), so the row filter sees both.
|
|
4965
5464
|
paramValues: params.ServerParameters ? { ...params.Parameters, ...params.ServerParameters } : params.Parameters,
|
|
4966
5465
|
paramTypes,
|
|
4967
|
-
|
|
5466
|
+
dialect: this.Dialect,
|
|
5467
|
+
columnTypes,
|
|
4968
5468
|
});
|
|
4969
5469
|
}
|
|
4970
5470
|
async InternalRunQuery(params, contextUser) {
|
|
@@ -4988,8 +5488,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4988
5488
|
try {
|
|
4989
5489
|
// Find and validate query
|
|
4990
5490
|
const query = this.findAndValidateQuery(params, contextUser);
|
|
4991
|
-
|
|
4992
|
-
|
|
5491
|
+
const requestedLabel = GenericDatabaseProvider.RequestedQueryLabel(params);
|
|
5492
|
+
// Process parameters (composition + Nunjucks templates). A query on an external data source
|
|
5493
|
+
// renders its values with that source's dialect, so its literals read as the remote database reads them.
|
|
5494
|
+
const dialectKey = query.ExternalDataSourceID ? await this.externalQueryDialectKey(query, contextUser) : undefined;
|
|
5495
|
+
const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params, dialectKey);
|
|
4993
5496
|
finalSQL = resolved.finalSQL;
|
|
4994
5497
|
const appliedParameters = resolved.appliedParameters;
|
|
4995
5498
|
// Opt-in: the approval must be current for the definition about to run
|
|
@@ -4997,13 +5500,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4997
5500
|
await this.ValidateQueryApprovalAsync(query, resolved.renderResult);
|
|
4998
5501
|
}
|
|
4999
5502
|
// Authorize what will actually run, before any cache, materialized or external read.
|
|
5000
|
-
this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser);
|
|
5503
|
+
const authorization = this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser, requestedLabel);
|
|
5504
|
+
// A projection star over an entity the user is denied a field on: the run drops the denied
|
|
5505
|
+
// columns, chosen by the database's description of the statement. An external source's
|
|
5506
|
+
// statement cannot be described here, so such a run is refused.
|
|
5507
|
+
if (authorization.NeedsColumnFiltering && query.ExternalDataSourceID) {
|
|
5508
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5509
|
+
}
|
|
5510
|
+
const columnFilter = authorization.NeedsColumnFiltering ? await this.queryColumnFilter(query, finalSQL, requestedLabel, contextUser) : null;
|
|
5511
|
+
const cacheSlot = this.queryResultCacheSlot(query, finalSQL, authorization.NeedsColumnFiltering, contextUser);
|
|
5001
5512
|
// ── Phase 2: materialized read redirect (plan §5) ──
|
|
5002
5513
|
// If the caller opted into DataSource:'Materialized' and this query has a fresh, Active
|
|
5003
5514
|
// RowFilterBroad materialization, serve from the materialized table with the row-filter params
|
|
5004
5515
|
// injected as BOUND predicates. On ANY uncertainty tryBuildMaterializedQueryPlan returns null and
|
|
5005
5516
|
// we fall through to the live execution below — a materialized read can never diverge from live.
|
|
5006
|
-
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues);
|
|
5517
|
+
const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues, finalSQL);
|
|
5007
5518
|
if (matPlan) {
|
|
5008
5519
|
// Use a LOCAL for the materialized SQL — never overwrite `finalSQL` (which stays the
|
|
5009
5520
|
// live-rendered SQL), so a fallback below runs the live path unchanged.
|
|
@@ -5044,6 +5555,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5044
5555
|
rows = paginated.paginatedResult;
|
|
5045
5556
|
matTotalRowCount = paginated.totalRowCount;
|
|
5046
5557
|
}
|
|
5558
|
+
rows = this.filterQueryRows(rows, columnFilter);
|
|
5047
5559
|
if (params.Enrichment?.EnricherKey) {
|
|
5048
5560
|
rows = await this.enrichQueryResults(rows, params, query, contextUser);
|
|
5049
5561
|
}
|
|
@@ -5099,10 +5611,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5099
5611
|
let executionTime;
|
|
5100
5612
|
let fullResult;
|
|
5101
5613
|
if (useSQLPaging) {
|
|
5614
|
+
// The paging wrapper may order by output position (`ORDER BY 1` on PostgreSQL); a page ordered
|
|
5615
|
+
// by a column the caller is denied would reveal how its values rank, so such a run is refused.
|
|
5616
|
+
if (columnFilter && columnFilter.Columns.length > 0 && columnFilter.Withheld.has(columnFilter.Columns[0].Name)) {
|
|
5617
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5618
|
+
}
|
|
5102
5619
|
// Check paged cache before executing SQL
|
|
5103
|
-
const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters);
|
|
5620
|
+
const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters, cacheSlot.PageKey(params));
|
|
5104
5621
|
if (pagedCacheHit) {
|
|
5105
|
-
return pagedCacheHit;
|
|
5622
|
+
return { ...pagedCacheHit, Results: this.filterQueryRows(pagedCacheHit.Results, columnFilter) };
|
|
5106
5623
|
}
|
|
5107
5624
|
const paging = QueryPagingEngine.WrapWithPaging(finalSQL, QueryPagingEngine.ResolveStartRow(params.StartRow), params.MaxRows, this.PlatformKey);
|
|
5108
5625
|
// Execute data + count queries in parallel
|
|
@@ -5114,27 +5631,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5114
5631
|
executionTime = Date.now() - start;
|
|
5115
5632
|
if (!dataResult)
|
|
5116
5633
|
throw new Error('Error executing paged query SQL');
|
|
5117
|
-
|
|
5118
|
-
this.
|
|
5634
|
+
this.ConvertByteArrayValuesToBase64(dataResult);
|
|
5635
|
+
paginatedResult = this.filterQueryRows(dataResult, columnFilter);
|
|
5119
5636
|
totalRowCount = countResult?.[0]?.TotalRowCount != null
|
|
5120
5637
|
? Number(countResult[0].TotalRowCount)
|
|
5121
5638
|
: paginatedResult.length;
|
|
5122
5639
|
}
|
|
5123
5640
|
else {
|
|
5124
5641
|
// Check full-result cache before executing
|
|
5125
|
-
const cachedResult = await this.checkQueryCache(query, params, appliedParameters);
|
|
5642
|
+
const cachedResult = await this.checkQueryCache(query, params, appliedParameters, cacheSlot.Key);
|
|
5126
5643
|
if (cachedResult) {
|
|
5127
|
-
return cachedResult;
|
|
5644
|
+
return { ...cachedResult, Results: this.filterQueryRows(cachedResult.Results, columnFilter) };
|
|
5128
5645
|
}
|
|
5129
5646
|
// No paging requested — execute full query, apply in-memory pagination as fallback
|
|
5130
5647
|
const timing = await this.executeQueryWithTiming(finalSQL, contextUser);
|
|
5131
5648
|
executionTime = timing.executionTime;
|
|
5132
5649
|
fullResult = timing.result;
|
|
5133
5650
|
const paginated = this.applyQueryPagination(fullResult, params);
|
|
5134
|
-
paginatedResult = paginated.paginatedResult;
|
|
5651
|
+
paginatedResult = this.filterQueryRows(paginated.paginatedResult, columnFilter);
|
|
5135
5652
|
totalRowCount = paginated.totalRowCount;
|
|
5136
5653
|
// Cache full (unpaginated) results if enabled (fire-and-forget)
|
|
5137
|
-
void this.cacheQueryResults(query, params.Parameters || {}, fullResult);
|
|
5654
|
+
void this.cacheQueryResults(query, params.Parameters || {}, fullResult, cacheSlot.Key);
|
|
5138
5655
|
}
|
|
5139
5656
|
// Optional, additive post-query enrichment (e.g. append an ML prediction
|
|
5140
5657
|
// column). Awaited so the appended columns are present in the response.
|
|
@@ -5184,6 +5701,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5184
5701
|
};
|
|
5185
5702
|
}
|
|
5186
5703
|
}
|
|
5704
|
+
/** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
|
|
5705
|
+
static { this.describedStatementMemo = new StatementMemo(500, 10 * 60 * 1000); }
|
|
5706
|
+
/**
|
|
5707
|
+
* Describes the result set of `sql` without returning its rows: each output column's name,
|
|
5708
|
+
* position, exact type, nullability and, for a pass-through column, the table or view column it
|
|
5709
|
+
* comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
|
|
5710
|
+
* runs it under `LIMIT 0` in a transaction that is rolled back).
|
|
5711
|
+
*
|
|
5712
|
+
* This base implementation describes nothing: it reports a failure. Providers for a database
|
|
5713
|
+
* that can describe a statement override it.
|
|
5714
|
+
*
|
|
5715
|
+
* @param sql - The rendered statement, in this provider's dialect.
|
|
5716
|
+
* @param _contextUser - The user the description is for.
|
|
5717
|
+
*/
|
|
5718
|
+
async DescribeStatement(sql, _contextUser) {
|
|
5719
|
+
return DescribeStatementFailure(`${this.constructor.name} cannot describe a statement.`);
|
|
5720
|
+
}
|
|
5721
|
+
/**
|
|
5722
|
+
* SECURITY — the output columns of `renderedSQL` that `user` must not receive
|
|
5723
|
+
* ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
|
|
5724
|
+
*
|
|
5725
|
+
* @throws Error with the refusal message when the statement cannot be described: without the
|
|
5726
|
+
* description no column can be shown to be safe, so the run is refused.
|
|
5727
|
+
*/
|
|
5728
|
+
async queryColumnFilter(query, renderedSQL, requestedLabel, contextUser) {
|
|
5729
|
+
const user = contextUser || this.CurrentUser;
|
|
5730
|
+
const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
|
|
5731
|
+
let columns = GenericDatabaseProvider.describedStatementMemo.Get(key);
|
|
5732
|
+
if (!columns) {
|
|
5733
|
+
const described = await this.DescribeStatement(renderedSQL, user);
|
|
5734
|
+
if (!described.Success) {
|
|
5735
|
+
LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}': its columns could not be described for field-level security (${described.Diagnostics.join('; ')}).`, verboseOnly: true });
|
|
5736
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5737
|
+
}
|
|
5738
|
+
columns = described.Columns;
|
|
5739
|
+
GenericDatabaseProvider.describedStatementMemo.Set(key, columns);
|
|
5740
|
+
}
|
|
5741
|
+
const readEntities = [...(FieldSecuritySQLGate.RelationEntities(renderedSQL, this.Entities, this.PlatformKey) ?? []), ...this.declaredQueryEntities(query)];
|
|
5742
|
+
return { Key: key, Columns: columns, Withheld: WithheldColumnNames(columns, this.Entities, readEntities, user) };
|
|
5743
|
+
}
|
|
5744
|
+
/** The catalog entities `query`'s `QueryEntities` rows name. */
|
|
5745
|
+
declaredQueryEntities(query) {
|
|
5746
|
+
const byID = IndexByUUID(this.Entities);
|
|
5747
|
+
return (query.QueryEntities ?? []).map(qe => byID.Get(qe.EntityID)).filter((e) => !!e);
|
|
5748
|
+
}
|
|
5749
|
+
/**
|
|
5750
|
+
* `rows` with the filter's withheld columns dropped, as new row objects. A column the
|
|
5751
|
+
* description does not list is dropped too, and the description is forgotten: the statement's
|
|
5752
|
+
* shape changed since it was described (a view redefined), so the next run describes it again.
|
|
5753
|
+
*/
|
|
5754
|
+
filterQueryRows(rows, filter) {
|
|
5755
|
+
if (!filter || rows.length === 0)
|
|
5756
|
+
return rows;
|
|
5757
|
+
const undescribed = UndescribedColumnNames(rows, filter.Columns);
|
|
5758
|
+
if (undescribed.size > 0) {
|
|
5759
|
+
GenericDatabaseProvider.describedStatementMemo.Delete(filter.Key);
|
|
5760
|
+
}
|
|
5761
|
+
return WithholdColumns(rows, undescribed.size > 0 ? new Set([...filter.Withheld, ...undescribed]) : filter.Withheld);
|
|
5762
|
+
}
|
|
5187
5763
|
/**
|
|
5188
5764
|
* Batch query execution — runs all queries in parallel.
|
|
5189
5765
|
*/
|
|
@@ -5333,22 +5909,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5333
5909
|
findAndValidateQuery(params, contextUser) {
|
|
5334
5910
|
const query = this.resolveQuery(params);
|
|
5335
5911
|
if (!query) {
|
|
5336
|
-
|
|
5337
|
-
|
|
5338
|
-
errorDetails = `Query '${params.QueryName}' not found`;
|
|
5339
|
-
if (params.CategoryPath) {
|
|
5340
|
-
errorDetails += ` in category path '${params.CategoryPath}'`;
|
|
5341
|
-
}
|
|
5342
|
-
else if (params.CategoryID) {
|
|
5343
|
-
errorDetails += ` in category ID '${params.CategoryID}'`;
|
|
5344
|
-
}
|
|
5345
|
-
}
|
|
5346
|
-
else if (params.QueryID) {
|
|
5347
|
-
errorDetails = `Query with ID '${params.QueryID}' not found`;
|
|
5348
|
-
}
|
|
5349
|
-
throw new Error(errorDetails);
|
|
5912
|
+
// Worded exactly as a refusal (QueryUnavailableMessage), so neither confirms the query exists.
|
|
5913
|
+
throw new Error(GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(params)));
|
|
5350
5914
|
}
|
|
5351
|
-
this.ValidateQueryForExecution(query, contextUser);
|
|
5915
|
+
this.ValidateQueryForExecution(query, contextUser, GenericDatabaseProvider.RequestedQueryLabel(params));
|
|
5352
5916
|
return query;
|
|
5353
5917
|
}
|
|
5354
5918
|
/**
|
|
@@ -5357,10 +5921,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5357
5921
|
*
|
|
5358
5922
|
* Delegates to {@link RenderPipeline.Run} for the composition → template
|
|
5359
5923
|
* pipeline. Paging is handled separately by the caller (InternalRunQuery).
|
|
5924
|
+
*
|
|
5925
|
+
* @param dialectKey - The dialect the template's values render for (`sqlString` literals,
|
|
5926
|
+
* booleans); this provider's platform when omitted. An external data source's query passes
|
|
5927
|
+
* the source's dialect.
|
|
5360
5928
|
*/
|
|
5361
|
-
processQueryParameters(query, parameters, contextUser, serverSet) {
|
|
5929
|
+
processQueryParameters(query, parameters, contextUser, serverSet, dialectKey) {
|
|
5362
5930
|
const result = RenderPipeline.Run(query.GetPlatformSQL(this.PlatformKey), {
|
|
5363
5931
|
Platform: this.PlatformKey,
|
|
5932
|
+
DialectKey: dialectKey,
|
|
5933
|
+
QueryID: query.ID,
|
|
5934
|
+
QueryName: query.Name,
|
|
5364
5935
|
ContextUser: contextUser ?? this.CurrentUser,
|
|
5365
5936
|
Parameters: parameters,
|
|
5366
5937
|
ServerParameters: serverSet?.ServerParameters,
|
|
@@ -5377,6 +5948,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5377
5948
|
}
|
|
5378
5949
|
return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
|
|
5379
5950
|
}
|
|
5951
|
+
/**
|
|
5952
|
+
* The dialect key of the external data source `query` reads, so its template values render as
|
|
5953
|
+
* that database reads literals; undefined when the source has no SQL dialect (a document
|
|
5954
|
+
* store), in which case the query renders with this provider's platform as before.
|
|
5955
|
+
*/
|
|
5956
|
+
async externalQueryDialectKey(query, contextUser) {
|
|
5957
|
+
const router = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
|
|
5958
|
+
const key = await router.GetQueryDialectKey(query.ExternalDataSourceID, contextUser, this);
|
|
5959
|
+
return key ?? undefined;
|
|
5960
|
+
}
|
|
5380
5961
|
/**
|
|
5381
5962
|
* Checks the columns an external-data-source query returned against the fields the Query
|
|
5382
5963
|
* *declares* (its QueryField metadata) and logs a warning naming any declared field that
|
|
@@ -5566,19 +6147,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5566
6147
|
return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
|
|
5567
6148
|
}
|
|
5568
6149
|
// wrapWithMaxRows is now handled by RenderPipeline.applyMaxRows
|
|
6150
|
+
/**
|
|
6151
|
+
* Where a server-side result cache keeps this run's rows: one slot per rendered statement and
|
|
6152
|
+
* dialect, and, when the caller is denied a field the statement's projection star reads, per
|
|
6153
|
+
* field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
|
|
6154
|
+
* runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
|
|
6155
|
+
* The rendered statement carries every parameter value, server-set ones included, so they need
|
|
6156
|
+
* no separate part of the key.
|
|
6157
|
+
*/
|
|
6158
|
+
queryResultCacheSlot(query, renderedSQL, needsColumnFiltering, contextUser) {
|
|
6159
|
+
const user = contextUser || this.CurrentUser;
|
|
6160
|
+
const profile = needsColumnFiltering && user ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : '';
|
|
6161
|
+
const key = `${query.ID}|${StatementMemo.KeyOf(renderedSQL, this.Dialect.Key)}|fs:${profile}`;
|
|
6162
|
+
return {
|
|
6163
|
+
Key: key,
|
|
6164
|
+
PageKey: (params) => `${key}|page:${QueryPagingEngine.ResolveStartRow(params.StartRow)}:${params.MaxRows ?? ''}`,
|
|
6165
|
+
};
|
|
6166
|
+
}
|
|
5569
6167
|
/**
|
|
5570
6168
|
* Checks the query cache for existing results and returns them if valid.
|
|
5571
6169
|
* Currently always returns null (query caching is not active).
|
|
6170
|
+
*
|
|
6171
|
+
* An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
|
|
6172
|
+
* stores under: it separates rendered statements and field-security profiles, so a slot never
|
|
6173
|
+
* serves one caller rows shaped for another. The returned rows must be the statement's full
|
|
6174
|
+
* output; the caller's withheld columns are dropped from them after the hit.
|
|
5572
6175
|
*/
|
|
5573
|
-
async checkQueryCache(_query, _params, _appliedParameters) {
|
|
6176
|
+
async checkQueryCache(_query, _params, _appliedParameters, _slotKey) {
|
|
5574
6177
|
return null;
|
|
5575
6178
|
}
|
|
5576
6179
|
/**
|
|
5577
6180
|
* Checks the paged cache for a specific page of query results.
|
|
5578
6181
|
* Returns a full RunQueryResult on hit, null on miss.
|
|
5579
6182
|
* Currently always returns null (query caching is not active).
|
|
6183
|
+
*
|
|
6184
|
+
* An override must look the page up by `slotKey` alone: it names the rendered statement, the
|
|
6185
|
+
* caller's field-security profile and the page, so a page cached for a restricted caller is
|
|
6186
|
+
* never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
|
|
6187
|
+
* from the returned rows after the hit.
|
|
5580
6188
|
*/
|
|
5581
|
-
async checkPagedQueryCache(_query, _params, _appliedParameters) {
|
|
6189
|
+
async checkPagedQueryCache(_query, _params, _appliedParameters, _slotKey) {
|
|
5582
6190
|
return null;
|
|
5583
6191
|
}
|
|
5584
6192
|
/**
|
|
@@ -5690,8 +6298,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5690
6298
|
/**
|
|
5691
6299
|
* Caches query results if caching is enabled for the query.
|
|
5692
6300
|
* Currently a no-op (query caching is not active).
|
|
6301
|
+
*
|
|
6302
|
+
* `results` is the statement's full output, before the caller's withheld columns are dropped.
|
|
6303
|
+
* An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
|
|
5693
6304
|
*/
|
|
5694
|
-
async cacheQueryResults(_query, _parameters, _results) {
|
|
6305
|
+
async cacheQueryResults(_query, _parameters, _results, _slotKey) {
|
|
5695
6306
|
// No-op: query caching has been removed
|
|
5696
6307
|
}
|
|
5697
6308
|
/**************************************************************************/
|
|
@@ -6185,6 +6796,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6185
6796
|
const uncachedItems = [];
|
|
6186
6797
|
// Track fingerprints for uncached items so we can write-through after SQL
|
|
6187
6798
|
const uncachedFingerprints = [];
|
|
6799
|
+
// Track per-entity mutation versions before SQL execution so an in-flight read does not
|
|
6800
|
+
// overwrite LocalCacheManager with pre-mutation rows if a save/delete lands mid-fetch.
|
|
6801
|
+
const uncachedMutationVersions = [];
|
|
6188
6802
|
let cacheHitCount = 0;
|
|
6189
6803
|
let cacheMissCount = 0;
|
|
6190
6804
|
const preparedItems = [];
|
|
@@ -6275,7 +6889,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6275
6889
|
LogError(`GetDatasetByName("${datasetName}"): status verification failed: ${statusErr instanceof Error ? statusErr.message : String(statusErr)}`);
|
|
6276
6890
|
}
|
|
6277
6891
|
}
|
|
6278
|
-
else if (recorded?.status?.Success
|
|
6892
|
+
else if (recorded?.status?.Success &&
|
|
6893
|
+
this.ServerCacheVerificationTTLMs > 0 &&
|
|
6894
|
+
(Date.now() - recorded.timestamp) <= this.ServerCacheVerificationTTLMs) {
|
|
6279
6895
|
liveStatus = recorded.status;
|
|
6280
6896
|
}
|
|
6281
6897
|
}
|
|
@@ -6323,11 +6939,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6323
6939
|
}
|
|
6324
6940
|
if (cached) {
|
|
6325
6941
|
cacheHitCount++;
|
|
6942
|
+
const materializedDatasetRows = await provider.MaterializeCachedRowsForCaller(cached.results, itemEntity, contextUser, false);
|
|
6326
6943
|
cachedResults.push({
|
|
6327
6944
|
EntityID: entityID,
|
|
6328
6945
|
EntityName: entityName,
|
|
6329
6946
|
Code: code,
|
|
6330
|
-
Results: this.projectDatasetRowsForCaller(datasetName, itemEntity,
|
|
6947
|
+
Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, materializedDatasetRows, contextUser),
|
|
6331
6948
|
LatestUpdateDate: latestUpdateDate,
|
|
6332
6949
|
Success: true,
|
|
6333
6950
|
});
|
|
@@ -6358,6 +6975,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6358
6975
|
uncachedItems.push(item);
|
|
6359
6976
|
// A narrowed read (the caller is denied fields) is never written to the shared slot.
|
|
6360
6977
|
uncachedFingerprints.push(deniedFields.size === 0 ? fingerprint : '');
|
|
6978
|
+
uncachedMutationVersions.push(provider.GetEntityMutationVersion(entityName));
|
|
6361
6979
|
}
|
|
6362
6980
|
// Phase 2: Execute SQL only for cache misses
|
|
6363
6981
|
let batchResults = [];
|
|
@@ -6414,8 +7032,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6414
7032
|
}
|
|
6415
7033
|
}
|
|
6416
7034
|
const latestUpdateDate = this.computeLatestUpdateDate(itemData, dateFieldToCheck, item);
|
|
6417
|
-
// Write-through: cache this result for future requests (including empty results)
|
|
6418
|
-
|
|
7035
|
+
// Write-through: cache this result for future requests (including empty results),
|
|
7036
|
+
// unless the entity was mutated while ExecuteSQLBatch / PostProcessRows was in flight.
|
|
7037
|
+
const mutatedDuringFetch = provider.GetEntityMutationVersion(entityName) !== uncachedMutationVersions[i];
|
|
7038
|
+
if (cacheAvailable && uncachedFingerprints[i] && !mutatedDuringFetch) {
|
|
6419
7039
|
const maxUpdatedAt = itemData.length > 0
|
|
6420
7040
|
? this.extractMaxUpdatedAtFromRows(itemData, dateFieldToCheck)
|
|
6421
7041
|
: new Date(0).toISOString();
|
|
@@ -6431,7 +7051,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6431
7051
|
// item.Results — these very arrays — to every engine subclass), so those slots
|
|
6432
7052
|
// must stay under the defensive deep-freeze like any RunView result.
|
|
6433
7053
|
const isMetadataScaffolding = datasetName === ProviderBase._mjMetadataDatasetName;
|
|
6434
|
-
|
|
7054
|
+
const rowsForCache = isMetadataScaffolding
|
|
7055
|
+
? itemData
|
|
7056
|
+
: provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName));
|
|
7057
|
+
await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, rowsForCache, maxUpdatedAt, undefined, undefined, this, undefined, isMetadataScaffolding ? { ProviderInternalScaffolding: true } : undefined);
|
|
6435
7058
|
}
|
|
6436
7059
|
sqlResults.push({
|
|
6437
7060
|
EntityID: entityID,
|
|
@@ -6760,7 +7383,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6760
7383
|
* `AIEngine.Models` to recover the driver class / APIName and call
|
|
6761
7384
|
* `EmbedText(model, text)` directly. If the EntityDocument does not specify
|
|
6762
7385
|
* a model (or the model isn't loaded) we fall back to
|
|
6763
|
-
* `EmbedTextLocal` (
|
|
7386
|
+
* `EmbedTextLocal` (the default local model) only as a last resort. The search
|
|
7387
|
+
* text is embedded as a query (`inputType: 'query'`). The index's
|
|
7388
|
+
* `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
|
|
7389
|
+
* the model's native size.
|
|
6764
7390
|
*
|
|
6765
7391
|
* Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
|
|
6766
7392
|
* which rehydrates the vector pool for `entityDocumentId` from
|
|
@@ -6787,15 +7413,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6787
7413
|
LogError(`searchEntitiesSemanticPass: EntityDocument AIModelID="${embeddingAIModelId}" not found in AIEngine.Models. Index/query model mismatch is likely — refusing to fall back silently.`);
|
|
6788
7414
|
return [];
|
|
6789
7415
|
}
|
|
6790
|
-
const result = await AIEngine.Instance.EmbedText(model, searchText);
|
|
7416
|
+
const result = await AIEngine.Instance.EmbedText(model, searchText, undefined, { inputType: 'query' });
|
|
6791
7417
|
queryVector = result?.vector ?? null;
|
|
6792
7418
|
}
|
|
6793
7419
|
else {
|
|
6794
7420
|
// No model on the EntityDocument — last-resort fallback to the
|
|
6795
7421
|
// highest-power local embedder. Logged because this path means
|
|
6796
7422
|
// indexing-time and query-time models can diverge.
|
|
6797
|
-
LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to
|
|
6798
|
-
const embed = await AIEngine.Instance.EmbedTextLocal(searchText);
|
|
7423
|
+
LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to the default local embedding model. Index/query mismatch possible.`);
|
|
7424
|
+
const embed = await AIEngine.Instance.EmbedTextLocal(searchText, { inputType: 'query' });
|
|
6799
7425
|
queryVector = embed?.result?.vector ?? null;
|
|
6800
7426
|
}
|
|
6801
7427
|
}
|