@memberjunction/generic-database-provider 6.2.2 → 6.3.0-edge.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GenericDatabaseProvider.d.ts +198 -20
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +1318 -157
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/NodeAsyncServerOperationScopeTracker.d.ts +20 -0
- package/dist/NodeAsyncServerOperationScopeTracker.d.ts.map +1 -0
- package/dist/NodeAsyncServerOperationScopeTracker.js +30 -0
- package/dist/NodeAsyncServerOperationScopeTracker.js.map +1 -0
- package/dist/UserCache.d.ts +32 -0
- package/dist/UserCache.d.ts.map +1 -1
- package/dist/UserCache.js +111 -12
- package/dist/UserCache.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +62 -0
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +800 -2
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/concurrency/fieldConflictDetector.d.ts +82 -0
- package/dist/concurrency/fieldConflictDetector.d.ts.map +1 -0
- package/dist/concurrency/fieldConflictDetector.js +285 -0
- package/dist/concurrency/fieldConflictDetector.js.map +1 -0
- package/dist/countOnlyBatch.d.ts +5 -1
- package/dist/countOnlyBatch.d.ts.map +1 -1
- package/dist/countOnlyBatch.js +6 -2
- package/dist/countOnlyBatch.js.map +1 -1
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/recordChangeSnapshot.d.ts +28 -0
- package/dist/recordChangeSnapshot.d.ts.map +1 -1
- package/dist/recordChangeSnapshot.js +66 -0
- package/dist/recordChangeSnapshot.js.map +1 -1
- package/dist/rowFilterParameters.d.ts +22 -0
- package/dist/rowFilterParameters.d.ts.map +1 -0
- package/dist/rowFilterParameters.js +23 -0
- package/dist/rowFilterParameters.js.map +1 -0
- package/dist/serverPrincipal.d.ts +45 -0
- package/dist/serverPrincipal.d.ts.map +1 -0
- package/dist/serverPrincipal.js +46 -0
- package/dist/serverPrincipal.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +14 -14
|
@@ -15,23 +15,25 @@
|
|
|
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, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, } from '@memberjunction/core';
|
|
19
|
-
import { BytesToBase64, GroupByUUID, IndexByUUID, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
18
|
+
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProjectEntityValueRowsForUser, FieldSecurityError, FieldSecuritySQLGate, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride, NormalizeAlternateBaseViewName, ResolveAlternateBaseView, LocalCacheManager, LogError, LogErrorEx, LogStatus, LogStatusEx, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, ServerOperationScopeManager, NormalizeRunViewParameters, CompositeFilterSQLCompiler, IsPostRunViewProtectedEntity, WellKnownUserSource, } from '@memberjunction/core';
|
|
19
|
+
import { BytesToBase64, EscapeSQLString, GroupByUUID, IndexByUUID, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UnwrapPhraseQuotes, UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
20
20
|
import { QueryPagingEngine } from './queryPagingEngine.js';
|
|
21
21
|
// QueryParameterProcessor is now called internally by RenderPipeline
|
|
22
22
|
import { createHash } from 'node:crypto';
|
|
23
23
|
import { v4 as uuidv4 } from 'uuid';
|
|
24
24
|
import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
25
25
|
import { GetDialect } from '@memberjunction/sql-dialect';
|
|
26
|
-
import { SqlDocument, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
26
|
+
import { SqlDocument, EditSet, SqlTokens, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
27
27
|
import { DescribeStatementFailure } from './describeStatement.js';
|
|
28
28
|
import { NamedQueryParameter, TypedBindValue, TypedQueryParameter } from './typedQueryParameter.js';
|
|
29
|
+
import { RowFilterParameterCollector } from './rowFilterParameters.js';
|
|
29
30
|
import { StatementMemo } from './statementMemo.js';
|
|
30
31
|
import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
|
|
31
32
|
import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './fieldSecurity/queryColumnSecurity.js';
|
|
32
33
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
33
34
|
import { RenderPipeline } from './renderPipeline.js';
|
|
34
35
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
36
|
+
import { AreEntityFieldValuesDifferent, ClientOldValueToFieldValue, DetectFieldConcurrencyConflicts, FindEntityFieldByCodeNameOrName, IsFieldOpaqueToClient, } from './concurrency/fieldConflictDetector.js';
|
|
35
37
|
import { GetQueryApprovalStateAsync, QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
|
|
36
38
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
37
39
|
import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
|
|
@@ -43,7 +45,11 @@ import { TransactionAffinity } from './TransactionAffinity.js';
|
|
|
43
45
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
44
46
|
import { ClientClauseScreen } from './clientClauseScreen.js';
|
|
45
47
|
import { IsSystemUser } from './systemUser.js';
|
|
46
|
-
import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
|
|
48
|
+
import { CreateSnapshots, FieldsLackingStoredValue, FieldsWrittenWithoutStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots, } from './recordChangeSnapshot.js';
|
|
49
|
+
import { NodeAsyncServerOperationScopeTracker } from './NodeAsyncServerOperationScopeTracker.js';
|
|
50
|
+
// Install Node AsyncLocalStorage-backed authority scope tracker on server startup so concurrent
|
|
51
|
+
// in-flight requests / remote operations maintain isolated ServerOperationScopeFrame stacks.
|
|
52
|
+
ServerOperationScopeManager.Instance.SetTracker(new NodeAsyncServerOperationScopeTracker());
|
|
47
53
|
import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
|
|
48
54
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
49
55
|
/**
|
|
@@ -158,6 +164,20 @@ export function FormatSqlParameterTypesForError(parameters) {
|
|
|
158
164
|
export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
159
165
|
constructor() {
|
|
160
166
|
super(...arguments);
|
|
167
|
+
/**
|
|
168
|
+
* Server-side concurrency check mode for entity UPDATEs (`'off' | 'log' | 'enforce'`).
|
|
169
|
+
* Defaults to `'off'` so direct server-side background saves pay zero extra lock-read or
|
|
170
|
+
* transaction round-trips unless opted in via provider configuration or per-save
|
|
171
|
+
* `EntitySaveOptions.ConcurrencyCheck` (GraphQL mutations with `OldValues___` always pass `'enforce'`).
|
|
172
|
+
*/
|
|
173
|
+
this.ConcurrencyCheck = 'off';
|
|
174
|
+
/**
|
|
175
|
+
* Controls whether entity UPDATEs against CodeGen-generated routines (`spUpdateGenerated === true`)
|
|
176
|
+
* bind only dirty columns instead of every loaded column. Defaults to `true`. Set to `false`
|
|
177
|
+
* (or configure `databaseSettings.deltaUpdates: false`) as an operational kill-switch to restore
|
|
178
|
+
* legacy full-row parameter binding across all saves.
|
|
179
|
+
*/
|
|
180
|
+
this.DeltaUpdates = true;
|
|
161
181
|
/**
|
|
162
182
|
* Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
|
|
163
183
|
* and Dataset slots. Within this window after a slot was written or last verified against
|
|
@@ -325,7 +345,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
325
345
|
*/
|
|
326
346
|
get LocalStorageProvider() {
|
|
327
347
|
if (!this._localStorageProvider) {
|
|
328
|
-
this._localStorageProvider = new InMemoryLocalStorageProvider();
|
|
348
|
+
this._localStorageProvider = this.ConfigData?.LocalStorageProvider ?? new InMemoryLocalStorageProvider();
|
|
329
349
|
}
|
|
330
350
|
return this._localStorageProvider;
|
|
331
351
|
}
|
|
@@ -364,6 +384,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
364
384
|
if (data?.LocalStorageProvider) {
|
|
365
385
|
this.SetLocalStorageProvider(data.LocalStorageProvider);
|
|
366
386
|
}
|
|
387
|
+
if (data?.ConcurrencyCheck) {
|
|
388
|
+
this.ConcurrencyCheck = data.ConcurrencyCheck;
|
|
389
|
+
}
|
|
390
|
+
if (data?.DeltaUpdates !== undefined) {
|
|
391
|
+
this.DeltaUpdates = data.DeltaUpdates;
|
|
392
|
+
}
|
|
367
393
|
return super.Config(data, providerToUse);
|
|
368
394
|
}
|
|
369
395
|
/**
|
|
@@ -814,6 +840,166 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
814
840
|
: null;
|
|
815
841
|
return activeActions.some((a) => a.RunMode === 'Durable' && !originatingSet?.Has(a.ID));
|
|
816
842
|
}
|
|
843
|
+
/**
|
|
844
|
+
* Dialect hook for reading a row under an exclusive/update row lock inside the save transaction
|
|
845
|
+
* immediately before `spUpdate*` executes.
|
|
846
|
+
*
|
|
847
|
+
* - SQL Server overrides to emit `SELECT [col1], ... FROM [schema].[BaseTable] WITH (UPDLOCK, ROWLOCK) WHERE ...`
|
|
848
|
+
* - PostgreSQL overrides to emit `SELECT "col1", ... FROM "schema"."BaseTable" WHERE ... FOR UPDATE`
|
|
849
|
+
*/
|
|
850
|
+
RenderLockedRowReadSQL(_entityInfo, _pkWhereClause, _columns) {
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
getEffectiveConcurrencyCheckMode(options) {
|
|
854
|
+
return options?.ConcurrencyCheck ?? this.ConcurrencyCheck;
|
|
855
|
+
}
|
|
856
|
+
ShouldCheckUpdateConcurrency(entity, options) {
|
|
857
|
+
if (this.getEffectiveConcurrencyCheckMode(options) === 'off') {
|
|
858
|
+
return false;
|
|
859
|
+
}
|
|
860
|
+
if (options?.SkipOldValuesCheck || options?.IgnoreDirtyState || options?.ReplayOnly) {
|
|
861
|
+
return false;
|
|
862
|
+
}
|
|
863
|
+
if (!entity.PrimaryKey || entity.PrimaryKey.KeyValuePairs.length === 0) {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
if (options?.ConcurrencyBaseline) {
|
|
867
|
+
for (const [key, rawBaseline] of Object.entries(options.ConcurrencyBaseline)) {
|
|
868
|
+
const f = FindEntityFieldByCodeNameOrName(entity.EntityInfo, key);
|
|
869
|
+
if (!f || f.ReadOnly || f.IsVirtual || f.IsPrimaryKey || IsFieldOpaqueToClient(f)) {
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
872
|
+
const coercedBaseline = ClientOldValueToFieldValue(f, rawBaseline);
|
|
873
|
+
const currentVal = entity.GetFieldByName(f.Name)?.Value;
|
|
874
|
+
if (AreEntityFieldValuesDifferent(f, coercedBaseline, currentVal, false)) {
|
|
875
|
+
return true;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return entity.Fields.some((f) => f.Dirty &&
|
|
880
|
+
!f.EntityFieldInfo.ReadOnly &&
|
|
881
|
+
!f.EntityFieldInfo.IsVirtual &&
|
|
882
|
+
!f.EntityFieldInfo.IsPrimaryKey &&
|
|
883
|
+
!IsFieldOpaqueToClient(f.EntityFieldInfo));
|
|
884
|
+
}
|
|
885
|
+
async CheckUpdateConcurrency(entity, user, options, entityResult) {
|
|
886
|
+
if (!this.ShouldCheckUpdateConcurrency(entity, options)) {
|
|
887
|
+
return true;
|
|
888
|
+
}
|
|
889
|
+
const values = this.collectConcurrencyCheckValues(entity, options);
|
|
890
|
+
return this.runLockedConcurrencyCheck(entity, user, this.getEffectiveConcurrencyCheckMode(options), values, entityResult);
|
|
891
|
+
}
|
|
892
|
+
PrepareQueuedUpdateConcurrencyCheck(entity, user, options, entityResult) {
|
|
893
|
+
if (!this.ShouldCheckUpdateConcurrency(entity, options)) {
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
const values = this.collectConcurrencyCheckValues(entity, options);
|
|
897
|
+
if (Object.keys(values.baselineValues).length === 0) {
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
const mode = this.getEffectiveConcurrencyCheckMode(options);
|
|
901
|
+
return () => this.runLockedConcurrencyCheck(entity, user, mode, values, entityResult);
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Collects, for each field the save changes, the value the caller believes the database holds
|
|
905
|
+
* (the `ConcurrencyBaseline` entry when one is supplied, otherwise the field's `OldValue`) and the
|
|
906
|
+
* value the save writes.
|
|
907
|
+
*/
|
|
908
|
+
collectConcurrencyCheckValues(entity, options) {
|
|
909
|
+
const baselineValues = {};
|
|
910
|
+
const newValues = {};
|
|
911
|
+
if (options?.ConcurrencyBaseline) {
|
|
912
|
+
for (const [key, rawBaseline] of Object.entries(options.ConcurrencyBaseline)) {
|
|
913
|
+
const f = FindEntityFieldByCodeNameOrName(entity.EntityInfo, key);
|
|
914
|
+
if (!f || f.ReadOnly || f.IsVirtual || f.IsPrimaryKey || IsFieldOpaqueToClient(f)) {
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
const coercedBaseline = ClientOldValueToFieldValue(f, rawBaseline);
|
|
918
|
+
const entityField = entity.GetFieldByName(f.Name);
|
|
919
|
+
const currentVal = entityField ? entityField.Value : undefined;
|
|
920
|
+
if (AreEntityFieldValuesDifferent(f, coercedBaseline, currentVal, false)) {
|
|
921
|
+
baselineValues[f.Name] = coercedBaseline;
|
|
922
|
+
newValues[f.Name] = currentVal;
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
for (const entityField of entity.Fields) {
|
|
927
|
+
const f = entityField.EntityFieldInfo;
|
|
928
|
+
if (entityField.Dirty &&
|
|
929
|
+
!f.ReadOnly &&
|
|
930
|
+
!f.IsVirtual &&
|
|
931
|
+
!f.IsPrimaryKey &&
|
|
932
|
+
!IsFieldOpaqueToClient(f) &&
|
|
933
|
+
!(f.Name in baselineValues)) {
|
|
934
|
+
baselineValues[f.Name] = entityField.OldValue;
|
|
935
|
+
newValues[f.Name] = entityField.Value;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return { baselineValues, newValues };
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* Reads the stored values of the changed columns under a row lock held by the current
|
|
942
|
+
* transaction, and compares them with the caller's baseline. A conflict is logged; in
|
|
943
|
+
* `'enforce'` mode it also fails `entityResult` and returns `false`.
|
|
944
|
+
*/
|
|
945
|
+
async runLockedConcurrencyCheck(entity, user, effectiveMode, values, entityResult) {
|
|
946
|
+
const { baselineValues, newValues } = values;
|
|
947
|
+
const columnsToRead = Object.keys(baselineValues);
|
|
948
|
+
if (columnsToRead.length === 0) {
|
|
949
|
+
return true;
|
|
950
|
+
}
|
|
951
|
+
const pkWhereClause = this.BuildPrimaryKeyWhereClause(entity.EntityInfo, entity.PrimaryKey);
|
|
952
|
+
if (!pkWhereClause) {
|
|
953
|
+
return true;
|
|
954
|
+
}
|
|
955
|
+
const sql = this.RenderLockedRowReadSQL(entity.EntityInfo, pkWhereClause, columnsToRead);
|
|
956
|
+
if (!sql) {
|
|
957
|
+
return true;
|
|
958
|
+
}
|
|
959
|
+
const rawRows = await this.ExecuteSQL(sql, undefined, {
|
|
960
|
+
description: `Concurrency check lock read for ${entity.EntityInfo.Name}`,
|
|
961
|
+
ignoreLogging: true,
|
|
962
|
+
}, user);
|
|
963
|
+
if (!rawRows || rawRows.length === 0) {
|
|
964
|
+
return true;
|
|
965
|
+
}
|
|
966
|
+
const processedRows = await this.PostProcessRows(rawRows, entity.EntityInfo, user);
|
|
967
|
+
const storedRow = processedRows[0] ?? rawRows[0];
|
|
968
|
+
this.TrimFixedWidthValues(entity.EntityInfo, storedRow);
|
|
969
|
+
const checkResult = DetectFieldConcurrencyConflicts(entity.EntityInfo, baselineValues, newValues, storedRow);
|
|
970
|
+
if (checkResult.ConflictingFields.length === 0) {
|
|
971
|
+
return true;
|
|
972
|
+
}
|
|
973
|
+
const msg = {
|
|
974
|
+
Message: 'Concurrent modification conflict: one or more fields modified by the caller were updated in the database since the record was loaded.',
|
|
975
|
+
ClientDifferences: checkResult.ClientDifferences,
|
|
976
|
+
DBDifferences: checkResult.DBDifferences,
|
|
977
|
+
Overlap: checkResult.Overlap,
|
|
978
|
+
};
|
|
979
|
+
LogErrorEx({
|
|
980
|
+
message: `Entity save concurrency conflict detected on ${entity.EntityInfo.Name}: ${JSON.stringify(msg)}`,
|
|
981
|
+
severity: 'warning',
|
|
982
|
+
category: 'GenericDatabaseProvider.CheckUpdateConcurrency',
|
|
983
|
+
metadata: {
|
|
984
|
+
entityName: entity.EntityInfo.Name,
|
|
985
|
+
mode: effectiveMode,
|
|
986
|
+
conflictingFields: checkResult.ConflictingFields,
|
|
987
|
+
clientDifferences: checkResult.ClientDifferences,
|
|
988
|
+
dbDifferences: checkResult.DBDifferences,
|
|
989
|
+
overlap: checkResult.Overlap,
|
|
990
|
+
},
|
|
991
|
+
});
|
|
992
|
+
if (effectiveMode === 'enforce') {
|
|
993
|
+
entityResult.Success = false;
|
|
994
|
+
entityResult.EndedAt = new Date();
|
|
995
|
+
entityResult.ConcurrencyConflict = {
|
|
996
|
+
ConflictingFields: checkResult.ConflictingFields,
|
|
997
|
+
};
|
|
998
|
+
entityResult.Message = `Concurrent modification conflict on ${entity.EntityInfo.Name} for field(s): ${checkResult.ConflictingFields.join(', ')}. Reload the record and retry your changes.`;
|
|
999
|
+
return false;
|
|
1000
|
+
}
|
|
1001
|
+
return true;
|
|
1002
|
+
}
|
|
817
1003
|
async OnDurableAfterSaveExecute(entity, user, options, context) {
|
|
818
1004
|
if (options.SkipEntityActions === true) {
|
|
819
1005
|
return;
|
|
@@ -834,14 +1020,41 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
834
1020
|
// Build parallel post-save tasks — geocoding and ISA sibling propagation
|
|
835
1021
|
// are independent (write to RecordGeoCode and RecordChange respectively).
|
|
836
1022
|
let geoResult = null;
|
|
837
|
-
// Geocoding:
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
1023
|
+
// Geocoding: outside an ambient/group transaction, await inline so the SP result
|
|
1024
|
+
// can be patched immediately. Inside an open transaction, defer external HTTP
|
|
1025
|
+
// geocoding I/O via RunAfterCommit so exclusive SQL X-locks are never held across
|
|
1026
|
+
// network round-trips (and rolled-back saves never call external geocoding APIs).
|
|
1027
|
+
let geoPromise = null;
|
|
1028
|
+
if (context.State['geoSyncNeeded']) {
|
|
1029
|
+
if (this.IsCallerInAmbientTransaction()) {
|
|
1030
|
+
this.RunAfterCommit(async () => {
|
|
1031
|
+
const deferredGeo = await GeoCodeSyncService.Instance.SyncIfChanged(entity, user).catch(e => {
|
|
1032
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1033
|
+
LogError(`GenericDatabaseProvider: Geo sync failed for ${entity.EntityInfo.Name}: ${msg}`);
|
|
1034
|
+
return null;
|
|
1035
|
+
});
|
|
1036
|
+
if (deferredGeo) {
|
|
1037
|
+
const latField = entity.Fields.find(f => f.Name === '__mj_Latitude');
|
|
1038
|
+
if (latField) {
|
|
1039
|
+
latField.Value = deferredGeo.Latitude;
|
|
1040
|
+
latField.ResetOldValue();
|
|
1041
|
+
}
|
|
1042
|
+
const lngField = entity.Fields.find(f => f.Name === '__mj_Longitude');
|
|
1043
|
+
if (lngField) {
|
|
1044
|
+
lngField.Value = deferredGeo.Longitude;
|
|
1045
|
+
lngField.ResetOldValue();
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
}, `GeoCodeSyncService(${entity.EntityInfo.Name})`);
|
|
1049
|
+
}
|
|
1050
|
+
else {
|
|
1051
|
+
geoPromise = GeoCodeSyncService.Instance.SyncIfChanged(entity, user).catch(e => {
|
|
1052
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1053
|
+
LogError(`GenericDatabaseProvider: Geo sync failed for ${entity.EntityInfo.Name}: ${msg}`);
|
|
1054
|
+
return null;
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
845
1058
|
// ISA sibling record-change propagation — when saving an overlapping-subtype entity,
|
|
846
1059
|
// propagate the record change to sibling branches so their change history stays in sync.
|
|
847
1060
|
const overlappingChangeData = saveSQLResult.extraData?.overlappingChangeData;
|
|
@@ -905,7 +1118,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
905
1118
|
const rv = new RunView();
|
|
906
1119
|
const result = await rv.RunView({
|
|
907
1120
|
EntityName: 'MJ: Record Geo Codes',
|
|
908
|
-
ExtraFilter: `EntityID='${entity.EntityInfo.ID}' AND RecordID='${recordId}'`,
|
|
1121
|
+
ExtraFilter: `EntityID='${entity.EntityInfo.ID}' AND RecordID='${EscapeSQLString(recordId)}'`,
|
|
909
1122
|
ResultType: 'entity_object'
|
|
910
1123
|
}, contextUser);
|
|
911
1124
|
if (result.Success && result.Results.length > 0) {
|
|
@@ -1000,6 +1213,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1000
1213
|
ReportEncryptionKeyUnavailable(decryptError);
|
|
1001
1214
|
continue;
|
|
1002
1215
|
}
|
|
1216
|
+
// Inactive rows (e.g., disabled template credentials seeded before activation)
|
|
1217
|
+
// may hold placeholder ciphertext from another environment; preserve ciphertext without spamming error logs.
|
|
1218
|
+
if (processedRow['IsActive'] === false || processedRow['IsActive'] === 0) {
|
|
1219
|
+
continue;
|
|
1220
|
+
}
|
|
1003
1221
|
const message = decryptError instanceof Error ? decryptError.message : String(decryptError);
|
|
1004
1222
|
LogError(`Failed to decrypt field "${field.Name}" on entity "${entityInfo.Name}": ${message}. ` +
|
|
1005
1223
|
'The encrypted value will be returned unchanged.');
|
|
@@ -1231,6 +1449,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1231
1449
|
getDialect() {
|
|
1232
1450
|
return null;
|
|
1233
1451
|
}
|
|
1452
|
+
/**
|
|
1453
|
+
* The binder a RunView's row filter binds the user's values into (#5713), or null to keep them
|
|
1454
|
+
* literal. The default binds untyped named parameters with the dialect's placeholders (`$n` on
|
|
1455
|
+
* PostgreSQL); a provider with no dialect keeps literals. Providers override it to choose the
|
|
1456
|
+
* parameter type.
|
|
1457
|
+
*/
|
|
1458
|
+
CreateRowFilterParameterBinder() {
|
|
1459
|
+
const dialect = this.getDialect();
|
|
1460
|
+
if (!dialect) {
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
return new RowFilterParameterCollector((index, value) => {
|
|
1464
|
+
const placeholder = dialect.Binding.ParameterPlaceholder(index);
|
|
1465
|
+
return { Placeholder: placeholder, Parameter: new NamedQueryParameter(placeholder.startsWith('@') ? placeholder.slice(1) : placeholder, value) };
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Runs several statements that all reference the same `parameters` (one RunView's data, count
|
|
1470
|
+
* and aggregate statements share its WHERE, row-filter parameters included). The default runs
|
|
1471
|
+
* each with the full list; SQL Server overrides it to send one batch that declares them once.
|
|
1472
|
+
*/
|
|
1473
|
+
async ExecuteSQLBatchWithSharedParameters(queries, parameters, options, contextUser) {
|
|
1474
|
+
const execOptions = options ? {
|
|
1475
|
+
description: options.description,
|
|
1476
|
+
ignoreLogging: options.ignoreLogging,
|
|
1477
|
+
isMutation: options.isMutation,
|
|
1478
|
+
ignoreAmbientTransaction: options.ignoreAmbientTransaction,
|
|
1479
|
+
} : undefined;
|
|
1480
|
+
return Promise.all(queries.map(query => this.ExecuteSQL(query, parameters, execOptions, contextUser)));
|
|
1481
|
+
}
|
|
1234
1482
|
/**
|
|
1235
1483
|
* Detects infrastructure-level connection errors (timeout, refused, pool closed)
|
|
1236
1484
|
* as opposed to query-level errors (bad SQL, constraint violations).
|
|
@@ -1506,10 +1754,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1506
1754
|
dirtyFields.add(f);
|
|
1507
1755
|
}
|
|
1508
1756
|
}
|
|
1509
|
-
// 2.
|
|
1510
|
-
|
|
1511
|
-
//
|
|
1512
|
-
|
|
1757
|
+
// 2. On normal UPDATEs where DeltaUpdates is enabled, the entity's spUpdate is CodeGen-generated,
|
|
1758
|
+
// and at least one field is dirty, pass ONLY the dirty fields (plus the PK appended by
|
|
1759
|
+
// RenderSaveCallBinding) to the stored procedure / function so untouched columns default to NULL
|
|
1760
|
+
// and retain their stored database values via ISNULL(@Param, [Col]) / COALESCE(p_param, "Col").
|
|
1761
|
+
// Provider-wide DeltaUpdates=false, forced saves (IgnoreDirtyState), ReplayOnly saves, and
|
|
1762
|
+
// entities with custom spUpdate implementations keep the full-row parameter map.
|
|
1763
|
+
const useDeltaUpdate = this.DeltaUpdates &&
|
|
1764
|
+
isUpdate &&
|
|
1765
|
+
!options?.IgnoreDirtyState &&
|
|
1766
|
+
!options?.ReplayOnly &&
|
|
1767
|
+
entity.EntityInfo.spUpdateGenerated &&
|
|
1768
|
+
(dirtyFields?.size ?? 0) > 0;
|
|
1769
|
+
const effectiveFieldValueMap = useDeltaUpdate
|
|
1770
|
+
? this.changedFieldValues(entity, fieldValueMap, dirtyFields)
|
|
1771
|
+
: fieldValueMap;
|
|
1772
|
+
// 3. Encrypt — between coercion and rendering, mutates the map in place.
|
|
1773
|
+
await this.EncryptFieldValuesForSave(entity, effectiveFieldValueMap, user);
|
|
1774
|
+
// 4. Render the provider-specific binding.
|
|
1775
|
+
const binding = this.RenderSaveCallBinding(entity, effectiveFieldValueMap, isUpdate, spName);
|
|
1513
1776
|
// 4. Resolve SaveReturnContext and wrap with result capture.
|
|
1514
1777
|
// `unprojectedSaveSQL` is the bare SP/function call (kept for `simpleSQL` fallback so
|
|
1515
1778
|
// SQL logging / migration replay never gets polluted with runtime datestamp projection wrappers).
|
|
@@ -1538,10 +1801,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1538
1801
|
const computeSimpleSQL = () => {
|
|
1539
1802
|
if (cachedSimpleSQL === undefined) {
|
|
1540
1803
|
const replaySQL = isNew
|
|
1541
|
-
? this.RenderReplaySaveSQL(binding, entity,
|
|
1804
|
+
? this.RenderReplaySaveSQL(binding, entity, effectiveFieldValueMap)
|
|
1542
1805
|
: options?.IgnoreDirtyState
|
|
1543
1806
|
? undefined
|
|
1544
|
-
: this.RenderReplayUpdateSQL(binding, entity,
|
|
1807
|
+
: this.RenderReplayUpdateSQL(binding, entity, useDeltaUpdate
|
|
1808
|
+
? effectiveFieldValueMap
|
|
1809
|
+
: this.changedFieldValues(entity, effectiveFieldValueMap, dirtyFields));
|
|
1545
1810
|
// A statement that runs with parameters is logged in its literal form, which replays alone.
|
|
1546
1811
|
cachedSimpleSQL = replaySQL ?? unprojectedSaveSQL.literalSQL ?? unprojectedSaveSQL.sql;
|
|
1547
1812
|
}
|
|
@@ -1552,8 +1817,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1552
1817
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
1553
1818
|
// audit row for ITS writes only — the entity keeps TrackRecordChanges for everyone else.
|
|
1554
1819
|
if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
|
|
1555
|
-
const
|
|
1556
|
-
const
|
|
1820
|
+
const snapshotFromRow = this.BuildsFullRecordJSONFromResultRow(entity, returnContext);
|
|
1821
|
+
const { NewData: newData, OldData: oldData } = await this.BuildRecordChangeSnapshots(entity, isUpdate, user, snapshotFromRow);
|
|
1822
|
+
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext, snapshotFromRow);
|
|
1557
1823
|
if (payload) {
|
|
1558
1824
|
// ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
|
|
1559
1825
|
// for SS subtype propagation without running DiffObjects + JSON.stringify twice.
|
|
@@ -1587,6 +1853,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1587
1853
|
}
|
|
1588
1854
|
return result;
|
|
1589
1855
|
}
|
|
1856
|
+
/**
|
|
1857
|
+
* True when the dialect builds this save's Record Change `FullRecordJSON` in SQL from the row the
|
|
1858
|
+
* save returned, instead of serializing the payload's snapshot. That row is what the database
|
|
1859
|
+
* stored, including columns another writer changed after this object was loaded, so the snapshot
|
|
1860
|
+
* cannot go stale. The base implementation never does; a dialect that can overrides this and
|
|
1861
|
+
* renders the snapshot in `WrapSaveCallWithRecordChange` under the same conditions.
|
|
1862
|
+
*/
|
|
1863
|
+
BuildsFullRecordJSONFromResultRow(_entity, _returnContext) {
|
|
1864
|
+
return false;
|
|
1865
|
+
}
|
|
1590
1866
|
/**
|
|
1591
1867
|
* The old and new snapshots a save's Record Change is built from. The audit trail stores
|
|
1592
1868
|
* whole payloads and projects them per reader, so both snapshots describe the whole record
|
|
@@ -1601,17 +1877,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1601
1877
|
* - **Create**: there is no stored row yet. A field the INSERT omits because the user may
|
|
1602
1878
|
* not supply it is left out rather than recorded with a value the record never got.
|
|
1603
1879
|
*
|
|
1880
|
+
* With `snapshotFromRow` (see {@link BuildsFullRecordJSONFromResultRow}) the snapshots feed only
|
|
1881
|
+
* the diff, so a restricted user's update reads stored values only for the fields their object
|
|
1882
|
+
* wrote without having read them.
|
|
1883
|
+
*
|
|
1604
1884
|
* The read runs on the save's connection: inside an open transaction it reads that
|
|
1605
1885
|
* transaction's state. A save queued in a transaction group is generated when `Save()` is
|
|
1606
1886
|
* called, so its snapshot reflects the row as of then — the same moment the object's own
|
|
1607
1887
|
* old values describe.
|
|
1608
1888
|
*/
|
|
1609
|
-
async BuildRecordChangeSnapshots(entity, isUpdate, user) {
|
|
1889
|
+
async BuildRecordChangeSnapshots(entity, isUpdate, user, snapshotFromRow = false) {
|
|
1610
1890
|
if (!isUpdate) {
|
|
1611
1891
|
return CreateSnapshots(entity);
|
|
1612
1892
|
}
|
|
1613
1893
|
const narrow = { NewData: entity.GetAll(false), OldData: entity.GetAll(true) };
|
|
1614
|
-
|
|
1894
|
+
// When the dialect builds FullRecordJSON from the returned row, the snapshots feed only the
|
|
1895
|
+
// diff, which needs a stored value only for a field the object wrote without having read it.
|
|
1896
|
+
const allLacking = FieldsLackingStoredValue(entity, user);
|
|
1897
|
+
const lacking = snapshotFromRow ? FieldsWrittenWithoutStoredValue(entity, allLacking) : allLacking;
|
|
1615
1898
|
if (lacking.size === 0) {
|
|
1616
1899
|
return narrow;
|
|
1617
1900
|
}
|
|
@@ -1748,11 +2031,307 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1748
2031
|
* `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
|
|
1749
2032
|
* Server — both preserve case.
|
|
1750
2033
|
*/
|
|
1751
|
-
|
|
2034
|
+
/**
|
|
2035
|
+
* Determines whether a count query can be safely executed against the entity's physical
|
|
2036
|
+
* `BaseTable` instead of the generated `BaseView`.
|
|
2037
|
+
*
|
|
2038
|
+
* Generated `BaseView`s only `LEFT OUTER JOIN` related lookup tables on single-row primary
|
|
2039
|
+
* keys and do not alter row cardinality. When 100% of columns referenced in `whereSQL`
|
|
2040
|
+
* are physical non-virtual columns on `BaseTable`, counting directly from `BaseTable`
|
|
2041
|
+
* bypasses expensive joins, outer applies, and view expansion while returning identical counts.
|
|
2042
|
+
*/
|
|
2043
|
+
CanCountFromBaseTable(entityInfo, whereSQL) {
|
|
2044
|
+
if (!entityInfo) {
|
|
2045
|
+
return false;
|
|
2046
|
+
}
|
|
2047
|
+
// 1) BaseView must be generated by CodeGen (hand-written custom views may filter rows)
|
|
2048
|
+
if (entityInfo.BaseViewGenerated !== true) {
|
|
2049
|
+
return false;
|
|
2050
|
+
}
|
|
2051
|
+
// 2) Must have a physical BaseTable and not be a virtual entity
|
|
2052
|
+
if (entityInfo.VirtualEntity || !entityInfo.BaseTable) {
|
|
2053
|
+
return false;
|
|
2054
|
+
}
|
|
2055
|
+
// 3) IS-A child entities join parent tables and inherit columns — never rewrite IS-A child entities
|
|
2056
|
+
if (entityInfo.IsChildType || Boolean(entityInfo.ParentID) || Boolean(entityInfo.ParentEntityInfo)) {
|
|
2057
|
+
return false;
|
|
2058
|
+
}
|
|
2059
|
+
// 4) Layered base views have an application-owned outer view that might filter rows
|
|
2060
|
+
if (entityInfo.HasLayeredBaseView) {
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
// 5) Soft-delete entities have `WHERE [DeletedAt] IS NULL` in the view; base table contains deleted rows
|
|
2064
|
+
if (entityInfo.DeleteType === 'Soft') {
|
|
2065
|
+
return false;
|
|
2066
|
+
}
|
|
2067
|
+
const trimmed = (whereSQL ?? '').trim();
|
|
2068
|
+
if (!trimmed) {
|
|
2069
|
+
return true;
|
|
2070
|
+
}
|
|
2071
|
+
if (!entityInfo.Fields || entityInfo.Fields.length === 0) {
|
|
2072
|
+
return false;
|
|
2073
|
+
}
|
|
2074
|
+
const tokens = GenericDatabaseProvider.extractWhereTokens(trimmed);
|
|
2075
|
+
if (tokens === null) {
|
|
2076
|
+
return false;
|
|
2077
|
+
}
|
|
2078
|
+
const physicalColumns = new Set(entityInfo.Fields
|
|
2079
|
+
.filter(f => !f.IsVirtual)
|
|
2080
|
+
.map(f => f.Name.toLowerCase()));
|
|
2081
|
+
const virtualColumns = new Set(entityInfo.Fields
|
|
2082
|
+
.filter(f => f.IsVirtual)
|
|
2083
|
+
.map(f => f.Name.toLowerCase()));
|
|
2084
|
+
const schemaLower = (entityInfo.SchemaName ?? '').trim().toLowerCase();
|
|
2085
|
+
const baseTableLower = entityInfo.BaseTable.trim().toLowerCase();
|
|
2086
|
+
const baseViewLower = (entityInfo.BaseView ?? '').trim().toLowerCase();
|
|
2087
|
+
let parenDepth = 0;
|
|
2088
|
+
const subqueryStartDepths = [];
|
|
2089
|
+
for (let idx = 0; idx < tokens.length; idx++) {
|
|
2090
|
+
const t = tokens[idx];
|
|
2091
|
+
if (t.kind === 'lparen') {
|
|
2092
|
+
parenDepth++;
|
|
2093
|
+
const next = tokens[idx + 1];
|
|
2094
|
+
if (next && next.kind === 'ident' && (next.value === 'select' || next.value === 'with')) {
|
|
2095
|
+
subqueryStartDepths.push(parenDepth);
|
|
2096
|
+
}
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
if (t.kind === 'rparen') {
|
|
2100
|
+
if (parenDepth === 0) {
|
|
2101
|
+
return false;
|
|
2102
|
+
}
|
|
2103
|
+
if (subqueryStartDepths.length > 0 && subqueryStartDepths[subqueryStartDepths.length - 1] === parenDepth) {
|
|
2104
|
+
subqueryStartDepths.pop();
|
|
2105
|
+
}
|
|
2106
|
+
parenDepth--;
|
|
2107
|
+
continue;
|
|
2108
|
+
}
|
|
2109
|
+
if (t.kind !== 'ident' && t.kind !== 'quoted') {
|
|
2110
|
+
continue;
|
|
2111
|
+
}
|
|
2112
|
+
const inSubquery = subqueryStartDepths.length > 0;
|
|
2113
|
+
const prev = tokens[idx - 1];
|
|
2114
|
+
const next = tokens[idx + 1];
|
|
2115
|
+
const isAfterDot = prev?.kind === 'dot';
|
|
2116
|
+
const isBeforeDot = next?.kind === 'dot';
|
|
2117
|
+
if (inSubquery) {
|
|
2118
|
+
if (baseViewLower && t.value === baseViewLower) {
|
|
2119
|
+
return false;
|
|
2120
|
+
}
|
|
2121
|
+
if (!isAfterDot && !isBeforeDot && next?.kind !== 'lparen' &&
|
|
2122
|
+
virtualColumns.has(t.value) && !physicalColumns.has(t.value)) {
|
|
2123
|
+
return false;
|
|
2124
|
+
}
|
|
2125
|
+
continue;
|
|
2126
|
+
}
|
|
2127
|
+
// Outer WHERE level: forbid joins/set-ops/bare SELECT; allow EXISTS (SELECT ...)
|
|
2128
|
+
if (t.kind === 'ident') {
|
|
2129
|
+
if (t.value === 'exists') {
|
|
2130
|
+
const afterParen = tokens[idx + 2];
|
|
2131
|
+
if (next?.kind === 'lparen' && afterParen?.kind === 'ident' &&
|
|
2132
|
+
(afterParen.value === 'select' || afterParen.value === 'with')) {
|
|
2133
|
+
continue;
|
|
2134
|
+
}
|
|
2135
|
+
return false;
|
|
2136
|
+
}
|
|
2137
|
+
if (GenericDatabaseProvider._forbiddenCountKeywords.has(t.value)) {
|
|
2138
|
+
return false;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
if (isBeforeDot) {
|
|
2142
|
+
const isBaseTableQualifier = t.value === baseTableLower;
|
|
2143
|
+
const isSchemaForBaseTable = Boolean(schemaLower) && t.value === schemaLower &&
|
|
2144
|
+
(tokens[idx + 2]?.kind === 'ident' || tokens[idx + 2]?.kind === 'quoted') &&
|
|
2145
|
+
tokens[idx + 2].value === baseTableLower;
|
|
2146
|
+
if (!isBaseTableQualifier && !isSchemaForBaseTable) {
|
|
2147
|
+
return false;
|
|
2148
|
+
}
|
|
2149
|
+
continue;
|
|
2150
|
+
}
|
|
2151
|
+
if (isAfterDot) {
|
|
2152
|
+
if (t.value !== baseTableLower && !physicalColumns.has(t.value)) {
|
|
2153
|
+
return false;
|
|
2154
|
+
}
|
|
2155
|
+
continue;
|
|
2156
|
+
}
|
|
2157
|
+
if (t.kind === 'ident' && GenericDatabaseProvider._allowedCountKeywords.has(t.value)) {
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
if (!physicalColumns.has(t.value)) {
|
|
2161
|
+
return false;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
return parenDepth === 0;
|
|
2165
|
+
}
|
|
2166
|
+
static { this._forbiddenCountKeywords = new Set([
|
|
2167
|
+
'select', 'from', 'join', 'exists', 'apply', 'with', 'union', 'intersect', 'except',
|
|
2168
|
+
]); }
|
|
2169
|
+
static { this._allowedCountKeywords = new Set([
|
|
2170
|
+
'and', 'or', 'not', 'is', 'null', 'in', 'between', 'like', 'ilike', 'escape',
|
|
2171
|
+
'true', 'false', 'asc', 'desc', 'cast', 'convert', 'coalesce', 'isnull', 'nullif',
|
|
2172
|
+
'lower', 'upper', 'ltrim', 'rtrim', 'trim', 'len', 'length',
|
|
2173
|
+
'getdate', 'getutcdate', 'sysdatetime', 'sysutcdatetime', 'now', 'current_timestamp', 'current_date',
|
|
2174
|
+
'dateadd', 'datediff', 'year', 'month', 'day', 'hour', 'minute', 'second',
|
|
2175
|
+
'at', 'time', 'zone', 'interval', 'extract', 'date_trunc', 'date_part', 'epoch',
|
|
2176
|
+
'as', 'case', 'when', 'then', 'else', 'end', 'where',
|
|
2177
|
+
'int', 'integer', 'bigint', 'smallint', 'tinyint',
|
|
2178
|
+
'varchar', 'nvarchar', 'char', 'nchar', 'text',
|
|
2179
|
+
'date', 'time', 'datetime', 'datetime2', 'datetimeoffset', 'timestamptz', 'decimal', 'numeric',
|
|
2180
|
+
'float', 'real', 'bit', 'boolean', 'uuid', 'uniqueidentifier', 'max',
|
|
2181
|
+
]); }
|
|
2182
|
+
/**
|
|
2183
|
+
* Linear O(N) character scanner (zero regexes — immune to ReDoS) that strips single-quoted
|
|
2184
|
+
* SQL string literals and `@p` / `$n` parameter placeholders, tokenizes bracketed `[Col]`,
|
|
2185
|
+
* double-quoted `"Col"`, bare identifiers, parentheses, and dots, and returns `null` if an
|
|
2186
|
+
* unclosed quote/bracket or comment token (`--`, `/*`) is encountered.
|
|
2187
|
+
*/
|
|
2188
|
+
static extractWhereTokens(sql) {
|
|
2189
|
+
const tokens = [];
|
|
2190
|
+
const len = sql.length;
|
|
2191
|
+
let i = 0;
|
|
2192
|
+
const isIdentStart = (ch) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch === 95;
|
|
2193
|
+
const isIdentPart = (ch) => isIdentStart(ch) || (ch >= 48 && ch <= 57);
|
|
2194
|
+
const isDigit = (ch) => ch >= 48 && ch <= 57;
|
|
2195
|
+
while (i < len) {
|
|
2196
|
+
const code = sql.charCodeAt(i);
|
|
2197
|
+
// Reject SQL line/block comments conservatively
|
|
2198
|
+
if ((code === 45 && i + 1 < len && sql.charCodeAt(i + 1) === 45) ||
|
|
2199
|
+
(code === 47 && i + 1 < len && sql.charCodeAt(i + 1) === 42)) {
|
|
2200
|
+
return null;
|
|
2201
|
+
}
|
|
2202
|
+
// N'...' national string literal prefix
|
|
2203
|
+
if ((code === 78 || code === 110) && i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2204
|
+
i += 2;
|
|
2205
|
+
let closed = false;
|
|
2206
|
+
while (i < len) {
|
|
2207
|
+
if (sql.charCodeAt(i) === 39) {
|
|
2208
|
+
if (i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2209
|
+
i += 2;
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
i++;
|
|
2213
|
+
closed = true;
|
|
2214
|
+
break;
|
|
2215
|
+
}
|
|
2216
|
+
i++;
|
|
2217
|
+
}
|
|
2218
|
+
if (!closed)
|
|
2219
|
+
return null;
|
|
2220
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2221
|
+
continue;
|
|
2222
|
+
}
|
|
2223
|
+
// '...' single-quoted string literal
|
|
2224
|
+
if (code === 39) {
|
|
2225
|
+
i++;
|
|
2226
|
+
let closed = false;
|
|
2227
|
+
while (i < len) {
|
|
2228
|
+
if (sql.charCodeAt(i) === 39) {
|
|
2229
|
+
if (i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2230
|
+
i += 2;
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
i++;
|
|
2234
|
+
closed = true;
|
|
2235
|
+
break;
|
|
2236
|
+
}
|
|
2237
|
+
i++;
|
|
2238
|
+
}
|
|
2239
|
+
if (!closed)
|
|
2240
|
+
return null;
|
|
2241
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2242
|
+
continue;
|
|
2243
|
+
}
|
|
2244
|
+
// @param token
|
|
2245
|
+
if (code === 64) {
|
|
2246
|
+
i++;
|
|
2247
|
+
while (i < len && isIdentPart(sql.charCodeAt(i))) {
|
|
2248
|
+
i++;
|
|
2249
|
+
}
|
|
2250
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2251
|
+
continue;
|
|
2252
|
+
}
|
|
2253
|
+
// $1 positional parameter token
|
|
2254
|
+
if (code === 36 && i + 1 < len && isDigit(sql.charCodeAt(i + 1))) {
|
|
2255
|
+
i += 2;
|
|
2256
|
+
while (i < len && isDigit(sql.charCodeAt(i))) {
|
|
2257
|
+
i++;
|
|
2258
|
+
}
|
|
2259
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2260
|
+
continue;
|
|
2261
|
+
}
|
|
2262
|
+
// [Identifier] bracketed column
|
|
2263
|
+
if (code === 91) {
|
|
2264
|
+
const start = i + 1;
|
|
2265
|
+
const end = sql.indexOf(']', start);
|
|
2266
|
+
if (end === -1)
|
|
2267
|
+
return null;
|
|
2268
|
+
const ident = sql.slice(start, end).trim().toLowerCase();
|
|
2269
|
+
if (ident.length > 0) {
|
|
2270
|
+
tokens.push({ kind: 'quoted', value: ident });
|
|
2271
|
+
}
|
|
2272
|
+
i = end + 1;
|
|
2273
|
+
continue;
|
|
2274
|
+
}
|
|
2275
|
+
// "Identifier" double-quoted column
|
|
2276
|
+
if (code === 34) {
|
|
2277
|
+
const start = i + 1;
|
|
2278
|
+
const end = sql.indexOf('"', start);
|
|
2279
|
+
if (end === -1)
|
|
2280
|
+
return null;
|
|
2281
|
+
const ident = sql.slice(start, end).trim().toLowerCase();
|
|
2282
|
+
if (ident.length > 0) {
|
|
2283
|
+
tokens.push({ kind: 'quoted', value: ident });
|
|
2284
|
+
}
|
|
2285
|
+
i = end + 1;
|
|
2286
|
+
continue;
|
|
2287
|
+
}
|
|
2288
|
+
// Numeric literal (skip digits so e.g. 1e5 isn't treated as identifier e5)
|
|
2289
|
+
if (isDigit(code)) {
|
|
2290
|
+
i++;
|
|
2291
|
+
while (i < len && (isIdentPart(sql.charCodeAt(i)) || sql.charCodeAt(i) === 46)) {
|
|
2292
|
+
i++;
|
|
2293
|
+
}
|
|
2294
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
// Bare identifier or keyword
|
|
2298
|
+
if (isIdentStart(code)) {
|
|
2299
|
+
const start = i;
|
|
2300
|
+
i++;
|
|
2301
|
+
while (i < len && isIdentPart(sql.charCodeAt(i))) {
|
|
2302
|
+
i++;
|
|
2303
|
+
}
|
|
2304
|
+
tokens.push({ kind: 'ident', value: sql.slice(start, i).toLowerCase() });
|
|
2305
|
+
continue;
|
|
2306
|
+
}
|
|
2307
|
+
if (code === 40) {
|
|
2308
|
+
tokens.push({ kind: 'lparen', value: '(' });
|
|
2309
|
+
}
|
|
2310
|
+
else if (code === 41) {
|
|
2311
|
+
tokens.push({ kind: 'rparen', value: ')' });
|
|
2312
|
+
}
|
|
2313
|
+
else if (code === 46) {
|
|
2314
|
+
tokens.push({ kind: 'dot', value: '.' });
|
|
2315
|
+
}
|
|
2316
|
+
else if (code > 32) {
|
|
2317
|
+
tokens.push({ kind: 'other', value: sql[i] });
|
|
2318
|
+
}
|
|
2319
|
+
i++;
|
|
2320
|
+
}
|
|
2321
|
+
return tokens;
|
|
2322
|
+
}
|
|
2323
|
+
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride, schemaNameOverride, whereSQL) {
|
|
1752
2324
|
const rowsAreLimited = usingPagination || maxRowsForQuery > 0;
|
|
1753
2325
|
if (!rowsAreLimited)
|
|
1754
2326
|
return null;
|
|
1755
|
-
|
|
2327
|
+
const effectiveBaseView = baseViewOverride ?? entityInfo.BaseView;
|
|
2328
|
+
const effectiveSchema = schemaNameOverride ?? entityInfo.SchemaName;
|
|
2329
|
+
const isStandardBaseView = !baseViewOverride ||
|
|
2330
|
+
(entityInfo.BaseView && baseViewOverride.trim().toLowerCase() === entityInfo.BaseView.trim().toLowerCase());
|
|
2331
|
+
const target = (isStandardBaseView && this.CanCountFromBaseTable(entityInfo, whereSQL ?? ''))
|
|
2332
|
+
? this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseTable)
|
|
2333
|
+
: this.QuoteSchemaAndView(effectiveSchema, effectiveBaseView);
|
|
2334
|
+
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${target}`;
|
|
1756
2335
|
}
|
|
1757
2336
|
/**
|
|
1758
2337
|
* Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
|
|
@@ -2053,36 +2632,184 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2053
2632
|
}
|
|
2054
2633
|
}
|
|
2055
2634
|
/**
|
|
2056
|
-
*
|
|
2057
|
-
*
|
|
2058
|
-
*
|
|
2059
|
-
*
|
|
2060
|
-
*
|
|
2061
|
-
*
|
|
2635
|
+
* Rewrites `@paramName` placeholders in `extraFilter` into dialect-specific bound parameter
|
|
2636
|
+
* placeholders (`@p0` on SQL Server, `$1` on PostgreSQL) using token-level lexing (`SqlTokens.Lex`)
|
|
2637
|
+
* and non-overlapping span edits (`EditSet`), and appends the corresponding {@link NamedQueryParameter}
|
|
2638
|
+
* entries to `queryParameters`.
|
|
2639
|
+
*
|
|
2640
|
+
* Token-level lexing ensures `@foo` inside string literals (`'...@foo...'`), SQL comments (`/* @foo *\/`,
|
|
2641
|
+
* `-- @foo`), quoted identifiers (`[@foo]`, `"@foo"`), and system variables (`@@ROWCOUNT`) are never
|
|
2642
|
+
* mistaken for parameter references.
|
|
2643
|
+
*/
|
|
2644
|
+
BindExtraFilterParameters(extraFilter, parameters, queryParameters) {
|
|
2645
|
+
const normalizedParams = NormalizeRunViewParameters(parameters);
|
|
2646
|
+
if (!extraFilter) {
|
|
2647
|
+
return '';
|
|
2648
|
+
}
|
|
2649
|
+
const lexed = SqlTokens.Lex(extraFilter, this.Dialect);
|
|
2650
|
+
const tokens = lexed.Tokens;
|
|
2651
|
+
let edits = EditSet.For(extraFilter);
|
|
2652
|
+
const boundPlaceholdersByParam = new Map();
|
|
2653
|
+
const targetParams = queryParameters ?? [];
|
|
2654
|
+
const bindScalar = (paramName, scalar) => {
|
|
2655
|
+
if (scalar === null || typeof scalar === 'string') {
|
|
2656
|
+
const index = targetParams.length;
|
|
2657
|
+
const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
|
|
2658
|
+
const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
2659
|
+
targetParams.push(new NamedQueryParameter(driverName, scalar));
|
|
2660
|
+
return placeholder;
|
|
2661
|
+
}
|
|
2662
|
+
if (typeof scalar === 'boolean') {
|
|
2663
|
+
const index = targetParams.length;
|
|
2664
|
+
const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
|
|
2665
|
+
const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
2666
|
+
const boundBool = this.Dialect.Binding.BooleanParameterValue(scalar);
|
|
2667
|
+
targetParams.push(new NamedQueryParameter(driverName, boundBool));
|
|
2668
|
+
return placeholder;
|
|
2669
|
+
}
|
|
2670
|
+
if (typeof scalar === 'number') {
|
|
2671
|
+
if (!Number.isFinite(scalar)) {
|
|
2672
|
+
throw new Error(`Invalid RunView parameter '@${paramName}': numeric parameter values must be finite numbers.`);
|
|
2673
|
+
}
|
|
2674
|
+
const index = targetParams.length;
|
|
2675
|
+
const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
|
|
2676
|
+
const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
2677
|
+
targetParams.push(new NamedQueryParameter(driverName, scalar));
|
|
2678
|
+
return placeholder;
|
|
2679
|
+
}
|
|
2680
|
+
if (scalar instanceof Date) {
|
|
2681
|
+
if (Number.isNaN(scalar.getTime())) {
|
|
2682
|
+
throw new Error(`Invalid RunView parameter '@${paramName}': Date parameter value is invalid.`);
|
|
2683
|
+
}
|
|
2684
|
+
const index = targetParams.length;
|
|
2685
|
+
const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
|
|
2686
|
+
const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
2687
|
+
targetParams.push(new NamedQueryParameter(driverName, scalar));
|
|
2688
|
+
return placeholder;
|
|
2689
|
+
}
|
|
2690
|
+
throw new Error(`Invalid RunView parameter '@${paramName}': unsupported value type '${typeof scalar}'.`);
|
|
2691
|
+
};
|
|
2692
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
2693
|
+
const token = tokens[i];
|
|
2694
|
+
if (token.Kind !== 'Word')
|
|
2695
|
+
continue;
|
|
2696
|
+
// On dialects that don't natively quote with `[...]` (e.g. PostgreSQL before TransformExternalSQLClause
|
|
2697
|
+
// rewrites `[col]` to `"col"`), `[@col]` is lexed as `[` + Word(`@col`) + `]`. Skip bracketed identifiers.
|
|
2698
|
+
const prev = tokens[i - 1];
|
|
2699
|
+
const next = tokens[i + 1];
|
|
2700
|
+
if (prev?.Text === '[' && prev.Span.End === token.Span.Start && next?.Text === ']' && next.Span.Start === token.Span.End) {
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
const match = /^@([A-Za-z_][A-Za-z0-9_]*)$/.exec(token.Text);
|
|
2704
|
+
if (!match)
|
|
2705
|
+
continue;
|
|
2706
|
+
const paramName = match[1];
|
|
2707
|
+
if (!normalizedParams.has(paramName)) {
|
|
2708
|
+
throw new Error(`RunView ExtraFilter references parameter '@${paramName}', but no value was provided in RunViewParams.Parameters.`);
|
|
2709
|
+
}
|
|
2710
|
+
let replacement = boundPlaceholdersByParam.get(paramName);
|
|
2711
|
+
if (replacement === undefined) {
|
|
2712
|
+
const rawValue = normalizedParams.get(paramName);
|
|
2713
|
+
if (Array.isArray(rawValue)) {
|
|
2714
|
+
if (rawValue.length === 0) {
|
|
2715
|
+
throw new Error(`RunView parameter '@${paramName}' cannot be an empty array.`);
|
|
2716
|
+
}
|
|
2717
|
+
const itemPlaceholders = rawValue.map((item) => bindScalar(paramName, item));
|
|
2718
|
+
replacement = itemPlaceholders.join(', ');
|
|
2719
|
+
}
|
|
2720
|
+
else {
|
|
2721
|
+
replacement = bindScalar(paramName, rawValue);
|
|
2722
|
+
}
|
|
2723
|
+
boundPlaceholdersByParam.set(paramName, replacement);
|
|
2724
|
+
}
|
|
2725
|
+
edits = edits.Replace(token.Span, replacement);
|
|
2726
|
+
}
|
|
2727
|
+
return edits.IsEmpty ? extraFilter : edits.Apply().Text;
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* Rewrites `@paramName` word tokens to `@replacementName` using dialect-aware token lexing
|
|
2731
|
+
* (`SqlTokens.Lex`) and non-overlapping span edits (`EditSet`), so `@paramName` inside string
|
|
2732
|
+
* literals, quoted/bracketed identifiers, line/nested block comments, and `@@system` variables
|
|
2733
|
+
* is never modified.
|
|
2062
2734
|
*/
|
|
2063
|
-
|
|
2064
|
-
if (!
|
|
2735
|
+
static RewriteSqlParameterReferences(sqlText, paramName, replacementName, dialect) {
|
|
2736
|
+
if (!sqlText) {
|
|
2737
|
+
return sqlText;
|
|
2738
|
+
}
|
|
2739
|
+
const targetToken = `@${paramName}`;
|
|
2740
|
+
const replacementToken = `@${replacementName}`;
|
|
2741
|
+
const lexed = SqlTokens.Lex(sqlText, dialect);
|
|
2742
|
+
let edits = EditSet.For(sqlText);
|
|
2743
|
+
for (const token of lexed.Tokens) {
|
|
2744
|
+
if (token.Kind === 'Word' && token.Text === targetToken) {
|
|
2745
|
+
edits = edits.Replace(token.Span, replacementToken);
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
return edits.IsEmpty ? sqlText : edits.Apply().Text;
|
|
2749
|
+
}
|
|
2750
|
+
/**
|
|
2751
|
+
* Applies {@link BindExtraFilterParameters} and {@link TransformExternalSQLClause} to a caller's
|
|
2752
|
+
* ExtraFilter and checks the result with {@link AssertClauseBalanced}. When the transform changes
|
|
2753
|
+
* the text and the filter is a chain of top-level AND terms, each term is transformed, checked
|
|
2754
|
+
* and parenthesized on its own. A PreRunView hook that ANDs a server predicate (such as tenant
|
|
2755
|
+
* scope) onto the caller's filter runs before this transform, so a rewrite that changes the
|
|
2756
|
+
* caller's term cannot reach the hook's term.
|
|
2757
|
+
*/
|
|
2758
|
+
PrepareExtraFilterSQL(extraFilter, entityInfo, parameters, queryParameters) {
|
|
2759
|
+
const targetParams = queryParameters ?? [];
|
|
2760
|
+
if (!extraFilter) {
|
|
2761
|
+
this.BindExtraFilterParameters(extraFilter, parameters, targetParams);
|
|
2065
2762
|
return '';
|
|
2066
|
-
|
|
2067
|
-
|
|
2763
|
+
}
|
|
2764
|
+
this.AssertClauseBalanced(extraFilter, 'ExtraFilter');
|
|
2765
|
+
const priorParamCount = targetParams.length;
|
|
2766
|
+
const boundFilter = this.BindExtraFilterParameters(extraFilter, parameters, targetParams);
|
|
2767
|
+
if (!boundFilter)
|
|
2768
|
+
return '';
|
|
2769
|
+
const allowedPlaceholders = new Set();
|
|
2770
|
+
for (let i = priorParamCount; i < targetParams.length; i++) {
|
|
2771
|
+
allowedPlaceholders.add(this.Dialect.Binding.ParameterPlaceholder(i));
|
|
2772
|
+
}
|
|
2773
|
+
const balanceOptions = allowedPlaceholders.size > 0 ? { AllowedParameterPlaceholders: allowedPlaceholders } : undefined;
|
|
2774
|
+
const transformed = this.TransformExternalSQLClause(boundFilter, entityInfo);
|
|
2775
|
+
const terms = transformed === boundFilter ? null : SplitTopLevelAndTerms(boundFilter, this.Dialect);
|
|
2068
2776
|
if (!terms || terms.length < 2) {
|
|
2069
|
-
this.AssertClauseBalanced(transformed, 'ExtraFilter');
|
|
2777
|
+
this.AssertClauseBalanced(transformed, 'ExtraFilter', balanceOptions);
|
|
2070
2778
|
return transformed;
|
|
2071
2779
|
}
|
|
2072
2780
|
return terms
|
|
2073
2781
|
.map((term) => {
|
|
2074
2782
|
const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
|
|
2075
|
-
this.AssertClauseBalanced(termSQL, 'ExtraFilter');
|
|
2783
|
+
this.AssertClauseBalanced(termSQL, 'ExtraFilter', balanceOptions);
|
|
2076
2784
|
return `(${termSQL})`;
|
|
2077
2785
|
})
|
|
2078
2786
|
.join(' AND ');
|
|
2079
2787
|
}
|
|
2788
|
+
/**
|
|
2789
|
+
* Compiles `params.Filter` (a structured `CompositeFilter` / `CompositeFilterDescriptor`) into a
|
|
2790
|
+
* parameterized SQL WHERE fragment for `entityInfo` using {@link CompositeFilterSQLCompiler.Compile}
|
|
2791
|
+
* and binds its parameters onto `queryParameters` via {@link BindExtraFilterParameters}.
|
|
2792
|
+
*/
|
|
2793
|
+
CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters) {
|
|
2794
|
+
if (!params.Filter) {
|
|
2795
|
+
return '';
|
|
2796
|
+
}
|
|
2797
|
+
const compiled = CompositeFilterSQLCompiler.Compile(params.Filter, entityInfo, {
|
|
2798
|
+
platform: this.PlatformKey,
|
|
2799
|
+
user,
|
|
2800
|
+
parameterPrefix: '_cf_',
|
|
2801
|
+
});
|
|
2802
|
+
if (!compiled.whereClause) {
|
|
2803
|
+
return '';
|
|
2804
|
+
}
|
|
2805
|
+
return this.BindExtraFilterParameters(compiled.whereClause, compiled.parameters, queryParameters);
|
|
2806
|
+
}
|
|
2080
2807
|
/**
|
|
2081
2808
|
* Optionally wraps a view query with user view run logging.
|
|
2082
2809
|
* SQL Server overrides to use spCreateUserViewRunWithDetail.
|
|
2083
2810
|
* Default: returns null (no view run logging).
|
|
2084
2811
|
*/
|
|
2085
|
-
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride) {
|
|
2812
|
+
async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride, _queryParameters) {
|
|
2086
2813
|
return null;
|
|
2087
2814
|
}
|
|
2088
2815
|
/**
|
|
@@ -2291,9 +3018,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2291
3018
|
entityInfo = this.EntityByID(viewEntity.EntityID) ?? null;
|
|
2292
3019
|
if (!entityInfo)
|
|
2293
3020
|
throw new Error(`Entity ID: ${viewEntity.EntityID} not found in metadata`);
|
|
3021
|
+
if (typeof params.EntityName === 'string' && params.EntityName.trim().length > 0) {
|
|
3022
|
+
const requestedEntity = this.EntityByName(params.EntityName.trim());
|
|
3023
|
+
if (!requestedEntity || !UUIDsEqual(requestedEntity.ID, entityInfo.ID)) {
|
|
3024
|
+
throw new Error(`EntityName '${params.EntityName}' does not match view '${viewEntity.Name ?? viewEntity.ID}' target entity '${entityInfo.Name}'.`);
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
2294
3027
|
}
|
|
2295
3028
|
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2296
3029
|
resolvedEntity = entityInfo;
|
|
3030
|
+
if (params.Aggregates &&
|
|
3031
|
+
params.Aggregates.length > 0 &&
|
|
3032
|
+
this.IsPostRunViewProtectedEntity(entityInfo.Name) &&
|
|
3033
|
+
!this.isSystemCaller(user)) {
|
|
3034
|
+
throw new Error(`Access denied: aggregate queries are not allowed on PostRunView-protected entity '${entityInfo.Name}' because PostRunView hooks cannot filter SQL aggregates.`);
|
|
3035
|
+
}
|
|
2297
3036
|
// A stored view's properties: refused here (Success:false, naming the property) before any SQL runs.
|
|
2298
3037
|
const propertyFilter = this.BuildViewPropertyFilter(viewEntity, entityInfo, params, user);
|
|
2299
3038
|
// ── External data source dispatch ──
|
|
@@ -2313,7 +3052,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2313
3052
|
// A saved view's stored WhereClause/OrderBy live on viewEntity, not params, and the
|
|
2314
3053
|
// normal SQL path that applies them runs below this early return — so fold them in
|
|
2315
3054
|
// here, else a UserView over an external entity silently returns unfiltered rows.
|
|
2316
|
-
const externalParams = await this.mergeExternalViewParams(params, viewEntity, user);
|
|
3055
|
+
const externalParams = await this.mergeExternalViewParams(params, viewEntity, user, entityInfo);
|
|
2317
3056
|
this.assertExternalClausesRespectFieldSecurity(entityInfo, externalParams, user);
|
|
2318
3057
|
const externalRouter = this.resolveExternalReadRouterOrThrow(`Entity '${entityInfo.Name}'`);
|
|
2319
3058
|
const externalResult = await externalRouter.RunViewExternal(entityInfo, externalParams, user, this);
|
|
@@ -2331,7 +3070,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2331
3070
|
return externalResult;
|
|
2332
3071
|
}
|
|
2333
3072
|
// ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
|
|
2334
|
-
const
|
|
3073
|
+
const queryParameters = [];
|
|
3074
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo, params.Parameters, queryParameters);
|
|
3075
|
+
const structuredFilter = this.CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters);
|
|
2335
3076
|
const userSearchString = params.UserSearchString ?? '';
|
|
2336
3077
|
const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
|
|
2337
3078
|
const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
|
|
@@ -2396,12 +3137,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2396
3137
|
const effectiveSchemaName = effectiveTarget.schemaName;
|
|
2397
3138
|
const topFragment = topSQL ? topSQL + ' ' : '';
|
|
2398
3139
|
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`;
|
|
2399
|
-
|
|
2400
|
-
// it when rows are limited (its pagination purpose), which previously left
|
|
2401
|
-
// count_only with no COUNT at all (silently returned TotalRowCount 0).
|
|
2402
|
-
let countSQL = params.ResultType === 'count_only'
|
|
2403
|
-
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`
|
|
2404
|
-
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName);
|
|
3140
|
+
let countSQL = null;
|
|
2405
3141
|
// ── WHERE clause assembly ──
|
|
2406
3142
|
let whereSQL = '';
|
|
2407
3143
|
let bHasWhere = false;
|
|
@@ -2445,6 +3181,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2445
3181
|
whereSQL = bHasWhere ? `${whereSQL} AND (${extraFilter})` : `(${extraFilter})`;
|
|
2446
3182
|
bHasWhere = true;
|
|
2447
3183
|
}
|
|
3184
|
+
// 2a. Structured Filter (CompositeFilter / CompositeFilterDescriptor)
|
|
3185
|
+
if (structuredFilter.length > 0) {
|
|
3186
|
+
whereSQL = bHasWhere ? `${whereSQL} AND (${structuredFilter})` : `(${structuredFilter})`;
|
|
3187
|
+
bHasWhere = true;
|
|
3188
|
+
}
|
|
2448
3189
|
// 2b. View properties: one typed predicate per property with a value, after the view's
|
|
2449
3190
|
// own clause and ExtraFilter. Row-level security is still ANDed on below.
|
|
2450
3191
|
if (propertyFilter.length > 0) {
|
|
@@ -2489,7 +3230,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2489
3230
|
// SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
|
|
2490
3231
|
if (!IsValidUUID(String(viewEntity?.ID ?? '')))
|
|
2491
3232
|
throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
|
|
2492
|
-
sExcludeSQL += ` UserViewID
|
|
3233
|
+
sExcludeSQL += ` UserViewID='${viewEntity?.ID}')`;
|
|
2493
3234
|
}
|
|
2494
3235
|
else {
|
|
2495
3236
|
// SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
|
|
@@ -2501,7 +3242,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2501
3242
|
// anything that is not a well-formed GUID before it reaches the query.
|
|
2502
3243
|
if (!/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/.test(excludeUserViewRunID))
|
|
2503
3244
|
throw new Error(`Invalid ExcludeUserViewRunID: must be a GUID`);
|
|
2504
|
-
sExcludeSQL += ` UserViewRunID
|
|
3245
|
+
sExcludeSQL += ` UserViewRunID='${excludeUserViewRunID}')`;
|
|
2505
3246
|
}
|
|
2506
3247
|
if (overrideExcludeFilter.length > 0) {
|
|
2507
3248
|
if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
|
|
@@ -2513,7 +3254,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2513
3254
|
bHasWhere = true;
|
|
2514
3255
|
}
|
|
2515
3256
|
// 5. Row-Level Security — role RLS AND API-key row filters (GetEffectiveRowFilterWhereClause; the role-RLS exemption applies only to the role layer)
|
|
2516
|
-
|
|
3257
|
+
// The user's values bind as parameters (#5713), so every user runs the same SQL text and
|
|
3258
|
+
// the database reuses one plan per query shape. Two paths keep literals because their
|
|
3259
|
+
// statement cannot carry parameters: the coalesced count batch (one UNION ALL across
|
|
3260
|
+
// views) and view-run logging (which rebuilds the statement around this WHERE). A
|
|
3261
|
+
// parameterized ExtraFilter also keeps them literal: its placeholders are numbered from
|
|
3262
|
+
// the same dialect sequence, and one statement binds a single parameter list.
|
|
3263
|
+
const logsViewRun = !!(viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user);
|
|
3264
|
+
const rlsBinder = countExecutor || logsViewRun || queryParameters.length > 0
|
|
3265
|
+
? null
|
|
3266
|
+
: this.CreateRowFilterParameterBinder();
|
|
3267
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '', rlsBinder ?? undefined);
|
|
3268
|
+
const rlsParameters = rlsBinder?.Parameters ?? [];
|
|
3269
|
+
const boundParameters = rlsParameters.length > 0 ? rlsParameters : undefined;
|
|
2517
3270
|
if (rlsWhereClause && rlsWhereClause.length > 0) {
|
|
2518
3271
|
whereSQL = bHasWhere ? `${whereSQL} AND (${rlsWhereClause})` : `(${rlsWhereClause})`;
|
|
2519
3272
|
bHasWhere = true;
|
|
@@ -2522,6 +3275,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2522
3275
|
// The count is the total matching the user-visible filters; the seek predicate is
|
|
2523
3276
|
// a pagination cursor, conceptually distinct from "how many records match overall".
|
|
2524
3277
|
const seekPredicateForData = usingKeyset ? keysetSeekPredicate : '';
|
|
3278
|
+
// ── COUNT query assembly (with automatic BaseTable rewrite when safe) ──
|
|
3279
|
+
const isCountOnly = params.ResultType === 'count_only';
|
|
3280
|
+
if (isCountOnly) {
|
|
3281
|
+
const isStandardBaseView = !effectiveBaseView ||
|
|
3282
|
+
(entityInfo.BaseView && effectiveBaseView.trim().toLowerCase() === entityInfo.BaseView.trim().toLowerCase());
|
|
3283
|
+
const countTarget = (isStandardBaseView && this.CanCountFromBaseTable(entityInfo, whereSQL))
|
|
3284
|
+
? this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseTable)
|
|
3285
|
+
: this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView);
|
|
3286
|
+
countSQL = `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${countTarget}`;
|
|
3287
|
+
}
|
|
3288
|
+
else {
|
|
3289
|
+
countSQL = this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName, whereSQL);
|
|
3290
|
+
}
|
|
2525
3291
|
if (bHasWhere) {
|
|
2526
3292
|
viewSQL += ` WHERE ${whereSQL}`;
|
|
2527
3293
|
if (countSQL)
|
|
@@ -2582,7 +3348,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2582
3348
|
// Pass entityInfo + effectiveBaseView so the logged read honors DataSource:'Materialized'
|
|
2583
3349
|
// (reads the snapshot). effectiveBaseView === entityInfo.BaseView on the default live path,
|
|
2584
3350
|
// so non-materialized reads are unchanged.
|
|
2585
|
-
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName);
|
|
3351
|
+
const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName, queryParameters);
|
|
2586
3352
|
if (logResult) {
|
|
2587
3353
|
viewSQL = logResult.executeViewSQL;
|
|
2588
3354
|
userViewRunID = logResult.runID;
|
|
@@ -2642,7 +3408,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2642
3408
|
const skipCount = params.SkipTotalRowCount === true && params.ResultType !== 'count_only';
|
|
2643
3409
|
const willNeedCount = countSQL && ((usingPagination && !skipCount) || params.ResultType === 'count_only');
|
|
2644
3410
|
if (willNeedCount) {
|
|
2645
|
-
if (countExecutor && params.ResultType === 'count_only') {
|
|
3411
|
+
if (countExecutor && params.ResultType === 'count_only' && queryParameters.length === 0) {
|
|
2646
3412
|
countExecutorPromise = countExecutor(countSQL);
|
|
2647
3413
|
}
|
|
2648
3414
|
else {
|
|
@@ -2655,22 +3421,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2655
3421
|
sqlQueries.push(aggregateSQL);
|
|
2656
3422
|
sqlQueryKeys.push('aggregate');
|
|
2657
3423
|
}
|
|
3424
|
+
// At most one of the two lists is non-empty: row-filter values stay literal when the
|
|
3425
|
+
// ExtraFilter binds parameters (step 5).
|
|
3426
|
+
const boundParams = queryParameters.length > 0 ? queryParameters : boundParameters;
|
|
3427
|
+
const boundBatchParams = queryParameters.length > 0 ? sqlQueries.map(() => queryParameters) : undefined;
|
|
2658
3428
|
const resultMap = {};
|
|
2659
3429
|
if (sqlQueries.length === 1 && !countExecutorPromise) {
|
|
2660
|
-
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0],
|
|
3430
|
+
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], boundParams, undefined, contextUser);
|
|
3431
|
+
}
|
|
3432
|
+
else if (sqlQueries.length > 1 && boundParameters) {
|
|
3433
|
+
const batchResults = await this.ExecuteSQLBatchWithSharedParameters(sqlQueries, boundParameters, undefined, contextUser);
|
|
3434
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2661
3435
|
}
|
|
2662
3436
|
else if (sqlQueries.length > 0 && countExecutorPromise) {
|
|
2663
3437
|
const [batchResults, countRes] = await Promise.all([
|
|
2664
3438
|
sqlQueries.length === 1
|
|
2665
|
-
? this.ExecuteSQL(sqlQueries[0],
|
|
2666
|
-
: this.ExecuteSQLBatch(sqlQueries,
|
|
3439
|
+
? this.ExecuteSQL(sqlQueries[0], boundParams, undefined, contextUser).then(r => [r])
|
|
3440
|
+
: this.ExecuteSQLBatch(sqlQueries, boundBatchParams, undefined, contextUser),
|
|
2667
3441
|
countExecutorPromise,
|
|
2668
3442
|
]);
|
|
2669
3443
|
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2670
3444
|
resultMap['count'] = countRes;
|
|
2671
3445
|
}
|
|
2672
3446
|
else if (sqlQueries.length > 1) {
|
|
2673
|
-
const batchResults = await this.ExecuteSQLBatch(sqlQueries,
|
|
3447
|
+
const batchResults = await this.ExecuteSQLBatch(sqlQueries, boundBatchParams, undefined, contextUser);
|
|
2674
3448
|
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
2675
3449
|
}
|
|
2676
3450
|
else if (countExecutorPromise) {
|
|
@@ -2702,7 +3476,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2702
3476
|
// time in the window, with nothing reading a single result. Callers that only read
|
|
2703
3477
|
// `Results` opt out explicitly with RunViewParams.SkipTotalRowCount; the provider
|
|
2704
3478
|
// never infers that from the value of MaxRows.
|
|
2705
|
-
const countResult = await this.ExecuteSQL(countSQL,
|
|
3479
|
+
const countResult = await this.ExecuteSQL(countSQL, boundParams, undefined, contextUser);
|
|
2706
3480
|
if (countResult && countResult.length > 0)
|
|
2707
3481
|
rowCount = countResult[0].TotalRowCount;
|
|
2708
3482
|
}
|
|
@@ -2781,6 +3555,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2781
3555
|
};
|
|
2782
3556
|
}
|
|
2783
3557
|
}
|
|
3558
|
+
/** Returns true when `entityName` is registered as requiring PostRunView row-level ACL hooks. */
|
|
3559
|
+
IsPostRunViewProtectedEntity(entityName) {
|
|
3560
|
+
return IsPostRunViewProtectedEntity(entityName);
|
|
3561
|
+
}
|
|
3562
|
+
/** Returns true when `user` represents the trusted internal server system identity. */
|
|
3563
|
+
isSystemCaller(user) {
|
|
3564
|
+
if (!user) {
|
|
3565
|
+
return false;
|
|
3566
|
+
}
|
|
3567
|
+
return IsSystemUser(user) || WellKnownUserSource.Instance.IsSystemUser(user);
|
|
3568
|
+
}
|
|
2784
3569
|
/** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
|
|
2785
3570
|
async LoadRunViewEntity(params, contextUser) {
|
|
2786
3571
|
if (params.ViewEntity)
|
|
@@ -2996,7 +3781,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2996
3781
|
}
|
|
2997
3782
|
/**
|
|
2998
3783
|
* Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
|
|
2999
|
-
* the columns this user is allowed to read when field security denies them any.
|
|
3784
|
+
* the columns this user is allowed to read when field security denies them any. With
|
|
3785
|
+
* `tableAlias`, every column (or the `*`) is qualified with it.
|
|
3000
3786
|
*
|
|
3001
3787
|
* Deliberately NOT routed through RunView, which is the other way to get this behavior.
|
|
3002
3788
|
* That reroute is the tidier long-term shape and is planned separately (it must pass
|
|
@@ -3004,19 +3790,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3004
3790
|
* — and it changes relationship loading, which stays on its current path). Filtering the
|
|
3005
3791
|
* column list here buys the same protection without touching either.
|
|
3006
3792
|
*/
|
|
3007
|
-
buildFieldSecuritySelectList(entityInfo, user) {
|
|
3793
|
+
buildFieldSecuritySelectList(entityInfo, user, tableAlias) {
|
|
3794
|
+
const prefix = tableAlias ? `${tableAlias}.` : '';
|
|
3008
3795
|
if (!user || !entityInfo.FieldLevelSecurityApplies) {
|
|
3009
|
-
return
|
|
3796
|
+
return `${prefix}*`; // the overwhelmingly common case — one boolean, unchanged SQL
|
|
3010
3797
|
}
|
|
3011
3798
|
const denied = entityInfo.GetDeniedReadFields(user);
|
|
3012
3799
|
if (denied.size === 0) {
|
|
3013
|
-
return
|
|
3800
|
+
return `${prefix}*`;
|
|
3014
3801
|
}
|
|
3015
3802
|
const allowed = entityInfo.Fields.filter(f => !denied.has(f.Name.trim().toLowerCase()));
|
|
3016
3803
|
if (allowed.length === 0) {
|
|
3017
|
-
return
|
|
3804
|
+
return `${prefix}*`; // degenerate; PKs are unrestrictable so this should be unreachable
|
|
3018
3805
|
}
|
|
3019
|
-
return allowed.map(f => this.QuoteIdentifier(f.Name)).join(', ');
|
|
3806
|
+
return allowed.map(f => `${prefix}${this.QuoteIdentifier(f.Name)}`).join(', ');
|
|
3020
3807
|
}
|
|
3021
3808
|
/**
|
|
3022
3809
|
* Builds the SQL field list string for a view query, using dialect-neutral quoting.
|
|
@@ -3223,13 +4010,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3223
4010
|
`a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
|
|
3224
4011
|
`tokens, such as an unbalanced quote or bracket.`);
|
|
3225
4012
|
}
|
|
3226
|
-
|
|
4013
|
+
// The built-in predicates have no phrase syntax, so they search a quoted phrase without its
|
|
4014
|
+
// quotes (UnwrapPhraseQuotes). A custom format is SQL, screened above as typed, so it gets
|
|
4015
|
+
// the term as typed.
|
|
4016
|
+
const phraseTerm = UnwrapPhraseQuotes(safeUserSearchString);
|
|
4017
|
+
const escapedTerm = this.escapeLikeTerm(phraseTerm);
|
|
3227
4018
|
for (const field of entityInfo.Fields) {
|
|
3228
4019
|
if (!field.IncludeInUserSearchAPI)
|
|
3229
4020
|
continue;
|
|
3230
4021
|
if (deniedSearchFields.has(field.Name.trim().toLowerCase()))
|
|
3231
4022
|
continue; // field security: not searchable
|
|
3232
|
-
const sParam = this.buildPerFieldSearchPredicate(field, escapedTerm, safeUserSearchString);
|
|
4023
|
+
const sParam = this.buildPerFieldSearchPredicate(field, escapedTerm, field.UserSearchParamFormatAPI ? safeUserSearchString : phraseTerm);
|
|
3233
4024
|
if (!sParam)
|
|
3234
4025
|
continue;
|
|
3235
4026
|
if (sUserSearchSQL.length > 0)
|
|
@@ -3298,6 +4089,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3298
4089
|
/**
|
|
3299
4090
|
* Build the SQL fragment that compares one EntityField against a user search term.
|
|
3300
4091
|
*
|
|
4092
|
+
* `createViewUserSearchSQL` passes the term without wrapping phrase quotes (`UnwrapPhraseQuotes`)
|
|
4093
|
+
* as `escapedTerm`, and as `rawSafeTerm` for a field without a custom format; a custom format
|
|
4094
|
+
* receives the term as typed. An override receives the same values.
|
|
4095
|
+
*
|
|
3301
4096
|
* Resolution order:
|
|
3302
4097
|
* 1. UserSearchParamFormatAPI (custom override) wins if set, with `{0}` replaced
|
|
3303
4098
|
* by the single-quote-escaped raw term. Caller is responsible for escaping
|
|
@@ -3570,8 +4365,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3570
4365
|
statuses[index] = { Success: false, ErrorMessage: `Entity ${hooked.EntityName ?? '(none)'} not found` };
|
|
3571
4366
|
continue;
|
|
3572
4367
|
}
|
|
3573
|
-
const
|
|
3574
|
-
|
|
4368
|
+
const queryParameters = [];
|
|
4369
|
+
const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user, queryParameters);
|
|
4370
|
+
items.push({
|
|
4371
|
+
index,
|
|
4372
|
+
item: { params: hooked },
|
|
4373
|
+
entityInfo,
|
|
4374
|
+
whereSQL,
|
|
4375
|
+
queryParameters: queryParameters.length > 0 ? queryParameters : undefined,
|
|
4376
|
+
});
|
|
3575
4377
|
}
|
|
3576
4378
|
catch (e) {
|
|
3577
4379
|
statuses[index] = { Success: false, ErrorMessage: e instanceof Error ? e.message : String(e) };
|
|
@@ -3708,7 +4510,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3708
4510
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: gateRejection });
|
|
3709
4511
|
continue;
|
|
3710
4512
|
}
|
|
3711
|
-
const entityInfo = item.params.EntityName
|
|
4513
|
+
const entityInfo = item.params.EntityName
|
|
4514
|
+
? this.EntityByName(item.params.EntityName)
|
|
4515
|
+
: (item.params.ViewEntity && item.params.ViewEntity.EntityID
|
|
4516
|
+
? this.EntityByID(item.params.ViewEntity.EntityID)
|
|
4517
|
+
: undefined);
|
|
3712
4518
|
// Read-permission gate for EVERY item whose entity is known, before any leg can answer:
|
|
3713
4519
|
// an item with no cache status, and an external entity, are served from the server cache
|
|
3714
4520
|
// on a hit WITHOUT re-entering InternalRunView, so a CanRead check that lived only on the
|
|
@@ -3719,6 +4525,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3719
4525
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: permissionError });
|
|
3720
4526
|
continue;
|
|
3721
4527
|
}
|
|
4528
|
+
if (item.params.Aggregates &&
|
|
4529
|
+
item.params.Aggregates.length > 0 &&
|
|
4530
|
+
this.IsPostRunViewProtectedEntity(entityInfo.Name) &&
|
|
4531
|
+
!this.isSystemCaller(user)) {
|
|
4532
|
+
errorResults.push({
|
|
4533
|
+
viewIndex: i,
|
|
4534
|
+
status: 'error',
|
|
4535
|
+
errorMessage: `Access denied: aggregate queries are not allowed on PostRunView-protected entity '${entityInfo.Name}' because PostRunView hooks cannot filter SQL aggregates.`,
|
|
4536
|
+
});
|
|
4537
|
+
continue;
|
|
4538
|
+
}
|
|
3722
4539
|
}
|
|
3723
4540
|
// Keyset queries bypass the cache entirely (per the AfterKey API contract):
|
|
3724
4541
|
// each call uses a different seek key, so cached entries would never be
|
|
@@ -3739,11 +4556,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3739
4556
|
itemsWithoutCacheCheck.push({ index: i, item });
|
|
3740
4557
|
continue;
|
|
3741
4558
|
}
|
|
4559
|
+
// PostRunView-protected entities enforce per-caller ACL filtering inside PostRunView
|
|
4560
|
+
// hooks driven by sibling permission tables (e.g., ArtifactPermission / CollectionPermission).
|
|
4561
|
+
// Global COUNT(*)/MAX(__mj_UpdatedAt) checks cannot detect ACL revocations on sibling tables,
|
|
4562
|
+
// so never return status: 'current'; always run the full query + PostRunView hook.
|
|
4563
|
+
if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4564
|
+
itemsWithoutCacheCheck.push({ index: i, item });
|
|
4565
|
+
continue;
|
|
4566
|
+
}
|
|
3742
4567
|
itemsNeedingValidation.push({ index: i, item, entityInfo });
|
|
3743
4568
|
}
|
|
3744
4569
|
// Phase 1: Check server's LocalCacheManager first (zero DB hits when within freshness window)
|
|
3745
4570
|
const currentResults = [];
|
|
3746
4571
|
const serverCacheStaleItems = [];
|
|
4572
|
+
const staleItemsNoTracking = [];
|
|
3747
4573
|
const serverCacheMissItems = [];
|
|
3748
4574
|
for (const { index, item, entityInfo } of itemsNeedingValidation) {
|
|
3749
4575
|
const entityLabel = item.params.EntityName || 'unknown';
|
|
@@ -3761,6 +4587,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3761
4587
|
fingerprint: resolved.fingerprint,
|
|
3762
4588
|
});
|
|
3763
4589
|
}
|
|
4590
|
+
else if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4591
|
+
// PostRunView-protected entities bypass differential / cached delta transport and run full query + PostRunView.
|
|
4592
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
4593
|
+
}
|
|
3764
4594
|
else if (entityInfo.TrackRecordChanges) {
|
|
3765
4595
|
// The client's copy is older and the entity tracks record changes: Phase 2 reads
|
|
3766
4596
|
// the DB status and sends only the changed rows, not the full cached copy.
|
|
@@ -3777,12 +4607,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3777
4607
|
}
|
|
3778
4608
|
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
3779
4609
|
const differentialItems = [];
|
|
3780
|
-
const staleItemsNoTracking = [];
|
|
3781
4610
|
/** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
|
|
3782
|
-
const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus) => {
|
|
4611
|
+
const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus, queryParameters) => {
|
|
3783
4612
|
LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
|
|
3784
4613
|
differentialItems.push({
|
|
3785
|
-
index, params: item.params, entityInfo, whereSQL,
|
|
4614
|
+
index, params: item.params, entityInfo, whereSQL, queryParameters,
|
|
3786
4615
|
clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
|
|
3787
4616
|
clientRowCount: item.cacheStatus.rowCount,
|
|
3788
4617
|
serverStatus,
|
|
@@ -3793,15 +4622,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3793
4622
|
const itemsForDBCheck = [];
|
|
3794
4623
|
for (const { index, item, entityInfo, serverCached, fingerprint } of serverCacheMissItems) {
|
|
3795
4624
|
try {
|
|
3796
|
-
const
|
|
3797
|
-
|
|
4625
|
+
const queryParameters = [];
|
|
4626
|
+
const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user, queryParameters);
|
|
4627
|
+
itemsForDBCheck.push({
|
|
4628
|
+
index,
|
|
4629
|
+
item,
|
|
4630
|
+
entityInfo,
|
|
4631
|
+
whereSQL,
|
|
4632
|
+
queryParameters: queryParameters.length > 0 ? queryParameters : undefined,
|
|
4633
|
+
serverCached,
|
|
4634
|
+
fingerprint,
|
|
4635
|
+
});
|
|
3798
4636
|
}
|
|
3799
4637
|
catch (e) {
|
|
3800
4638
|
errorResults.push({ viewIndex: index, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
|
|
3801
4639
|
}
|
|
3802
4640
|
}
|
|
3803
4641
|
const cacheStatusResults = await this.getBatchedServerCacheStatus(itemsForDBCheck, contextUser);
|
|
3804
|
-
for (const { index, item, entityInfo, whereSQL, serverCached, fingerprint } of itemsForDBCheck) {
|
|
4642
|
+
for (const { index, item, entityInfo, whereSQL, queryParameters, serverCached, fingerprint } of itemsForDBCheck) {
|
|
3805
4643
|
const serverStatus = cacheStatusResults.get(index);
|
|
3806
4644
|
if (!serverStatus || !serverStatus.success) {
|
|
3807
4645
|
const statusError = serverStatus?.errorMessage || 'Failed to get cache status';
|
|
@@ -3818,12 +4656,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3818
4656
|
if (this.isCacheCurrent(cachedSlotStatus, serverStatus)) {
|
|
3819
4657
|
// Server cache slot is confirmed current against SQL — refresh its verification timestamp in O(1)
|
|
3820
4658
|
LocalCacheManager.Instance.TouchRunViewResultVerifiedAt(fingerprint);
|
|
3821
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4659
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3822
4660
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
3823
4661
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3824
4662
|
}
|
|
4663
|
+
else if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4664
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
4665
|
+
}
|
|
3825
4666
|
else if (entityInfo.TrackRecordChanges) {
|
|
3826
|
-
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
4667
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
|
|
3827
4668
|
}
|
|
3828
4669
|
else {
|
|
3829
4670
|
LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
|
|
@@ -3836,7 +4677,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3836
4677
|
// Evict the stale server slot and refresh from DB so LocalCacheManager and the client self-heal.
|
|
3837
4678
|
LogStatusEx({ message: ` ♻️ [SmartCache RECONCILE-EVICT] "${entityLabel}" — server cache slot disagreed with DB status; invalidating and refreshing from DB`, verboseOnly: true });
|
|
3838
4679
|
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
3839
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4680
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3840
4681
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3841
4682
|
}
|
|
3842
4683
|
else {
|
|
@@ -3845,15 +4686,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3845
4686
|
continue;
|
|
3846
4687
|
}
|
|
3847
4688
|
}
|
|
3848
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4689
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
3849
4690
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches DB (server cache miss)`, verboseOnly: true });
|
|
3850
4691
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
3851
4692
|
}
|
|
3852
|
-
else if (entityInfo.TrackRecordChanges) {
|
|
3853
|
-
queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
|
|
4693
|
+
else if (entityInfo.TrackRecordChanges && !this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4694
|
+
queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
|
|
3854
4695
|
}
|
|
3855
4696
|
else {
|
|
3856
|
-
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
|
|
4697
|
+
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking or PostRunView-protected)`, verboseOnly: true });
|
|
3857
4698
|
staleItemsNoTracking.push({ index, params: item.params });
|
|
3858
4699
|
}
|
|
3859
4700
|
}
|
|
@@ -3901,7 +4742,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3901
4742
|
// DB-validated stale items (no change tracking)
|
|
3902
4743
|
...staleItemsNoTracking.map(({ index, params: viewParams }) => this.runFullQueryAndCacheResult(viewParams, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
3903
4744
|
// DB-validated differential items
|
|
3904
|
-
...differentialItems.map(({ index, params: viewParams, entityInfo, whereSQL, clientMaxUpdatedAt, clientRowCount, serverStatus }) => this.runDifferentialQueryAndReturn(viewParams, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
|
|
4745
|
+
...differentialItems.map(({ index, params: viewParams, entityInfo, whereSQL, queryParameters, clientMaxUpdatedAt, clientRowCount, serverStatus }) => this.runDifferentialQueryAndReturn(viewParams, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, index, contextUser, callerFieldsByIndex.get(index) ?? null, queryParameters)),
|
|
3905
4746
|
];
|
|
3906
4747
|
const fullQueryResults = await Promise.all(queryPromises);
|
|
3907
4748
|
const allResults = [...errorResults, ...currentResults, ...fullQueryResults];
|
|
@@ -3971,6 +4812,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3971
4812
|
}, user);
|
|
3972
4813
|
if (hooked && Array.isArray(hooked.Results)) {
|
|
3973
4814
|
rowBearing.results = hooked.Results;
|
|
4815
|
+
if (typeof hooked.TotalRowCount === 'number') {
|
|
4816
|
+
rowBearing.rowCount = hooked.TotalRowCount;
|
|
4817
|
+
}
|
|
4818
|
+
else {
|
|
4819
|
+
rowBearing.rowCount = hooked.Results.length;
|
|
4820
|
+
}
|
|
3974
4821
|
}
|
|
3975
4822
|
}
|
|
3976
4823
|
const entities = params.map(p => p.params.EntityName || 'unknown').join(', ');
|
|
@@ -3990,19 +4837,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3990
4837
|
* Handles ExtraFilter, UserSearch, and Row-Level Security.
|
|
3991
4838
|
* Subclasses can override to add platform-specific SQL transformations (e.g., identifier quoting).
|
|
3992
4839
|
*/
|
|
3993
|
-
async buildWhereClauseForCacheCheck(params, entityInfo, user) {
|
|
4840
|
+
async buildWhereClauseForCacheCheck(params, entityInfo, user, queryParameters) {
|
|
3994
4841
|
let whereSQL = '';
|
|
3995
4842
|
let bHasWhere = false;
|
|
3996
4843
|
// PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
|
|
3997
|
-
// check then
|
|
3998
|
-
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
|
|
4844
|
+
// check and post-bind field-security gate then run on the result, as on the main view path.
|
|
4845
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo, params.Parameters, queryParameters);
|
|
3999
4846
|
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
4847
|
+
this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [extraFilter], user);
|
|
4000
4848
|
if (extraFilter.length > 0) {
|
|
4001
4849
|
if (!this.ValidateUserProvidedSQLClause(extraFilter))
|
|
4002
4850
|
throw new Error(`Invalid Extra Filter: ${extraFilter}`);
|
|
4003
4851
|
whereSQL = `(${extraFilter})`;
|
|
4004
4852
|
bHasWhere = true;
|
|
4005
4853
|
}
|
|
4854
|
+
const structuredFilter = this.CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters);
|
|
4855
|
+
if (structuredFilter.length > 0) {
|
|
4856
|
+
whereSQL = bHasWhere ? `${whereSQL} AND (${structuredFilter})` : `(${structuredFilter})`;
|
|
4857
|
+
bHasWhere = true;
|
|
4858
|
+
}
|
|
4006
4859
|
// Free text, not a SQL fragment — deliberately NOT run through
|
|
4007
4860
|
// ValidateUserProvidedSQLClause. See the equivalent note on the view path above (#4392).
|
|
4008
4861
|
if (params.UserSearchString && params.UserSearchString.length > 0) {
|
|
@@ -4043,7 +4896,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4043
4896
|
const results = new Map();
|
|
4044
4897
|
if (items.length === 0)
|
|
4045
4898
|
return results;
|
|
4046
|
-
const promises = items.map(async ({ index, item, entityInfo, whereSQL }) => {
|
|
4899
|
+
const promises = items.map(async ({ index, item, entityInfo, whereSQL, queryParameters }) => {
|
|
4047
4900
|
try {
|
|
4048
4901
|
// Probe the SAME physical view the read targets — for a DataSource:'Materialized' read that's
|
|
4049
4902
|
// the materialized_vw<CodeName> snapshot (a full SELECT * of the base view, so it carries
|
|
@@ -4053,7 +4906,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4053
4906
|
// matches the SQL Server override and is defense-in-depth on the PG/default path.)
|
|
4054
4907
|
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
|
|
4055
4908
|
const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveTarget.viewName, whereSQL, effectiveTarget.schemaName);
|
|
4056
|
-
const
|
|
4909
|
+
const boundParams = queryParameters && queryParameters.length > 0 ? queryParameters : undefined;
|
|
4910
|
+
const rows = await this.ExecuteSQL(statusSQL, boundParams, undefined, contextUser);
|
|
4057
4911
|
if (rows && rows.length > 0) {
|
|
4058
4912
|
const row = rows[0];
|
|
4059
4913
|
results.set(index, {
|
|
@@ -4206,6 +5060,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4206
5060
|
if (typeof params.UserSearchString === 'string' && params.UserSearchString.trim().length > 0) {
|
|
4207
5061
|
throw new Error(`UserSearchString is not supported for external-data-source entity '${entityName}'. Use ExtraFilter instead.`);
|
|
4208
5062
|
}
|
|
5063
|
+
if (params.Parameters && Object.keys(params.Parameters).some((k) => params.Parameters[k] !== undefined)) {
|
|
5064
|
+
throw new Error(`Parameterized ExtraFilter (Parameters) is not supported for external-data-source entity '${entityName}'.`);
|
|
5065
|
+
}
|
|
4209
5066
|
// Apply the same forbidden-keyword screen the MJ-DB path runs on caller-supplied SQL
|
|
4210
5067
|
// clauses before they're passed to the remote driver. The driver still parameterizes
|
|
4211
5068
|
// values, but this blocks obvious injection of statement-terminating / DDL keywords.
|
|
@@ -4265,11 +5122,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4265
5122
|
* OrderByClause is used only when the caller supplied no OrderBy. Returns params unchanged
|
|
4266
5123
|
* when there is no saved view.
|
|
4267
5124
|
*/
|
|
4268
|
-
async mergeExternalViewParams(params, viewEntity, user) {
|
|
4269
|
-
if (!viewEntity)
|
|
5125
|
+
async mergeExternalViewParams(params, viewEntity, user, entityInfo) {
|
|
5126
|
+
if (!viewEntity && !params.Filter)
|
|
4270
5127
|
return params;
|
|
4271
5128
|
const merged = { ...params };
|
|
4272
|
-
|
|
5129
|
+
let callerFilter = params.ExtraFilter || '';
|
|
5130
|
+
if (params.Filter && entityInfo) {
|
|
5131
|
+
const literalStructured = CompositeFilterSQLCompiler.CompileLiteral(params.Filter, entityInfo, {
|
|
5132
|
+
platform: this.PlatformKey,
|
|
5133
|
+
user,
|
|
5134
|
+
}).trim();
|
|
5135
|
+
if (literalStructured) {
|
|
5136
|
+
callerFilter = callerFilter ? `(${callerFilter}) AND (${literalStructured})` : literalStructured;
|
|
5137
|
+
merged.ExtraFilter = callerFilter;
|
|
5138
|
+
}
|
|
5139
|
+
delete merged.Filter;
|
|
5140
|
+
}
|
|
5141
|
+
if (!viewEntity)
|
|
5142
|
+
return merged;
|
|
4273
5143
|
if (viewEntity.WhereClause && viewEntity.WhereClause.length > 0) {
|
|
4274
5144
|
const renderedWhere = (await this.RenderViewWhereClause(viewEntity, user))?.trim();
|
|
4275
5145
|
if (renderedWhere) {
|
|
@@ -4314,6 +5184,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4314
5184
|
async resolveFromServerCache(item, index, entityLabel, contextUser) {
|
|
4315
5185
|
if (!LocalCacheManager.Instance.IsInitialized)
|
|
4316
5186
|
return null;
|
|
5187
|
+
if (item.params.EntityName && this.IsPostRunViewProtectedEntity(item.params.EntityName)) {
|
|
5188
|
+
return null;
|
|
5189
|
+
}
|
|
4317
5190
|
if (!this.runViewCacheEligible(item.params) || this.cacheDeniedForViewOnlyRequest(item.params, contextUser)) {
|
|
4318
5191
|
return null;
|
|
4319
5192
|
}
|
|
@@ -4372,7 +5245,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4372
5245
|
const cacheEntity = viewParams ? this.resolveEntityForRunViewParams(viewParams) : undefined;
|
|
4373
5246
|
const materialized = await this.MaterializeCachedRowsForCaller(serverCached.results, cacheEntity, contextUser, true);
|
|
4374
5247
|
const results = callerFields
|
|
4375
|
-
? ProjectRowsToFields(materialized, callerFields)
|
|
5248
|
+
? ProjectRowsToFields(materialized, callerFields, { PreserveFrozen: true })
|
|
4376
5249
|
: materialized;
|
|
4377
5250
|
return {
|
|
4378
5251
|
viewIndex,
|
|
@@ -4392,8 +5265,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4392
5265
|
* Includes updated/created rows and deleted record IDs.
|
|
4393
5266
|
* Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
|
|
4394
5267
|
*/
|
|
4395
|
-
async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null) {
|
|
5268
|
+
async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null, queryParameters) {
|
|
4396
5269
|
try {
|
|
5270
|
+
if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
5271
|
+
return await this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
|
|
5272
|
+
}
|
|
4397
5273
|
const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
|
|
4398
5274
|
if (!clientMaxUpdatedDate) {
|
|
4399
5275
|
// Unparseable client timestamp — can't trust the differential math; fall
|
|
@@ -4401,7 +5277,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4401
5277
|
return this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
|
|
4402
5278
|
}
|
|
4403
5279
|
const since = clientMaxUpdatedDate.toISOString();
|
|
4404
|
-
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser);
|
|
5280
|
+
const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser, queryParameters);
|
|
4405
5281
|
const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, since, contextUser);
|
|
4406
5282
|
// Validation: detect hidden deletes not tracked in RecordChanges
|
|
4407
5283
|
const newInserts = updatedRows.filter(row => {
|
|
@@ -4501,7 +5377,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4501
5377
|
* Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
|
|
4502
5378
|
* timestamp in ISO 8601 form as its own predicate group.
|
|
4503
5379
|
*/
|
|
4504
|
-
async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser) {
|
|
5380
|
+
async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser, queryParameters) {
|
|
4505
5381
|
try {
|
|
4506
5382
|
const timestampFilter = `(${this.QuoteIdentifier('__mj_UpdatedAt')} > '${this.toSQLTimestamp(sinceTimestamp)}')`;
|
|
4507
5383
|
const combinedWhere = whereSQL
|
|
@@ -4519,7 +5395,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4519
5395
|
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
4520
5396
|
sql += ` ORDER BY ${orderBy}`;
|
|
4521
5397
|
}
|
|
4522
|
-
const
|
|
5398
|
+
const boundParams = queryParameters && queryParameters.length > 0 ? queryParameters : undefined;
|
|
5399
|
+
const rawRows = await this.ExecuteSQL(sql, boundParams, undefined, contextUser);
|
|
4523
5400
|
const processed = await this.PostProcessRows(rawRows, entityInfo, (contextUser ?? this.CurrentUser), { preserveRestrictedApiCiphertext: true });
|
|
4524
5401
|
return processed;
|
|
4525
5402
|
}
|
|
@@ -4770,9 +5647,32 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4770
5647
|
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
4771
5648
|
* @throws Error if the user does not have permission to run the query
|
|
4772
5649
|
*/
|
|
5650
|
+
static { this.RESTRICTED_MAGIC_LINK_ARTIFACT_QUERY_IDS = new Set([
|
|
5651
|
+
'34d2d4d2-c727-4366-996f-3aaf87fc103e', // GetArtifactVersionsByID
|
|
5652
|
+
'8f84dfb4-c38e-4b8d-80e7-9ccf30039e77', // GetConversationComplete
|
|
5653
|
+
'ee272535-9d1d-4e4b-8613-1332cb564501', // GetConversationArtifactsMap
|
|
5654
|
+
'a1b2c3d4-e5f6-4789-abcd-123456789abc', // GetConversationArtifactsForAgent
|
|
5655
|
+
]); }
|
|
5656
|
+
static isMagicLinkRestrictedArtifactQuery(query, user) {
|
|
5657
|
+
if (!user || (!user.IsMagicLinkAnonymous && !user.MagicLinkScope)) {
|
|
5658
|
+
return false;
|
|
5659
|
+
}
|
|
5660
|
+
if (query.ID && GenericDatabaseProvider.RESTRICTED_MAGIC_LINK_ARTIFACT_QUERY_IDS.has(NormalizeUUID(query.ID))) {
|
|
5661
|
+
return true;
|
|
5662
|
+
}
|
|
5663
|
+
const normalized = (query.Name ?? '').trim().toLowerCase();
|
|
5664
|
+
return (normalized === 'getartifactversionsbyid' ||
|
|
5665
|
+
normalized === 'getconversationcomplete' ||
|
|
5666
|
+
normalized === 'getconversationartifactsmap' ||
|
|
5667
|
+
normalized === 'getconversationartifactsforagent');
|
|
5668
|
+
}
|
|
4773
5669
|
ValidateQueryForExecution(query, contextUser, requestedLabel = query.ID) {
|
|
4774
5670
|
const user = contextUser || this.CurrentUser;
|
|
4775
5671
|
if (user) {
|
|
5672
|
+
if (GenericDatabaseProvider.isMagicLinkRestrictedArtifactQuery(query, user)) {
|
|
5673
|
+
this.logQueryRunRefusal(query, user, { deniedEntities: ['MJ: Artifacts', 'MJ: Conversations'] });
|
|
5674
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5675
|
+
}
|
|
4776
5676
|
const result = query.UserCanRun(user);
|
|
4777
5677
|
if (!result.canRun) {
|
|
4778
5678
|
// This gate, not the rendered-SQL one, is where a role-list denial lands: it
|
|
@@ -4961,6 +5861,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4961
5861
|
* refuses, carrying the rendering's error.
|
|
4962
5862
|
*/
|
|
4963
5863
|
authorizeQueryRun(query, parameters, user, logRefusal = true) {
|
|
5864
|
+
if (GenericDatabaseProvider.isMagicLinkRestrictedArtifactQuery(query, user)) {
|
|
5865
|
+
const refusal = { canRun: false, deniedEntities: ['MJ: Artifacts', 'MJ: Conversations'] };
|
|
5866
|
+
if (logRefusal) {
|
|
5867
|
+
this.logQueryRunRefusal(query, user, refusal);
|
|
5868
|
+
}
|
|
5869
|
+
return refusal;
|
|
5870
|
+
}
|
|
4964
5871
|
const base = query.UserCanRun(user);
|
|
4965
5872
|
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
4966
5873
|
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
@@ -4987,7 +5894,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4987
5894
|
return !!permissions && permissions.length > 0;
|
|
4988
5895
|
}
|
|
4989
5896
|
/**
|
|
4990
|
-
* Resolves a category path string to a
|
|
5897
|
+
* Resolves a category path string to a query category ID, from `QueryEngine`.
|
|
4991
5898
|
*/
|
|
4992
5899
|
resolveCategoryPath(categoryPath) {
|
|
4993
5900
|
if (!categoryPath)
|
|
@@ -4995,10 +5902,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4995
5902
|
const segments = categoryPath.split('/').map(s => s.trim()).filter(s => s.length > 0);
|
|
4996
5903
|
if (segments.length === 0)
|
|
4997
5904
|
return null;
|
|
5905
|
+
const categories = QueryEngine.Instance.QueryCategories;
|
|
4998
5906
|
let currentCategory = null;
|
|
4999
5907
|
for (const segment of segments) {
|
|
5000
5908
|
const parentId = currentCategory !== null ? currentCategory.ID : null;
|
|
5001
|
-
currentCategory =
|
|
5909
|
+
currentCategory = categories.find(cat => cat.Name.trim().toLowerCase() === segment.toLowerCase() && UUIDsEqual(cat.ParentID, parentId)) ?? null;
|
|
5002
5910
|
if (!currentCategory)
|
|
5003
5911
|
return null;
|
|
5004
5912
|
}
|
|
@@ -6253,13 +7161,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6253
7161
|
// No enricher registered under this key (providing package not loaded) — no-op.
|
|
6254
7162
|
return rows;
|
|
6255
7163
|
}
|
|
6256
|
-
//
|
|
6257
|
-
//
|
|
6258
|
-
const queryInfo = this.Queries.find(q => UUIDsEqual(q.ID, query.ID));
|
|
7164
|
+
// The QueryInfo metadata exists only when this provider loads query metadata; the ID
|
|
7165
|
+
// always reaches the enricher, which can resolve the query from QueryEngine.
|
|
7166
|
+
const queryInfo = this.LoadsQueryMetadata ? this.Queries.find(q => UUIDsEqual(q.ID, query.ID)) : undefined;
|
|
6259
7167
|
return await enricher.EnrichResults({
|
|
6260
7168
|
rows,
|
|
6261
7169
|
config: enrichment.Config ?? {},
|
|
6262
7170
|
query: queryInfo,
|
|
7171
|
+
queryID: query.ID,
|
|
6263
7172
|
contextUser,
|
|
6264
7173
|
provider: this,
|
|
6265
7174
|
});
|
|
@@ -6319,11 +7228,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6319
7228
|
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
6320
7229
|
if (!pk)
|
|
6321
7230
|
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
6322
|
-
|
|
6323
|
-
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
6324
|
-
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
7231
|
+
return `${this.QuoteIdentifier(pk.CodeName)}=${this.RenderPrimaryKeyLiteral(pk, val.Value, entityInfo.Name)}`;
|
|
6325
7232
|
}).join(' AND ');
|
|
6326
7233
|
}
|
|
7234
|
+
/**
|
|
7235
|
+
* A primary key value as a SQL literal: quoted with embedded quotes escaped, or a plain number
|
|
7236
|
+
* for a key that takes no quotes. These statements are built as text, and a key value can come
|
|
7237
|
+
* from the client, so an unquoted value that isn't a number throws.
|
|
7238
|
+
*/
|
|
7239
|
+
RenderPrimaryKeyLiteral(field, value, entityName) {
|
|
7240
|
+
return this.RenderKeyLiteral(value, field?.NeedsQuotes ?? false, field?.Name, entityName);
|
|
7241
|
+
}
|
|
7242
|
+
/**
|
|
7243
|
+
* {@link RenderPrimaryKeyLiteral} for a caller that has the key's quoting rule but not its field.
|
|
7244
|
+
*/
|
|
7245
|
+
RenderKeyLiteral(value, needsQuotes, fieldName, entityName) {
|
|
7246
|
+
if (needsQuotes) {
|
|
7247
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
7248
|
+
}
|
|
7249
|
+
const raw = String(value);
|
|
7250
|
+
if (!/^-?\d+(\.\d+)?$/.test(raw)) {
|
|
7251
|
+
throw new Error(`Invalid non-numeric value provided for numeric key field ${fieldName} on entity ${entityName}`);
|
|
7252
|
+
}
|
|
7253
|
+
return raw;
|
|
7254
|
+
}
|
|
6327
7255
|
/**
|
|
6328
7256
|
* Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
|
|
6329
7257
|
* Server and PostgreSQL), in place, and returns the row.
|
|
@@ -6372,8 +7300,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6372
7300
|
const where = this.BuildPrimaryKeyWhereClause(entityInfo, compositeKey);
|
|
6373
7301
|
// Append Read row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
6374
7302
|
let fullWhere = where;
|
|
7303
|
+
let rlsParameters = [];
|
|
6375
7304
|
if (user) {
|
|
6376
|
-
const
|
|
7305
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7306
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '', rlsBinder ?? undefined);
|
|
7307
|
+
if (rlsBinder?.Parameters?.length) {
|
|
7308
|
+
rlsParameters = rlsBinder.Parameters;
|
|
7309
|
+
}
|
|
6377
7310
|
if (rlsWhereClause && rlsWhereClause.length > 0) {
|
|
6378
7311
|
fullWhere = `${where} AND (${rlsWhereClause})`;
|
|
6379
7312
|
}
|
|
@@ -6389,7 +7322,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6389
7322
|
// Unrestricted users keep the literal `SELECT *` — byte-identical SQL, no plan churn.
|
|
6390
7323
|
const selectList = this.buildFieldSecuritySelectList(entityInfo, user);
|
|
6391
7324
|
const sql = `SELECT ${selectList} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${fullWhere}`;
|
|
6392
|
-
const
|
|
7325
|
+
const queryParams = rlsParameters.length > 0 ? rlsParameters : undefined;
|
|
7326
|
+
const rawData = await this.ExecuteSQL(sql, queryParams, undefined, user);
|
|
6393
7327
|
const d = await this.PostProcessRows(rawData, entityInfo, user);
|
|
6394
7328
|
if (d && d.length > 0) {
|
|
6395
7329
|
const ret = this.TrimFixedWidthValues(entityInfo, d[0]);
|
|
@@ -6413,15 +7347,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6413
7347
|
}
|
|
6414
7348
|
// An EntityRelationship joins on ONE column (RelatedEntityJoinField / JoinEntityJoinField)
|
|
6415
7349
|
// that references this entity's key — a single-column foreign-key target by metadata design.
|
|
6416
|
-
const
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
if (
|
|
6420
|
-
|
|
6421
|
-
|
|
6422
|
-
else {
|
|
6423
|
-
// many to many — use join view
|
|
6424
|
-
relSql = `SELECT _theview.* FROM ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.RelatedEntityBaseView)} _theview INNER JOIN ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.JoinView)} _jv ON _theview.${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = _jv.${this.QuoteIdentifier(relInfo.JoinEntityInverseJoinField)} WHERE _jv.${this.QuoteIdentifier(relInfo.JoinEntityJoinField)} = ${quotes}${pkValue}${quotes}`;
|
|
7350
|
+
const relSql = this.BuildRelatedRowsLoadSQL(relInfo, relEntityInfo, ret[entity.FirstPrimaryKey.Name], // first-pk-ok: relationship join field is a single-column FK target
|
|
7351
|
+
entity.FirstPrimaryKey.NeedsQuotes, // first-pk-ok: relationship join field is a single-column FK target
|
|
7352
|
+
user);
|
|
7353
|
+
if (relSql === null) {
|
|
7354
|
+
LogStatus(`[GenericDatabaseProvider] Skipping relationship '${rel}' on '${entityInfo.Name}': the user cannot read '${relEntityInfo.Name}'.`);
|
|
7355
|
+
continue;
|
|
6425
7356
|
}
|
|
6426
7357
|
const rawRelData = await this.ExecuteSQL(relSql, undefined, undefined, user);
|
|
6427
7358
|
if (rawRelData && rawRelData.length > 0) {
|
|
@@ -6433,6 +7364,34 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6433
7364
|
}
|
|
6434
7365
|
return null;
|
|
6435
7366
|
}
|
|
7367
|
+
/**
|
|
7368
|
+
* Builds the SELECT for one relationship of a single-record load, or returns null when the
|
|
7369
|
+
* user may not read the related entity at all (the caller skips the relationship).
|
|
7370
|
+
*
|
|
7371
|
+
* The related rows get the same protection the parent row gets: the column list leaves out
|
|
7372
|
+
* fields the user may not read, and the user's Read row filter narrows the rows. A user with
|
|
7373
|
+
* no field denials and no row filter gets the same SQL as before. With no user (server-side
|
|
7374
|
+
* system work) nothing is narrowed, which matches the parent load.
|
|
7375
|
+
*
|
|
7376
|
+
* For a many-to-many relationship the row filter is applied inside a derived table over the
|
|
7377
|
+
* related view, so its column names cannot clash with the join view's.
|
|
7378
|
+
*/
|
|
7379
|
+
BuildRelatedRowsLoadSQL(relInfo, relEntityInfo, pkValue, pkNeedsQuotes, user) {
|
|
7380
|
+
if (user && !relEntityInfo.GetUserPermisions(user)?.CanRead) {
|
|
7381
|
+
return null;
|
|
7382
|
+
}
|
|
7383
|
+
const keyLiteral = this.RenderKeyLiteral(pkValue, pkNeedsQuotes, relInfo.RelatedEntityJoinField, relEntityInfo.Name);
|
|
7384
|
+
const rowFilter = user ? relEntityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '') : '';
|
|
7385
|
+
const relatedView = this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.RelatedEntityBaseView);
|
|
7386
|
+
if (relInfo.Type.trim().toLowerCase() === 'one to many') {
|
|
7387
|
+
const filterClause = rowFilter ? ` AND (${rowFilter})` : '';
|
|
7388
|
+
return `SELECT ${this.buildFieldSecuritySelectList(relEntityInfo, user)} FROM ${relatedView} WHERE ${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = ${keyLiteral}${filterClause}`;
|
|
7389
|
+
}
|
|
7390
|
+
// many to many — through the join view
|
|
7391
|
+
const columns = this.buildFieldSecuritySelectList(relEntityInfo, user, '_theview');
|
|
7392
|
+
const source = rowFilter ? `(SELECT * FROM ${relatedView} WHERE (${rowFilter}))` : relatedView;
|
|
7393
|
+
return `SELECT ${columns} FROM ${source} _theview INNER JOIN ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.JoinView)} _jv ON _theview.${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = _jv.${this.QuoteIdentifier(relInfo.JoinEntityInverseJoinField)} WHERE _jv.${this.QuoteIdentifier(relInfo.JoinEntityJoinField)} = ${keyLiteral}`;
|
|
7394
|
+
}
|
|
6436
7395
|
/**************************************************************************/
|
|
6437
7396
|
// Row-Level Security Checks
|
|
6438
7397
|
/**************************************************************************/
|
|
@@ -6443,23 +7402,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6443
7402
|
*/
|
|
6444
7403
|
async CheckRecordRLS(entity, user, type) {
|
|
6445
7404
|
const entityInfo = entity.EntityInfo;
|
|
6446
|
-
const
|
|
7405
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7406
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, type, '', rlsBinder ?? undefined);
|
|
6447
7407
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6448
7408
|
return true;
|
|
6449
7409
|
}
|
|
6450
7410
|
const pkWhere = entity.PrimaryKeys.map(pk => {
|
|
6451
7411
|
const fieldInfo = entityInfo.FieldByName(pk.Name);
|
|
6452
|
-
|
|
6453
|
-
//
|
|
6454
|
-
//
|
|
6455
|
-
//
|
|
6456
|
-
|
|
6457
|
-
// pass RLS on rows the caller cannot see.
|
|
6458
|
-
const safeVal = quotes ? String(pk.Value).replace(/'/g, "''") : pk.Value;
|
|
6459
|
-
return `${this.QuoteIdentifier(pk.Name)}=${quotes}${safeVal}${quotes}`;
|
|
7412
|
+
// Rendered as on the Load()-by-PK path above. The PK value can be CLIENT-SUPPLIED here
|
|
7413
|
+
// (the update resolver loads OldValues from the client for entities without record
|
|
7414
|
+
// tracking), and this method's only job is an authorization decision — a crafted PK
|
|
7415
|
+
// must not make the COUNT(*) pass RLS on rows the caller cannot see.
|
|
7416
|
+
return `${this.QuoteIdentifier(pk.Name)}=${this.RenderPrimaryKeyLiteral(fieldInfo, pk.Value, entityInfo.Name)}`;
|
|
6460
7417
|
}).join(' AND ');
|
|
6461
7418
|
const sql = `SELECT COUNT(*) AS cnt FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${pkWhere} AND (${rlsWhereClause})`;
|
|
6462
|
-
const
|
|
7419
|
+
const queryParams = rlsBinder?.Parameters?.length ? rlsBinder.Parameters : undefined;
|
|
7420
|
+
const result = await this.ExecuteSQL(sql, queryParams, undefined, user);
|
|
6463
7421
|
return result && result.length > 0 && Number(result[0]['cnt']) > 0;
|
|
6464
7422
|
}
|
|
6465
7423
|
/**
|
|
@@ -6472,13 +7430,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6472
7430
|
*/
|
|
6473
7431
|
async CheckCreateRLS(entity, user) {
|
|
6474
7432
|
const entityInfo = entity.EntityInfo;
|
|
6475
|
-
const
|
|
7433
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7434
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Create, '', rlsBinder ?? undefined);
|
|
6476
7435
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6477
7436
|
return true;
|
|
6478
7437
|
}
|
|
6479
|
-
const
|
|
6480
|
-
const
|
|
6481
|
-
|
|
7438
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, false, rlsBinder?.Parameters?.length ?? 0);
|
|
7439
|
+
const allParams = [
|
|
7440
|
+
...(rlsBinder?.Parameters ?? []),
|
|
7441
|
+
...syntheticRow.parameters
|
|
7442
|
+
];
|
|
7443
|
+
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
7444
|
+
const result = await this.ExecuteSQL(sql, allParams.length > 0 ? allParams : undefined, undefined, user);
|
|
6482
7445
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
6483
7446
|
}
|
|
6484
7447
|
/**
|
|
@@ -6497,7 +7460,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6497
7460
|
*/
|
|
6498
7461
|
async CheckUpdateRLSPostImage(entity, user) {
|
|
6499
7462
|
const entityInfo = entity.EntityInfo;
|
|
6500
|
-
const
|
|
7463
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7464
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Update, '', rlsBinder ?? undefined);
|
|
6501
7465
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6502
7466
|
return true;
|
|
6503
7467
|
}
|
|
@@ -6509,11 +7473,61 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6509
7473
|
return true; // pre-image check already passed and no filter-referenced column changed
|
|
6510
7474
|
}
|
|
6511
7475
|
}
|
|
6512
|
-
const
|
|
6513
|
-
const
|
|
6514
|
-
|
|
7476
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, false, rlsBinder?.Parameters?.length ?? 0);
|
|
7477
|
+
const allParams = [
|
|
7478
|
+
...(rlsBinder?.Parameters ?? []),
|
|
7479
|
+
...syntheticRow.parameters
|
|
7480
|
+
];
|
|
7481
|
+
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
7482
|
+
const result = await this.ExecuteSQL(sql, allParams.length > 0 ? allParams : undefined, undefined, user);
|
|
6515
7483
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
6516
7484
|
}
|
|
7485
|
+
/**
|
|
7486
|
+
* Evaluates an arbitrary SQL `whereClause` against an entity's pending in-memory field values
|
|
7487
|
+
* using the same typed synthetic-row subquery (`SELECT CASE WHEN (...) THEN 1 ELSE 0 END`)
|
|
7488
|
+
* used by Create/Update RLS post-image enforcement, without taking or blocking on table locks.
|
|
7489
|
+
*
|
|
7490
|
+
* When `dirtyOnlyOptimization` is `true` and `whereClause` decomposes cleanly into simple
|
|
7491
|
+
* column comparisons whose referenced columns are all clean on `entity`, returns `true`
|
|
7492
|
+
* without a database round-trip (safe only when the pre-image was already verified).
|
|
7493
|
+
*/
|
|
7494
|
+
async EvaluateSyntheticRowWhereClause(entity, whereClause, user, dirtyOnlyOptimization = false) {
|
|
7495
|
+
const trimmed = whereClause.trim();
|
|
7496
|
+
if (trimmed.length === 0) {
|
|
7497
|
+
return true;
|
|
7498
|
+
}
|
|
7499
|
+
const parentFieldNames = entity.EntityInfo?.ParentEntityFieldNames;
|
|
7500
|
+
const nonIsaVirtualNames = new Set((entity.EntityInfo?.Fields ?? [])
|
|
7501
|
+
.filter(f => f.IsVirtual && !parentFieldNames?.has(f.Name))
|
|
7502
|
+
.map(f => f.Name.trim().toLowerCase()));
|
|
7503
|
+
if (nonIsaVirtualNames.size > 0) {
|
|
7504
|
+
const matchedVirtual = ClientClauseScreen.ExtractStatementIdentifierTokens(trimmed, this.Dialect).filter(tok => nonIsaVirtualNames.has(tok.trim().toLowerCase()));
|
|
7505
|
+
if (matchedVirtual.length > 0) {
|
|
7506
|
+
LogError(`EvaluateSyntheticRowWhereClause refused for entity '${entity.EntityInfo?.Name}': write-side whereClause references non-IS-A virtual view column(s) [${matchedVirtual.join(', ')}]`);
|
|
7507
|
+
return false;
|
|
7508
|
+
}
|
|
7509
|
+
}
|
|
7510
|
+
if (dirtyOnlyOptimization) {
|
|
7511
|
+
const referencedColumns = this.TryExtractSimpleFilterColumns(trimmed);
|
|
7512
|
+
if (referencedColumns) {
|
|
7513
|
+
const dirtyNames = new Set(entity.Fields.filter(f => f.Dirty).map(f => f.Name.trim().toLowerCase()));
|
|
7514
|
+
const touchesFilterColumn = referencedColumns.some(c => dirtyNames.has(c));
|
|
7515
|
+
if (!touchesFilterColumn) {
|
|
7516
|
+
return true;
|
|
7517
|
+
}
|
|
7518
|
+
}
|
|
7519
|
+
}
|
|
7520
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entity.EntityInfo, true);
|
|
7521
|
+
const sql = `SELECT CASE WHEN (${trimmed}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
7522
|
+
try {
|
|
7523
|
+
const result = await this.ExecuteSQL(sql, syntheticRow.parameters.length > 0 ? syntheticRow.parameters : undefined, undefined, user);
|
|
7524
|
+
return Boolean(result && result.length > 0 && Number(result[0]['pass']) === 1);
|
|
7525
|
+
}
|
|
7526
|
+
catch (err) {
|
|
7527
|
+
LogError(`EvaluateSyntheticRowWhereClause failed for entity '${entity.EntityInfo?.Name}': ${err instanceof Error ? err.message : String(err)}`);
|
|
7528
|
+
return false;
|
|
7529
|
+
}
|
|
7530
|
+
}
|
|
6517
7531
|
/**
|
|
6518
7532
|
* Attempts to fully decompose an RLS WHERE clause into the lower-cased column names it
|
|
6519
7533
|
* references. Returns the columns ONLY when the whole clause is a conjunction of simple
|
|
@@ -6541,6 +7555,67 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6541
7555
|
}
|
|
6542
7556
|
return columns.length > 0 ? columns : null;
|
|
6543
7557
|
}
|
|
7558
|
+
/**
|
|
7559
|
+
* Builds field projections and query parameters for an RLS synthetic-row subquery.
|
|
7560
|
+
* Null fields are projected as typed `CAST(NULL AS <sqltype>)`.
|
|
7561
|
+
* Non-null fields are bound as query parameters rather than interpolated literals.
|
|
7562
|
+
*/
|
|
7563
|
+
BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, includeISAParentFields = false, paramStartIndex = 0) {
|
|
7564
|
+
const dialect = this.getDialect();
|
|
7565
|
+
const parts = [];
|
|
7566
|
+
const parameters = [];
|
|
7567
|
+
const parentFieldNames = includeISAParentFields ? entityInfo.ParentEntityFieldNames : undefined;
|
|
7568
|
+
for (const field of entityInfo.Fields) {
|
|
7569
|
+
if (field.IsVirtual && !parentFieldNames?.has(field.Name))
|
|
7570
|
+
continue;
|
|
7571
|
+
const val = entity.Get(field.Name);
|
|
7572
|
+
if (val == null) {
|
|
7573
|
+
parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7574
|
+
}
|
|
7575
|
+
else if (val instanceof Uint8Array) {
|
|
7576
|
+
const hex = Buffer.from(val).toString('hex');
|
|
7577
|
+
const hexExpr = dialect?.BinaryTypeNames.includes('bytea')
|
|
7578
|
+
? `decode('${hex}', 'hex')`
|
|
7579
|
+
: (hex.length > 0 ? `0x${hex}` : '0x');
|
|
7580
|
+
parts.push(`${hexExpr} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7581
|
+
}
|
|
7582
|
+
else {
|
|
7583
|
+
const paramIdx = paramStartIndex + parameters.length;
|
|
7584
|
+
const placeholder = dialect ? dialect.Binding.ParameterPlaceholder(paramIdx) : `@_syn_p${paramIdx}`;
|
|
7585
|
+
const paramName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
7586
|
+
let boundValue;
|
|
7587
|
+
if (typeof val === 'boolean' || val instanceof Date || typeof val === 'number') {
|
|
7588
|
+
boundValue = val;
|
|
7589
|
+
}
|
|
7590
|
+
else if (field.NeedsQuotes) {
|
|
7591
|
+
boundValue = String(val);
|
|
7592
|
+
}
|
|
7593
|
+
else {
|
|
7594
|
+
const num = Number(String(val));
|
|
7595
|
+
if (!Number.isFinite(num)) {
|
|
7596
|
+
throw new Error(`Cannot build RLS projection: value for numeric field ${field.Name} does not parse as a number`);
|
|
7597
|
+
}
|
|
7598
|
+
boundValue = num;
|
|
7599
|
+
}
|
|
7600
|
+
parameters.push(new NamedQueryParameter(paramName, boundValue));
|
|
7601
|
+
const baseType = field.Type;
|
|
7602
|
+
if (baseType && baseType.trim().length > 0) {
|
|
7603
|
+
const isBinary = /^(var)?binary$/i.test(baseType.trim());
|
|
7604
|
+
const charLength = field.Length === -1 || isBinary ? field.Length : field.MaxLength;
|
|
7605
|
+
const mapped = dialect?.MapDataTypeToString(baseType, charLength, field.Precision, field.Scale);
|
|
7606
|
+
const mappedType = mapped ?? field.SQLFullType ?? baseType;
|
|
7607
|
+
parts.push(`CAST(${placeholder} AS ${mappedType}) AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7608
|
+
}
|
|
7609
|
+
else if (field.SQLFullType && field.SQLFullType.trim().length > 0) {
|
|
7610
|
+
parts.push(`CAST(${placeholder} AS ${field.SQLFullType}) AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7611
|
+
}
|
|
7612
|
+
else {
|
|
7613
|
+
parts.push(`${placeholder} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7614
|
+
}
|
|
7615
|
+
}
|
|
7616
|
+
}
|
|
7617
|
+
return { projections: parts.join(', '), parameters };
|
|
7618
|
+
}
|
|
6544
7619
|
/**
|
|
6545
7620
|
* Builds field projections for an RLS synthetic-row subquery (Create post-image and
|
|
6546
7621
|
* Update post-image checks).
|
|
@@ -6552,10 +7627,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6552
7627
|
* `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
|
|
6553
7628
|
* type fails the save (throw) rather than emitting an untyped NULL.
|
|
6554
7629
|
*/
|
|
6555
|
-
BuildRLSSyntheticRowProjections(entity, entityInfo) {
|
|
7630
|
+
BuildRLSSyntheticRowProjections(entity, entityInfo, includeISAParentFields = false) {
|
|
6556
7631
|
const parts = [];
|
|
7632
|
+
const parentFieldNames = includeISAParentFields ? entityInfo.ParentEntityFieldNames : undefined;
|
|
6557
7633
|
for (const field of entityInfo.Fields) {
|
|
6558
|
-
if (field.IsVirtual)
|
|
7634
|
+
if (field.IsVirtual && !parentFieldNames?.has(field.Name))
|
|
6559
7635
|
continue;
|
|
6560
7636
|
const val = entity.Get(field.Name);
|
|
6561
7637
|
parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
@@ -6649,6 +7725,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6649
7725
|
BuildParameterPlaceholder(index) {
|
|
6650
7726
|
return `$${index + 1}`;
|
|
6651
7727
|
}
|
|
7728
|
+
/** An ItemFilter that is exactly `1=0` (spacing aside): the caller wants no rows from the item. */
|
|
7729
|
+
static { this._noRowItemFilter = /^\s*1\s*=\s*0\s*$/; }
|
|
7730
|
+
/** Whether a dataset ItemFilter asks for no rows at all, so the item needs no read. */
|
|
7731
|
+
static isNoRowItemFilter(filter) {
|
|
7732
|
+
return !!filter && GenericDatabaseProvider._noRowItemFilter.test(filter);
|
|
7733
|
+
}
|
|
6652
7734
|
/**
|
|
6653
7735
|
* Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
|
|
6654
7736
|
* denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
|
|
@@ -6757,7 +7839,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6757
7839
|
*
|
|
6758
7840
|
* An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
|
|
6759
7841
|
* CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
|
|
6760
|
-
* item runs no SQL and fails the dataset.
|
|
7842
|
+
* item runs no SQL and fails the dataset. An item whose ItemFilter is exactly `1=0` runs no SQL
|
|
7843
|
+
* either: it returns an empty, successful result.
|
|
6761
7844
|
*/
|
|
6762
7845
|
async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
|
|
6763
7846
|
const provider = (providerToUse ?? this);
|
|
@@ -6792,6 +7875,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6792
7875
|
const cacheAvailable = !forceRefresh && cache.IsInitialized && this.TrustLocalCacheCompletely;
|
|
6793
7876
|
const errorResults = [];
|
|
6794
7877
|
const cachedResults = [];
|
|
7878
|
+
// Items the caller asked for with a no-row ItemFilter: answered without a read.
|
|
7879
|
+
const noRowResults = [];
|
|
6795
7880
|
const uncachedQueries = [];
|
|
6796
7881
|
const uncachedItems = [];
|
|
6797
7882
|
// Track fingerprints for uncached items so we can write-through after SQL
|
|
@@ -6839,6 +7924,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6839
7924
|
});
|
|
6840
7925
|
continue;
|
|
6841
7926
|
}
|
|
7927
|
+
// An ItemFilter of exactly `1=0` asks for no rows, whatever the stored WhereClause or the
|
|
7928
|
+
// caller's row filter add to it, so the item is answered without a read. The scoped
|
|
7929
|
+
// metadata reload (ProviderBase.TryPartialMetadataReload) sends it for every item it does
|
|
7930
|
+
// not reload; each used to run its own empty SELECT, one pool connection apiece.
|
|
7931
|
+
if (GenericDatabaseProvider.isNoRowItemFilter(itemFilters?.find(f => f?.ItemCode === code)?.Filter)) {
|
|
7932
|
+
noRowResults.push({
|
|
7933
|
+
EntityID: entityID,
|
|
7934
|
+
EntityName: entityName,
|
|
7935
|
+
Code: code,
|
|
7936
|
+
Results: [],
|
|
7937
|
+
LatestUpdateDate: this.computeLatestUpdateDate([], String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt'), item),
|
|
7938
|
+
Success: true,
|
|
7939
|
+
});
|
|
7940
|
+
continue;
|
|
7941
|
+
}
|
|
6842
7942
|
// The row filter keys the slot, so one user's filtered rows are never served to another.
|
|
6843
7943
|
const rowFilterKey = scope.RowFilter || undefined;
|
|
6844
7944
|
const fingerprint = cacheAvailable
|
|
@@ -7040,21 +8140,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7040
8140
|
? this.extractMaxUpdatedAtFromRows(itemData, dateFieldToCheck)
|
|
7041
8141
|
: new Date(0).toISOString();
|
|
7042
8142
|
const syntheticParams = { EntityName: entityName };
|
|
7043
|
-
//
|
|
7044
|
-
//
|
|
7045
|
-
//
|
|
7046
|
-
//
|
|
7047
|
-
|
|
7048
|
-
// Freezing them makes metadata bootstrap throw and the process starts blind.
|
|
7049
|
-
//
|
|
7050
|
-
// Every OTHER dataset is served to arbitrary consumers (BaseEngine.Load hands
|
|
7051
|
-
// item.Results — these very arrays — to every engine subclass), so those slots
|
|
7052
|
-
// must stay under the defensive deep-freeze like any RunView result.
|
|
7053
|
-
const isMetadataScaffolding = datasetName === ProviderBase._mjMetadataDatasetName;
|
|
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);
|
|
8143
|
+
// Every dataset's slots — MJ_Metadata's included — hold rows that later readers are
|
|
8144
|
+
// served (BaseEngine.Load hands item.Results to every engine subclass; the GraphQL
|
|
8145
|
+
// dataset resolver hands MJ_Metadata to every client), so they are frozen like any
|
|
8146
|
+
// RunView result. The metadata assembly copies the rows it writes to.
|
|
8147
|
+
await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName)), maxUpdatedAt, undefined, undefined, this);
|
|
7058
8148
|
}
|
|
7059
8149
|
sqlResults.push({
|
|
7060
8150
|
EntityID: entityID,
|
|
@@ -7065,11 +8155,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7065
8155
|
Success: itemData !== null && itemData !== undefined,
|
|
7066
8156
|
});
|
|
7067
8157
|
}
|
|
7068
|
-
// Merge results: errors + cached + SQL (maintain original item order via code matching)
|
|
8158
|
+
// Merge results: errors + no-row + cached + SQL (maintain original item order via code matching)
|
|
7069
8159
|
const results = [];
|
|
7070
8160
|
for (const item of items) {
|
|
7071
8161
|
const code = String(item['Code']);
|
|
7072
8162
|
const found = errorResults.find(r => r.Code === code)
|
|
8163
|
+
?? noRowResults.find(r => r.Code === code)
|
|
7073
8164
|
?? cachedResults.find(r => r.Code === code)
|
|
7074
8165
|
?? sqlResults.find(r => r.Code === code);
|
|
7075
8166
|
if (found)
|
|
@@ -7591,6 +8682,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7591
8682
|
}
|
|
7592
8683
|
this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
|
|
7593
8684
|
}
|
|
8685
|
+
/**
|
|
8686
|
+
* Savepoint- and token-aware coalesced post-commit scheduling.
|
|
8687
|
+
*
|
|
8688
|
+
* Entries recorded inside an open transaction retain their owning depth so savepoint rollbacks
|
|
8689
|
+
* drop rolled-back registrations without touching earlier frames' registrations under the same
|
|
8690
|
+
* key; surviving entries deduplicate once at outermost commit (`'last-wins'` or `'first-wins'`).
|
|
8691
|
+
*/
|
|
8692
|
+
ScheduleAfterCommit(coalesceKey, task, description = 'post-commit task', token, mode = 'last-wins') {
|
|
8693
|
+
if (!coalesceKey) {
|
|
8694
|
+
this.RunAfterCommit(task, description, token);
|
|
8695
|
+
return;
|
|
8696
|
+
}
|
|
8697
|
+
if (token) {
|
|
8698
|
+
this.registerPostCommitTaskWithToken(task, description, token, coalesceKey, mode);
|
|
8699
|
+
return;
|
|
8700
|
+
}
|
|
8701
|
+
if (!this.IsCallerInAmbientTransaction()) {
|
|
8702
|
+
this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode);
|
|
8703
|
+
return;
|
|
8704
|
+
}
|
|
8705
|
+
this._postCommitTasks.push({
|
|
8706
|
+
Task: task,
|
|
8707
|
+
Description: description,
|
|
8708
|
+
Depth: this._transactionDepth,
|
|
8709
|
+
CoalesceKey: coalesceKey,
|
|
8710
|
+
CoalesceMode: mode,
|
|
8711
|
+
});
|
|
8712
|
+
}
|
|
8713
|
+
ExecuteDetachedPostCommitTask(task, description) {
|
|
8714
|
+
this.runDetachedTask(task, description);
|
|
8715
|
+
}
|
|
7594
8716
|
/**
|
|
7595
8717
|
* Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
|
|
7596
8718
|
* provider: outside a transaction it returns a token whose epoch is `null`, which says the work
|
|
@@ -7605,14 +8727,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7605
8727
|
}
|
|
7606
8728
|
return this._frameTracker.Capture();
|
|
7607
8729
|
}
|
|
7608
|
-
registerPostCommitTaskWithToken(task, description, token) {
|
|
8730
|
+
registerPostCommitTaskWithToken(task, description, token, coalesceKey, coalesceMode) {
|
|
7609
8731
|
const resolution = this._frameTracker.Resolve(token, this._doomed);
|
|
7610
8732
|
switch (resolution.Kind) {
|
|
7611
8733
|
case 'run':
|
|
7612
|
-
|
|
8734
|
+
if (coalesceKey) {
|
|
8735
|
+
this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, coalesceMode ?? 'last-wins');
|
|
8736
|
+
}
|
|
8737
|
+
else {
|
|
8738
|
+
this.runDetachedTask(task, description);
|
|
8739
|
+
}
|
|
7613
8740
|
return;
|
|
7614
8741
|
case 'queue':
|
|
7615
|
-
this._postCommitTasks.push({
|
|
8742
|
+
this._postCommitTasks.push({
|
|
8743
|
+
Task: task,
|
|
8744
|
+
Description: description,
|
|
8745
|
+
Depth: resolution.Depth,
|
|
8746
|
+
...(coalesceKey ? { CoalesceKey: coalesceKey, CoalesceMode: coalesceMode ?? 'last-wins' } : {}),
|
|
8747
|
+
});
|
|
7616
8748
|
return;
|
|
7617
8749
|
case 'drop':
|
|
7618
8750
|
if (resolution.Unknown) {
|
|
@@ -7649,15 +8781,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7649
8781
|
}
|
|
7650
8782
|
/** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
|
|
7651
8783
|
async runPostCommitTasks(tasks) {
|
|
7652
|
-
|
|
8784
|
+
const effectiveTasks = this.coalescePostCommitTasks(tasks);
|
|
8785
|
+
if (effectiveTasks.length === 0) {
|
|
7653
8786
|
return;
|
|
7654
8787
|
}
|
|
7655
|
-
LogStatus(`Running ${
|
|
7656
|
-
for (const entry of
|
|
8788
|
+
LogStatus(`Running ${effectiveTasks.length} post-commit task(s) after transaction commit`);
|
|
8789
|
+
for (const entry of effectiveTasks) {
|
|
7657
8790
|
// Detached from the committer's (now stale) membership explicitly, not merely by epoch mismatch.
|
|
7658
8791
|
await this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(entry.Task, entry.Description));
|
|
7659
8792
|
}
|
|
7660
8793
|
}
|
|
8794
|
+
/** Deduplicates entries sharing a `CoalesceKey` after savepoint rollbacks have already been pruned. */
|
|
8795
|
+
coalescePostCommitTasks(tasks) {
|
|
8796
|
+
let hasCoalesced = false;
|
|
8797
|
+
const winnerIndex = new Map();
|
|
8798
|
+
for (let i = 0; i < tasks.length; i++) {
|
|
8799
|
+
const entry = tasks[i];
|
|
8800
|
+
if (!entry.CoalesceKey) {
|
|
8801
|
+
continue;
|
|
8802
|
+
}
|
|
8803
|
+
hasCoalesced = true;
|
|
8804
|
+
if ((entry.CoalesceMode ?? 'last-wins') === 'first-wins') {
|
|
8805
|
+
if (!winnerIndex.has(entry.CoalesceKey)) {
|
|
8806
|
+
winnerIndex.set(entry.CoalesceKey, i);
|
|
8807
|
+
}
|
|
8808
|
+
}
|
|
8809
|
+
else {
|
|
8810
|
+
winnerIndex.set(entry.CoalesceKey, i);
|
|
8811
|
+
}
|
|
8812
|
+
}
|
|
8813
|
+
if (!hasCoalesced) {
|
|
8814
|
+
return tasks;
|
|
8815
|
+
}
|
|
8816
|
+
return tasks.filter((entry, idx) => !entry.CoalesceKey || winnerIndex.get(entry.CoalesceKey) === idx);
|
|
8817
|
+
}
|
|
7661
8818
|
/** Detach the whole queue (outermost commit succeeded). */
|
|
7662
8819
|
takePostCommitTasks() {
|
|
7663
8820
|
const tasks = this._postCommitTasks;
|
|
@@ -7773,6 +8930,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7773
8930
|
}
|
|
7774
8931
|
await this.endBatchLevelIfOpen(true);
|
|
7775
8932
|
if (committedTasks) {
|
|
8933
|
+
this.BumpTransactionEpoch();
|
|
7776
8934
|
await this.runPostCommitTasks(committedTasks);
|
|
7777
8935
|
await this.AfterPhysicalCommit();
|
|
7778
8936
|
}
|
|
@@ -7782,6 +8940,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7782
8940
|
await this.WithTransactionLock(() => this.rollbackTransactionCore());
|
|
7783
8941
|
}
|
|
7784
8942
|
finally {
|
|
8943
|
+
if (this._transactionDepth === 0) {
|
|
8944
|
+
this.BumpTransactionEpoch();
|
|
8945
|
+
}
|
|
7785
8946
|
await this.endBatchLevelIfOpen(false);
|
|
7786
8947
|
}
|
|
7787
8948
|
}
|