@memberjunction/generic-database-provider 6.2.0-edge.3 → 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 } 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';
@@ -34,8 +34,10 @@ import { QueueManager } from '@memberjunction/queue';
34
34
  import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
35
35
  import { BuildEntityChangeContext } from '@memberjunction/actions-base';
36
36
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
+ import { TransactionAffinity } from './TransactionAffinity.js';
37
38
  import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
38
- import { EncryptionEngine } from '@memberjunction/encryption';
39
+ import { ClientClauseScreen } from './clientClauseScreen.js';
40
+ import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
39
41
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
40
42
  /**
41
43
  * Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
@@ -95,16 +97,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
95
97
  * release hands them to the enclosing frame.
96
98
  */
97
99
  this._postCommitTasks = [];
98
- /**
99
- * Tasks whose own transaction already settled, held back because an UNRELATED transaction is
100
- * open on this instance. Running them now would enlist their writes in it — on one connection,
101
- * that means a rollback of work that has nothing to do with them. Drained when this provider
102
- * goes idle, whichever way that transaction ends.
103
- */
104
- this._idlePostCommitTasks = [];
105
100
  /** Identity of each open frame and the fate of recent transactions, for {@link PostCommitToken}s. */
106
101
  this._frameTracker = new TransactionFrameTracker();
102
+ /** Which async scope the open transaction belongs to (#4786). See {@link IsCallerInAmbientTransaction}. */
103
+ this._affinity = new TransactionAffinity();
104
+ /** Epoch whose foreign join was already reported, so a transaction reports at most one (#4786). */
105
+ this._foreignJoinReportedEpoch = null;
107
106
  this._txMutex = Promise.resolve();
107
+ /**
108
+ * Batch levels this provider has opened and not yet closed.
109
+ *
110
+ * The open happens only after a begin SUCCEEDS, while a commit or rollback closes in a
111
+ * `finally` — so a rollback issued for a begin that threw would close a level it never opened.
112
+ * That happens for real: a nested begin whose savepoint creation fails leaves the caller's
113
+ * catch to roll back, and the seventeen generated cascade-delete overrides are written exactly
114
+ * that way. Closing an outer unit of work's batch early un-batches the rest of its saves, which
115
+ * then write to the shared cache one by one — the uncommitted-rows-in-the-fleet failure the
116
+ * batch exists to prevent.
117
+ */
118
+ this._openBatchLevels = 0;
108
119
  }
109
120
  /**
110
121
  * Returns the active local storage provider, lazily creating an
@@ -144,22 +155,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
144
155
  SetLocalStorageProvider(provider) {
145
156
  this._localStorageProvider = provider;
146
157
  }
158
+ /**
159
+ * Installs {@link ProviderConfigDataBase.LocalStorageProvider}, when the configuration carries
160
+ * one, before the base configuration loads metadata. A server fleet passes its shared (Redis)
161
+ * store this way so the metadata load and the engines loaded at startup use it from the first
162
+ * read: the first server to start fills the shared cache, and the others read it instead of
163
+ * each querying the database and broadcasting what they loaded.
164
+ */
165
+ async Config(data, providerToUse) {
166
+ if (data?.LocalStorageProvider) {
167
+ this.SetLocalStorageProvider(data.LocalStorageProvider);
168
+ }
169
+ return super.Config(data, providerToUse);
170
+ }
147
171
  /**************************************************************************/
148
172
  // SQL Logging — Session Management & Statement Logging
149
173
  /**************************************************************************/
150
174
  static { this._sqlLoggingSessionsKey = 'MJ_GenericDatabaseProvider_SqlLoggingSessions'; }
175
+ static { this._cachedSqlLoggingSessions = null; }
151
176
  get _sqlLoggingSessions() {
177
+ if (GenericDatabaseProvider._cachedSqlLoggingSessions) {
178
+ return GenericDatabaseProvider._cachedSqlLoggingSessions;
179
+ }
152
180
  const g = MJGlobal.Instance.GetGlobalObjectStore();
153
181
  if (g) {
154
182
  if (!g[GenericDatabaseProvider._sqlLoggingSessionsKey]) {
155
183
  g[GenericDatabaseProvider._sqlLoggingSessionsKey] = new Map();
156
184
  }
157
- return g[GenericDatabaseProvider._sqlLoggingSessionsKey];
185
+ GenericDatabaseProvider._cachedSqlLoggingSessions = g[GenericDatabaseProvider._sqlLoggingSessionsKey];
186
+ return GenericDatabaseProvider._cachedSqlLoggingSessions;
158
187
  }
159
188
  else {
160
189
  throw new Error('No global object store available for SQL logging session');
161
190
  }
162
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
+ }
163
198
  /**
164
199
  * Creates a new SQL logging session that will capture all SQL operations to a file.
165
200
  * Returns a disposable session object that must be disposed to stop logging.
@@ -276,7 +311,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
276
311
  const hasVerboseSession = allSessions.some(s => s.options.verboseOutput === true);
277
312
  if (hasVerboseSession) {
278
313
  console.log('=== SQL LOGGING DEBUG ===');
279
- console.log(`Query to log: ${query.substring(0, 100)}...`);
314
+ console.log(`Query to log: ${ApplyStatementTransforms(query, allSessions).substring(0, 100)}...`);
280
315
  console.log(`Context user email: ${contextUser?.Email || 'NOT_PROVIDED'}`);
281
316
  console.log(`Active sessions count: ${this._sqlLoggingSessions.size}`);
282
317
  console.log(`All sessions:`, allSessions.map(s => ({
@@ -366,6 +401,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
366
401
  * save succeeds is not a durability improvement, it is a different feature.
367
402
  */
368
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
+ }
369
408
  // FIRST STATEMENT, and deliberately before the first `await`. After-hooks are dispatched
370
409
  // fire-and-forget, and the moment this method yields, the save completes and `finalizeSave()`
371
410
  // reloads the entity — resetting every field's OldValue to its new value. A change context
@@ -377,8 +416,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
377
416
  // rolled-back save never fires it (see RunAfterCommit).
378
417
  const postCommitToken = this.CapturePostCommitToken();
379
418
  try {
380
- const engine = EntityActionEngineServer.Instance;
381
- await engine.Config(false, user);
419
+ if (!engine.Loaded) {
420
+ await engine.Config(false, user);
421
+ }
382
422
  const newRecord = entityChange.IsCreate;
383
423
  const baseTypeType = baseType === 'save' ? (newRecord ? 'Create' : 'Update') : 'Delete';
384
424
  const invocationType = baseType === 'validate' ? 'Validate' : before ? 'Before' + baseTypeType : 'After' + baseTypeType;
@@ -447,10 +487,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
447
487
  try {
448
488
  if (baseType === 'delete')
449
489
  return; // delete not yet supported for AI actions
450
- await AIEngine.Instance.Config(false, user);
490
+ const ai = AIEngine.Instance;
491
+ if (!ai.Loaded) {
492
+ await ai.Config(false, user);
493
+ }
451
494
  const actions = this.GetEntityAIActions(entity.EntityInfo, before);
452
495
  if (actions && actions.length > 0) {
453
- const ai = AIEngine.Instance;
454
496
  for (let i = 0; i < actions.length; i++) {
455
497
  const a = actions[i];
456
498
  if ((a.TriggerEvent === 'before save' && before) || (a.TriggerEvent === 'after save' && !before)) {
@@ -655,8 +697,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
655
697
  if (datetimeFields.length > 0 && !entityInfo.ExternalDataSourceID) {
656
698
  processedRows = await this.AdjustDatetimeFields(processedRows, datetimeFields, entityInfo);
657
699
  }
658
- // Step 2: Encryption decryption
659
- 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);
660
702
  if (encryptedFields.length === 0)
661
703
  return processedRows;
662
704
  const encryptionEngine = EncryptionEngine.Instance;
@@ -674,6 +716,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
674
716
  processedRow[field.Name] = decryptedValue;
675
717
  }
676
718
  catch (decryptError) {
719
+ // A key this install wasn't given (an app's own key) is configuration, not a
720
+ // fault: one warning per key, and the value stays encrypted.
721
+ if (IsEncryptionKeyUnavailable(decryptError)) {
722
+ ReportEncryptionKeyUnavailable(decryptError);
723
+ continue;
724
+ }
677
725
  const message = decryptError instanceof Error ? decryptError.message : String(decryptError);
678
726
  LogError(`Failed to decrypt field "${field.Name}" on entity "${entityInfo.Name}": ${message}. ` +
679
727
  'The encrypted value will be returned unchanged.');
@@ -683,6 +731,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
683
731
  return processedRow;
684
732
  }));
685
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
+ }
686
746
  /**
687
747
  * Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
688
748
  * own read paths but returns entity rows — the transaction groups. Every row a provider hands
@@ -1013,6 +1073,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1013
1073
  const pkValues = entity.PrimaryKey?.KeyValuePairs?.map((p) => p.Value) ?? [];
1014
1074
  return this.allocateSaveCallSuffixForPk(entity.TransactionGroup, entity.EntityInfo.SchemaName, entity.EntityInfo.BaseTable, pkValues);
1015
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
+ }
1016
1118
  /**
1017
1119
  * Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
1018
1120
  * record saves for migration replay (SQL Server's Metadata_Sync migrations) override
@@ -1023,6 +1125,28 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1023
1125
  RenderReplaySaveSQL(_binding, _entity, _fieldValues) {
1024
1126
  return undefined;
1025
1127
  }
1128
+ /**
1129
+ * Optional replay form of an UPDATE for the SQL log only (never executed). Receives just the
1130
+ * fields this save CHANGED. A recording that carried the whole row would, on replay, overwrite
1131
+ * every column of the target row with the recording database's values — including settings a
1132
+ * deploying application tuned on purpose (an MJ metadata sync that only flipped
1133
+ * `AllowUserSearchAPI` on 'MJ: Content Items' also reset that consumer's
1134
+ * `TrustServerCacheCompletely`). Dialects whose update procs keep unpassed columns override
1135
+ * this. Default: no replay form, the plain save SQL is logged.
1136
+ */
1137
+ RenderReplayUpdateSQL(_binding, _entity, _changedFieldValues) {
1138
+ return undefined;
1139
+ }
1140
+ /** The entries of a save's parameter map whose fields this save actually changed. */
1141
+ changedFieldValues(entity, fieldValues, dirtyFields) {
1142
+ const changed = new Map();
1143
+ for (const [f, value] of fieldValues) {
1144
+ const isDirty = dirtyFields ? dirtyFields.has(f) : !!entity.GetFieldByName(f.Name)?.Dirty;
1145
+ if (isDirty)
1146
+ changed.set(f, value);
1147
+ }
1148
+ return changed;
1149
+ }
1026
1150
  /**
1027
1151
  * Concrete implementation of the abstract save-SQL builder defined on
1028
1152
  * `DatabaseProviderBase`. Iterates fields via the single `IsSPParameter`
@@ -1038,6 +1162,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1038
1162
  const spName = this.GetCreateUpdateSPName(entity, isNew);
1039
1163
  // 1. Iterate fields, apply IsSPParameter + PK rules, coerce values.
1040
1164
  const fieldValueMap = new Map();
1165
+ const dirtyFields = isUpdate ? new Set() : undefined;
1041
1166
  for (const f of entity.EntityInfo.Fields) {
1042
1167
  if (!f.IsSPParameter(isUpdate))
1043
1168
  continue;
@@ -1075,22 +1200,51 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1075
1200
  if (coerced.kind === 'skip')
1076
1201
  continue;
1077
1202
  fieldValueMap.set(f, coerced.value);
1203
+ if (dirtyFields && theField?.Dirty) {
1204
+ dirtyFields.add(f);
1205
+ }
1078
1206
  }
1079
1207
  // 2. Encrypt — between coercion and rendering, mutates the map in place.
1080
1208
  await this.EncryptFieldValuesForSave(entity, fieldValueMap, user);
1081
1209
  // 3. Render the provider-specific binding.
1082
1210
  const binding = this.RenderSaveCallBinding(entity, fieldValueMap, isUpdate, spName);
1083
- // 4. Wrap with result capture. This is the "no-record-change" save
1084
- // shape; we also keep it as simpleSQL so consumers (e.g.
1085
- // DatabaseProviderBase's `simpleSQLFallback` flow) have a
1086
- // record-change-free form to fall back to.
1087
- 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;
1088
1227
  let saveSQL = baseSaveSQL;
1089
1228
  // A CREATE's logged form is guarded on the primary key so a migration replay of
1090
- // the recording converges on a database that already holds the row (#4503).
1091
- // Updates and dialects without a replay form log the plain save SQL.
1092
- const replaySQL = isNew ? this.RenderReplaySaveSQL(binding, entity, fieldValueMap) : undefined;
1093
- const simpleSQL = replaySQL ?? baseSaveSQL.sql;
1229
+ // the recording converges on a database that already holds the row (#4503). An
1230
+ // UPDATE's logged form carries only the fields this save changed, so a replay never
1231
+ // resets the target's other columns. A forced save (IgnoreDirtyState, e.g. MetadataSync's
1232
+ // `alwaysPush`) asked to re-impose the whole row, so it keeps the full-row form. Dialects
1233
+ // without a replay form log the plain save 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
+ };
1094
1248
  // 5. Optionally wrap with record-change emission.
1095
1249
  let overlappingChangeData;
1096
1250
  // Per-save suppression: a high-volume machine writer (integration sync) opts out of the
@@ -1098,27 +1252,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1098
1252
  if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
1099
1253
  const newData = entity.GetAll(false);
1100
1254
  const oldData = isUpdate ? entity.GetAll(true) : null;
1101
- // ISA propagation hook: capture the diff for SS subtype propagation.
1102
- // Returned via `extraData` so the SS subclass can consume it without re-diffing.
1103
- if (isUpdate && oldData) {
1104
- const diffChanges = this.DiffObjects(oldData, newData, entity.EntityInfo, "'");
1105
- 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) {
1106
1260
  overlappingChangeData = {
1107
- changesJSON: JSON.stringify(diffChanges),
1108
- changesDescription: this.CreateUserDescriptionOfChanges(diffChanges),
1261
+ changesJSON: payload.changesJSON,
1262
+ changesDescription: payload.changesDescription,
1109
1263
  };
1110
1264
  }
1111
- }
1112
- const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext);
1113
- if (payload) {
1114
- saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity);
1265
+ saveSQL = this.WrapSaveCallWithRecordChange(saveSQL, binding, payload, entity, options, returnContext);
1115
1266
  }
1116
1267
  }
1117
1268
  const result = {
1118
1269
  fullSQL: saveSQL.sql,
1119
- simpleSQL,
1270
+ get simpleSQL() {
1271
+ return computeSimpleSQL();
1272
+ },
1120
1273
  parameters: saveSQL.parameters ?? null,
1121
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
+ }
1122
1284
  if (overlappingChangeData) {
1123
1285
  result.extraData = { overlappingChangeData };
1124
1286
  }
@@ -1408,6 +1570,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1408
1570
  TransformExternalSQLClause(clause, _entityInfo) {
1409
1571
  return clause;
1410
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
+ }
1411
1612
  /**
1412
1613
  * Optionally wraps a view query with user view run logging.
1413
1614
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
@@ -1492,11 +1693,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1492
1693
  return externalResult;
1493
1694
  }
1494
1695
  // ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
1495
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
1696
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
1496
1697
  const userSearchString = params.UserSearchString ?? '';
1497
1698
  const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
1498
1699
  const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
1499
1700
  const saveViewResults = params.SaveViewResults ?? false;
1701
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
1702
+ this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
1500
1703
  // ── TOP / pagination mode ──
1501
1704
  // Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
1502
1705
  // and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
@@ -1557,18 +1760,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1557
1760
  // 1. View where clause
1558
1761
  if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
1559
1762
  const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
1560
- // SECURITY: a stored view WhereClause originates from a client save, so pass the
1561
- // rendered clause through the same screen ExtraFilter gets. The one exemption is
1562
- // CustomWhereClause views: those are admin-authored (MJUserViewEntityServer's save
1563
- // gate restricts setting/changing them to Owner-type users) and may legitimately
1564
- // contain constructs the screen blocks. Auto-generated clauses (FilterState /
1565
- // SmartFilter / nested {%UserView%} templates) always pass — the screen permits
1566
- // plain SELECT subqueries and blocks only stacked statements, DML, comments,
1567
- // 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);
1568
1772
  const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
1569
1773
  if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
1570
1774
  throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
1571
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
+ });
1572
1782
  whereSQL = `(${renderedWhere})`;
1573
1783
  bHasWhere = true;
1574
1784
  }
@@ -1613,8 +1823,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1613
1823
  // first column's value with a prior run — refuse rather than return the wrong rows.
1614
1824
  this.assertSingleColumnPrimaryKey(entityInfo, 'ExcludeUserViewRunID / ExcludeDataFromAllPriorViewRuns');
1615
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
1616
- 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`);
1617
1830
  sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
1831
+ }
1618
1832
  else {
1619
1833
  // SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
1620
1834
  // interpolated directly into SQL here. Unlike ExtraFilter/OrderBy/
@@ -1630,6 +1844,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1630
1844
  if (overrideExcludeFilter.length > 0) {
1631
1845
  if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
1632
1846
  throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
1847
+ this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
1633
1848
  sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
1634
1849
  }
1635
1850
  whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
@@ -1692,6 +1907,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1692
1907
  const orderBy = rawOrderBy.length > 0
1693
1908
  ? (usingKeyset || orderByIsPkFallback ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
1694
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
+ }
1695
1916
  // View run logging (SQL Server-specific, others return null)
1696
1917
  let userViewRunID = '';
1697
1918
  if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
@@ -1873,6 +2094,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1873
2094
  /**************************************************************************/
1874
2095
  // InternalRunView Helpers
1875
2096
  /**************************************************************************/
2097
+ /**
2098
+ * Builds the aggregate query without running the caller's text. Each expression must be a single
2099
+ * aggregate function call over this entity's columns: the query runs the SQL that
2100
+ * {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
2101
+ * dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
2102
+ * per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
2103
+ * request order, which is how `RunViewCore` reads their values back.
2104
+ */
2105
+ BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
2106
+ const columns = entityInfo.Fields.map((f) => f.Name);
2107
+ const items = [];
2108
+ const validationErrors = [];
2109
+ for (const agg of aggregates ?? []) {
2110
+ const screened = this.screenAggregateExpression(agg.expression, columns);
2111
+ if ('SQL' in screened) {
2112
+ items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
2113
+ }
2114
+ else {
2115
+ validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
2116
+ }
2117
+ }
2118
+ if (items.length === 0)
2119
+ return { aggregateSQL: null, validationErrors };
2120
+ const where = whereSQL ? ` WHERE ${whereSQL}` : '';
2121
+ return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
2122
+ }
2123
+ /** The SQL to run for one caller aggregate expression, or why it is refused. */
2124
+ screenAggregateExpression(expression, columns) {
2125
+ const check = CheckAggregateExpression(expression, this.Dialect, columns);
2126
+ if (!check.IsAllowed || check.SQL === null)
2127
+ return { Error: `Invalid aggregate expression: ${check.Reason}` };
2128
+ const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
2129
+ return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
2130
+ }
1876
2131
  /**
1877
2132
  * Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
1878
2133
  * the columns this user is allowed to read when field security denies them any.
@@ -2071,9 +2326,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2071
2326
  // Note this restores the pre-#4392 screen for this path; it does not close the
2072
2327
  // unquoted-format hole, which the denylist never covered (`1) OR 1=1` carries no
2073
2328
  // forbidden keyword). Quoting `{0}` in the format is what actually closes that.
2074
- 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)) {
2075
2332
  throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
2076
- `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.`);
2077
2336
  }
2078
2337
  const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
2079
2338
  for (const field of entityInfo.Fields) {
@@ -2105,6 +2364,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2105
2364
  sUserSearchSQL = '(1=0)';
2106
2365
  }
2107
2366
  }
2367
+ // A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
2368
+ this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
2108
2369
  return sUserSearchSQL;
2109
2370
  }
2110
2371
  /**
@@ -2204,6 +2465,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2204
2465
  return true;
2205
2466
  }
2206
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
+ /**************************************************************************/
2207
2512
  // RenderViewWhereClause — View Template Rendering
2208
2513
  /**************************************************************************/
2209
2514
  /**
@@ -2309,6 +2614,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2309
2614
  /**************************************************************************/
2310
2615
  // RunViewsWithCacheCheck — Shared Implementation
2311
2616
  /**************************************************************************/
2617
+ /**
2618
+ * Row count and newest `__mj_UpdatedAt` for each view, read from the database and never from
2619
+ * a cache. Uses the same WHERE clause (filter, user search, row-level security, pre-run hooks)
2620
+ * and the same batched status query as {@link RunViewsWithCacheCheck}. One entry per param,
2621
+ * in order; a failure is reported per entry.
2622
+ */
2623
+ async GetRunViewsDatabaseStatus(params, contextUser) {
2624
+ const user = contextUser || this.CurrentUser;
2625
+ const statuses = params.map(() => ({ Success: false, ErrorMessage: 'not checked' }));
2626
+ if (!user) {
2627
+ return statuses.map(() => ({ Success: false, ErrorMessage: 'No user context available' }));
2628
+ }
2629
+ const items = await this.buildDatabaseStatusItems(params, user, statuses);
2630
+ const results = await this.getBatchedServerCacheStatus(items, contextUser);
2631
+ for (const { index } of items) {
2632
+ const status = results.get(index);
2633
+ statuses[index] = status?.success
2634
+ ? { Success: true, RowCount: status.rowCount ?? 0, MaxUpdatedAt: status.maxUpdatedAt }
2635
+ : { Success: false, ErrorMessage: status?.errorMessage ?? 'no status returned' };
2636
+ }
2637
+ return statuses;
2638
+ }
2639
+ /** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
2640
+ async buildDatabaseStatusItems(params, user, statuses) {
2641
+ const items = [];
2642
+ for (let index = 0; index < params.length; index++) {
2643
+ try {
2644
+ const viewParams = { ...params[index] };
2645
+ this.ResolvePlatformSQLInParams(viewParams);
2646
+ const hooked = await this.RunPreRunViewHooks(viewParams, user);
2647
+ const entityInfo = hooked.EntityName ? this.EntityByName(hooked.EntityName) : undefined;
2648
+ if (!entityInfo) {
2649
+ statuses[index] = { Success: false, ErrorMessage: `Entity ${hooked.EntityName ?? '(none)'} not found` };
2650
+ continue;
2651
+ }
2652
+ const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user);
2653
+ items.push({ index, item: { params: hooked }, entityInfo, whereSQL });
2654
+ }
2655
+ catch (e) {
2656
+ statuses[index] = { Success: false, ErrorMessage: e instanceof Error ? e.message : String(e) };
2657
+ }
2658
+ }
2659
+ return items;
2660
+ }
2312
2661
  /**
2313
2662
  * Smart cache validation for batch RunViews.
2314
2663
  * For each view request, if cacheStatus is provided, checks if the cache is current
@@ -2498,6 +2847,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2498
2847
  const noCacheStatusServedFromCache = [];
2499
2848
  const noCacheStatusNeedsDB = [];
2500
2849
  for (const entry of itemsWithoutCacheCheck) {
2850
+ // A param carrying BypassCache lands here because it is ineligible for a cache status,
2851
+ // NOT because the caller has nothing cached — and those two must not be treated alike.
2852
+ // Serving it from the server cache is precisely what it asked not to happen: its
2853
+ // documented contract is "the query always hits the database", and it is the only way a
2854
+ // client can escape a server slot that a missed invalidation left stale. The write side
2855
+ // already refuses to store such a result (runViewCacheEligible starts with
2856
+ // !param.BypassCache); this is the matching read-side gate.
2857
+ if (entry.item.params.BypassCache) {
2858
+ LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — BypassCache requested, going to the database`, verboseOnly: true });
2859
+ noCacheStatusNeedsDB.push(entry);
2860
+ continue;
2861
+ }
2501
2862
  if (LocalCacheManager.Instance.IsInitialized) {
2502
2863
  const rlsWhereClause = this.ComputeRunViewRLSWhereClause(entry.item.params, contextUser);
2503
2864
  const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(entry.item.params);
@@ -2617,7 +2978,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2617
2978
  async buildWhereClauseForCacheCheck(params, entityInfo, user) {
2618
2979
  let whereSQL = '';
2619
2980
  let bHasWhere = false;
2620
- 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');
2621
2985
  if (extraFilter.length > 0) {
2622
2986
  if (!this.ValidateUserProvidedSQLClause(extraFilter))
2623
2987
  throw new Error(`Invalid Extra Filter: ${extraFilter}`);
@@ -2639,6 +3003,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2639
3003
  }
2640
3004
  return whereSQL;
2641
3005
  }
3006
+ /**
3007
+ * The freshness probe for one view: a row count, plus the newest `__mj_UpdatedAt` **when the
3008
+ * entity has that column**. Selecting it unconditionally made the probe fail outright for an
3009
+ * entity whose view does not carry it, instead of comparing by count alone the way
3010
+ * `BaseEngine.SweepAgainstDatabase` documents.
3011
+ */
3012
+ BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
3013
+ const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
3014
+ const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
3015
+ // `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
3016
+ // throwing: a freshness check must not be the thing that breaks a sweep.
3017
+ if (!entityInfo.Fields?.some(f => f.IsUpdatedAtField)) {
3018
+ return `SELECT ${count} ${from}`;
3019
+ }
3020
+ return `SELECT ${count}, MAX(${this.QuoteIdentifier('__mj_UpdatedAt')}) AS ${this.QuoteIdentifier('MaxUpdatedAt')} ${from}`;
3021
+ }
2642
3022
  /**
2643
3023
  * Executes cache status checks for multiple views.
2644
3024
  * Default: parallel individual queries (works on all platforms).
@@ -2657,7 +3037,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2657
3037
  // (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
2658
3038
  // matches the SQL Server override and is defense-in-depth on the PG/default path.)
2659
3039
  const effectiveView = await this.resolveEffectiveBaseView(entityInfo, item.params, contextUser);
2660
- const statusSQL = `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}, MAX(${this.QuoteIdentifier('__mj_UpdatedAt')}) AS ${this.QuoteIdentifier('MaxUpdatedAt')} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
3040
+ const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL);
2661
3041
  const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
2662
3042
  if (rows && rows.length > 0) {
2663
3043
  const row = rows[0];
@@ -3014,6 +3394,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3014
3394
  if (orderBy.length > 0) {
3015
3395
  if (!this.ValidateUserProvidedSQLClause(orderBy))
3016
3396
  throw new Error(`Invalid OrderBy clause: ${orderBy}`);
3397
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
3017
3398
  sql += ` ORDER BY ${orderBy}`;
3018
3399
  }
3019
3400
  return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
@@ -3043,6 +3424,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3043
3424
  const itemsWithoutValidationSQL = [];
3044
3425
  const firstFetchWithValidation = [];
3045
3426
  const errorResults = [];
3427
+ const definitionHashes = new Map();
3046
3428
  for (let i = 0; i < params.length; i++) {
3047
3429
  const item = params[i];
3048
3430
  const query = this.resolveQuery(item.params);
@@ -3058,7 +3440,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3058
3440
  errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage: `User does not have permission to run query: ${query.Name}.${deniedMsg}` });
3059
3441
  continue;
3060
3442
  }
3061
- 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.
3062
3450
  if (query.CacheValidationSQL) {
3063
3451
  // First fetch for a validated query — run the validation status
3064
3452
  // anyway so the fresh response is STAMPED with the validation
@@ -3104,7 +3492,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3104
3492
  ...staleItems.map(({ index, params: queryParams, query }) => this.runFullQueryAndReturnForQuery(queryParams, index, 'stale', contextUser, query.ID, cacheStatusResults.get(index))),
3105
3493
  ];
3106
3494
  const fullQueryResults = await Promise.all(fullQueryPromises);
3107
- 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) });
3108
3499
  allResults.sort((a, b) => a.queryIndex - b.queryIndex);
3109
3500
  return { success: true, results: allResults };
3110
3501
  }
@@ -3136,7 +3527,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3136
3527
  resolvable: true,
3137
3528
  authorized: !user || query.UserCanRun(user).canRun,
3138
3529
  categoryPath: query.CategoryPath,
3139
- queryName: query.Name
3530
+ queryName: query.Name,
3531
+ queryId: query.ID,
3532
+ definition: this.QueryDefinitionSignatureFor(query)
3140
3533
  };
3141
3534
  }
3142
3535
  catch (e) {
@@ -3144,6 +3537,31 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3144
3537
  return { resolvable: false, authorized: false };
3145
3538
  }
3146
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
+ }
3147
3565
  /**
3148
3566
  * Resolves a query from RunQueryParams (by ID or Name+CategoryPath).
3149
3567
  * Uses QueryEngine as the single source of truth for query metadata.
@@ -3236,22 +3654,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3236
3654
  const promises = items.map(async ({ index, query }) => {
3237
3655
  try {
3238
3656
  const rows = await this.ExecuteSQL(query.CacheValidationSQL, undefined, undefined, contextUser);
3239
- if (rows && rows.length > 0) {
3240
- const row = rows[0];
3241
- results.set(index, {
3242
- success: true,
3243
- // Both spellings accepted. The shipped `CacheValidationSQL` field description tells authors
3244
- // to return `TotalRows`, while this has only ever read `RowCount` — so a query written
3245
- // from the documentation yields `Number(undefined)` = NaN, `NaN !== NaN` makes the slot
3246
- // never validate, and NaN is then written back into the client's cache entry where `??`
3247
- // cannot clear it. Silent, permanent degradation to always-refetch, with no error.
3248
- rowCount: Number(row['RowCount'] ?? row['TotalRows']),
3249
- maxUpdatedAt: row['MaxUpdatedAt'] ? new Date(String(row['MaxUpdatedAt'])).toISOString() : undefined,
3250
- });
3251
- }
3252
- else {
3253
- results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
3254
- }
3657
+ results.set(index, this.QueryCacheStatusFromRow(rows?.[0]));
3255
3658
  }
3256
3659
  catch (e) {
3257
3660
  results.set(index, { success: false, errorMessage: e instanceof Error ? e.message : String(e) });
@@ -3260,6 +3663,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3260
3663
  await Promise.all(promises);
3261
3664
  return results;
3262
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
+ }
3263
3690
  /**
3264
3691
  * Runs a full query and returns results with cache metadata.
3265
3692
  */
@@ -3790,7 +4217,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3790
4217
  async ExecuteAdhocQuery(params, contextUser) {
3791
4218
  try {
3792
4219
  const validator = SQLExpressionValidator.Instance;
3793
- const validation = validator.validateFullQuery(params.SQL);
4220
+ const validation = validator.ValidateFullQuery(params.SQL, this.PlatformKey);
3794
4221
  const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
3795
4222
  if (!validation.valid || !statementCheck.IsReadOnly) {
3796
4223
  return {
@@ -3973,6 +4400,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3973
4400
  const ttlSeconds = await router.GetCacheTTLSeconds(externalDataSourceID, contextUser, this);
3974
4401
  const cacheable = !params.SQL && ttlSeconds > 0 && LocalCacheManager.Instance.IsInitialized;
3975
4402
  let fingerprint;
4403
+ let definition;
3976
4404
  if (cacheable) {
3977
4405
  // MaxRows/StartRow shape the result set, and the data source ID disambiguates slots.
3978
4406
  const fingerprintParams = {
@@ -3982,7 +4410,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3982
4410
  __eds: externalDataSourceID,
3983
4411
  };
3984
4412
  fingerprint = LocalCacheManager.Instance.GenerateRunQueryFingerprint(query.ID, query.Name, fingerprintParams, this.InstanceConnectionString, query.CategoryPath);
3985
- 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);
3986
4416
  if (cached) {
3987
4417
  return {
3988
4418
  QueryID: cached.queryId ?? query.ID,
@@ -4013,7 +4443,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4013
4443
  const { paginatedResult, totalRowCount } = this.applyQueryPagination(checked.Results, params);
4014
4444
  if (cacheable && fingerprint) {
4015
4445
  // Fire-and-forget store with the data source's TTL (ms).
4016
- 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}`));
4017
4447
  }
4018
4448
  return { ...checked, Results: paginatedResult, RowCount: paginatedResult.length, TotalRowCount: totalRowCount };
4019
4449
  }
@@ -4308,9 +4738,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4308
4738
  const ret = d[0];
4309
4739
  // Trim trailing spaces for fixed-width char fields (char/nchar pad with spaces on both SQL Server and PG)
4310
4740
  for (const field of entityInfo.Fields) {
4311
- if (field.TSType === EntityFieldTSType.String &&
4312
- field.Type.toLowerCase().includes('char') &&
4313
- !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) {
4314
4743
  const val = ret[field.Name];
4315
4744
  if (typeof val === 'string')
4316
4745
  ret[field.Name] = val.trimEnd();
@@ -4388,6 +4817,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4388
4817
  /**
4389
4818
  * Checks whether a new record's field values pass the Create RLS filter.
4390
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.
4391
4824
  */
4392
4825
  async CheckCreateRLS(entity, user) {
4393
4826
  const entityInfo = entity.EntityInfo;
@@ -4395,7 +4828,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4395
4828
  if (!rlsWhereClause || rlsWhereClause.length === 0) {
4396
4829
  return true;
4397
4830
  }
4398
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, false);
4831
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4399
4832
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4400
4833
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4401
4834
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4428,7 +4861,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4428
4861
  return true; // pre-image check already passed and no filter-referenced column changed
4429
4862
  }
4430
4863
  }
4431
- const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo, true);
4864
+ const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
4432
4865
  const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
4433
4866
  const result = await this.ExecuteSQL(sql, undefined, undefined, user);
4434
4867
  return result && result.length > 0 && Number(result[0]['pass']) === 1;
@@ -4464,22 +4897,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4464
4897
  * Builds field projections for an RLS synthetic-row subquery (Create post-image and
4465
4898
  * Update post-image checks).
4466
4899
  *
4467
- * @param includeNulls - The Update post-image REQUIRES null fields to be projected as
4468
- * typed NULLs: a filter referencing a column the caller just nulled must see SQL NULL,
4469
- * not a missing column. A bare `SELECT NULL AS Col` is untyped and can evaluate
4470
- * differently from a real row, so nulls are emitted as `CAST(NULL AS <sqltype>)` using
4471
- * the field's metadata-resolved type. An unresolvable type fails the save (throw)
4472
- * rather than emitting an untyped NULL. The Create check keeps its historical
4473
- * skip-nulls behavior (includeNulls=false).
4474
- */
4475
- 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) {
4476
4908
  const parts = [];
4477
4909
  for (const field of entityInfo.Fields) {
4478
4910
  if (field.IsVirtual)
4479
4911
  continue;
4480
4912
  const val = entity.Get(field.Name);
4481
- if (val == null && !includeNulls)
4482
- continue;
4483
4913
  parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
4484
4914
  }
4485
4915
  return parts.join(', ');
@@ -4508,7 +4938,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4508
4938
  // spot check and still emits `CAST(NULL AS nvarchar(50))` on the very next field.
4509
4939
  const baseType = field.Type;
4510
4940
  if (!baseType || baseType.trim().length === 0) {
4511
- 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`);
4512
4942
  }
4513
4943
  // `field.Length` is the SYSTEM (byte) length from `sys.columns`, but
4514
4944
  // `MapDataTypeToString` takes a CHARACTER count — `RuntimeSchemaManager` calls it as
@@ -4520,8 +4950,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4520
4950
  // the CAST becomes illegal and the RLS post-image gate throws on SQL SERVER: the exact
4521
4951
  // failure this change set out to remove from PostgreSQL, relocated to the primary
4522
4952
  // platform. `MaxLength` does the halving, but flattens the `-1` MAX sentinel to 0, so
4523
- // the sentinel is passed through explicitly.
4524
- 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;
4525
4958
  // `getDialect()` is nullable on this base. Falling back to `SQLFullType` — the exact
4526
4959
  // string this used to emit — keeps SQL Server, whose vocabulary that already is,
4527
4960
  // byte-identical to its previous behaviour.
@@ -4568,12 +5001,56 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4568
5001
  BuildParameterPlaceholder(index) {
4569
5002
  return `$${index + 1}`;
4570
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
+ }
4571
5044
  /**
4572
5045
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
4573
5046
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
4574
5047
  *
4575
5048
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
4576
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.
4577
5054
  */
4578
5055
  async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
4579
5056
  const provider = (providerToUse ?? this);
@@ -4620,7 +5097,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4620
5097
  const code = String(item['Code']);
4621
5098
  const entityName = String(item['Entity']);
4622
5099
  const entityID = String(item['EntityID']);
4623
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4624
5100
  // External-data-source entities have no MJ base view — their data is proxied live and
4625
5101
  // can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
4626
5102
  // rather than silently querying a non-existent (or wrongly same-named) local view.
@@ -4637,19 +5113,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4637
5113
  });
4638
5114
  continue;
4639
5115
  }
4640
- // Build effective filter (WhereClause + optional runtime ItemFilter)
4641
- let effectiveFilter = whereClause;
4642
- if (itemFilters && itemFilters.length > 0) {
4643
- const filter = itemFilters.find(f => f.ItemCode === code);
4644
- if (filter) {
4645
- effectiveFilter = whereClause
4646
- ? `${whereClause} AND (${filter.Filter})`
4647
- : filter.Filter;
4648
- }
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;
4649
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;
4650
5133
  // Try cache first
4651
5134
  if (cacheAvailable) {
4652
- 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));
4653
5136
  const cached = await cache.GetRunViewResult(fingerprint);
4654
5137
  if (cached) {
4655
5138
  cacheHitCount++;
@@ -4681,12 +5164,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4681
5164
  });
4682
5165
  continue;
4683
5166
  }
4684
- const filterSQL = effectiveFilter ? 'WHERE ' + effectiveFilter : '';
5167
+ const whereSQL = this.datasetItemWhereClause(scope);
5168
+ const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
4685
5169
  uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
4686
5170
  uncachedItems.push(item);
4687
5171
  // Store fingerprint for write-through caching after SQL
4688
5172
  const fp = cacheAvailable
4689
- ? 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))
4690
5174
  : '';
4691
5175
  uncachedFingerprints.push(fp);
4692
5176
  }
@@ -4814,6 +5298,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4814
5298
  /**
4815
5299
  * Retrieves status information for a dataset by name: per-entity row count and
4816
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.
4817
5304
  */
4818
5305
  async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
4819
5306
  const overallStart = performance.now();
@@ -4852,33 +5339,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4852
5339
  // in GetDatasetByName.
4853
5340
  const updateDates = [];
4854
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
+ }
4855
5358
  const itemMeta = [];
4856
- const queries = items.map((item) => {
5359
+ const queries = items.map((item, index) => {
4857
5360
  const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
4858
5361
  const entityBaseView = String(item['EntityBaseView']);
4859
- const code = String(item['Code']);
4860
5362
  const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
4861
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
4862
5363
  itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
4863
5364
  // The floor for the reported timestamp: an edit to the dataset DEFINITION itself
4864
5365
  // (item added, filter changed) must read as a change even when no entity row moved.
4865
5366
  const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
4866
5367
  const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
4867
5368
  const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
4868
- // Same filter composition as GetDatasetByName's data read — the stored item
4869
- // WhereClause AND'd with any runtime filter — so status and data describe the same
4870
- // row set. (Every shipped MJ_Metadata item has a NULL WhereClause, so for metadata
4871
- // this is identical to an unfiltered aggregate.)
4872
- let effectiveFilter = whereClause;
4873
- if (itemFilters && itemFilters.length > 0) {
4874
- const filter = itemFilters.find(f => f.ItemCode === code);
4875
- if (filter) {
4876
- effectiveFilter = whereClause
4877
- ? `${whereClause} AND (${filter.Filter})`
4878
- : filter.Filter;
4879
- }
4880
- }
4881
- const filterSQL = effectiveFilter ? ' WHERE ' + effectiveFilter : '';
5369
+ const whereSQL = this.datasetItemWhereClause(scopes[index]);
5370
+ const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
4882
5371
  return `SELECT ` +
4883
5372
  `CASE ` +
4884
5373
  `WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
@@ -5114,10 +5603,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5114
5603
  const data = result.data;
5115
5604
  const matches = data?.matches ?? [];
5116
5605
  const out = [];
5606
+ const seenRecordIds = new Set();
5117
5607
  for (const m of matches) {
5118
5608
  const recordId = String(m.metadata?.['RecordID'] ?? '');
5119
5609
  if (!recordId)
5120
5610
  continue;
5611
+ const normalizedKey = recordId.toLowerCase();
5612
+ if (seenRecordIds.has(normalizedKey))
5613
+ continue;
5614
+ seenRecordIds.add(normalizedKey);
5121
5615
  out.push({
5122
5616
  ID: recordId,
5123
5617
  Score: m.score,
@@ -5141,12 +5635,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5141
5635
  get IsDoomed() {
5142
5636
  return this._doomed;
5143
5637
  }
5144
- /**
5145
- * Throw if a statement would run on the pool while frames are still open
5146
- * after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
5147
- * — outermost begin has depth 1 before the handle is published, and
5148
- * concurrent reads on SQL Server legitimately use the pool in that window.
5149
- */
5150
5638
  /**
5151
5639
  * A debounced metadata refresh is timer-driven, so it can fire at any point of a caller's
5152
5640
  * unit of work — including the microtask window while the ambient transaction is being
@@ -5156,21 +5644,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5156
5644
  * Metadata reads are not part of anyone's unit of work, so wait for the transaction to end
5157
5645
  * before starting one (#4486).
5158
5646
  *
5159
- * This narrows the window rather than closing it: the check runs when the timer fires, and
5160
- * the batch is issued several round trips later, so a transaction that begins in between
5161
- * is still joined. That case is now harmless to the process — the batch fails, the dataset
5162
- * reports it, and the loaded metadata stays — but the refresh itself is lost until the next
5163
- * member write. Running the metadata batch on the pool regardless of the ambient
5164
- * transaction is #4514 (alongside #4454, the commit-side half of the same window).
5647
+ * Under scope affinity (#4786) the timer inherits the membership of the code that scheduled it
5648
+ * (re-arms included), so the refresh can only ever join the transaction whose scope scheduled
5649
+ * it — and only if that transaction is still open when the batch is issued, several round trips
5650
+ * after this check ran. It never joins a transaction someone else begins later. That remaining
5651
+ * window is harmless to the process — the batch fails, the dataset reports it, and the loaded
5652
+ * metadata stays — but the refresh itself is lost until the next member write. The check is
5653
+ * instance-wide, so an unrelated transaction also defers the refresh. Running the metadata
5654
+ * batch on the pool regardless of the ambient transaction is #4514 (alongside #4454, the
5655
+ * commit-side half of the same window).
5165
5656
  */
5166
5657
  get MetadataMemberRefreshMustWait() {
5167
5658
  return this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction;
5168
5659
  }
5660
+ /**
5661
+ * Throw if a statement from a member of the ambient transaction would run on the pool while its
5662
+ * frames are still open after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
5663
+ * — outermost begin has depth 1 before the handle is published, and concurrent reads on SQL
5664
+ * Server legitimately use the pool in that window. Callers outside the transaction's scope
5665
+ * (see {@link IsCallerInAmbientTransaction}) do not use its handle, so a subclass should apply
5666
+ * this check only to members' statements.
5667
+ */
5169
5668
  AssertAmbientTransactionUsable() {
5170
5669
  if (this._doomed) {
5171
5670
  throw new DoomedTransactionError(`SQL issued at depth ${this._transactionDepth} while the ambient transaction is doomed would autocommit on the pool`);
5172
5671
  }
5173
5672
  }
5673
+ /**
5674
+ * Whether the calling async scope is part of this provider's ambient transaction (#4786). A shared
5675
+ * provider's open transaction belongs to the scope that began it and its descendants; every other
5676
+ * caller must run on the pool, as if no transaction were open. Subclasses consult this — not merely
5677
+ * "is a handle open" — before routing a statement to the transaction handle.
5678
+ */
5679
+ IsCallerInAmbientTransaction() {
5680
+ return this._affinity.IsCallerMember;
5681
+ }
5682
+ /** Members of the open transaction share RunViews only with each other (see {@link ProviderBase.RunViewDedupScope}). */
5683
+ get RunViewDedupScope() {
5684
+ return this.IsCallerInAmbientTransaction() ? `tx:${this._affinity.CurrentEpoch}` : '';
5685
+ }
5174
5686
  /**
5175
5687
  * Drop a dead physical handle without going through public RollbackTransaction.
5176
5688
  * Default is RollbackPhysicalTransaction if one is open. Subclasses override
@@ -5204,8 +5716,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5204
5716
  }
5205
5717
  }
5206
5718
  /**
5207
- * Queue `task` until the outermost commit of the ambient transaction, or start it now when
5208
- * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract.
5719
+ * Queue `task` until the outermost commit of the caller's transaction, or start it now when
5720
+ * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract. Work
5721
+ * registered by a caller outside the open transaction's scope (#4786) is not tied to that
5722
+ * transaction: it starts now, detached, on the pool, whether or not that transaction is open.
5209
5723
  *
5210
5724
  * - Queued tasks run once, in registration order, after the outermost commit succeeds and the
5211
5725
  * transaction lock is released — so a task may begin its own transaction. The committer
@@ -5219,26 +5733,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5219
5733
  * token was captured in, rolled back — including a savepoint rolled back inside a transaction
5220
5734
  * that went on to commit — or if the token matches nothing this provider knows; otherwise it
5221
5735
  * is queued at the deepest captured frame that is still open. A token captured outside any
5222
- * transaction always runs. "Runs" means immediately when this provider is idle, and otherwise
5223
- * once it is: a task must never have its own writes rolled back by an unrelated transaction.
5736
+ * transaction always runs.
5737
+ * - "Starts now" means fire-and-forget under {@link TransactionAffinity.RunDetached}: the task is
5738
+ * in no transaction on this provider (its statements run on the pool), the caller never awaits
5739
+ * it, and a `BeginTransaction` in the task's synchronous prefix stays in the task's own scope.
5740
+ * If the task begins a transaction while another is open on this instance, it joins that one as
5741
+ * a savepoint (logged) — a task that needs its own transaction belongs on an independent instance.
5224
5742
  */
5225
5743
  RunAfterCommit(task, description = 'post-commit task', token) {
5226
5744
  if (token) {
5227
5745
  this.registerPostCommitTaskWithToken(task, description, token);
5228
5746
  return;
5229
5747
  }
5230
- if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
5231
- super.RunAfterCommit(task, description);
5748
+ if (!this.IsCallerInAmbientTransaction()) {
5749
+ // No transaction open, or not the caller's: either way the task is not tied to one.
5750
+ this.runDetachedTask(task, description);
5232
5751
  return;
5233
5752
  }
5234
5753
  this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
5235
5754
  }
5236
5755
  /**
5237
- * Snapshot of the open transaction frames. Synchronous, and never `undefined` on this provider:
5238
- * outside a transaction it returns a token whose epoch is `null`, which says the work is already
5239
- * durable rather than saying nothing. See {@link DatabaseProviderBase.CapturePostCommitToken}.
5756
+ * Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
5757
+ * provider: outside a transaction it returns a token whose epoch is `null`, which says the work
5758
+ * is already durable rather than saying nothing. See
5759
+ * {@link DatabaseProviderBase.CapturePostCommitToken}. Work registered by a caller outside the
5760
+ * open transaction's scope (#4786) is not tied to that transaction, so such a caller gets the
5761
+ * same `null`-epoch token.
5240
5762
  */
5241
5763
  CapturePostCommitToken() {
5764
+ if (!this.IsCallerInAmbientTransaction()) {
5765
+ return { Epoch: null, FrameIds: [] };
5766
+ }
5242
5767
  return this._frameTracker.Capture();
5243
5768
  }
5244
5769
  registerPostCommitTaskWithToken(task, description, token) {
@@ -5266,33 +5791,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5266
5791
  get PendingPostCommitTaskCount() {
5267
5792
  return this._postCommitTasks.length;
5268
5793
  }
5269
- /** Number of tasks waiting only for this provider to go idle. */
5794
+ /**
5795
+ * @deprecated Always 0. Post-commit work not tied to the caller's transaction used to be held
5796
+ * until this provider went idle; with scope affinity (#4786) it starts immediately on the pool, so
5797
+ * there is no idle queue left to count. Kept for one release.
5798
+ */
5270
5799
  get PendingIdlePostCommitTaskCount() {
5271
- return this._idlePostCommitTasks.length;
5800
+ return 0;
5272
5801
  }
5273
5802
  /**
5274
- * Run work whose own transaction has already settled. Immediate when this provider is idle;
5275
- * otherwise held until it is, so the task's writes cannot join — and be rolled back with — a
5276
- * transaction it has nothing to do with.
5803
+ * Start work that is not tied to the caller's transaction now, fire-and-forget; never throws.
5804
+ * Detached so it is in no transaction on this provider — its statements run on the pool, even
5805
+ * while an unrelated transaction is open — and so a begin in its synchronous prefix cannot make
5806
+ * the caller a member (see {@link TransactionAffinity.Claim}).
5277
5807
  */
5278
5808
  runDetachedTask(task, description) {
5279
- if (this._transactionDepth === 0 && !this.HasPhysicalTransaction) {
5280
- super.RunAfterCommit(task, description);
5281
- return;
5282
- }
5283
- this._idlePostCommitTasks.push({ Task: task, Description: description, Depth: 0 });
5284
- }
5285
- /** Run everything that was waiting for this provider to go idle. Never throws. */
5286
- async drainIdlePostCommitTasks() {
5287
- if (this._idlePostCommitTasks.length === 0 || this._transactionDepth > 0 || this.HasPhysicalTransaction) {
5288
- return;
5289
- }
5290
- const tasks = this._idlePostCommitTasks;
5291
- this._idlePostCommitTasks = [];
5292
- LogStatus(`Running ${tasks.length} post-commit task(s) held back by an unrelated transaction`);
5293
- for (const entry of tasks) {
5294
- await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
5295
- }
5809
+ void this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(task, description));
5296
5810
  }
5297
5811
  /** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
5298
5812
  async runPostCommitTasks(tasks) {
@@ -5301,7 +5815,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5301
5815
  }
5302
5816
  LogStatus(`Running ${tasks.length} post-commit task(s) after transaction commit`);
5303
5817
  for (const entry of tasks) {
5304
- await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
5818
+ // Detached from the committer's (now stale) membership explicitly, not merely by epoch mismatch.
5819
+ await this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(entry.Task, entry.Description));
5305
5820
  }
5306
5821
  }
5307
5822
  /** Detach the whole queue (outermost commit succeeded). */
@@ -5359,29 +5874,79 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5359
5874
  */
5360
5875
  async ResetTransactionState() {
5361
5876
  await this.WithTransactionLock(() => this.abandonDoomedTransaction());
5362
- await this.drainIdlePostCommitTasks();
5877
+ // The frames are gone, so no settle will ever close this instance's batch. Drop it here or
5878
+ // its entities count as pending forever and every cached read of them misses.
5879
+ this._openBatchLevels = 0;
5880
+ await LocalCacheManager.Instance.AbandonEntityEventBatch(this);
5363
5881
  }
5882
+ /**
5883
+ * Cache maintenance for the saves inside a transaction waits for the outermost settle: one
5884
+ * rewrite per cached slot on commit instead of one per save, and nothing written for work that
5885
+ * is rolled back.
5886
+ *
5887
+ * The batch is opened HERE, on the raw primitive, not only in
5888
+ * `DatabaseProviderBase.BeginEntityTransaction` — 41 call sites across the repo use
5889
+ * `BeginTransaction()` directly, including new-user creation on first login, the magic-link
5890
+ * service, the roles/users sync resolver, `MergeRecords` and every generated cascade-delete
5891
+ * override. Those saves each published their own cache write, and a rollback left rows in the
5892
+ * shared cache that were never committed. `BeginEntityTransaction` still opens
5893
+ * its own level on top; the levels are depth-counted, so the batch applies once, at the
5894
+ * outermost settle, either way.
5895
+ */
5364
5896
  async BeginTransaction() {
5365
- return this.WithTransactionLock(() => this.beginTransactionCore());
5897
+ // Claimed before the first await (the lock's): see TransactionAffinity.Claim for why.
5898
+ const membership = this._affinity.Claim();
5899
+ try {
5900
+ await this.WithTransactionLock(() => this.beginTransactionCore(membership));
5901
+ }
5902
+ catch (e) {
5903
+ // Every failure path, including a begin refused while doomed. A no-op for a membership
5904
+ // already bound (a member's failed nested begin): see TransactionAffinity.Release.
5905
+ this._affinity.Release(membership);
5906
+ throw e;
5907
+ }
5908
+ LocalCacheManager.Instance.BeginEntityEventBatch(this);
5909
+ this._openBatchLevels++;
5910
+ }
5911
+ /** Closes one batch level, but only if this provider opened one. @internal */
5912
+ async endBatchLevelIfOpen(succeeded) {
5913
+ if (this._openBatchLevels <= 0) {
5914
+ return;
5915
+ }
5916
+ this._openBatchLevels--;
5917
+ await LocalCacheManager.Instance.EndEntityEventBatch(this, succeeded);
5366
5918
  }
5367
5919
  async CommitTransaction() {
5368
5920
  // null = not the outermost commit, so nothing drains and the subclass hook does not run.
5369
- const committedTasks = await this.WithTransactionLock(async () => {
5370
- const outermost = this._transactionDepth === 1;
5371
- const tasks = await this.commitTransactionCore();
5372
- return outermost ? tasks : null;
5373
- });
5921
+ let committedTasks;
5922
+ try {
5923
+ committedTasks = await this.WithTransactionLock(async () => {
5924
+ const outermost = this._transactionDepth === 1;
5925
+ const tasks = await this.commitTransactionCore();
5926
+ return outermost ? tasks : null;
5927
+ });
5928
+ }
5929
+ catch (e) {
5930
+ // The commit failed: the rows may not be in the database, so the batch settles as a
5931
+ // failure (its slots are invalidated) rather than being left open.
5932
+ await this.endBatchLevelIfOpen(false);
5933
+ throw e;
5934
+ }
5935
+ await this.endBatchLevelIfOpen(true);
5374
5936
  if (committedTasks) {
5375
5937
  await this.runPostCommitTasks(committedTasks);
5376
5938
  await this.AfterPhysicalCommit();
5377
5939
  }
5378
- await this.drainIdlePostCommitTasks();
5379
5940
  }
5380
5941
  async RollbackTransaction() {
5381
- await this.WithTransactionLock(() => this.rollbackTransactionCore());
5382
- await this.drainIdlePostCommitTasks();
5942
+ try {
5943
+ await this.WithTransactionLock(() => this.rollbackTransactionCore());
5944
+ }
5945
+ finally {
5946
+ await this.endBatchLevelIfOpen(false);
5947
+ }
5383
5948
  }
5384
- async beginTransactionCore() {
5949
+ async beginTransactionCore(membership) {
5385
5950
  if (this._doomed) {
5386
5951
  throw new DoomedTransactionError();
5387
5952
  }
@@ -5391,6 +5956,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5391
5956
  if (this._transactionDepth === 1) {
5392
5957
  this._abandonedByFailedCommit = false;
5393
5958
  await this.BeginPhysicalTransaction();
5959
+ this._affinity.OpenEpoch();
5960
+ this._affinity.Bind(membership);
5394
5961
  return;
5395
5962
  }
5396
5963
  if (!this.HasPhysicalTransaction) {
@@ -5406,6 +5973,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5406
5973
  this._savepointCounter--;
5407
5974
  throw savepointError;
5408
5975
  }
5976
+ // Only once the savepoint exists (as the outermost binds only after BEGIN): a begin that
5977
+ // failed to join must not leave its caller's statements routed to the transaction handle.
5978
+ this.bindJoiningMembership(membership);
5409
5979
  }
5410
5980
  catch (e) {
5411
5981
  if (this._transactionDepth > 0) {
@@ -5424,14 +5994,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5424
5994
  throw e;
5425
5995
  }
5426
5996
  }
5997
+ /**
5998
+ * A nested begin joins the open transaction as a savepoint. When the caller was not already part of
5999
+ * it, that is an unrelated unit of work entangling itself with someone else's transaction on a shared
6000
+ * instance: its savepoint commits only if the owner commits, and settling out of order corrupts both.
6001
+ * Joining keeps pre-#4786 behaviour — waiting for the owner instead can deadlock when the owner is
6002
+ * itself waiting on this work (a coalesced entity-action rerun) — so it is reported, once per
6003
+ * transaction, instead of silently happening. The joiner stays bound to the owner's transaction
6004
+ * after its own savepoint is released: its later plain statements keep running on that
6005
+ * transaction until the owner ends it.
6006
+ */
6007
+ bindJoiningMembership(membership) {
6008
+ const epoch = this._affinity.CurrentEpoch;
6009
+ if (membership.Epoch !== epoch && this._foreignJoinReportedEpoch !== epoch) {
6010
+ this._foreignJoinReportedEpoch = epoch;
6011
+ LogError(`${this.constructor.name}: a transaction was begun by code outside the async scope of the transaction ` +
6012
+ `already open on this provider instance, so it joins that transaction as a savepoint. Its writes now ` +
6013
+ `commit or roll back with a unit of work it is not part of, and its later statements keep running ` +
6014
+ `in that transaction until its owner ends it. Run independent units of work on ` +
6015
+ `CreateIndependentInstance() or a per-request provider (#4786).`);
6016
+ }
6017
+ this._affinity.Bind(membership);
6018
+ }
6019
+ /** Savepoint SQL is the provider's own bookkeeping: it must reach the handle whichever scope settles the frame. */
6020
+ async executeTransactionControlSQL(sql, description) {
6021
+ await this._affinity.RunAsMember(() => this.ExecuteSQL(sql, undefined, { description, ignoreLogging: true }));
6022
+ }
5427
6023
  async createSavepoint(savepointName) {
5428
6024
  const sql = this.Dialect.CreateSavepointSQL(savepointName);
5429
- const options = {
5430
- description: `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`,
5431
- ignoreLogging: true,
5432
- };
5433
6025
  try {
5434
- await this.ExecuteSQL(sql, undefined, options);
6026
+ await this.executeTransactionControlSQL(sql, `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`);
5435
6027
  }
5436
6028
  catch (savepointError) {
5437
6029
  if (this.HasPhysicalTransaction && this.isDoomedPhysicalTransactionError(savepointError)) {
@@ -5507,10 +6099,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5507
6099
  const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
5508
6100
  if (releaseSQL) {
5509
6101
  try {
5510
- await this.ExecuteSQL(releaseSQL, undefined, {
5511
- description: `Releasing savepoint ${savepointName}`,
5512
- ignoreLogging: true,
5513
- });
6102
+ await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName}`);
5514
6103
  }
5515
6104
  catch (e) {
5516
6105
  await this.AbandonPhysicalTransaction();
@@ -5555,16 +6144,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5555
6144
  throw new Error('Savepoint stack mismatch - no savepoint to rollback to');
5556
6145
  }
5557
6146
  try {
5558
- await this.ExecuteSQL(this.Dialect.RollbackToSavepointSQL(savepointName), undefined, {
5559
- description: `Rolling back to savepoint ${savepointName}`,
5560
- ignoreLogging: true,
5561
- });
6147
+ await this.executeTransactionControlSQL(this.Dialect.RollbackToSavepointSQL(savepointName), `Rolling back to savepoint ${savepointName}`);
5562
6148
  const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
5563
6149
  if (releaseSQL) {
5564
- await this.ExecuteSQL(releaseSQL, undefined, {
5565
- description: `Releasing savepoint ${savepointName} after rollback`,
5566
- ignoreLogging: true,
5567
- });
6150
+ await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName} after rollback`);
5568
6151
  }
5569
6152
  this.discardPostCommitTasks(this._transactionDepth, `savepoint ${savepointName} was rolled back`);
5570
6153
  this._savepointStack.pop();
@@ -5595,10 +6178,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5595
6178
  this._savepointCounter = 0;
5596
6179
  }
5597
6180
  /**
5598
- * Back to depth 0. A successful commit detaches the post-commit queue first, so anything still
5599
- * queued here belongs to a transaction that rolled back, failed, or was abandoned.
6181
+ * Back to depth 0 — every ending of the transaction goes through here, so it is also where the
6182
+ * transaction's memberships go stale. A successful commit detaches the post-commit queue first, so
6183
+ * anything still queued here belongs to a transaction that rolled back, failed, or was abandoned.
5600
6184
  */
5601
6185
  clearTransactionState() {
6186
+ this._affinity.CloseEpoch();
5602
6187
  this._transactionDepth = 0;
5603
6188
  this._doomed = false;
5604
6189
  this.clearSavepointState();