@memberjunction/generic-database-provider 6.2.0 → 6.3.0-edge.0

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.
@@ -15,15 +15,15 @@
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, } from '@memberjunction/core';
19
+ import { BytesToBase64, 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
29
  import { StatementMemo } from './statementMemo.js';
@@ -32,6 +32,7 @@ import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './
32
32
  // QueryCompositionEngine is now owned by RenderPipeline
33
33
  import { RenderPipeline } from './renderPipeline.js';
34
34
  import { UseJsonArgShape } from './crudSprocFieldRules.js';
35
+ import { AreEntityFieldValuesDifferent, ClientOldValueToFieldValue, DetectFieldConcurrencyConflicts, FindEntityFieldByCodeNameOrName, IsFieldOpaqueToClient, } from './concurrency/fieldConflictDetector.js';
35
36
  import { GetQueryApprovalStateAsync, QueryEngine, ViewInfo, } from '@memberjunction/core-entities';
36
37
  import { AIEngine } from '@memberjunction/aiengine';
37
38
  import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
@@ -44,6 +45,10 @@ import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBat
44
45
  import { ClientClauseScreen } from './clientClauseScreen.js';
45
46
  import { IsSystemUser } from './systemUser.js';
46
47
  import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
48
+ import { NodeAsyncServerOperationScopeTracker } from './NodeAsyncServerOperationScopeTracker.js';
49
+ // Install Node AsyncLocalStorage-backed authority scope tracker on server startup so concurrent
50
+ // in-flight requests / remote operations maintain isolated ServerOperationScopeFrame stacks.
51
+ ServerOperationScopeManager.Instance.SetTracker(new NodeAsyncServerOperationScopeTracker());
47
52
  import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
48
53
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
49
54
  /**
@@ -158,6 +163,20 @@ export function FormatSqlParameterTypesForError(parameters) {
158
163
  export class GenericDatabaseProvider extends DatabaseProviderBase {
159
164
  constructor() {
160
165
  super(...arguments);
166
+ /**
167
+ * Server-side concurrency check mode for entity UPDATEs (`'off' | 'log' | 'enforce'`).
168
+ * Defaults to `'off'` so direct server-side background saves pay zero extra lock-read or
169
+ * transaction round-trips unless opted in via provider configuration or per-save
170
+ * `EntitySaveOptions.ConcurrencyCheck` (GraphQL mutations with `OldValues___` always pass `'enforce'`).
171
+ */
172
+ this.ConcurrencyCheck = 'off';
173
+ /**
174
+ * Controls whether entity UPDATEs against CodeGen-generated routines (`spUpdateGenerated === true`)
175
+ * bind only dirty columns instead of every loaded column. Defaults to `true`. Set to `false`
176
+ * (or configure `databaseSettings.deltaUpdates: false`) as an operational kill-switch to restore
177
+ * legacy full-row parameter binding across all saves.
178
+ */
179
+ this.DeltaUpdates = true;
161
180
  /**
162
181
  * Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
163
182
  * and Dataset slots. Within this window after a slot was written or last verified against
@@ -364,6 +383,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
364
383
  if (data?.LocalStorageProvider) {
365
384
  this.SetLocalStorageProvider(data.LocalStorageProvider);
366
385
  }
386
+ if (data?.ConcurrencyCheck) {
387
+ this.ConcurrencyCheck = data.ConcurrencyCheck;
388
+ }
389
+ if (data?.DeltaUpdates !== undefined) {
390
+ this.DeltaUpdates = data.DeltaUpdates;
391
+ }
367
392
  return super.Config(data, providerToUse);
368
393
  }
369
394
  /**
@@ -814,6 +839,138 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
814
839
  : null;
815
840
  return activeActions.some((a) => a.RunMode === 'Durable' && !originatingSet?.Has(a.ID));
816
841
  }
842
+ /**
843
+ * Dialect hook for reading a row under an exclusive/update row lock inside the save transaction
844
+ * immediately before `spUpdate*` executes.
845
+ *
846
+ * - SQL Server overrides to emit `SELECT [col1], ... FROM [schema].[BaseTable] WITH (UPDLOCK, ROWLOCK) WHERE ...`
847
+ * - PostgreSQL overrides to emit `SELECT "col1", ... FROM "schema"."BaseTable" WHERE ... FOR UPDATE`
848
+ */
849
+ RenderLockedRowReadSQL(_entityInfo, _pkWhereClause, _columns) {
850
+ return null;
851
+ }
852
+ getEffectiveConcurrencyCheckMode(options) {
853
+ return options?.ConcurrencyCheck ?? this.ConcurrencyCheck;
854
+ }
855
+ ShouldCheckUpdateConcurrency(entity, options) {
856
+ if (this.getEffectiveConcurrencyCheckMode(options) === 'off') {
857
+ return false;
858
+ }
859
+ if (options?.SkipOldValuesCheck || options?.IgnoreDirtyState || options?.ReplayOnly) {
860
+ return false;
861
+ }
862
+ if (!entity.PrimaryKey || entity.PrimaryKey.KeyValuePairs.length === 0) {
863
+ return false;
864
+ }
865
+ if (options?.ConcurrencyBaseline) {
866
+ for (const [key, rawBaseline] of Object.entries(options.ConcurrencyBaseline)) {
867
+ const f = FindEntityFieldByCodeNameOrName(entity.EntityInfo, key);
868
+ if (!f || f.ReadOnly || f.IsVirtual || f.IsPrimaryKey || IsFieldOpaqueToClient(f)) {
869
+ continue;
870
+ }
871
+ const coercedBaseline = ClientOldValueToFieldValue(f, rawBaseline);
872
+ const currentVal = entity.GetFieldByName(f.Name)?.Value;
873
+ if (AreEntityFieldValuesDifferent(f, coercedBaseline, currentVal, false)) {
874
+ return true;
875
+ }
876
+ }
877
+ }
878
+ return entity.Fields.some((f) => f.Dirty &&
879
+ !f.EntityFieldInfo.ReadOnly &&
880
+ !f.EntityFieldInfo.IsVirtual &&
881
+ !f.EntityFieldInfo.IsPrimaryKey &&
882
+ !IsFieldOpaqueToClient(f.EntityFieldInfo));
883
+ }
884
+ async CheckUpdateConcurrency(entity, user, options, entityResult) {
885
+ if (!this.ShouldCheckUpdateConcurrency(entity, options)) {
886
+ return true;
887
+ }
888
+ const effectiveMode = this.getEffectiveConcurrencyCheckMode(options);
889
+ const baselineValues = {};
890
+ const newValues = {};
891
+ if (options?.ConcurrencyBaseline) {
892
+ for (const [key, rawBaseline] of Object.entries(options.ConcurrencyBaseline)) {
893
+ const f = FindEntityFieldByCodeNameOrName(entity.EntityInfo, key);
894
+ if (!f || f.ReadOnly || f.IsVirtual || f.IsPrimaryKey || IsFieldOpaqueToClient(f)) {
895
+ continue;
896
+ }
897
+ const coercedBaseline = ClientOldValueToFieldValue(f, rawBaseline);
898
+ const entityField = entity.GetFieldByName(f.Name);
899
+ const currentVal = entityField ? entityField.Value : undefined;
900
+ if (AreEntityFieldValuesDifferent(f, coercedBaseline, currentVal, false)) {
901
+ baselineValues[f.Name] = coercedBaseline;
902
+ newValues[f.Name] = currentVal;
903
+ }
904
+ }
905
+ }
906
+ for (const entityField of entity.Fields) {
907
+ const f = entityField.EntityFieldInfo;
908
+ if (entityField.Dirty &&
909
+ !f.ReadOnly &&
910
+ !f.IsVirtual &&
911
+ !f.IsPrimaryKey &&
912
+ !IsFieldOpaqueToClient(f) &&
913
+ !(f.Name in baselineValues)) {
914
+ baselineValues[f.Name] = entityField.OldValue;
915
+ newValues[f.Name] = entityField.Value;
916
+ }
917
+ }
918
+ const columnsToRead = Object.keys(baselineValues);
919
+ if (columnsToRead.length === 0) {
920
+ return true;
921
+ }
922
+ const pkWhereClause = this.BuildPrimaryKeyWhereClause(entity.EntityInfo, entity.PrimaryKey);
923
+ if (!pkWhereClause) {
924
+ return true;
925
+ }
926
+ const sql = this.RenderLockedRowReadSQL(entity.EntityInfo, pkWhereClause, columnsToRead);
927
+ if (!sql) {
928
+ return true;
929
+ }
930
+ const rawRows = await this.ExecuteSQL(sql, undefined, {
931
+ description: `Concurrency check lock read for ${entity.EntityInfo.Name}`,
932
+ ignoreLogging: true,
933
+ }, user);
934
+ if (!rawRows || rawRows.length === 0) {
935
+ return true;
936
+ }
937
+ const processedRows = await this.PostProcessRows(rawRows, entity.EntityInfo, user);
938
+ const storedRow = processedRows[0] ?? rawRows[0];
939
+ this.TrimFixedWidthValues(entity.EntityInfo, storedRow);
940
+ const checkResult = DetectFieldConcurrencyConflicts(entity.EntityInfo, baselineValues, newValues, storedRow);
941
+ if (checkResult.ConflictingFields.length === 0) {
942
+ return true;
943
+ }
944
+ const msg = {
945
+ Message: 'Concurrent modification conflict: one or more fields modified by the caller were updated in the database since the record was loaded.',
946
+ ClientDifferences: checkResult.ClientDifferences,
947
+ DBDifferences: checkResult.DBDifferences,
948
+ Overlap: checkResult.Overlap,
949
+ };
950
+ LogErrorEx({
951
+ message: `Entity save concurrency conflict detected on ${entity.EntityInfo.Name}: ${JSON.stringify(msg)}`,
952
+ severity: 'warning',
953
+ category: 'GenericDatabaseProvider.CheckUpdateConcurrency',
954
+ metadata: {
955
+ entityName: entity.EntityInfo.Name,
956
+ mode: effectiveMode,
957
+ conflictingFields: checkResult.ConflictingFields,
958
+ clientDifferences: checkResult.ClientDifferences,
959
+ dbDifferences: checkResult.DBDifferences,
960
+ overlap: checkResult.Overlap,
961
+ },
962
+ });
963
+ if (effectiveMode === 'enforce') {
964
+ entityResult.Success = false;
965
+ entityResult.EndedAt = new Date();
966
+ entityResult.ConcurrencyConflict = {
967
+ ConflictingFields: checkResult.ConflictingFields,
968
+ };
969
+ entityResult.Message = `Concurrent modification conflict on ${entity.EntityInfo.Name} for field(s): ${checkResult.ConflictingFields.join(', ')}. Reload the record and retry your changes.`;
970
+ return false;
971
+ }
972
+ return true;
973
+ }
817
974
  async OnDurableAfterSaveExecute(entity, user, options, context) {
818
975
  if (options.SkipEntityActions === true) {
819
976
  return;
@@ -1000,6 +1157,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1000
1157
  ReportEncryptionKeyUnavailable(decryptError);
1001
1158
  continue;
1002
1159
  }
1160
+ // Inactive rows (e.g., disabled template credentials seeded before activation)
1161
+ // may hold placeholder ciphertext from another environment; preserve ciphertext without spamming error logs.
1162
+ if (processedRow['IsActive'] === false || processedRow['IsActive'] === 0) {
1163
+ continue;
1164
+ }
1003
1165
  const message = decryptError instanceof Error ? decryptError.message : String(decryptError);
1004
1166
  LogError(`Failed to decrypt field "${field.Name}" on entity "${entityInfo.Name}": ${message}. ` +
1005
1167
  'The encrypted value will be returned unchanged.');
@@ -1506,10 +1668,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1506
1668
  dirtyFields.add(f);
1507
1669
  }
1508
1670
  }
1509
- // 2. Encrypt — between coercion and rendering, mutates the map in place.
1510
- await this.EncryptFieldValuesForSave(entity, fieldValueMap, user);
1511
- // 3. Render the provider-specific binding.
1512
- const binding = this.RenderSaveCallBinding(entity, fieldValueMap, isUpdate, spName);
1671
+ // 2. On normal UPDATEs where DeltaUpdates is enabled, the entity's spUpdate is CodeGen-generated,
1672
+ // and at least one field is dirty, pass ONLY the dirty fields (plus the PK appended by
1673
+ // RenderSaveCallBinding) to the stored procedure / function so untouched columns default to NULL
1674
+ // and retain their stored database values via ISNULL(@Param, [Col]) / COALESCE(p_param, "Col").
1675
+ // Provider-wide DeltaUpdates=false, forced saves (IgnoreDirtyState), ReplayOnly saves, and
1676
+ // entities with custom spUpdate implementations keep the full-row parameter map.
1677
+ const useDeltaUpdate = this.DeltaUpdates &&
1678
+ isUpdate &&
1679
+ !options?.IgnoreDirtyState &&
1680
+ !options?.ReplayOnly &&
1681
+ entity.EntityInfo.spUpdateGenerated &&
1682
+ (dirtyFields?.size ?? 0) > 0;
1683
+ const effectiveFieldValueMap = useDeltaUpdate
1684
+ ? this.changedFieldValues(entity, fieldValueMap, dirtyFields)
1685
+ : fieldValueMap;
1686
+ // 3. Encrypt — between coercion and rendering, mutates the map in place.
1687
+ await this.EncryptFieldValuesForSave(entity, effectiveFieldValueMap, user);
1688
+ // 4. Render the provider-specific binding.
1689
+ const binding = this.RenderSaveCallBinding(entity, effectiveFieldValueMap, isUpdate, spName);
1513
1690
  // 4. Resolve SaveReturnContext and wrap with result capture.
1514
1691
  // `unprojectedSaveSQL` is the bare SP/function call (kept for `simpleSQL` fallback so
1515
1692
  // SQL logging / migration replay never gets polluted with runtime datestamp projection wrappers).
@@ -1538,10 +1715,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1538
1715
  const computeSimpleSQL = () => {
1539
1716
  if (cachedSimpleSQL === undefined) {
1540
1717
  const replaySQL = isNew
1541
- ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
1718
+ ? this.RenderReplaySaveSQL(binding, entity, effectiveFieldValueMap)
1542
1719
  : options?.IgnoreDirtyState
1543
1720
  ? undefined
1544
- : this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap, dirtyFields));
1721
+ : this.RenderReplayUpdateSQL(binding, entity, useDeltaUpdate
1722
+ ? effectiveFieldValueMap
1723
+ : this.changedFieldValues(entity, effectiveFieldValueMap, dirtyFields));
1545
1724
  // A statement that runs with parameters is logged in its literal form, which replays alone.
1546
1725
  cachedSimpleSQL = replaySQL ?? unprojectedSaveSQL.literalSQL ?? unprojectedSaveSQL.sql;
1547
1726
  }
@@ -2053,36 +2232,184 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2053
2232
  }
2054
2233
  }
2055
2234
  /**
2056
- * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
2057
- * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
2058
- * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
2059
- * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
2060
- * runs before this transform, so a rewrite that changes the caller's term cannot reach the
2061
- * hook's term.
2235
+ * Rewrites `@paramName` placeholders in `extraFilter` into dialect-specific bound parameter
2236
+ * placeholders (`@p0` on SQL Server, `$1` on PostgreSQL) using token-level lexing (`SqlTokens.Lex`)
2237
+ * and non-overlapping span edits (`EditSet`), and appends the corresponding {@link NamedQueryParameter}
2238
+ * entries to `queryParameters`.
2239
+ *
2240
+ * Token-level lexing ensures `@foo` inside string literals (`'...@foo...'`), SQL comments (`/* @foo *\/`,
2241
+ * `-- @foo`), quoted identifiers (`[@foo]`, `"@foo"`), and system variables (`@@ROWCOUNT`) are never
2242
+ * mistaken for parameter references.
2062
2243
  */
2063
- PrepareExtraFilterSQL(extraFilter, entityInfo) {
2064
- if (!extraFilter)
2244
+ BindExtraFilterParameters(extraFilter, parameters, queryParameters) {
2245
+ const normalizedParams = NormalizeRunViewParameters(parameters);
2246
+ if (!extraFilter) {
2065
2247
  return '';
2066
- const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
2067
- const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
2248
+ }
2249
+ const lexed = SqlTokens.Lex(extraFilter, this.Dialect);
2250
+ const tokens = lexed.Tokens;
2251
+ let edits = EditSet.For(extraFilter);
2252
+ const boundPlaceholdersByParam = new Map();
2253
+ const targetParams = queryParameters ?? [];
2254
+ const bindScalar = (paramName, scalar) => {
2255
+ if (scalar === null || typeof scalar === 'string') {
2256
+ const index = targetParams.length;
2257
+ const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
2258
+ const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
2259
+ targetParams.push(new NamedQueryParameter(driverName, scalar));
2260
+ return placeholder;
2261
+ }
2262
+ if (typeof scalar === 'boolean') {
2263
+ const index = targetParams.length;
2264
+ const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
2265
+ const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
2266
+ const boundBool = this.Dialect.Binding.BooleanParameterValue(scalar);
2267
+ targetParams.push(new NamedQueryParameter(driverName, boundBool));
2268
+ return placeholder;
2269
+ }
2270
+ if (typeof scalar === 'number') {
2271
+ if (!Number.isFinite(scalar)) {
2272
+ throw new Error(`Invalid RunView parameter '@${paramName}': numeric parameter values must be finite numbers.`);
2273
+ }
2274
+ const index = targetParams.length;
2275
+ const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
2276
+ const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
2277
+ targetParams.push(new NamedQueryParameter(driverName, scalar));
2278
+ return placeholder;
2279
+ }
2280
+ if (scalar instanceof Date) {
2281
+ if (Number.isNaN(scalar.getTime())) {
2282
+ throw new Error(`Invalid RunView parameter '@${paramName}': Date parameter value is invalid.`);
2283
+ }
2284
+ const index = targetParams.length;
2285
+ const placeholder = this.Dialect.Binding.ParameterPlaceholder(index);
2286
+ const driverName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
2287
+ targetParams.push(new NamedQueryParameter(driverName, scalar));
2288
+ return placeholder;
2289
+ }
2290
+ throw new Error(`Invalid RunView parameter '@${paramName}': unsupported value type '${typeof scalar}'.`);
2291
+ };
2292
+ for (let i = 0; i < tokens.length; i++) {
2293
+ const token = tokens[i];
2294
+ if (token.Kind !== 'Word')
2295
+ continue;
2296
+ // On dialects that don't natively quote with `[...]` (e.g. PostgreSQL before TransformExternalSQLClause
2297
+ // rewrites `[col]` to `"col"`), `[@col]` is lexed as `[` + Word(`@col`) + `]`. Skip bracketed identifiers.
2298
+ const prev = tokens[i - 1];
2299
+ const next = tokens[i + 1];
2300
+ if (prev?.Text === '[' && prev.Span.End === token.Span.Start && next?.Text === ']' && next.Span.Start === token.Span.End) {
2301
+ continue;
2302
+ }
2303
+ const match = /^@([A-Za-z_][A-Za-z0-9_]*)$/.exec(token.Text);
2304
+ if (!match)
2305
+ continue;
2306
+ const paramName = match[1];
2307
+ if (!normalizedParams.has(paramName)) {
2308
+ throw new Error(`RunView ExtraFilter references parameter '@${paramName}', but no value was provided in RunViewParams.Parameters.`);
2309
+ }
2310
+ let replacement = boundPlaceholdersByParam.get(paramName);
2311
+ if (replacement === undefined) {
2312
+ const rawValue = normalizedParams.get(paramName);
2313
+ if (Array.isArray(rawValue)) {
2314
+ if (rawValue.length === 0) {
2315
+ throw new Error(`RunView parameter '@${paramName}' cannot be an empty array.`);
2316
+ }
2317
+ const itemPlaceholders = rawValue.map((item) => bindScalar(paramName, item));
2318
+ replacement = itemPlaceholders.join(', ');
2319
+ }
2320
+ else {
2321
+ replacement = bindScalar(paramName, rawValue);
2322
+ }
2323
+ boundPlaceholdersByParam.set(paramName, replacement);
2324
+ }
2325
+ edits = edits.Replace(token.Span, replacement);
2326
+ }
2327
+ return edits.IsEmpty ? extraFilter : edits.Apply().Text;
2328
+ }
2329
+ /**
2330
+ * Rewrites `@paramName` word tokens to `@replacementName` using dialect-aware token lexing
2331
+ * (`SqlTokens.Lex`) and non-overlapping span edits (`EditSet`), so `@paramName` inside string
2332
+ * literals, quoted/bracketed identifiers, line/nested block comments, and `@@system` variables
2333
+ * is never modified.
2334
+ */
2335
+ static RewriteSqlParameterReferences(sqlText, paramName, replacementName, dialect) {
2336
+ if (!sqlText) {
2337
+ return sqlText;
2338
+ }
2339
+ const targetToken = `@${paramName}`;
2340
+ const replacementToken = `@${replacementName}`;
2341
+ const lexed = SqlTokens.Lex(sqlText, dialect);
2342
+ let edits = EditSet.For(sqlText);
2343
+ for (const token of lexed.Tokens) {
2344
+ if (token.Kind === 'Word' && token.Text === targetToken) {
2345
+ edits = edits.Replace(token.Span, replacementToken);
2346
+ }
2347
+ }
2348
+ return edits.IsEmpty ? sqlText : edits.Apply().Text;
2349
+ }
2350
+ /**
2351
+ * Applies {@link BindExtraFilterParameters} and {@link TransformExternalSQLClause} to a caller's
2352
+ * ExtraFilter and checks the result with {@link AssertClauseBalanced}. When the transform changes
2353
+ * the text and the filter is a chain of top-level AND terms, each term is transformed, checked
2354
+ * and parenthesized on its own. A PreRunView hook that ANDs a server predicate (such as tenant
2355
+ * scope) onto the caller's filter runs before this transform, so a rewrite that changes the
2356
+ * caller's term cannot reach the hook's term.
2357
+ */
2358
+ PrepareExtraFilterSQL(extraFilter, entityInfo, parameters, queryParameters) {
2359
+ const targetParams = queryParameters ?? [];
2360
+ if (!extraFilter) {
2361
+ this.BindExtraFilterParameters(extraFilter, parameters, targetParams);
2362
+ return '';
2363
+ }
2364
+ this.AssertClauseBalanced(extraFilter, 'ExtraFilter');
2365
+ const priorParamCount = targetParams.length;
2366
+ const boundFilter = this.BindExtraFilterParameters(extraFilter, parameters, targetParams);
2367
+ if (!boundFilter)
2368
+ return '';
2369
+ const allowedPlaceholders = new Set();
2370
+ for (let i = priorParamCount; i < targetParams.length; i++) {
2371
+ allowedPlaceholders.add(this.Dialect.Binding.ParameterPlaceholder(i));
2372
+ }
2373
+ const balanceOptions = allowedPlaceholders.size > 0 ? { AllowedParameterPlaceholders: allowedPlaceholders } : undefined;
2374
+ const transformed = this.TransformExternalSQLClause(boundFilter, entityInfo);
2375
+ const terms = transformed === boundFilter ? null : SplitTopLevelAndTerms(boundFilter, this.Dialect);
2068
2376
  if (!terms || terms.length < 2) {
2069
- this.AssertClauseBalanced(transformed, 'ExtraFilter');
2377
+ this.AssertClauseBalanced(transformed, 'ExtraFilter', balanceOptions);
2070
2378
  return transformed;
2071
2379
  }
2072
2380
  return terms
2073
2381
  .map((term) => {
2074
2382
  const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
2075
- this.AssertClauseBalanced(termSQL, 'ExtraFilter');
2383
+ this.AssertClauseBalanced(termSQL, 'ExtraFilter', balanceOptions);
2076
2384
  return `(${termSQL})`;
2077
2385
  })
2078
2386
  .join(' AND ');
2079
2387
  }
2388
+ /**
2389
+ * Compiles `params.Filter` (a structured `CompositeFilter` / `CompositeFilterDescriptor`) into a
2390
+ * parameterized SQL WHERE fragment for `entityInfo` using {@link CompositeFilterSQLCompiler.Compile}
2391
+ * and binds its parameters onto `queryParameters` via {@link BindExtraFilterParameters}.
2392
+ */
2393
+ CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters) {
2394
+ if (!params.Filter) {
2395
+ return '';
2396
+ }
2397
+ const compiled = CompositeFilterSQLCompiler.Compile(params.Filter, entityInfo, {
2398
+ platform: this.PlatformKey,
2399
+ user,
2400
+ parameterPrefix: '_cf_',
2401
+ });
2402
+ if (!compiled.whereClause) {
2403
+ return '';
2404
+ }
2405
+ return this.BindExtraFilterParameters(compiled.whereClause, compiled.parameters, queryParameters);
2406
+ }
2080
2407
  /**
2081
2408
  * Optionally wraps a view query with user view run logging.
2082
2409
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
2083
2410
  * Default: returns null (no view run logging).
2084
2411
  */
2085
- async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride) {
2412
+ async executeSQLForUserViewRunLogging(_viewId, _entityInfo, _effectiveBaseView, _whereSQL, _orderBySQL, _user, _schemaNameOverride, _queryParameters) {
2086
2413
  return null;
2087
2414
  }
2088
2415
  /**
@@ -2313,7 +2640,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2313
2640
  // A saved view's stored WhereClause/OrderBy live on viewEntity, not params, and the
2314
2641
  // normal SQL path that applies them runs below this early return — so fold them in
2315
2642
  // here, else a UserView over an external entity silently returns unfiltered rows.
2316
- const externalParams = await this.mergeExternalViewParams(params, viewEntity, user);
2643
+ const externalParams = await this.mergeExternalViewParams(params, viewEntity, user, entityInfo);
2317
2644
  this.assertExternalClausesRespectFieldSecurity(entityInfo, externalParams, user);
2318
2645
  const externalRouter = this.resolveExternalReadRouterOrThrow(`Entity '${entityInfo.Name}'`);
2319
2646
  const externalResult = await externalRouter.RunViewExternal(entityInfo, externalParams, user, this);
@@ -2331,7 +2658,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2331
2658
  return externalResult;
2332
2659
  }
2333
2660
  // ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
2334
- const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
2661
+ const queryParameters = [];
2662
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo, params.Parameters, queryParameters);
2663
+ const structuredFilter = this.CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters);
2335
2664
  const userSearchString = params.UserSearchString ?? '';
2336
2665
  const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
2337
2666
  const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
@@ -2445,6 +2774,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2445
2774
  whereSQL = bHasWhere ? `${whereSQL} AND (${extraFilter})` : `(${extraFilter})`;
2446
2775
  bHasWhere = true;
2447
2776
  }
2777
+ // 2a. Structured Filter (CompositeFilter / CompositeFilterDescriptor)
2778
+ if (structuredFilter.length > 0) {
2779
+ whereSQL = bHasWhere ? `${whereSQL} AND (${structuredFilter})` : `(${structuredFilter})`;
2780
+ bHasWhere = true;
2781
+ }
2448
2782
  // 2b. View properties: one typed predicate per property with a value, after the view's
2449
2783
  // own clause and ExtraFilter. Row-level security is still ANDed on below.
2450
2784
  if (propertyFilter.length > 0) {
@@ -2582,7 +2916,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2582
2916
  // Pass entityInfo + effectiveBaseView so the logged read honors DataSource:'Materialized'
2583
2917
  // (reads the snapshot). effectiveBaseView === entityInfo.BaseView on the default live path,
2584
2918
  // so non-materialized reads are unchanged.
2585
- const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName);
2919
+ const logResult = await this.executeSQLForUserViewRunLogging(Number(viewEntity.ID), entityInfo, effectiveBaseView, whereSQL, orderBy, user, effectiveSchemaName, queryParameters);
2586
2920
  if (logResult) {
2587
2921
  viewSQL = logResult.executeViewSQL;
2588
2922
  userViewRunID = logResult.runID;
@@ -2642,7 +2976,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2642
2976
  const skipCount = params.SkipTotalRowCount === true && params.ResultType !== 'count_only';
2643
2977
  const willNeedCount = countSQL && ((usingPagination && !skipCount) || params.ResultType === 'count_only');
2644
2978
  if (willNeedCount) {
2645
- if (countExecutor && params.ResultType === 'count_only') {
2979
+ if (countExecutor && params.ResultType === 'count_only' && queryParameters.length === 0) {
2646
2980
  countExecutorPromise = countExecutor(countSQL);
2647
2981
  }
2648
2982
  else {
@@ -2655,22 +2989,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2655
2989
  sqlQueries.push(aggregateSQL);
2656
2990
  sqlQueryKeys.push('aggregate');
2657
2991
  }
2992
+ const boundParams = queryParameters.length > 0 ? queryParameters : undefined;
2993
+ const boundBatchParams = queryParameters.length > 0 ? sqlQueries.map(() => queryParameters) : undefined;
2658
2994
  const resultMap = {};
2659
2995
  if (sqlQueries.length === 1 && !countExecutorPromise) {
2660
- resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser);
2996
+ resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], boundParams, undefined, contextUser);
2661
2997
  }
2662
2998
  else if (sqlQueries.length > 0 && countExecutorPromise) {
2663
2999
  const [batchResults, countRes] = await Promise.all([
2664
3000
  sqlQueries.length === 1
2665
- ? this.ExecuteSQL(sqlQueries[0], undefined, undefined, contextUser).then(r => [r])
2666
- : this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser),
3001
+ ? this.ExecuteSQL(sqlQueries[0], boundParams, undefined, contextUser).then(r => [r])
3002
+ : this.ExecuteSQLBatch(sqlQueries, boundBatchParams, undefined, contextUser),
2667
3003
  countExecutorPromise,
2668
3004
  ]);
2669
3005
  sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
2670
3006
  resultMap['count'] = countRes;
2671
3007
  }
2672
3008
  else if (sqlQueries.length > 1) {
2673
- const batchResults = await this.ExecuteSQLBatch(sqlQueries, undefined, undefined, contextUser);
3009
+ const batchResults = await this.ExecuteSQLBatch(sqlQueries, boundBatchParams, undefined, contextUser);
2674
3010
  sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
2675
3011
  }
2676
3012
  else if (countExecutorPromise) {
@@ -2702,7 +3038,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2702
3038
  // time in the window, with nothing reading a single result. Callers that only read
2703
3039
  // `Results` opt out explicitly with RunViewParams.SkipTotalRowCount; the provider
2704
3040
  // never infers that from the value of MaxRows.
2705
- const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
3041
+ const countResult = await this.ExecuteSQL(countSQL, boundParams, undefined, contextUser);
2706
3042
  if (countResult && countResult.length > 0)
2707
3043
  rowCount = countResult[0].TotalRowCount;
2708
3044
  }
@@ -3223,13 +3559,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3223
3559
  `a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
3224
3560
  `tokens, such as an unbalanced quote or bracket.`);
3225
3561
  }
3226
- const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
3562
+ // The built-in predicates have no phrase syntax, so they search a quoted phrase without its
3563
+ // quotes (UnwrapPhraseQuotes). A custom format is SQL, screened above as typed, so it gets
3564
+ // the term as typed.
3565
+ const phraseTerm = UnwrapPhraseQuotes(safeUserSearchString);
3566
+ const escapedTerm = this.escapeLikeTerm(phraseTerm);
3227
3567
  for (const field of entityInfo.Fields) {
3228
3568
  if (!field.IncludeInUserSearchAPI)
3229
3569
  continue;
3230
3570
  if (deniedSearchFields.has(field.Name.trim().toLowerCase()))
3231
3571
  continue; // field security: not searchable
3232
- const sParam = this.buildPerFieldSearchPredicate(field, escapedTerm, safeUserSearchString);
3572
+ const sParam = this.buildPerFieldSearchPredicate(field, escapedTerm, field.UserSearchParamFormatAPI ? safeUserSearchString : phraseTerm);
3233
3573
  if (!sParam)
3234
3574
  continue;
3235
3575
  if (sUserSearchSQL.length > 0)
@@ -3298,6 +3638,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3298
3638
  /**
3299
3639
  * Build the SQL fragment that compares one EntityField against a user search term.
3300
3640
  *
3641
+ * `createViewUserSearchSQL` passes the term without wrapping phrase quotes (`UnwrapPhraseQuotes`)
3642
+ * as `escapedTerm`, and as `rawSafeTerm` for a field without a custom format; a custom format
3643
+ * receives the term as typed. An override receives the same values.
3644
+ *
3301
3645
  * Resolution order:
3302
3646
  * 1. UserSearchParamFormatAPI (custom override) wins if set, with `{0}` replaced
3303
3647
  * by the single-quote-escaped raw term. Caller is responsible for escaping
@@ -3570,8 +3914,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3570
3914
  statuses[index] = { Success: false, ErrorMessage: `Entity ${hooked.EntityName ?? '(none)'} not found` };
3571
3915
  continue;
3572
3916
  }
3573
- const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user);
3574
- items.push({ index, item: { params: hooked }, entityInfo, whereSQL });
3917
+ const queryParameters = [];
3918
+ const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user, queryParameters);
3919
+ items.push({
3920
+ index,
3921
+ item: { params: hooked },
3922
+ entityInfo,
3923
+ whereSQL,
3924
+ queryParameters: queryParameters.length > 0 ? queryParameters : undefined,
3925
+ });
3575
3926
  }
3576
3927
  catch (e) {
3577
3928
  statuses[index] = { Success: false, ErrorMessage: e instanceof Error ? e.message : String(e) };
@@ -3779,10 +4130,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3779
4130
  const differentialItems = [];
3780
4131
  const staleItemsNoTracking = [];
3781
4132
  /** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
3782
- const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus) => {
4133
+ const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus, queryParameters) => {
3783
4134
  LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
3784
4135
  differentialItems.push({
3785
- index, params: item.params, entityInfo, whereSQL,
4136
+ index, params: item.params, entityInfo, whereSQL, queryParameters,
3786
4137
  clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
3787
4138
  clientRowCount: item.cacheStatus.rowCount,
3788
4139
  serverStatus,
@@ -3793,15 +4144,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3793
4144
  const itemsForDBCheck = [];
3794
4145
  for (const { index, item, entityInfo, serverCached, fingerprint } of serverCacheMissItems) {
3795
4146
  try {
3796
- const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user);
3797
- itemsForDBCheck.push({ index, item, entityInfo, whereSQL, serverCached, fingerprint });
4147
+ const queryParameters = [];
4148
+ const whereSQL = await this.buildWhereClauseForCacheCheck(item.params, entityInfo, user, queryParameters);
4149
+ itemsForDBCheck.push({
4150
+ index,
4151
+ item,
4152
+ entityInfo,
4153
+ whereSQL,
4154
+ queryParameters: queryParameters.length > 0 ? queryParameters : undefined,
4155
+ serverCached,
4156
+ fingerprint,
4157
+ });
3798
4158
  }
3799
4159
  catch (e) {
3800
4160
  errorResults.push({ viewIndex: index, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) });
3801
4161
  }
3802
4162
  }
3803
4163
  const cacheStatusResults = await this.getBatchedServerCacheStatus(itemsForDBCheck, contextUser);
3804
- for (const { index, item, entityInfo, whereSQL, serverCached, fingerprint } of itemsForDBCheck) {
4164
+ for (const { index, item, entityInfo, whereSQL, queryParameters, serverCached, fingerprint } of itemsForDBCheck) {
3805
4165
  const serverStatus = cacheStatusResults.get(index);
3806
4166
  if (!serverStatus || !serverStatus.success) {
3807
4167
  const statusError = serverStatus?.errorMessage || 'Failed to get cache status';
@@ -3823,7 +4183,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3823
4183
  currentResults.push({ viewIndex: index, status: 'current' });
3824
4184
  }
3825
4185
  else if (entityInfo.TrackRecordChanges) {
3826
- queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
4186
+ queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
3827
4187
  }
3828
4188
  else {
3829
4189
  LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
@@ -3850,7 +4210,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3850
4210
  currentResults.push({ viewIndex: index, status: 'current' });
3851
4211
  }
3852
4212
  else if (entityInfo.TrackRecordChanges) {
3853
- queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
4213
+ queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
3854
4214
  }
3855
4215
  else {
3856
4216
  LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
@@ -3901,7 +4261,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3901
4261
  // DB-validated stale items (no change tracking)
3902
4262
  ...staleItemsNoTracking.map(({ index, params: viewParams }) => this.runFullQueryAndCacheResult(viewParams, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
3903
4263
  // 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)),
4264
+ ...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
4265
  ];
3906
4266
  const fullQueryResults = await Promise.all(queryPromises);
3907
4267
  const allResults = [...errorResults, ...currentResults, ...fullQueryResults];
@@ -3990,19 +4350,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3990
4350
  * Handles ExtraFilter, UserSearch, and Row-Level Security.
3991
4351
  * Subclasses can override to add platform-specific SQL transformations (e.g., identifier quoting).
3992
4352
  */
3993
- async buildWhereClauseForCacheCheck(params, entityInfo, user) {
4353
+ async buildWhereClauseForCacheCheck(params, entityInfo, user, queryParameters) {
3994
4354
  let whereSQL = '';
3995
4355
  let bHasWhere = false;
3996
4356
  // PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
3997
- // check then runs on the result, as on the main view path.
3998
- const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
4357
+ // check and post-bind field-security gate then run on the result, as on the main view path.
4358
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo, params.Parameters, queryParameters);
3999
4359
  this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
4360
+ this.AssertClausesRespectFieldSecurityForEntity(entityInfo, [extraFilter], user);
4000
4361
  if (extraFilter.length > 0) {
4001
4362
  if (!this.ValidateUserProvidedSQLClause(extraFilter))
4002
4363
  throw new Error(`Invalid Extra Filter: ${extraFilter}`);
4003
4364
  whereSQL = `(${extraFilter})`;
4004
4365
  bHasWhere = true;
4005
4366
  }
4367
+ const structuredFilter = this.CompileStructuredRunViewFilter(params, entityInfo, user, queryParameters);
4368
+ if (structuredFilter.length > 0) {
4369
+ whereSQL = bHasWhere ? `${whereSQL} AND (${structuredFilter})` : `(${structuredFilter})`;
4370
+ bHasWhere = true;
4371
+ }
4006
4372
  // Free text, not a SQL fragment — deliberately NOT run through
4007
4373
  // ValidateUserProvidedSQLClause. See the equivalent note on the view path above (#4392).
4008
4374
  if (params.UserSearchString && params.UserSearchString.length > 0) {
@@ -4043,7 +4409,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4043
4409
  const results = new Map();
4044
4410
  if (items.length === 0)
4045
4411
  return results;
4046
- const promises = items.map(async ({ index, item, entityInfo, whereSQL }) => {
4412
+ const promises = items.map(async ({ index, item, entityInfo, whereSQL, queryParameters }) => {
4047
4413
  try {
4048
4414
  // Probe the SAME physical view the read targets — for a DataSource:'Materialized' read that's
4049
4415
  // the materialized_vw<CodeName> snapshot (a full SELECT * of the base view, so it carries
@@ -4053,7 +4419,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4053
4419
  // matches the SQL Server override and is defense-in-depth on the PG/default path.)
4054
4420
  const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
4055
4421
  const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveTarget.viewName, whereSQL, effectiveTarget.schemaName);
4056
- const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
4422
+ const boundParams = queryParameters && queryParameters.length > 0 ? queryParameters : undefined;
4423
+ const rows = await this.ExecuteSQL(statusSQL, boundParams, undefined, contextUser);
4057
4424
  if (rows && rows.length > 0) {
4058
4425
  const row = rows[0];
4059
4426
  results.set(index, {
@@ -4206,6 +4573,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4206
4573
  if (typeof params.UserSearchString === 'string' && params.UserSearchString.trim().length > 0) {
4207
4574
  throw new Error(`UserSearchString is not supported for external-data-source entity '${entityName}'. Use ExtraFilter instead.`);
4208
4575
  }
4576
+ if (params.Parameters && Object.keys(params.Parameters).some((k) => params.Parameters[k] !== undefined)) {
4577
+ throw new Error(`Parameterized ExtraFilter (Parameters) is not supported for external-data-source entity '${entityName}'.`);
4578
+ }
4209
4579
  // Apply the same forbidden-keyword screen the MJ-DB path runs on caller-supplied SQL
4210
4580
  // clauses before they're passed to the remote driver. The driver still parameterizes
4211
4581
  // values, but this blocks obvious injection of statement-terminating / DDL keywords.
@@ -4265,11 +4635,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4265
4635
  * OrderByClause is used only when the caller supplied no OrderBy. Returns params unchanged
4266
4636
  * when there is no saved view.
4267
4637
  */
4268
- async mergeExternalViewParams(params, viewEntity, user) {
4269
- if (!viewEntity)
4638
+ async mergeExternalViewParams(params, viewEntity, user, entityInfo) {
4639
+ if (!viewEntity && !params.Filter)
4270
4640
  return params;
4271
4641
  const merged = { ...params };
4272
- const callerFilter = params.ExtraFilter || '';
4642
+ let callerFilter = params.ExtraFilter || '';
4643
+ if (params.Filter && entityInfo) {
4644
+ const literalStructured = CompositeFilterSQLCompiler.CompileLiteral(params.Filter, entityInfo, {
4645
+ platform: this.PlatformKey,
4646
+ user,
4647
+ }).trim();
4648
+ if (literalStructured) {
4649
+ callerFilter = callerFilter ? `(${callerFilter}) AND (${literalStructured})` : literalStructured;
4650
+ merged.ExtraFilter = callerFilter;
4651
+ }
4652
+ delete merged.Filter;
4653
+ }
4654
+ if (!viewEntity)
4655
+ return merged;
4273
4656
  if (viewEntity.WhereClause && viewEntity.WhereClause.length > 0) {
4274
4657
  const renderedWhere = (await this.RenderViewWhereClause(viewEntity, user))?.trim();
4275
4658
  if (renderedWhere) {
@@ -4392,7 +4775,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4392
4775
  * Includes updated/created rows and deleted record IDs.
4393
4776
  * Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
4394
4777
  */
4395
- async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null) {
4778
+ async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null, queryParameters) {
4396
4779
  try {
4397
4780
  const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
4398
4781
  if (!clientMaxUpdatedDate) {
@@ -4401,7 +4784,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4401
4784
  return this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
4402
4785
  }
4403
4786
  const since = clientMaxUpdatedDate.toISOString();
4404
- const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser);
4787
+ const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser, queryParameters);
4405
4788
  const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, since, contextUser);
4406
4789
  // Validation: detect hidden deletes not tracked in RecordChanges
4407
4790
  const newInserts = updatedRows.filter(row => {
@@ -4501,7 +4884,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4501
4884
  * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
4502
4885
  * timestamp in ISO 8601 form as its own predicate group.
4503
4886
  */
4504
- async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser) {
4887
+ async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser, queryParameters) {
4505
4888
  try {
4506
4889
  const timestampFilter = `(${this.QuoteIdentifier('__mj_UpdatedAt')} > '${this.toSQLTimestamp(sinceTimestamp)}')`;
4507
4890
  const combinedWhere = whereSQL
@@ -4519,7 +4902,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4519
4902
  this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
4520
4903
  sql += ` ORDER BY ${orderBy}`;
4521
4904
  }
4522
- const rawRows = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
4905
+ const boundParams = queryParameters && queryParameters.length > 0 ? queryParameters : undefined;
4906
+ const rawRows = await this.ExecuteSQL(sql, boundParams, undefined, contextUser);
4523
4907
  const processed = await this.PostProcessRows(rawRows, entityInfo, (contextUser ?? this.CurrentUser), { preserveRestrictedApiCiphertext: true });
4524
4908
  return processed;
4525
4909
  }
@@ -6514,6 +6898,52 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6514
6898
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
6515
6899
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
6516
6900
  }
6901
+ /**
6902
+ * Evaluates an arbitrary SQL `whereClause` against an entity's pending in-memory field values
6903
+ * using the same typed synthetic-row subquery (`SELECT CASE WHEN (...) THEN 1 ELSE 0 END`)
6904
+ * used by Create/Update RLS post-image enforcement, without taking or blocking on table locks.
6905
+ *
6906
+ * When `dirtyOnlyOptimization` is `true` and `whereClause` decomposes cleanly into simple
6907
+ * column comparisons whose referenced columns are all clean on `entity`, returns `true`
6908
+ * without a database round-trip (safe only when the pre-image was already verified).
6909
+ */
6910
+ async EvaluateSyntheticRowWhereClause(entity, whereClause, user, dirtyOnlyOptimization = false) {
6911
+ const trimmed = whereClause.trim();
6912
+ if (trimmed.length === 0) {
6913
+ return true;
6914
+ }
6915
+ const parentFieldNames = entity.EntityInfo?.ParentEntityFieldNames;
6916
+ const nonIsaVirtualNames = new Set((entity.EntityInfo?.Fields ?? [])
6917
+ .filter(f => f.IsVirtual && !parentFieldNames?.has(f.Name))
6918
+ .map(f => f.Name.trim().toLowerCase()));
6919
+ if (nonIsaVirtualNames.size > 0) {
6920
+ const matchedVirtual = ClientClauseScreen.ExtractStatementIdentifierTokens(trimmed, this.Dialect).filter(tok => nonIsaVirtualNames.has(tok.trim().toLowerCase()));
6921
+ if (matchedVirtual.length > 0) {
6922
+ LogError(`EvaluateSyntheticRowWhereClause refused for entity '${entity.EntityInfo?.Name}': write-side whereClause references non-IS-A virtual view column(s) [${matchedVirtual.join(', ')}]`);
6923
+ return false;
6924
+ }
6925
+ }
6926
+ if (dirtyOnlyOptimization) {
6927
+ const referencedColumns = this.TryExtractSimpleFilterColumns(trimmed);
6928
+ if (referencedColumns) {
6929
+ const dirtyNames = new Set(entity.Fields.filter(f => f.Dirty).map(f => f.Name.trim().toLowerCase()));
6930
+ const touchesFilterColumn = referencedColumns.some(c => dirtyNames.has(c));
6931
+ if (!touchesFilterColumn) {
6932
+ return true;
6933
+ }
6934
+ }
6935
+ }
6936
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entity.EntityInfo, true);
6937
+ const sql = `SELECT CASE WHEN (${trimmed}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
6938
+ try {
6939
+ const result = await this.ExecuteSQL(sql, undefined, undefined, user);
6940
+ return Boolean(result && result.length > 0 && Number(result[0]['pass']) === 1);
6941
+ }
6942
+ catch (err) {
6943
+ LogError(`EvaluateSyntheticRowWhereClause failed for entity '${entity.EntityInfo?.Name}': ${err instanceof Error ? err.message : String(err)}`);
6944
+ return false;
6945
+ }
6946
+ }
6517
6947
  /**
6518
6948
  * Attempts to fully decompose an RLS WHERE clause into the lower-cased column names it
6519
6949
  * references. Returns the columns ONLY when the whole clause is a conjunction of simple
@@ -6552,10 +6982,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6552
6982
  * `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
6553
6983
  * type fails the save (throw) rather than emitting an untyped NULL.
6554
6984
  */
6555
- BuildRLSSyntheticRowProjections(entity, entityInfo) {
6985
+ BuildRLSSyntheticRowProjections(entity, entityInfo, includeISAParentFields = false) {
6556
6986
  const parts = [];
6987
+ const parentFieldNames = includeISAParentFields ? entityInfo.ParentEntityFieldNames : undefined;
6557
6988
  for (const field of entityInfo.Fields) {
6558
- if (field.IsVirtual)
6989
+ if (field.IsVirtual && !parentFieldNames?.has(field.Name))
6559
6990
  continue;
6560
6991
  const val = entity.Get(field.Name);
6561
6992
  parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
@@ -6649,6 +7080,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6649
7080
  BuildParameterPlaceholder(index) {
6650
7081
  return `$${index + 1}`;
6651
7082
  }
7083
+ /** An ItemFilter that is exactly `1=0` (spacing aside): the caller wants no rows from the item. */
7084
+ static { this._noRowItemFilter = /^\s*1\s*=\s*0\s*$/; }
7085
+ /** Whether a dataset ItemFilter asks for no rows at all, so the item needs no read. */
7086
+ static isNoRowItemFilter(filter) {
7087
+ return !!filter && GenericDatabaseProvider._noRowItemFilter.test(filter);
7088
+ }
6652
7089
  /**
6653
7090
  * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
6654
7091
  * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
@@ -6757,7 +7194,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6757
7194
  *
6758
7195
  * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
6759
7196
  * 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.
7197
+ * item runs no SQL and fails the dataset. An item whose ItemFilter is exactly `1=0` runs no SQL
7198
+ * either: it returns an empty, successful result.
6761
7199
  */
6762
7200
  async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
6763
7201
  const provider = (providerToUse ?? this);
@@ -6792,6 +7230,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6792
7230
  const cacheAvailable = !forceRefresh && cache.IsInitialized && this.TrustLocalCacheCompletely;
6793
7231
  const errorResults = [];
6794
7232
  const cachedResults = [];
7233
+ // Items the caller asked for with a no-row ItemFilter: answered without a read.
7234
+ const noRowResults = [];
6795
7235
  const uncachedQueries = [];
6796
7236
  const uncachedItems = [];
6797
7237
  // Track fingerprints for uncached items so we can write-through after SQL
@@ -6839,6 +7279,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6839
7279
  });
6840
7280
  continue;
6841
7281
  }
7282
+ // An ItemFilter of exactly `1=0` asks for no rows, whatever the stored WhereClause or the
7283
+ // caller's row filter add to it, so the item is answered without a read. The scoped
7284
+ // metadata reload (ProviderBase.TryPartialMetadataReload) sends it for every item it does
7285
+ // not reload; each used to run its own empty SELECT, one pool connection apiece.
7286
+ if (GenericDatabaseProvider.isNoRowItemFilter(itemFilters?.find(f => f?.ItemCode === code)?.Filter)) {
7287
+ noRowResults.push({
7288
+ EntityID: entityID,
7289
+ EntityName: entityName,
7290
+ Code: code,
7291
+ Results: [],
7292
+ LatestUpdateDate: this.computeLatestUpdateDate([], String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt'), item),
7293
+ Success: true,
7294
+ });
7295
+ continue;
7296
+ }
6842
7297
  // The row filter keys the slot, so one user's filtered rows are never served to another.
6843
7298
  const rowFilterKey = scope.RowFilter || undefined;
6844
7299
  const fingerprint = cacheAvailable
@@ -7065,11 +7520,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
7065
7520
  Success: itemData !== null && itemData !== undefined,
7066
7521
  });
7067
7522
  }
7068
- // Merge results: errors + cached + SQL (maintain original item order via code matching)
7523
+ // Merge results: errors + no-row + cached + SQL (maintain original item order via code matching)
7069
7524
  const results = [];
7070
7525
  for (const item of items) {
7071
7526
  const code = String(item['Code']);
7072
7527
  const found = errorResults.find(r => r.Code === code)
7528
+ ?? noRowResults.find(r => r.Code === code)
7073
7529
  ?? cachedResults.find(r => r.Code === code)
7074
7530
  ?? sqlResults.find(r => r.Code === code);
7075
7531
  if (found)
@@ -7514,6 +7970,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
7514
7970
  IsCallerInAmbientTransaction() {
7515
7971
  return this._affinity.IsCallerMember;
7516
7972
  }
7973
+ /** See {@link IEntityDataProvider.RunOutsideAmbientTransaction}: `fn` runs with no membership in this provider's transaction. */
7974
+ RunOutsideAmbientTransaction(fn) {
7975
+ return this._affinity.RunDetached(fn);
7976
+ }
7517
7977
  /** Members of the open transaction share RunViews only with each other (see {@link ProviderBase.RunViewDedupScope}). */
7518
7978
  get RunViewDedupScope() {
7519
7979
  return this.IsCallerInAmbientTransaction() ? `tx:${this._affinity.CurrentEpoch}` : '';
@@ -7769,6 +8229,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
7769
8229
  }
7770
8230
  await this.endBatchLevelIfOpen(true);
7771
8231
  if (committedTasks) {
8232
+ this.BumpTransactionEpoch();
7772
8233
  await this.runPostCommitTasks(committedTasks);
7773
8234
  await this.AfterPhysicalCommit();
7774
8235
  }
@@ -7778,6 +8239,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
7778
8239
  await this.WithTransactionLock(() => this.rollbackTransactionCore());
7779
8240
  }
7780
8241
  finally {
8242
+ if (this._transactionDepth === 0) {
8243
+ this.BumpTransactionEpoch();
8244
+ }
7781
8245
  await this.endBatchLevelIfOpen(false);
7782
8246
  }
7783
8247
  }