@memberjunction/generic-database-provider 6.2.0-edge.4 → 6.2.0-edge.5

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 { SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
- import { BytesToBase64, IsByteArray, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
18
+ import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
+ import { BytesToBase64, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
20
20
  import { QueryPagingEngine } from './queryPagingEngine.js';
21
21
  // QueryParameterProcessor is now called internally by RenderPipeline
22
22
  import { createHash } from 'node:crypto';
23
23
  import { v4 as uuidv4 } from 'uuid';
24
- import { SqlLoggingSessionImpl } from './SqlLogger.js';
24
+ import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
25
25
  import { GetDialect } from '@memberjunction/sql-dialect';
26
- import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression } from '@memberjunction/sql-parser';
26
+ import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
27
27
  // QueryCompositionEngine is now owned by RenderPipeline
28
28
  import { RenderPipeline } from './renderPipeline.js';
29
29
  import { UseJsonArgShape } from './crudSprocFieldRules.js';
@@ -36,6 +36,7 @@ import { BuildEntityChangeContext } from '@memberjunction/actions-base';
36
36
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
37
  import { TransactionAffinity } from './TransactionAffinity.js';
38
38
  import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
39
+ import { ClientClauseScreen } from './clientClauseScreen.js';
39
40
  import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
40
41
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
41
42
  /**
@@ -171,18 +172,29 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
171
172
  // SQL Logging — Session Management & Statement Logging
172
173
  /**************************************************************************/
173
174
  static { this._sqlLoggingSessionsKey = 'MJ_GenericDatabaseProvider_SqlLoggingSessions'; }
175
+ static { this._cachedSqlLoggingSessions = null; }
174
176
  get _sqlLoggingSessions() {
177
+ if (GenericDatabaseProvider._cachedSqlLoggingSessions) {
178
+ return GenericDatabaseProvider._cachedSqlLoggingSessions;
179
+ }
175
180
  const g = MJGlobal.Instance.GetGlobalObjectStore();
176
181
  if (g) {
177
182
  if (!g[GenericDatabaseProvider._sqlLoggingSessionsKey]) {
178
183
  g[GenericDatabaseProvider._sqlLoggingSessionsKey] = new Map();
179
184
  }
180
- return g[GenericDatabaseProvider._sqlLoggingSessionsKey];
185
+ GenericDatabaseProvider._cachedSqlLoggingSessions = g[GenericDatabaseProvider._sqlLoggingSessionsKey];
186
+ return GenericDatabaseProvider._cachedSqlLoggingSessions;
181
187
  }
182
188
  else {
183
189
  throw new Error('No global object store available for SQL logging session');
184
190
  }
185
191
  }
192
+ /**
193
+ * Fast O(1) check for whether any SQL logging sessions are currently active.
194
+ */
195
+ get HasActiveSqlLoggingSessions() {
196
+ return this._sqlLoggingSessions.size > 0;
197
+ }
186
198
  /**
187
199
  * Creates a new SQL logging session that will capture all SQL operations to a file.
188
200
  * Returns a disposable session object that must be disposed to stop logging.
@@ -299,7 +311,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
299
311
  const hasVerboseSession = allSessions.some(s => s.options.verboseOutput === true);
300
312
  if (hasVerboseSession) {
301
313
  console.log('=== SQL LOGGING DEBUG ===');
302
- console.log(`Query to log: ${query.substring(0, 100)}...`);
314
+ console.log(`Query to log: ${ApplyStatementTransforms(query, allSessions).substring(0, 100)}...`);
303
315
  console.log(`Context user email: ${contextUser?.Email || 'NOT_PROVIDED'}`);
304
316
  console.log(`Active sessions count: ${this._sqlLoggingSessions.size}`);
305
317
  console.log(`All sessions:`, allSessions.map(s => ({
@@ -389,6 +401,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
389
401
  * save succeeds is not a durability improvement, it is a different feature.
390
402
  */
391
403
  async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs) {
404
+ const engine = EntityActionEngineServer.Instance;
405
+ if (engine.Loaded && engine.GetActionsByEntityName(entity.EntityInfo.Name, 'Active').length === 0) {
406
+ return [];
407
+ }
392
408
  // FIRST STATEMENT, and deliberately before the first `await`. After-hooks are dispatched
393
409
  // fire-and-forget, and the moment this method yields, the save completes and `finalizeSave()`
394
410
  // reloads the entity — resetting every field's OldValue to its new value. A change context
@@ -400,8 +416,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
400
416
  // rolled-back save never fires it (see RunAfterCommit).
401
417
  const postCommitToken = this.CapturePostCommitToken();
402
418
  try {
403
- const engine = EntityActionEngineServer.Instance;
404
- await engine.Config(false, user);
419
+ if (!engine.Loaded) {
420
+ await engine.Config(false, user);
421
+ }
405
422
  const newRecord = entityChange.IsCreate;
406
423
  const baseTypeType = baseType === 'save' ? (newRecord ? 'Create' : 'Update') : 'Delete';
407
424
  const invocationType = baseType === 'validate' ? 'Validate' : before ? 'Before' + baseTypeType : 'After' + baseTypeType;
@@ -470,10 +487,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
470
487
  try {
471
488
  if (baseType === 'delete')
472
489
  return; // delete not yet supported for AI actions
473
- await AIEngine.Instance.Config(false, user);
490
+ const ai = AIEngine.Instance;
491
+ if (!ai.Loaded) {
492
+ await ai.Config(false, user);
493
+ }
474
494
  const actions = this.GetEntityAIActions(entity.EntityInfo, before);
475
495
  if (actions && actions.length > 0) {
476
- const ai = AIEngine.Instance;
477
496
  for (let i = 0; i < actions.length; i++) {
478
497
  const a = actions[i];
479
498
  if ((a.TriggerEvent === 'before save' && before) || (a.TriggerEvent === 'after save' && !before)) {
@@ -678,8 +697,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
678
697
  if (datetimeFields.length > 0 && !entityInfo.ExternalDataSourceID) {
679
698
  processedRows = await this.AdjustDatetimeFields(processedRows, datetimeFields, entityInfo);
680
699
  }
681
- // Step 2: Encryption decryption
682
- const encryptedFields = entityInfo.Fields.filter((field) => field.Encrypt && field.EncryptionKeyID);
700
+ // Step 2: Encryption decryption — memoized per EntityInfo (like DatetimeFields/BinaryFields)
701
+ const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
683
702
  if (encryptedFields.length === 0)
684
703
  return processedRows;
685
704
  const encryptionEngine = EncryptionEngine.Instance;
@@ -712,6 +731,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
712
731
  return processedRow;
713
732
  }));
714
733
  }
734
+ static { this._encryptedFieldsCache = new WeakMap(); }
735
+ static getEncryptedFields(entityInfo) {
736
+ let entry = GenericDatabaseProvider._encryptedFieldsCache.get(entityInfo);
737
+ if (!entry || entry.fieldCount !== entityInfo.Fields.length) {
738
+ entry = {
739
+ fieldCount: entityInfo.Fields.length,
740
+ fields: entityInfo.Fields.filter((field) => field.Encrypt && field.EncryptionKeyID),
741
+ };
742
+ GenericDatabaseProvider._encryptedFieldsCache.set(entityInfo, entry);
743
+ }
744
+ return entry.fields;
745
+ }
715
746
  /**
716
747
  * Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
717
748
  * own read paths but returns entity rows — the transaction groups. Every row a provider hands
@@ -1042,6 +1073,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1042
1073
  const pkValues = entity.PrimaryKey?.KeyValuePairs?.map((p) => p.Value) ?? [];
1043
1074
  return this.allocateSaveCallSuffixForPk(entity.TransactionGroup, entity.EntityInfo.SchemaName, entity.EntityInfo.BaseTable, pkValues);
1044
1075
  }
1076
+ /**
1077
+ * Builds the dialect-quoted, comma-separated column list for {@link EntityInfo.DatestampReturnFields}
1078
+ * (primary key column(s) followed by `__mj_CreatedAt` and `__mj_UpdatedAt`) using {@link QuoteIdentifier}.
1079
+ *
1080
+ * Examples:
1081
+ * - SQL Server: `[ID], [__mj_CreatedAt], [__mj_UpdatedAt]`
1082
+ * - PostgreSQL: `"ID", "__mj_CreatedAt", "__mj_UpdatedAt"`
1083
+ */
1084
+ GetDatestampSelectColumnsSQL(entityInfo) {
1085
+ const fields = entityInfo.DatestampReturnFields ?? entityInfo.PrimaryKeys ?? [];
1086
+ return fields.map((f) => this.QuoteIdentifier(f.Name)).join(', ');
1087
+ }
1088
+ /**
1089
+ * Resolves the compile-time vs. effective runtime {@link SaveReturnContext} for a save operation.
1090
+ *
1091
+ * Centralizes the `SaveReturnMode` decision logic in `GenericDatabaseProvider` so dialect providers
1092
+ * (`SQLServerDataProvider`, `PostgreSQLDataProvider`, and future providers) never duplicate the
1093
+ * rules for:
1094
+ * - `spReturnMode`: the return shape compiled into the stored procedure / function (`EntityInfo.SaveReturnMode`).
1095
+ * - `effectiveReturnMode`: the return shape requested for this call (`options?.SaveReturnMode ?? spReturnMode`).
1096
+ * - `needsDatestampProjection`: `true` when the compiled routine returns the full row (`spReturnMode === 'full'`)
1097
+ * but the caller requested `'datestamps_only'` at runtime, requiring the provider to project the result down
1098
+ * to `datestampSelectColumnsSQL` before wire transmission.
1099
+ */
1100
+ ResolveSaveReturnContext(entity, options) {
1101
+ const spReturnMode = entity.EntityInfo.SaveReturnMode ?? 'full';
1102
+ const effectiveReturnMode = options?.SaveReturnMode ?? spReturnMode;
1103
+ const spReturnsDatestampsOnly = spReturnMode === 'datestamps_only';
1104
+ const needsDatestampProjection = !spReturnsDatestampsOnly && effectiveReturnMode === 'datestamps_only';
1105
+ const datestampSelectColumnsSQL = this.GetDatestampSelectColumnsSQL(entity.EntityInfo);
1106
+ const routineSelectColumnsSQL = needsDatestampProjection ? datestampSelectColumnsSQL : '*';
1107
+ const finalSelectColumnsSQL = effectiveReturnMode === 'datestamps_only' ? datestampSelectColumnsSQL : '*';
1108
+ return {
1109
+ spReturnMode,
1110
+ effectiveReturnMode,
1111
+ spReturnsDatestampsOnly,
1112
+ needsDatestampProjection,
1113
+ datestampSelectColumnsSQL,
1114
+ routineSelectColumnsSQL,
1115
+ finalSelectColumnsSQL,
1116
+ };
1117
+ }
1045
1118
  /**
1046
1119
  * Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
1047
1120
  * record saves for migration replay (SQL Server's Metadata_Sync migrations) override
@@ -1065,10 +1138,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1065
1138
  return undefined;
1066
1139
  }
1067
1140
  /** The entries of a save's parameter map whose fields this save actually changed. */
1068
- changedFieldValues(entity, fieldValues) {
1141
+ changedFieldValues(entity, fieldValues, dirtyFields) {
1069
1142
  const changed = new Map();
1070
1143
  for (const [f, value] of fieldValues) {
1071
- if (entity.GetFieldByName(f.Name)?.Dirty)
1144
+ const isDirty = dirtyFields ? dirtyFields.has(f) : !!entity.GetFieldByName(f.Name)?.Dirty;
1145
+ if (isDirty)
1072
1146
  changed.set(f, value);
1073
1147
  }
1074
1148
  return changed;
@@ -1088,6 +1162,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1088
1162
  const spName = this.GetCreateUpdateSPName(entity, isNew);
1089
1163
  // 1. Iterate fields, apply IsSPParameter + PK rules, coerce values.
1090
1164
  const fieldValueMap = new Map();
1165
+ const dirtyFields = isUpdate ? new Set() : undefined;
1091
1166
  for (const f of entity.EntityInfo.Fields) {
1092
1167
  if (!f.IsSPParameter(isUpdate))
1093
1168
  continue;
@@ -1125,16 +1200,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1125
1200
  if (coerced.kind === 'skip')
1126
1201
  continue;
1127
1202
  fieldValueMap.set(f, coerced.value);
1203
+ if (dirtyFields && theField?.Dirty) {
1204
+ dirtyFields.add(f);
1205
+ }
1128
1206
  }
1129
1207
  // 2. Encrypt — between coercion and rendering, mutates the map in place.
1130
1208
  await this.EncryptFieldValuesForSave(entity, fieldValueMap, user);
1131
1209
  // 3. Render the provider-specific binding.
1132
1210
  const binding = this.RenderSaveCallBinding(entity, fieldValueMap, isUpdate, spName);
1133
- // 4. Wrap with result capture. This is the "no-record-change" save
1134
- // shape; we also keep it as simpleSQL so consumers (e.g.
1135
- // DatabaseProviderBase's `simpleSQLFallback` flow) have a
1136
- // record-change-free form to fall back to.
1137
- const baseSaveSQL = this.WrapSaveCallForResult(binding, entity, spName);
1211
+ // 4. Resolve SaveReturnContext and wrap with result capture.
1212
+ // `unprojectedSaveSQL` is the bare SP/function call (kept for `simpleSQL` fallback so
1213
+ // SQL logging / migration replay never gets polluted with runtime datestamp projection wrappers).
1214
+ // When `returnContext.needsDatestampProjection` is true, `ProjectSaveCallToDatestamps`
1215
+ // projects the executed result down to `datestampSelectColumnsSQL`.
1216
+ const returnContext = this.ResolveSaveReturnContext(entity, options);
1217
+ const unprojectedSaveSQL = this.WrapSaveCallForResult(binding, entity, spName, undefined, {
1218
+ ...returnContext,
1219
+ effectiveReturnMode: returnContext.spReturnMode,
1220
+ needsDatestampProjection: false,
1221
+ routineSelectColumnsSQL: '*',
1222
+ finalSelectColumnsSQL: returnContext.spReturnsDatestampsOnly ? returnContext.datestampSelectColumnsSQL : '*',
1223
+ });
1224
+ const baseSaveSQL = returnContext.needsDatestampProjection
1225
+ ? this.ProjectSaveCallToDatestamps(binding, entity, spName, returnContext)
1226
+ : unprojectedSaveSQL;
1138
1227
  let saveSQL = baseSaveSQL;
1139
1228
  // A CREATE's logged form is guarded on the primary key so a migration replay of
1140
1229
  // the recording converges on a database that already holds the row (#4503). An
@@ -1142,12 +1231,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1142
1231
  // resets the target's other columns. A forced save (IgnoreDirtyState, e.g. MetadataSync's
1143
1232
  // `alwaysPush`) asked to re-impose the whole row, so it keeps the full-row form. Dialects
1144
1233
  // without a replay form log the plain save SQL.
1145
- const replaySQL = isNew
1146
- ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
1147
- : options?.IgnoreDirtyState
1148
- ? undefined
1149
- : this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap));
1150
- const simpleSQL = replaySQL ?? baseSaveSQL.sql;
1234
+ // Computed lazily and memoized so saves with SQL logging off skip replay/literal rendering.
1235
+ let cachedSimpleSQL;
1236
+ const computeSimpleSQL = () => {
1237
+ if (cachedSimpleSQL === undefined) {
1238
+ const replaySQL = isNew
1239
+ ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
1240
+ : options?.IgnoreDirtyState
1241
+ ? undefined
1242
+ : this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap, dirtyFields));
1243
+ // A statement that runs with parameters is logged in its literal form, which replays alone.
1244
+ cachedSimpleSQL = replaySQL ?? unprojectedSaveSQL.literalSQL ?? unprojectedSaveSQL.sql;
1245
+ }
1246
+ return cachedSimpleSQL;
1247
+ };
1151
1248
  // 5. Optionally wrap with record-change emission.
1152
1249
  let overlappingChangeData;
1153
1250
  // Per-save suppression: a high-volume machine writer (integration sync) opts out of the
@@ -1155,27 +1252,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1155
1252
  if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
1156
1253
  const newData = entity.GetAll(false);
1157
1254
  const oldData = isUpdate ? entity.GetAll(true) : null;
1158
- // ISA propagation hook: capture the diff for SS subtype propagation.
1159
- // Returned via `extraData` so the SS subclass can consume it without re-diffing.
1160
- if (isUpdate && oldData) {
1161
- const diffChanges = this.DiffObjects(oldData, newData, entity.EntityInfo, "'");
1162
- if (diffChanges && Object.keys(diffChanges).length > 0) {
1255
+ const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
1256
+ if (payload) {
1257
+ // ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
1258
+ // for SS subtype propagation without running DiffObjects + JSON.stringify twice.
1259
+ if (isUpdate && oldData && payload.changesJSON) {
1163
1260
  overlappingChangeData = {
1164
- changesJSON: JSON.stringify(diffChanges),
1165
- changesDescription: this.CreateUserDescriptionOfChanges(diffChanges),
1261
+ changesJSON: payload.changesJSON,
1262
+ changesDescription: payload.changesDescription,
1166
1263
  };
1167
1264
  }
1168
- }
1169
- const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
1170
- if (payload) {
1171
- saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity);
1265
+ saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity, options, returnContext);
1172
1266
  }
1173
1267
  }
1174
1268
  const result = {
1175
1269
  fullSQL: saveSQL.sql,
1176
- simpleSQL,
1270
+ get simpleSQL() {
1271
+ return computeSimpleSQL();
1272
+ },
1177
1273
  parameters: saveSQL.parameters ?? null,
1178
1274
  };
1275
+ if ('literalSQL' in saveSQL) {
1276
+ Object.defineProperty(result, 'literalSQL', {
1277
+ enumerable: true,
1278
+ configurable: true,
1279
+ get() {
1280
+ return saveSQL.literalSQL;
1281
+ },
1282
+ });
1283
+ }
1179
1284
  if (overlappingChangeData) {
1180
1285
  result.extraData = { overlappingChangeData };
1181
1286
  }
@@ -1465,6 +1570,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1465
1570
  TransformExternalSQLClause(clause, _entityInfo) {
1466
1571
  return clause;
1467
1572
  }
1573
+ /**
1574
+ * Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
1575
+ * WhereClause) stays inside the parentheses this provider puts around it, read with this
1576
+ * provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
1577
+ * security, which also carries API-key row filters and guest scope; a piece that closes its
1578
+ * parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
1579
+ * caller controls.
1580
+ */
1581
+ AssertClauseBalanced(clause, label, options) {
1582
+ const check = IsBalancedSQLFragment(clause, this.Dialect, options);
1583
+ if (!check.IsBalanced) {
1584
+ throw new Error(`Invalid ${label}: ${check.Reason}`);
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
1589
+ * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
1590
+ * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
1591
+ * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
1592
+ * runs before this transform, so a rewrite that changes the caller's term cannot reach the
1593
+ * hook's term.
1594
+ */
1595
+ PrepareExtraFilterSQL(extraFilter, entityInfo) {
1596
+ if (!extraFilter)
1597
+ return '';
1598
+ const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
1599
+ const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
1600
+ if (!terms || terms.length < 2) {
1601
+ this.AssertClauseBalanced(transformed, 'ExtraFilter');
1602
+ return transformed;
1603
+ }
1604
+ return terms
1605
+ .map((term) => {
1606
+ const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
1607
+ this.AssertClauseBalanced(termSQL, 'ExtraFilter');
1608
+ return `(${termSQL})`;
1609
+ })
1610
+ .join(' AND ');
1611
+ }
1468
1612
  /**
1469
1613
  * Optionally wraps a view query with user view run logging.
1470
1614
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
@@ -1549,11 +1693,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1549
1693
  return externalResult;
1550
1694
  }
1551
1695
  // ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
1552
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
1696
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
1553
1697
  const userSearchString = params.UserSearchString ?? '';
1554
1698
  const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
1555
1699
  const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
1556
1700
  const saveViewResults = params.SaveViewResults ?? false;
1701
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
1702
+ this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
1557
1703
  // ── TOP / pagination mode ──
1558
1704
  // Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
1559
1705
  // and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
@@ -1614,18 +1760,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1614
1760
  // 1. View where clause
1615
1761
  if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
1616
1762
  const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
1617
- // SECURITY: a stored view WhereClause originates from a client save, so pass the
1618
- // rendered clause through the same screen ExtraFilter gets. The one exemption is
1619
- // CustomWhereClause views: those are admin-authored (MJUserViewEntityServer's save
1620
- // gate restricts setting/changing them to Owner-type users) and may legitimately
1621
- // contain constructs the screen blocks. Auto-generated clauses (FilterState /
1622
- // SmartFilter / nested {%UserView%} templates) always pass — the screen permits
1623
- // plain SELECT subqueries and blocks only stacked statements, DML, comments,
1624
- // UNION and WAITFOR.
1763
+ // SECURITY: a stored view WhereClause originates from a client save, so the rendered
1764
+ // clause passes the full client-clause screen (ScreenStoredViewWhereClause) and the
1765
+ // keyword denylist ExtraFilter gets. The one exemption is CustomWhereClause views:
1766
+ // those are admin-authored (MJUserViewEntityServer's save gate restricts setting/
1767
+ // changing them to Owner-type users) and may legitimately contain constructs the
1768
+ // screens block. Auto-generated clauses (FilterState / SmartFilter / nested
1769
+ // {%UserView%} templates) are written against entity base views, which the screens
1770
+ // permit when the running user reads each of those entities unscoped.
1771
+ this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
1625
1772
  const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
1626
1773
  if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
1627
1774
  throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
1628
1775
  }
1776
+ // CustomWhereClause views too: an unbalanced clause would take row-level security
1777
+ // out of force for everyone who runs the view. Only their admin-written text may
1778
+ // carry comments.
1779
+ this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
1780
+ AllowComments: isCustomWhereClause,
1781
+ });
1629
1782
  whereSQL = `(${renderedWhere})`;
1630
1783
  bHasWhere = true;
1631
1784
  }
@@ -1670,8 +1823,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1670
1823
  // first column's value with a prior run — refuse rather than return the wrong rows.
1671
1824
  this.assertSingleColumnPrimaryKey(entityInfo, 'ExcludeUserViewRunID / ExcludeDataFromAllPriorViewRuns');
1672
1825
  let sExcludeSQL = `${this.QuoteIdentifier(entityInfo.FirstPrimaryKey.Name)} NOT IN (SELECT RecordID FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwUserViewRunDetails')} WHERE EntityID='${viewEntity?.EntityID}' AND`; // first-pk-ok: guarded above — view-run RecordID is a single bare key value, PrimaryKeys.length === 1 enforced
1673
- if (params.ExcludeDataFromAllPriorViewRuns === true)
1826
+ if (params.ExcludeDataFromAllPriorViewRuns === true) {
1827
+ // SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
1828
+ if (!IsValidUUID(String(viewEntity?.ID ?? '')))
1829
+ throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
1674
1830
  sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
1831
+ }
1675
1832
  else {
1676
1833
  // SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
1677
1834
  // interpolated directly into SQL here. Unlike ExtraFilter/OrderBy/
@@ -1687,6 +1844,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1687
1844
  if (overrideExcludeFilter.length > 0) {
1688
1845
  if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
1689
1846
  throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
1847
+ this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
1690
1848
  sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
1691
1849
  }
1692
1850
  whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
@@ -1749,6 +1907,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1749
1907
  const orderBy = rawOrderBy.length > 0
1750
1908
  ? (usingKeyset || orderByIsPkFallback ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
1751
1909
  : '';
1910
+ if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
1911
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
1912
+ // No caller OrderBy means the sort came from the saved view's stored sort state.
1913
+ if (!params.OrderBy && viewEntity)
1914
+ this.ScreenStoredViewOrderBy(orderBy, user);
1915
+ }
1752
1916
  // View run logging (SQL Server-specific, others return null)
1753
1917
  let userViewRunID = '';
1754
1918
  if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
@@ -2162,9 +2326,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2162
2326
  // Note this restores the pre-#4392 screen for this path; it does not close the
2163
2327
  // unquoted-format hole, which the denylist never covered (`1) OR 1=1` carries no
2164
2328
  // forbidden keyword). Quoting `{0}` in the format is what actually closes that.
2165
- if (this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields) && !this.ValidateUserProvidedSQLClause(userSearchString)) {
2329
+ //
2330
+ // The screen reads the quote-doubled term, because that is the text `{0}` becomes.
2331
+ if (this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields) && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
2166
2332
  throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
2167
- `which splices the term directly into SQL, and the term contains forbidden keywords.`);
2333
+ `which splices the term directly into SQL, and the term is not allowed there: it contains ` +
2334
+ `a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
2335
+ `tokens, such as an unbalanced quote or bracket.`);
2168
2336
  }
2169
2337
  const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
2170
2338
  for (const field of entityInfo.Fields) {
@@ -2196,6 +2364,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2196
2364
  sUserSearchSQL = '(1=0)';
2197
2365
  }
2198
2366
  }
2367
+ // A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
2368
+ this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
2199
2369
  return sUserSearchSQL;
2200
2370
  }
2201
2371
  /**
@@ -2295,6 +2465,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2295
2465
  return true;
2296
2466
  }
2297
2467
  /**************************************************************************/
2468
+ // Client clause screening
2469
+ /**************************************************************************/
2470
+ /**
2471
+ * SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
2472
+ * Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
2473
+ * fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
2474
+ */
2475
+ AssertClauseFragmentIsSingleStatement(clause, label) {
2476
+ ClientClauseScreen.AssertSingleStatementFragment(clause, label, this.Dialect);
2477
+ }
2478
+ /**
2479
+ * SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
2480
+ * against this provider's entities and dialect, with `contextUser` as the acting user. With
2481
+ * `entityInfo`, the clause is screened in the form this provider runs a client clause for that
2482
+ * entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
2483
+ * outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
2484
+ * saved-view save gate (`MJUserViewEntityServer`).
2485
+ */
2486
+ ScreenClientClause(clause, label, contextUser, entityInfo) {
2487
+ const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
2488
+ ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
2489
+ }
2490
+ /**
2491
+ * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
2492
+ * Any user who can save a view can write its WhereClause, directly or through FilterState or a
2493
+ * Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
2494
+ * can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
2495
+ * request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
2496
+ * `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
2497
+ */
2498
+ ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
2499
+ if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
2500
+ return; // truthy — the DB may hand back true or 1
2501
+ this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
2502
+ this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
2503
+ }
2504
+ /**
2505
+ * SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
2506
+ * the full client-clause screen. Any user who can save a view can write those.
2507
+ */
2508
+ ScreenStoredViewOrderBy(orderBy, user) {
2509
+ this.ScreenClientClause(orderBy, 'OrderBy', user);
2510
+ }
2511
+ /**************************************************************************/
2298
2512
  // RenderViewWhereClause — View Template Rendering
2299
2513
  /**************************************************************************/
2300
2514
  /**
@@ -2764,7 +2978,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2764
2978
  async buildWhereClauseForCacheCheck(params, entityInfo, user) {
2765
2979
  let whereSQL = '';
2766
2980
  let bHasWhere = false;
2767
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
2981
+ // PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
2982
+ // check then runs on the result, as on the main view path.
2983
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
2984
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
2768
2985
  if (extraFilter.length > 0) {
2769
2986
  if (!this.ValidateUserProvidedSQLClause(extraFilter))
2770
2987
  throw new Error(`Invalid Extra Filter: ${extraFilter}`);
@@ -3177,6 +3394,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3177
3394
  if (orderBy.length > 0) {
3178
3395
  if (!this.ValidateUserProvidedSQLClause(orderBy))
3179
3396
  throw new Error(`Invalid OrderBy clause: ${orderBy}`);
3397
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
3180
3398
  sql += ` ORDER BY ${orderBy}`;
3181
3399
  }
3182
3400
  return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
@@ -3206,6 +3424,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3206
3424
  const itemsWithoutValidationSQL = [];
3207
3425
  const firstFetchWithValidation = [];
3208
3426
  const errorResults = [];
3427
+ const definitionHashes = new Map();
3209
3428
  for (let i = 0; i < params.length; i++) {
3210
3429
  const item = params[i];
3211
3430
  const query = this.resolveQuery(item.params);
@@ -3221,7 +3440,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3221
3440
  errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage: `User does not have permission to run query: ${query.Name}.${deniedMsg}` });
3222
3441
  continue;
3223
3442
  }
3224
- if (!item.cacheStatus) {
3443
+ const definition = this.QueryDefinitionSignatureFor(query);
3444
+ if (definition) {
3445
+ definitionHashes.set(i, definition.Hash);
3446
+ }
3447
+ if (!item.cacheStatus || this.clientSlotDefinitionDiffers(item.cacheStatus, definition)) {
3448
+ // No slot, or the client's slot holds rows of another definition of the query:
3449
+ // whatever CacheValidationSQL says about the data, those rows came from other SQL.
3225
3450
  if (query.CacheValidationSQL) {
3226
3451
  // First fetch for a validated query — run the validation status
3227
3452
  // anyway so the fresh response is STAMPED with the validation
@@ -3267,7 +3492,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3267
3492
  ...staleItems.map(({ index, params: queryParams, query }) => this.runFullQueryAndReturnForQuery(queryParams, index, 'stale', contextUser, query.ID, cacheStatusResults.get(index))),
3268
3493
  ];
3269
3494
  const fullQueryResults = await Promise.all(fullQueryPromises);
3270
- const allResults = [...errorResults, ...currentResults, ...fullQueryResults];
3495
+ const allResults = [...errorResults, ...currentResults, ...fullQueryResults]
3496
+ .map(result => result.status === 'error' || !definitionHashes.has(result.queryIndex)
3497
+ ? result
3498
+ : { ...result, definitionHash: definitionHashes.get(result.queryIndex) });
3271
3499
  allResults.sort((a, b) => a.queryIndex - b.queryIndex);
3272
3500
  return { success: true, results: allResults };
3273
3501
  }
@@ -3299,7 +3527,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3299
3527
  resolvable: true,
3300
3528
  authorized: !user || query.UserCanRun(user).canRun,
3301
3529
  categoryPath: query.CategoryPath,
3302
- queryName: query.Name
3530
+ queryName: query.Name,
3531
+ queryId: query.ID,
3532
+ definition: this.QueryDefinitionSignatureFor(query)
3303
3533
  };
3304
3534
  }
3305
3535
  catch (e) {
@@ -3307,6 +3537,31 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3307
3537
  return { resolvable: false, authorized: false };
3308
3538
  }
3309
3539
  }
3540
+ /**
3541
+ * The definition signature of `query` on this provider's platform: what a RunQuery cache slot
3542
+ * of the query must have been written under to be served. Computed by `QueryEngine` from the
3543
+ * same metadata this provider executes. Undefined when the engine cannot compute it, which
3544
+ * disables the definition check for that read rather than failing it.
3545
+ */
3546
+ QueryDefinitionSignatureFor(query) {
3547
+ try {
3548
+ return QueryEngine.Instance.GetDefinitionSignature(query.ID, this.PlatformKey);
3549
+ }
3550
+ catch (e) {
3551
+ LogStatusEx({ message: `QueryDefinitionSignatureFor: could not compute the definition of query '${query.Name}' (${e instanceof Error ? e.message : String(e)}) — skipping the definition check.`, verboseOnly: true });
3552
+ return undefined;
3553
+ }
3554
+ }
3555
+ /**
3556
+ * True when a client sent the definition hash its slot was written under and it is not this
3557
+ * server's. A client that sends none (a release before the hash existed) gets no definition check.
3558
+ */
3559
+ clientSlotDefinitionDiffers(cacheStatus, definition) {
3560
+ if (cacheStatus.definitionHash == null || !definition) {
3561
+ return false;
3562
+ }
3563
+ return cacheStatus.definitionHash !== definition.Hash;
3564
+ }
3310
3565
  /**
3311
3566
  * Resolves a query from RunQueryParams (by ID or Name+CategoryPath).
3312
3567
  * Uses QueryEngine as the single source of truth for query metadata.
@@ -3399,22 +3654,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3399
3654
  const promises = items.map(async ({ index, query }) => {
3400
3655
  try {
3401
3656
  const rows = await this.ExecuteSQL(query.CacheValidationSQL, undefined, undefined, contextUser);
3402
- if (rows && rows.length > 0) {
3403
- const row = rows[0];
3404
- results.set(index, {
3405
- success: true,
3406
- // Both spellings accepted. The shipped `CacheValidationSQL` field description tells authors
3407
- // to return `TotalRows`, while this has only ever read `RowCount` — so a query written
3408
- // from the documentation yields `Number(undefined)` = NaN, `NaN !== NaN` makes the slot
3409
- // never validate, and NaN is then written back into the client's cache entry where `??`
3410
- // cannot clear it. Silent, permanent degradation to always-refetch, with no error.
3411
- rowCount: Number(row['RowCount'] ?? row['TotalRows']),
3412
- maxUpdatedAt: row['MaxUpdatedAt'] ? new Date(String(row['MaxUpdatedAt'])).toISOString() : undefined,
3413
- });
3414
- }
3415
- else {
3416
- results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
3417
- }
3657
+ results.set(index, this.QueryCacheStatusFromRow(rows?.[0]));
3418
3658
  }
3419
3659
  catch (e) {
3420
3660
  results.set(index, { success: false, errorMessage: e instanceof Error ? e.message : String(e) });
@@ -3423,6 +3663,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3423
3663
  await Promise.all(promises);
3424
3664
  return results;
3425
3665
  }
3666
+ /**
3667
+ * Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
3668
+ * an empty result: zero rows, no timestamp.
3669
+ *
3670
+ * Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
3671
+ * tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
3672
+ * of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
3673
+ * validate, and NaN is then written back into the client's cache entry where `??` cannot clear
3674
+ * it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
3675
+ * batch the validation SQL read their rows through this too.
3676
+ */
3677
+ QueryCacheStatusFromRow(row) {
3678
+ if (!row) {
3679
+ return { success: true, rowCount: 0, maxUpdatedAt: undefined };
3680
+ }
3681
+ const maxUpdatedAt = row['MaxUpdatedAt'];
3682
+ return {
3683
+ success: true,
3684
+ rowCount: Number(row['RowCount'] ?? row['TotalRows']),
3685
+ maxUpdatedAt: maxUpdatedAt
3686
+ ? (maxUpdatedAt instanceof Date ? maxUpdatedAt : new Date(String(maxUpdatedAt))).toISOString()
3687
+ : undefined,
3688
+ };
3689
+ }
3426
3690
  /**
3427
3691
  * Runs a full query and returns results with cache metadata.
3428
3692
  */
@@ -3953,7 +4217,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3953
4217
  async ExecuteAdhocQuery(params, contextUser) {
3954
4218
  try {
3955
4219
  const validator = SQLExpressionValidator.Instance;
3956
- const validation = validator.validateFullQuery(params.SQL);
4220
+ const validation = validator.ValidateFullQuery(params.SQL, this.PlatformKey);
3957
4221
  const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
3958
4222
  if (!validation.valid || !statementCheck.IsReadOnly) {
3959
4223
  return {
@@ -4136,6 +4400,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4136
4400
  const ttlSeconds = await router.GetCacheTTLSeconds(externalDataSourceID, contextUser, this);
4137
4401
  const cacheable = !params.SQL && ttlSeconds > 0 && LocalCacheManager.Instance.IsInitialized;
4138
4402
  let fingerprint;
4403
+ let definition;
4139
4404
  if (cacheable) {
4140
4405
  // MaxRows/StartRow shape the result set, and the data source ID disambiguates slots.
4141
4406
  const fingerprintParams = {
@@ -4145,7 +4410,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4145
4410
  __eds: externalDataSourceID,
4146
4411
  };
4147
4412
  fingerprint = LocalCacheManager.Instance.GenerateRunQueryFingerprint(query.ID, query.Name, fingerprintParams, this.InstanceConnectionString, query.CategoryPath);
4148
- const cached = await LocalCacheManager.Instance.GetRunQueryResult(fingerprint); // TTL-enforced
4413
+ definition = this.QueryDefinitionSignatureFor(query);
4414
+ // TTL-enforced, and a miss when the slot was written under another definition of the query.
4415
+ const cached = await LocalCacheManager.Instance.GetRunQueryResult(fingerprint, definition);
4149
4416
  if (cached) {
4150
4417
  return {
4151
4418
  QueryID: cached.queryId ?? query.ID,
@@ -4176,7 +4443,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4176
4443
  const { paginatedResult, totalRowCount } = this.applyQueryPagination(checked.Results, params);
4177
4444
  if (cacheable && fingerprint) {
4178
4445
  // Fire-and-forget store with the data source's TTL (ms).
4179
- LocalCacheManager.Instance.SetRunQueryResult(fingerprint, query.Name, paginatedResult, '', totalRowCount, query.ID, ttlSeconds * 1000).catch(e => LogError(`External RunQuery cache write failed: ${e}`));
4446
+ LocalCacheManager.Instance.SetRunQueryResult(fingerprint, query.Name, paginatedResult, '', totalRowCount, query.ID, ttlSeconds * 1000, undefined, definition).catch(e => LogError(`External RunQuery cache write failed: ${e}`));
4180
4447
  }
4181
4448
  return { ...checked, Results: paginatedResult, RowCount: paginatedResult.length, TotalRowCount: totalRowCount };
4182
4449
  }
@@ -4471,9 +4738,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4471
4738
  const ret = d[0];
4472
4739
  // Trim trailing spaces for fixed-width char fields (char/nchar pad with spaces on both SQL Server and PG)
4473
4740
  for (const field of entityInfo.Fields) {
4474
- if (field.TSType === EntityFieldTSType.String &&
4475
- field.Type.toLowerCase().includes('char') &&
4476
- !field.Type.toLowerCase().includes('varchar')) {
4741
+ const isFixedWidth = field.FixedWidthColumn ?? (field.TSType === EntityFieldTSType.String && (field.Type.trim().toLowerCase() === 'char' || field.Type.trim().toLowerCase() === 'nchar'));
4742
+ if (isFixedWidth) {
4477
4743
  const val = ret[field.Name];
4478
4744
  if (typeof val === 'string')
4479
4745
  ret[field.Name] = val.trimEnd();
@@ -4551,6 +4817,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4551
4817
  /**
4552
4818
  * Checks whether a new record's field values pass the Create RLS filter.
4553
4819
  * Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
4820
+ * Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
4821
+ * filter that references a column the new row leaves NULL evaluates instead of failing to bind.
4822
+ * The row is what the caller sends: a column the database fills on insert (a non-literal default
4823
+ * or a trigger) is seen as NULL here.
4554
4824
  */
4555
4825
  async CheckCreateRLS(entity, user) {
4556
4826
  const entityInfo = entity.EntityInfo;
@@ -4558,7 +4828,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4558
4828
  if (!rlsWhereClause || rlsWhereClause.length === 0) {
4559
4829
  return true;
4560
4830
  }
4561
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, false);
4831
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4562
4832
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4563
4833
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4564
4834
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4591,7 +4861,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4591
4861
  return true; // pre-image check already passed and no filter-referenced column changed
4592
4862
  }
4593
4863
  }
4594
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, true);
4864
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4595
4865
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4596
4866
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4597
4867
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4627,22 +4897,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4627
4897
  * Builds field projections for an RLS synthetic-row subquery (Create post-image and
4628
4898
  * Update post-image checks).
4629
4899
  *
4630
- * @param includeNulls - The Update post-image REQUIRES null fields to be projected as
4631
- * typed NULLs: a filter referencing a column the caller just nulled must see SQL NULL,
4632
- * not a missing column. A bare `SELECT NULL AS Col` is untyped and can evaluate
4633
- * differently from a real row, so nulls are emitted as `CAST(NULL AS <sqltype>)` using
4634
- * the field's metadata-resolved type. An unresolvable type fails the save (throw)
4635
- * rather than emitting an untyped NULL. The Create check keeps its historical
4636
- * skip-nulls behavior (includeNulls=false).
4637
- */
4638
- BuildRLSSyntheticRowProjections(entity, entityInfo, includeNulls) {
4900
+ * Every non-virtual field is projected, null fields included: a filter referencing a
4901
+ * column the row leaves NULL must see SQL NULL, not a missing column (which fails to
4902
+ * bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
4903
+ * untyped and can evaluate differently from a real row, so nulls are emitted as
4904
+ * `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
4905
+ * type fails the save (throw) rather than emitting an untyped NULL.
4906
+ */
4907
+ BuildRLSSyntheticRowProjections(entity, entityInfo) {
4639
4908
  const parts = [];
4640
4909
  for (const field of entityInfo.Fields) {
4641
4910
  if (field.IsVirtual)
4642
4911
  continue;
4643
4912
  const val = entity.Get(field.Name);
4644
- if (val == null && !includeNulls)
4645
- continue;
4646
4913
  parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
4647
4914
  }
4648
4915
  return parts.join(', ');
@@ -4671,7 +4938,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4671
4938
  // spot check and still emits `CAST(NULL AS nvarchar(50))` on the very next field.
4672
4939
  const baseType = field.Type;
4673
4940
  if (!baseType || baseType.trim().length === 0) {
4674
- throw new Error(`Cannot build RLS post-image projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
4941
+ throw new Error(`Cannot build RLS row projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
4675
4942
  }
4676
4943
  // `field.Length` is the SYSTEM (byte) length from `sys.columns`, but
4677
4944
  // `MapDataTypeToString` takes a CHARACTER count — `RuntimeSchemaManager` calls it as
@@ -4683,8 +4950,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4683
4950
  // the CAST becomes illegal and the RLS post-image gate throws on SQL SERVER: the exact
4684
4951
  // failure this change set out to remove from PostgreSQL, relocated to the primary
4685
4952
  // platform. `MaxLength` does the halving, but flattens the `-1` MAX sentinel to 0, so
4686
- // the sentinel is passed through explicitly.
4687
- const charLength = field.Length === -1 ? -1 : field.MaxLength;
4953
+ // the sentinel is passed through explicitly. `MaxLength` is also 0 for `binary`/`varbinary`,
4954
+ // whose length is a byte count, and SQL Server rejects `VARBINARY(0)`, so those keep
4955
+ // `field.Length`.
4956
+ const isBinary = /^(var)?binary$/i.test(baseType.trim());
4957
+ const charLength = field.Length === -1 || isBinary ? field.Length : field.MaxLength;
4688
4958
  // `getDialect()` is nullable on this base. Falling back to `SQLFullType` — the exact
4689
4959
  // string this used to emit — keeps SQL Server, whose vocabulary that already is,
4690
4960
  // byte-identical to its previous behaviour.
@@ -4731,12 +5001,56 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4731
5001
  BuildParameterPlaceholder(index) {
4732
5002
  return `$${index + 1}`;
4733
5003
  }
5004
+ /**
5005
+ * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
5006
+ * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
5007
+ * that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
5008
+ * user checks: every authenticated client loads it to learn the schema, including principals
5009
+ * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
5010
+ */
5011
+ resolveDatasetItemScope(datasetName, item, itemFilters, contextUser) {
5012
+ const code = String(item['Code']);
5013
+ const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
5014
+ const clientFilter = itemFilters?.find(f => f?.ItemCode === code)?.Filter ?? '';
5015
+ if (clientFilter && !this.ValidateUserProvidedSQLClause(clientFilter)) {
5016
+ return { Filter: '', RowFilter: '', Refusal: `Invalid ItemFilter for dataset item '${code}': contains one or more forbidden keywords` };
5017
+ }
5018
+ const filter = whereClause && clientFilter ? `${whereClause} AND (${clientFilter})` : (whereClause || clientFilter);
5019
+ if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
5020
+ return { Filter: filter, RowFilter: '', Refusal: null };
5021
+ }
5022
+ const entityName = String(item['Entity']);
5023
+ const entity = this.EntityByName(entityName);
5024
+ if (!entity) {
5025
+ return { Filter: filter, RowFilter: '', Refusal: `Entity '${entityName}' of dataset item '${code}' not found in metadata` };
5026
+ }
5027
+ if (!entity.GetUserPermisions(contextUser)?.CanRead) {
5028
+ return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
5029
+ }
5030
+ return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
5031
+ }
5032
+ /**
5033
+ * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
5034
+ * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
5035
+ * level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
5036
+ */
5037
+ datasetItemWhereClause(scope) {
5038
+ if (!scope.RowFilter)
5039
+ return scope.Filter;
5040
+ if (!scope.Filter)
5041
+ return scope.RowFilter;
5042
+ return `(${scope.RowFilter}) AND ((${scope.Filter}))`;
5043
+ }
4734
5044
  /**
4735
5045
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
4736
5046
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
4737
5047
  *
4738
5048
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
4739
5049
  * while PG (and the default) use parallel individual queries.
5050
+ *
5051
+ * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
5052
+ * CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
5053
+ * item runs no SQL and fails the dataset.
4740
5054
  */
4741
5055
  async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
4742
5056
  const provider = (providerToUse ?? this);
@@ -4783,7 +5097,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4783
5097
  const code = String(item['Code']);
4784
5098
  const entityName = String(item['Entity']);
4785
5099
  const entityID = String(item['EntityID']);
4786
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4787
5100
  // External-data-source entities have no MJ base view — their data is proxied live and
4788
5101
  // can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
4789
5102
  // rather than silently querying a non-existent (or wrongly same-named) local view.
@@ -4800,19 +5113,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4800
5113
  });
4801
5114
  continue;
4802
5115
  }
4803
- // Build effective filter (WhereClause + optional runtime ItemFilter)
4804
- let effectiveFilter = whereClause;
4805
- if (itemFilters && itemFilters.length > 0) {
4806
- const filter = itemFilters.find(f => f.ItemCode === code);
4807
- if (filter) {
4808
- effectiveFilter = whereClause
4809
- ? `${whereClause} AND (${filter.Filter})`
4810
- : filter.Filter;
4811
- }
5116
+ // The item's filter and the caller's row filter, or why it is refused. A refused item
5117
+ // never reaches the cache or the database.
5118
+ const scope = provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser);
5119
+ if (scope.Refusal) {
5120
+ errorResults.push({
5121
+ EntityID: entityID,
5122
+ EntityName: entityName,
5123
+ Code: code,
5124
+ Results: [],
5125
+ LatestUpdateDate: undefined,
5126
+ Status: scope.Refusal,
5127
+ Success: false,
5128
+ });
5129
+ continue;
4812
5130
  }
5131
+ // The row filter keys the slot, so one user's filtered rows are never served to another.
5132
+ const rowFilterKey = scope.RowFilter || undefined;
4813
5133
  // Try cache first
4814
5134
  if (cacheAvailable) {
4815
- const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString, undefined, this.datasetCacheSegment(datasetName, code));
5135
+ const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code));
4816
5136
  const cached = await cache.GetRunViewResult(fingerprint);
4817
5137
  if (cached) {
4818
5138
  cacheHitCount++;
@@ -4844,12 +5164,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4844
5164
  });
4845
5165
  continue;
4846
5166
  }
4847
- const filterSQL = effectiveFilter ? 'WHERE ' + effectiveFilter : '';
5167
+ const whereSQL = this.datasetItemWhereClause(scope);
5168
+ const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
4848
5169
  uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
4849
5170
  uncachedItems.push(item);
4850
5171
  // Store fingerprint for write-through caching after SQL
4851
5172
  const fp = cacheAvailable
4852
- ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString, undefined, this.datasetCacheSegment(datasetName, code))
5173
+ ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
4853
5174
  : '';
4854
5175
  uncachedFingerprints.push(fp);
4855
5176
  }
@@ -4977,6 +5298,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4977
5298
  /**
4978
5299
  * Retrieves status information for a dataset by name: per-entity row count and
4979
5300
  * latest update date. Uses ExecuteSQLBatch for per-item status queries.
5301
+ *
5302
+ * Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
5303
+ * status fails with the refusal and no status SQL runs.
4980
5304
  */
4981
5305
  async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
4982
5306
  const overallStart = performance.now();
@@ -5015,33 +5339,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5015
5339
  // in GetDatasetByName.
5016
5340
  const updateDates = [];
5017
5341
  let overallLatestDate = new Date(1900, 1, 1);
5342
+ // Same scope as GetDatasetByName's data read — the stored item WhereClause, the caller's
5343
+ // ItemFilter and the caller's row filter — so status and data describe the same row set.
5344
+ // (Every shipped MJ_Metadata item has a NULL WhereClause and no row filter, so for
5345
+ // metadata this is an unfiltered aggregate.)
5346
+ const scopes = items.map(item => provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser));
5347
+ const refusal = scopes.find(scope => scope.Refusal)?.Refusal;
5348
+ if (refusal) {
5349
+ return {
5350
+ DatasetID: String(items[0]['DatasetID']),
5351
+ DatasetName: datasetName,
5352
+ Success: false,
5353
+ Status: refusal,
5354
+ LatestUpdateDate: new Date(0),
5355
+ EntityUpdateDates: [],
5356
+ };
5357
+ }
5018
5358
  const itemMeta = [];
5019
- const queries = items.map((item) => {
5359
+ const queries = items.map((item, index) => {
5020
5360
  const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
5021
5361
  const entityBaseView = String(item['EntityBaseView']);
5022
- const code = String(item['Code']);
5023
5362
  const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
5024
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
5025
5363
  itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
5026
5364
  // The floor for the reported timestamp: an edit to the dataset DEFINITION itself
5027
5365
  // (item added, filter changed) must read as a change even when no entity row moved.
5028
5366
  const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
5029
5367
  const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
5030
5368
  const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
5031
- // Same filter composition as GetDatasetByName's data read — the stored item
5032
- // WhereClause AND'd with any runtime filter — so status and data describe the same
5033
- // row set. (Every shipped MJ_Metadata item has a NULL WhereClause, so for metadata
5034
- // this is identical to an unfiltered aggregate.)
5035
- let effectiveFilter = whereClause;
5036
- if (itemFilters && itemFilters.length > 0) {
5037
- const filter = itemFilters.find(f => f.ItemCode === code);
5038
- if (filter) {
5039
- effectiveFilter = whereClause
5040
- ? `${whereClause} AND (${filter.Filter})`
5041
- : filter.Filter;
5042
- }
5043
- }
5044
- const filterSQL = effectiveFilter ? ' WHERE ' + effectiveFilter : '';
5369
+ const whereSQL = this.datasetItemWhereClause(scopes[index]);
5370
+ const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
5045
5371
  return `SELECT ` +
5046
5372
  `CASE ` +
5047
5373
  `WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
@@ -5277,10 +5603,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5277
5603
  const data = result.data;
5278
5604
  const matches = data?.matches ?? [];
5279
5605
  const out = [];
5606
+ const seenRecordIds = new Set();
5280
5607
  for (const m of matches) {
5281
5608
  const recordId = String(m.metadata?.['RecordID'] ?? '');
5282
5609
  if (!recordId)
5283
5610
  continue;
5611
+ const normalizedKey = recordId.toLowerCase();
5612
+ if (seenRecordIds.has(normalizedKey))
5613
+ continue;
5614
+ seenRecordIds.add(normalizedKey);
5284
5615
  out.push({
5285
5616
  ID: recordId,
5286
5617
  Score: m.score,