@memberjunction/generic-database-provider 5.51.2 → 5.51.4

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,12 +15,13 @@
15
15
  *
16
16
  * @module @memberjunction/generic-database-provider
17
17
  */
18
- import { DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
- import { MJGlobal, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
18
+ import { BaseEntity, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
19
+ import { IsValidUUID, MJGlobal, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
20
20
  import { QueryPagingEngine } from './queryPagingEngine.js';
21
21
  // QueryParameterProcessor is now called internally by RenderPipeline
22
22
  import { v4 as uuidv4 } from 'uuid';
23
23
  import { SqlLoggingSessionImpl } from './SqlLogger.js';
24
+ import { IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
24
25
  // QueryCompositionEngine is now owned by RenderPipeline
25
26
  import { RenderPipeline } from './renderPipeline.js';
26
27
  import { useJsonArgShape } from './crudSprocFieldRules.js';
@@ -30,7 +31,13 @@ import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
30
31
  import { QueueManager } from '@memberjunction/queue';
31
32
  import { EntityActionEngineServer } from '@memberjunction/actions';
32
33
  import { EncryptionEngine } from '@memberjunction/encryption';
34
+ import { ClientClauseScreen } from './clientClauseScreen.js';
33
35
  import { GeoCodeSyncService } from '@memberjunction/geo-core';
36
+ /**
37
+ * Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
38
+ * queries): run it read-only and roll back, so it can neither write nor leave session state behind.
39
+ */
40
+ const CALLER_SQL_OPTIONS = { readOnlyTransaction: true, description: 'caller-supplied query' };
34
41
  /**
35
42
  * GenericDatabaseProvider is an intermediate abstract class that implements shared
36
43
  * entity action, AI action, encryption, and view WHERE clause rendering logic.
@@ -997,6 +1004,44 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
997
1004
  TransformExternalSQLClause(clause, _entityInfo) {
998
1005
  return clause;
999
1006
  }
1007
+ /**
1008
+ * Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
1009
+ * WhereClause) stays inside the parentheses this provider puts around it, read with this
1010
+ * provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
1011
+ * security, which also carries guest scope; a piece that closes its parentheses early, such as
1012
+ * `1=1) OR (1=1`, would leave those filters on one side of an OR the caller controls.
1013
+ */
1014
+ AssertClauseBalanced(clause, label, options) {
1015
+ const check = IsBalancedSQLFragment(clause, this.Dialect, options);
1016
+ if (!check.IsBalanced) {
1017
+ throw new Error(`Invalid ${label}: ${check.Reason}`);
1018
+ }
1019
+ }
1020
+ /**
1021
+ * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
1022
+ * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
1023
+ * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
1024
+ * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
1025
+ * runs before this transform, so a rewrite that changes the caller's term cannot reach the
1026
+ * hook's term.
1027
+ */
1028
+ PrepareExtraFilterSQL(extraFilter, entityInfo) {
1029
+ if (!extraFilter)
1030
+ return '';
1031
+ const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
1032
+ const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
1033
+ if (!terms || terms.length < 2) {
1034
+ this.AssertClauseBalanced(transformed, 'ExtraFilter');
1035
+ return transformed;
1036
+ }
1037
+ return terms
1038
+ .map((term) => {
1039
+ const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
1040
+ this.AssertClauseBalanced(termSQL, 'ExtraFilter');
1041
+ return `(${termSQL})`;
1042
+ })
1043
+ .join(' AND ');
1044
+ }
1000
1045
  /**
1001
1046
  * Optionally wraps a view query with user view run logging.
1002
1047
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
@@ -1072,11 +1117,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1072
1117
  return externalResult;
1073
1118
  }
1074
1119
  // ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
1075
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
1120
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
1076
1121
  const userSearchString = params.UserSearchString ?? '';
1077
1122
  const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
1078
1123
  const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
1079
1124
  const saveViewResults = params.SaveViewResults ?? false;
1125
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
1126
+ this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
1080
1127
  // ── TOP / pagination mode ──
1081
1128
  // Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
1082
1129
  // and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
@@ -1134,6 +1181,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1134
1181
  // 1. View where clause
1135
1182
  if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
1136
1183
  const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
1184
+ // SECURITY: a stored view WhereClause originates from a client save, so the rendered
1185
+ // clause passes the full client-clause screen (ScreenStoredViewWhereClause). The one
1186
+ // exemption is CustomWhereClause views: those are admin-authored (MJUserViewEntityServer's
1187
+ // save gate restricts setting/changing them to Owner-type users) and may legitimately
1188
+ // contain constructs the screen blocks. Auto-generated clauses (FilterState / SmartFilter /
1189
+ // nested {%UserView%} templates) are written against entity base views, which the screen
1190
+ // permits when the running user reads each of those entities unscoped.
1191
+ this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
1192
+ const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
1193
+ // CustomWhereClause views too: an unbalanced clause would take row-level security
1194
+ // out of force for everyone who runs the view. Only their admin-written text may
1195
+ // carry comments.
1196
+ this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
1197
+ AllowComments: isCustomWhereClause,
1198
+ });
1137
1199
  whereSQL = `(${renderedWhere})`;
1138
1200
  bHasWhere = true;
1139
1201
  }
@@ -1146,7 +1208,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1146
1208
  }
1147
1209
  // 3. User search string
1148
1210
  if (userSearchString.length > 0) {
1149
- if (!this.ValidateUserProvidedSQLClause(userSearchString))
1211
+ if (!this.IsUserSearchTermAllowed(userSearchString))
1150
1212
  throw new Error(`Invalid User Search SQL clause: ${userSearchString}, contains one more for forbidden keywords`);
1151
1213
  const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, userSearchString);
1152
1214
  if (sUserSearchSQL.length > 0) {
@@ -1157,8 +1219,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1157
1219
  // 4. Exclude UserViewRunID
1158
1220
  if ((excludeUserViewRunID.length > 0) || params.ExcludeDataFromAllPriorViewRuns === true) {
1159
1221
  let sExcludeSQL = `${this.QuoteIdentifier(entityInfo.FirstPrimaryKey?.Name ?? 'ID')} NOT IN (SELECT RecordID FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwUserViewRunDetails')} WHERE EntityID='${viewEntity?.EntityID}' AND`;
1160
- if (params.ExcludeDataFromAllPriorViewRuns === true)
1222
+ if (params.ExcludeDataFromAllPriorViewRuns === true) {
1223
+ // SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
1224
+ if (!IsValidUUID(String(viewEntity?.ID ?? '')))
1225
+ throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
1161
1226
  sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
1227
+ }
1162
1228
  else {
1163
1229
  // SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
1164
1230
  // interpolated directly into SQL here. Unlike ExtraFilter/UserSearchString/
@@ -1173,6 +1239,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1173
1239
  if (overrideExcludeFilter.length > 0) {
1174
1240
  if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
1175
1241
  throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
1242
+ this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
1176
1243
  sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
1177
1244
  }
1178
1245
  whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
@@ -1210,6 +1277,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1210
1277
  const orderBy = rawOrderBy.length > 0
1211
1278
  ? (usingKeyset ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
1212
1279
  : '';
1280
+ if (orderBy.length > 0 && !usingKeyset) {
1281
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
1282
+ // No caller OrderBy means the sort came from the saved view's stored sort state.
1283
+ if (!params.OrderBy && viewEntity)
1284
+ this.ScreenStoredViewOrderBy(orderBy, user);
1285
+ }
1213
1286
  // View run logging (SQL Server-specific, others return null)
1214
1287
  let userViewRunID = '';
1215
1288
  if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
@@ -1365,6 +1438,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1365
1438
  /**************************************************************************/
1366
1439
  // InternalRunView Helpers
1367
1440
  /**************************************************************************/
1441
+ /**
1442
+ * Builds the aggregate query without running the caller's text. Each expression must be a single
1443
+ * aggregate function call over this entity's columns: the query runs the SQL that
1444
+ * {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
1445
+ * dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
1446
+ * per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
1447
+ * request order, which is how `RunViewCore` reads their values back.
1448
+ */
1449
+ BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
1450
+ const columns = entityInfo.Fields.map((f) => f.Name);
1451
+ const items = [];
1452
+ const validationErrors = [];
1453
+ for (const agg of aggregates ?? []) {
1454
+ const screened = this.screenAggregateExpression(agg.expression, columns);
1455
+ if ('SQL' in screened) {
1456
+ items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
1457
+ }
1458
+ else {
1459
+ validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
1460
+ }
1461
+ }
1462
+ if (items.length === 0)
1463
+ return { aggregateSQL: null, validationErrors };
1464
+ const where = whereSQL ? ` WHERE ${whereSQL}` : '';
1465
+ return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
1466
+ }
1467
+ /** The SQL to run for one caller aggregate expression, or why it is refused. */
1468
+ screenAggregateExpression(expression, columns) {
1469
+ const check = CheckAggregateExpression(expression, this.Dialect, columns);
1470
+ if (!check.IsAllowed || check.SQL === null)
1471
+ return { Error: `Invalid aggregate expression: ${check.Reason}` };
1472
+ const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
1473
+ return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
1474
+ }
1368
1475
  /**
1369
1476
  * Builds the SQL field list string for a view query, using dialect-neutral quoting.
1370
1477
  * Returns '*' if no specific fields are resolved.
@@ -1442,6 +1549,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1442
1549
  * - skips fields that are not sensible text-search targets (non-text types,
1443
1550
  * unbounded text columns when FTX is off).
1444
1551
  */
1552
+ /**
1553
+ * Screens a user search term with {@link ValidateUserProvidedSQLClause}. The screen reads the
1554
+ * quote-doubled term, because that is the text {@link createViewUserSearchSQL} splices, so a
1555
+ * term such as `O'Leary` is read as complete SQL tokens.
1556
+ */
1557
+ IsUserSearchTermAllowed(userSearchString) {
1558
+ return this.ValidateUserProvidedSQLClause(userSearchString.replace(/'/g, "''"));
1559
+ }
1445
1560
  createViewUserSearchSQL(entityInfo, userSearchString) {
1446
1561
  let sUserSearchSQL = '';
1447
1562
  const safeUserSearchString = userSearchString.replace(/'/g, "''");
@@ -1478,6 +1593,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1478
1593
  if (sUserSearchSQL.length > 0)
1479
1594
  sUserSearchSQL = '(' + sUserSearchSQL + ')';
1480
1595
  }
1596
+ // A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
1597
+ this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
1481
1598
  return sUserSearchSQL;
1482
1599
  }
1483
1600
  /**
@@ -1537,6 +1654,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1537
1654
  return true;
1538
1655
  }
1539
1656
  /**************************************************************************/
1657
+ // Client clause screening
1658
+ /**************************************************************************/
1659
+ /**
1660
+ * SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
1661
+ * Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
1662
+ * fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
1663
+ */
1664
+ AssertClauseFragmentIsSingleStatement(clause, label) {
1665
+ ClientClauseScreen.AssertSingleStatementFragment(clause, label, this.Dialect);
1666
+ }
1667
+ /**
1668
+ * SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
1669
+ * against this provider's entities and dialect, with `contextUser` as the acting user. With
1670
+ * `entityInfo`, the clause is screened in the form this provider runs a client clause for that
1671
+ * entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
1672
+ * outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
1673
+ * saved-view save gate (`MJUserViewEntityServer`).
1674
+ */
1675
+ ScreenClientClause(clause, label, contextUser, entityInfo) {
1676
+ const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
1677
+ ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
1678
+ }
1679
+ /**
1680
+ * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
1681
+ * Any user who can save a view can write its WhereClause, directly or through FilterState or a
1682
+ * Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
1683
+ * can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
1684
+ * request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
1685
+ * `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
1686
+ */
1687
+ ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
1688
+ if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
1689
+ return; // truthy — the DB may hand back true or 1
1690
+ this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
1691
+ this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
1692
+ }
1693
+ /**
1694
+ * SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
1695
+ * the full client-clause screen. Any user who can save a view can write those.
1696
+ */
1697
+ ScreenStoredViewOrderBy(orderBy, user) {
1698
+ this.ScreenClientClause(orderBy, 'OrderBy', user);
1699
+ }
1700
+ /**************************************************************************/
1540
1701
  // RenderViewWhereClause — View Template Rendering
1541
1702
  /**************************************************************************/
1542
1703
  /**
@@ -1881,7 +2042,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1881
2042
  async buildWhereClauseForCacheCheck(params, entityInfo, user) {
1882
2043
  let whereSQL = '';
1883
2044
  let bHasWhere = false;
1884
- const extraFilter = this.TransformExternalSQLClause(params.ExtraFilter || '', entityInfo);
2045
+ // PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
2046
+ // check then runs on the result, as on the main view path.
2047
+ const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
2048
+ this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
1885
2049
  if (extraFilter.length > 0) {
1886
2050
  if (!this.ValidateUserProvidedSQLClause(extraFilter))
1887
2051
  throw new Error(`Invalid Extra Filter: ${extraFilter}`);
@@ -1889,7 +2053,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1889
2053
  bHasWhere = true;
1890
2054
  }
1891
2055
  if (params.UserSearchString && params.UserSearchString.length > 0) {
1892
- if (!this.ValidateUserProvidedSQLClause(params.UserSearchString))
2056
+ if (!this.IsUserSearchTermAllowed(params.UserSearchString))
1893
2057
  throw new Error(`Invalid User Search SQL clause: ${params.UserSearchString}`);
1894
2058
  const sUserSearchSQL = this.createViewUserSearchSQL(entityInfo, params.UserSearchString);
1895
2059
  if (sUserSearchSQL.length > 0) {
@@ -2266,6 +2430,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2266
2430
  if (orderBy.length > 0) {
2267
2431
  if (!this.ValidateUserProvidedSQLClause(orderBy))
2268
2432
  throw new Error(`Invalid OrderBy clause: ${orderBy}`);
2433
+ this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
2269
2434
  sql += ` ORDER BY ${orderBy}`;
2270
2435
  }
2271
2436
  return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
@@ -2586,7 +2751,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2586
2751
  if (pagedCacheHit) {
2587
2752
  return pagedCacheHit;
2588
2753
  }
2589
- const paging = QueryPagingEngine.WrapWithPaging(finalSQL, params.StartRow, params.MaxRows, this.PlatformKey);
2754
+ const paging = QueryPagingEngine.WrapWithPaging(finalSQL, QueryPagingEngine.ResolveStartRow(params.StartRow), params.MaxRows, this.PlatformKey);
2590
2755
  // Execute data + count queries in parallel
2591
2756
  const start = Date.now();
2592
2757
  const [dataResult, countResult] = await Promise.all([
@@ -2635,7 +2800,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2635
2800
  Results: paginatedResult,
2636
2801
  RowCount: paginatedResult.length,
2637
2802
  TotalRowCount: totalRowCount,
2638
- PageNumber: useSQLPaging ? Math.floor(params.StartRow / params.MaxRows) + 1 : undefined,
2803
+ PageNumber: useSQLPaging
2804
+ ? Math.floor(QueryPagingEngine.ResolveStartRow(params.StartRow) / params.MaxRows) + 1
2805
+ : undefined,
2639
2806
  PageSize: useSQLPaging ? params.MaxRows : undefined,
2640
2807
  ExecutionTime: executionTime,
2641
2808
  ErrorMessage: '',
@@ -2676,8 +2843,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2676
2843
  async ExecuteAdhocQuery(params, contextUser) {
2677
2844
  try {
2678
2845
  const validator = SQLExpressionValidator.Instance;
2679
- const validation = validator.validateFullQuery(params.SQL);
2680
- if (!validation.valid) {
2846
+ const validation = validator.ValidateFullQuery(params.SQL, this.PlatformKey);
2847
+ const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
2848
+ if (!validation.valid || !statementCheck.IsReadOnly) {
2681
2849
  return {
2682
2850
  Success: false,
2683
2851
  QueryID: '',
@@ -2686,17 +2854,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2686
2854
  RowCount: 0,
2687
2855
  TotalRowCount: 0,
2688
2856
  ExecutionTime: 0,
2689
- ErrorMessage: validation.error || 'SQL validation failed',
2857
+ ErrorMessage: !validation.valid
2858
+ ? validation.error || 'SQL validation failed'
2859
+ : `Ad-hoc SQL must be a single read query: ${statementCheck.Reason}.`,
2690
2860
  };
2691
2861
  }
2692
- const { result, executionTime } = await this.executeQueryWithTiming(params.SQL, contextUser);
2693
- const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
2862
+ const { rows, totalRowCount, executionTime } = await this.runAdhocSQL(params, contextUser);
2694
2863
  return {
2695
2864
  Success: true,
2696
2865
  QueryID: '',
2697
2866
  QueryName: 'Ad-Hoc Query',
2698
- Results: paginatedResult,
2699
- RowCount: paginatedResult.length,
2867
+ Results: rows,
2868
+ RowCount: rows.length,
2700
2869
  TotalRowCount: totalRowCount,
2701
2870
  ExecutionTime: executionTime,
2702
2871
  ErrorMessage: '',
@@ -2717,6 +2886,60 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2717
2886
  };
2718
2887
  }
2719
2888
  }
2889
+ /**
2890
+ * Runs validated ad-hoc SQL. It is rendered the way caller-supplied SQL always is: composition
2891
+ * tokens resolved, comments removed, and a single read query required. With `MaxRows` the
2892
+ * database returns that page and a count runs beside it, as for saved queries, so the server
2893
+ * sends one page rather than every row; without it every row is returned, offset by `StartRow`
2894
+ * when one is given. `TimeoutSeconds` limits every statement the run sends.
2895
+ */
2896
+ async runAdhocSQL(params, contextUser) {
2897
+ const usePaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
2898
+ const startRow = QueryPagingEngine.ResolveStartRow(params.StartRow);
2899
+ const rendered = RenderPipeline.Run(params.SQL, {
2900
+ Platform: this.PlatformKey,
2901
+ ContextUser: contextUser,
2902
+ RequireReadStatement: true,
2903
+ ...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
2904
+ });
2905
+ const options = this.adhocSQLOptions(params);
2906
+ if (!usePaging) {
2907
+ const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
2908
+ const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
2909
+ return { rows: paginatedResult, totalRowCount, executionTime };
2910
+ }
2911
+ const start = Date.now();
2912
+ const [dataResult, total] = await Promise.all([
2913
+ this.ExecuteSQL(rendered.FinalSQL, undefined, options, contextUser),
2914
+ this.countAdhocRows(rendered.PagingResult?.CountSQL ?? null, options, contextUser),
2915
+ ]);
2916
+ const rows = dataResult ?? [];
2917
+ return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
2918
+ }
2919
+ /**
2920
+ * The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
2921
+ * fails does not fail the run: some queries page fine but cannot be counted (duplicate column
2922
+ * names are legal in a result but not inside the count's wrap), so the caller reports a lower
2923
+ * bound instead.
2924
+ */
2925
+ async countAdhocRows(countSQL, options, contextUser) {
2926
+ if (!countSQL)
2927
+ return null;
2928
+ try {
2929
+ const countResult = await this.ExecuteSQL(countSQL, undefined, options, contextUser);
2930
+ const total = Number(countResult?.[0]?.TotalRowCount);
2931
+ return Number.isFinite(total) && total >= 0 ? Math.floor(total) : null;
2932
+ }
2933
+ catch (e) {
2934
+ LogError(`Ad-hoc query row count failed; reporting a lower-bound total. ${e instanceof Error ? e.message : String(e)}`);
2935
+ return null;
2936
+ }
2937
+ }
2938
+ /** The options every statement of an ad-hoc run uses: caller-SQL protections, plus its timeout. */
2939
+ adhocSQLOptions(params) {
2940
+ const seconds = params.TimeoutSeconds;
2941
+ return seconds && seconds > 0 ? { ...CALLER_SQL_OPTIONS, timeoutMs: seconds * 1000 } : CALLER_SQL_OPTIONS;
2942
+ }
2720
2943
  /**
2721
2944
  * Finds a query from RunQueryParams and validates user permissions.
2722
2945
  * Uses `resolveQuery()` for lookup and `ValidateQueryForExecution()` for permissions.
@@ -2880,7 +3103,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2880
3103
  const resolved = this.resolveSpecParameters(spec, contextUser);
2881
3104
  finalSQL = resolved.finalSQL;
2882
3105
  // Execute
2883
- const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser);
3106
+ const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
2884
3107
  return {
2885
3108
  Success: true,
2886
3109
  QueryID: '',
@@ -2930,6 +3153,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2930
3153
  Dependencies: spec.Dependencies,
2931
3154
  OriginalSQL: spec.SQL,
2932
3155
  MaxRows: spec.MaxRows,
3156
+ RequireReadStatement: true,
2933
3157
  });
2934
3158
  if (!result.HasCompositions && !spec.UsesTemplate && spec.Parameters && Object.keys(spec.Parameters).length > 0) {
2935
3159
  LogStatus('Warning: Parameters provided but query does not use templates. Parameters will be ignored.');
@@ -2955,9 +3179,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2955
3179
  /**
2956
3180
  * Executes the query SQL and tracks execution time.
2957
3181
  */
2958
- async executeQueryWithTiming(sql, contextUser) {
3182
+ async executeQueryWithTiming(sql, contextUser, parameters, options) {
2959
3183
  const start = Date.now();
2960
- const result = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
3184
+ const result = await this.ExecuteSQL(sql, parameters, options, contextUser);
2961
3185
  const executionTime = Date.now() - start;
2962
3186
  if (!result) {
2963
3187
  throw new Error('Error executing query SQL');
@@ -3244,12 +3468,56 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3244
3468
  BuildParameterPlaceholder(index) {
3245
3469
  return `$${index + 1}`;
3246
3470
  }
3471
+ /**
3472
+ * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
3473
+ * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
3474
+ * that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
3475
+ * user checks: every authenticated client loads it to learn the schema, including principals
3476
+ * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
3477
+ */
3478
+ resolveDatasetItemScope(datasetName, item, itemFilters, contextUser) {
3479
+ const code = String(item['Code']);
3480
+ const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
3481
+ const clientFilter = itemFilters?.find(f => f?.ItemCode === code)?.Filter ?? '';
3482
+ if (clientFilter && !this.ValidateUserProvidedSQLClause(clientFilter)) {
3483
+ return { Filter: '', RowFilter: '', Refusal: `Invalid ItemFilter for dataset item '${code}': contains one or more forbidden keywords` };
3484
+ }
3485
+ const filter = whereClause && clientFilter ? `${whereClause} AND (${clientFilter})` : (whereClause || clientFilter);
3486
+ if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
3487
+ return { Filter: filter, RowFilter: '', Refusal: null };
3488
+ }
3489
+ const entityName = String(item['Entity']);
3490
+ const entity = this.EntityByName(entityName);
3491
+ if (!entity) {
3492
+ return { Filter: filter, RowFilter: '', Refusal: `Entity '${entityName}' of dataset item '${code}' not found in metadata` };
3493
+ }
3494
+ if (!entity.GetUserPermisions(contextUser)?.CanRead) {
3495
+ return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
3496
+ }
3497
+ return { Filter: filter, RowFilter: entity.GetUserRowLevelSecurityWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
3498
+ }
3499
+ /**
3500
+ * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
3501
+ * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
3502
+ * level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
3503
+ */
3504
+ datasetItemWhereClause(scope) {
3505
+ if (!scope.RowFilter)
3506
+ return scope.Filter;
3507
+ if (!scope.Filter)
3508
+ return scope.RowFilter;
3509
+ return `(${scope.RowFilter}) AND ((${scope.Filter}))`;
3510
+ }
3247
3511
  /**
3248
3512
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
3249
3513
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
3250
3514
  *
3251
3515
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
3252
3516
  * while PG (and the default) use parallel individual queries.
3517
+ *
3518
+ * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
3519
+ * CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
3520
+ * item runs no SQL and fails the dataset.
3253
3521
  */
3254
3522
  async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
3255
3523
  const provider = (providerToUse ?? this);
@@ -3295,7 +3563,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3295
3563
  const code = String(item['Code']);
3296
3564
  const entityName = String(item['Entity']);
3297
3565
  const entityID = String(item['EntityID']);
3298
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
3299
3566
  // External-data-source entities have no MJ base view — their data is proxied live and
3300
3567
  // can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
3301
3568
  // rather than silently querying a non-existent (or wrongly same-named) local view.
@@ -3312,19 +3579,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3312
3579
  });
3313
3580
  continue;
3314
3581
  }
3315
- // Build effective filter (WhereClause + optional runtime ItemFilter)
3316
- let effectiveFilter = whereClause;
3317
- if (itemFilters && itemFilters.length > 0) {
3318
- const filter = itemFilters.find(f => f.ItemCode === code);
3319
- if (filter) {
3320
- effectiveFilter = whereClause
3321
- ? `${whereClause} AND (${filter.Filter})`
3322
- : filter.Filter;
3323
- }
3582
+ // The item's filter and the caller's row filter, or why it is refused. A refused item
3583
+ // never reaches the cache or the database.
3584
+ const scope = provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser);
3585
+ if (scope.Refusal) {
3586
+ errorResults.push({
3587
+ EntityID: entityID,
3588
+ EntityName: entityName,
3589
+ Code: code,
3590
+ Results: [],
3591
+ LatestUpdateDate: undefined,
3592
+ Status: scope.Refusal,
3593
+ Success: false,
3594
+ });
3595
+ continue;
3324
3596
  }
3597
+ // The row filter keys the slot, so one user's filtered rows are never served to another.
3598
+ const rowFilterKey = scope.RowFilter || undefined;
3325
3599
  // Try cache first
3326
3600
  if (cacheAvailable) {
3327
- const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString);
3601
+ const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code));
3328
3602
  const cached = await cache.GetRunViewResult(fingerprint);
3329
3603
  if (cached) {
3330
3604
  cacheHitCount++;
@@ -3356,12 +3630,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3356
3630
  });
3357
3631
  continue;
3358
3632
  }
3359
- const filterSQL = effectiveFilter ? 'WHERE ' + effectiveFilter : '';
3633
+ const whereSQL = this.datasetItemWhereClause(scope);
3634
+ const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
3360
3635
  uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
3361
3636
  uncachedItems.push(item);
3362
3637
  // Store fingerprint for write-through caching after SQL
3363
3638
  const fp = cacheAvailable
3364
- ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString)
3639
+ ? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
3365
3640
  : '';
3366
3641
  uncachedFingerprints.push(fp);
3367
3642
  }
@@ -3450,13 +3725,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3450
3725
  /**
3451
3726
  * Retrieves status information for a dataset by name: per-entity row count and
3452
3727
  * latest update date. Uses ExecuteSQLBatch for per-item status queries.
3728
+ *
3729
+ * Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
3730
+ * status fails with the refusal and no status SQL runs.
3453
3731
  */
3454
3732
  async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
3455
3733
  const overallStart = performance.now();
3456
3734
  const provider = (providerToUse ?? this);
3457
3735
  const schema = provider.MJCoreSchemaName;
3458
- const cache = LocalCacheManager.Instance;
3459
- const cacheAvailable = cache.IsInitialized && this.TrustLocalCacheCompletely;
3460
3736
  // Fetch dataset items metadata (lightweight — just the dataset definition, not entity data)
3461
3737
  const sSQL = `SELECT di.*, ` +
3462
3738
  `e.${provider.QuoteIdentifier('BaseView')} AS ${provider.QuoteIdentifier('EntityBaseView')}, ` +
@@ -3478,115 +3754,80 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3478
3754
  EntityUpdateDates: [],
3479
3755
  };
3480
3756
  }
3481
- // Phase 1: Try to derive status from cached data for each item
3757
+ // Status ALWAYS comes from SQL — never from cached dataset slots. This method is the
3758
+ // staleness ORACLE: RefreshIfNeeded/CheckToSeeIfRefreshNeeded compare its answer against
3759
+ // locally held metadata to decide whether that metadata is stale, and the client's
3760
+ // smart-cache checks ride it over the wire. Deriving the answer from the very cache whose
3761
+ // freshness is in question closes a loop: a slot the write path failed to maintain
3762
+ // reports itself current forever, and stale permission metadata is then served until
3763
+ // process restart (the FLS over-the-wire leak). The queries are cheap — one batched
3764
+ // MAX/COUNT aggregate per item — and the cache remains fully in play for the DATA reads
3765
+ // in GetDatasetByName.
3482
3766
  const updateDates = [];
3483
3767
  let overallLatestDate = new Date(1900, 1, 1);
3484
- let cacheHitCount = 0;
3485
- let cacheMissCount = 0;
3486
- // Collect items that need SQL fallback
3487
- const uncachedItems = [];
3488
- const uncachedItemMeta = [];
3489
- for (const item of items) {
3490
- const entityID = String(item['EntityID']);
3491
- const entityName = String(item['Entity']);
3492
- const code = String(item['Code']);
3768
+ // Same scope as GetDatasetByName's data read — the stored item WhereClause, the caller's
3769
+ // ItemFilter and the caller's row filter — so status and data describe the same row set.
3770
+ // (Every shipped MJ_Metadata item has a NULL WhereClause and no row filter, so for
3771
+ // metadata this is an unfiltered aggregate.)
3772
+ const scopes = items.map(item => provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser));
3773
+ const refusal = scopes.find(scope => scope.Refusal)?.Refusal;
3774
+ if (refusal) {
3775
+ return {
3776
+ DatasetID: String(items[0]['DatasetID']),
3777
+ DatasetName: datasetName,
3778
+ Success: false,
3779
+ Status: refusal,
3780
+ LatestUpdateDate: new Date(0),
3781
+ EntityUpdateDates: [],
3782
+ };
3783
+ }
3784
+ const itemMeta = [];
3785
+ const queries = items.map((item, index) => {
3786
+ const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
3787
+ const entityBaseView = String(item['EntityBaseView']);
3493
3788
  const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
3494
- const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
3495
- // Build effective filter for fingerprint
3496
- let effectiveFilter = whereClause;
3497
- if (itemFilters && itemFilters.length > 0) {
3498
- const filter = itemFilters.find(f => f.ItemCode === code);
3499
- if (filter) {
3500
- effectiveFilter = whereClause
3501
- ? `${whereClause} AND (${filter.Filter})`
3502
- : filter.Filter;
3503
- }
3504
- }
3789
+ itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
3790
+ // The floor for the reported timestamp: an edit to the dataset DEFINITION itself
3791
+ // (item added, filter changed) must read as a change even when no entity row moved.
3505
3792
  const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
3506
3793
  const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
3507
- const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime()));
3508
- // Try to derive status from cached data
3509
- if (cacheAvailable) {
3510
- const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: effectiveFilter }, this.InstanceConnectionString);
3511
- const cached = await cache.GetRunViewResult(fingerprint);
3512
- if (cached) {
3513
- cacheHitCount++;
3514
- // Derive MAX(dateField) and COUNT(*) directly from cached rows
3515
- let maxDateFromRows = new Date(1900, 1, 1);
3516
- for (const row of cached.results) {
3517
- const record = row;
3518
- if (record[dateFieldToCheck]) {
3519
- const d = new Date(String(record[dateFieldToCheck]));
3520
- if (d > maxDateFromRows)
3521
- maxDateFromRows = d;
3522
- }
3523
- }
3524
- const updateDate = maxDateFromRows > datasetMaxUpdatedAt ? maxDateFromRows : datasetMaxUpdatedAt;
3525
- updateDates.push({
3526
- EntityID: entityID,
3527
- EntityName: entityName,
3528
- RowCount: cached.results.length,
3529
- UpdateDate: updateDate,
3530
- });
3531
- if (updateDate > overallLatestDate)
3532
- overallLatestDate = updateDate;
3533
- continue; // No SQL needed for this item
3534
- }
3535
- }
3536
- // Cache miss — need SQL fallback
3537
- cacheMissCount++;
3538
- uncachedItems.push(item);
3539
- uncachedItemMeta.push({ entityID, entityName, datasetMaxUpdatedAt: datasetMaxUpdatedAt.toISOString() });
3540
- }
3541
- // Phase 2: Execute SQL only for cache misses
3542
- if (uncachedItems.length > 0) {
3543
- const queries = uncachedItems.map((item, idx) => {
3544
- const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
3545
- const entityBaseView = String(item['EntityBaseView']);
3546
- const code = String(item['Code']);
3547
- const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
3548
- const meta = uncachedItemMeta[idx];
3549
- let filterSQL = '';
3550
- if (itemFilters && itemFilters.length > 0) {
3551
- const filter = itemFilters.find(f => f.ItemCode === code);
3552
- if (filter)
3553
- filterSQL = ' WHERE ' + filter.Filter;
3554
- }
3555
- return `SELECT ` +
3556
- `CASE ` +
3557
- `WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${meta.datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
3558
- `ELSE '${meta.datasetMaxUpdatedAt}' ` +
3559
- `END AS ${provider.QuoteIdentifier('UpdateDate')}, ` +
3560
- `COUNT(*) AS ${provider.QuoteIdentifier('TheRowCount')} ` +
3561
- `FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)}${filterSQL}`;
3562
- });
3563
- let batchResults = [];
3564
- try {
3565
- batchResults = await provider.ExecuteSQLBatch(queries, undefined, undefined, contextUser);
3566
- }
3567
- catch (err) {
3568
- LogError(`GetDatasetStatusByName: Batch execution failed: ${err instanceof Error ? err.message : String(err)}`);
3569
- }
3570
- for (let i = 0; i < uncachedItemMeta.length; i++) {
3571
- const meta = uncachedItemMeta[i];
3572
- const statusRows = batchResults[i];
3573
- if (statusRows && statusRows.length > 0) {
3574
- const updateDate = new Date(String(statusRows[0]['UpdateDate']));
3575
- updateDates.push({
3576
- EntityID: meta.entityID,
3577
- EntityName: meta.entityName,
3578
- RowCount: Number(statusRows[0]['TheRowCount']),
3579
- UpdateDate: updateDate,
3580
- });
3581
- if (updateDate > overallLatestDate) {
3582
- overallLatestDate = updateDate;
3583
- }
3794
+ const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
3795
+ const whereSQL = this.datasetItemWhereClause(scopes[index]);
3796
+ const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
3797
+ return `SELECT ` +
3798
+ `CASE ` +
3799
+ `WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
3800
+ `ELSE '${datasetMaxUpdatedAt}' ` +
3801
+ `END AS ${provider.QuoteIdentifier('UpdateDate')}, ` +
3802
+ `COUNT(*) AS ${provider.QuoteIdentifier('TheRowCount')} ` +
3803
+ `FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)}${filterSQL}`;
3804
+ });
3805
+ let batchResults = [];
3806
+ try {
3807
+ batchResults = await provider.ExecuteSQLBatch(queries, undefined, undefined, contextUser);
3808
+ }
3809
+ catch (err) {
3810
+ LogError(`GetDatasetStatusByName: Batch execution failed: ${err instanceof Error ? err.message : String(err)}`);
3811
+ }
3812
+ for (let i = 0; i < itemMeta.length; i++) {
3813
+ const meta = itemMeta[i];
3814
+ const statusRows = batchResults[i];
3815
+ if (statusRows && statusRows.length > 0) {
3816
+ const updateDate = new Date(String(statusRows[0]['UpdateDate']));
3817
+ updateDates.push({
3818
+ EntityID: meta.entityID,
3819
+ EntityName: meta.entityName,
3820
+ RowCount: Number(statusRows[0]['TheRowCount']),
3821
+ UpdateDate: updateDate,
3822
+ });
3823
+ if (updateDate > overallLatestDate) {
3824
+ overallLatestDate = updateDate;
3584
3825
  }
3585
3826
  }
3586
3827
  }
3587
3828
  const elapsedMs = (performance.now() - overallStart).toFixed(1);
3588
3829
  LogStatusEx({
3589
- message: `📊 [Dataset Status] GetDatasetStatusByName("${datasetName}"): ${cacheHitCount} cache-derived, ${cacheMissCount} SQL queries — ${elapsedMs}ms`,
3830
+ message: `📊 [Dataset Status] GetDatasetStatusByName("${datasetName}"): ${items.length} SQL status queries — ${elapsedMs}ms`,
3590
3831
  verboseOnly: true
3591
3832
  });
3592
3833
  if (updateDates.length === 0) {
@@ -3647,6 +3888,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3647
3888
  /**************************************************************************/
3648
3889
  // Dataset Cache Helpers
3649
3890
  /**************************************************************************/
3891
+ /**
3892
+ * Cache namespace for one dataset item's rows.
3893
+ *
3894
+ * `GetDatasetByName` caches each item through the same RunView fingerprint builder as an
3895
+ * ordinary read, supplying only entity + the item's WhereClause — and every shipped item has a
3896
+ * NULL WhereClause, so without this segment the two share one cache slot and the dataset is
3897
+ * served whatever an ordinary read left there, including rows deleted since.
3898
+ *
3899
+ * Keyed by dataset + item code so two items over the same entity also stay distinct. Callers
3900
+ * must use it on both the read and the write-through, or dataset reads stop finding dataset
3901
+ * writes.
3902
+ */
3903
+ datasetCacheSegment(datasetName, itemCode) {
3904
+ return `${datasetName}/${itemCode}`;
3905
+ }
3650
3906
  /**
3651
3907
  * Computes the latest update date for a dataset item from its result rows and dataset metadata.
3652
3908
  * Used by both the cache-hit and cache-miss paths in GetDatasetByName.