@memberjunction/generic-database-provider 6.2.0-edge.6 → 6.2.0-edge.7

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.
Files changed (86) hide show
  1. package/README.md +150 -0
  2. package/dist/GenericDatabaseProvider.d.ts +244 -39
  3. package/dist/GenericDatabaseProvider.d.ts.map +1 -1
  4. package/dist/GenericDatabaseProvider.js +676 -233
  5. package/dist/GenericDatabaseProvider.js.map +1 -1
  6. package/dist/clientClauseScreen.d.ts +16 -72
  7. package/dist/clientClauseScreen.d.ts.map +1 -1
  8. package/dist/clientClauseScreen.js +34 -278
  9. package/dist/clientClauseScreen.js.map +1 -1
  10. package/dist/composition/compositionAssembler.d.ts +33 -0
  11. package/dist/composition/compositionAssembler.d.ts.map +1 -0
  12. package/dist/composition/compositionAssembler.js +270 -0
  13. package/dist/composition/compositionAssembler.js.map +1 -0
  14. package/dist/composition/compositionInfo.d.ts +7 -0
  15. package/dist/composition/compositionInfo.d.ts.map +1 -0
  16. package/dist/composition/compositionInfo.js +31 -0
  17. package/dist/composition/compositionInfo.js.map +1 -0
  18. package/dist/composition/compositionLookup.d.ts +44 -0
  19. package/dist/composition/compositionLookup.d.ts.map +1 -0
  20. package/dist/composition/compositionLookup.js +122 -0
  21. package/dist/composition/compositionLookup.js.map +1 -0
  22. package/dist/composition/compositionRender.d.ts +136 -0
  23. package/dist/composition/compositionRender.d.ts.map +1 -0
  24. package/dist/composition/compositionRender.js +264 -0
  25. package/dist/composition/compositionRender.js.map +1 -0
  26. package/dist/composition/compositionTypes.d.ts +40 -0
  27. package/dist/composition/compositionTypes.d.ts.map +1 -0
  28. package/dist/composition/compositionTypes.js +2 -0
  29. package/dist/composition/compositionTypes.js.map +1 -0
  30. package/dist/composition/quotedTagRefusal.d.ts +44 -0
  31. package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
  32. package/dist/composition/quotedTagRefusal.js +132 -0
  33. package/dist/composition/quotedTagRefusal.js.map +1 -0
  34. package/dist/composition/renderSteps.d.ts +16 -0
  35. package/dist/composition/renderSteps.d.ts.map +1 -0
  36. package/dist/composition/renderSteps.js +42 -0
  37. package/dist/composition/renderSteps.js.map +1 -0
  38. package/dist/composition/safetyGate.d.ts +46 -0
  39. package/dist/composition/safetyGate.d.ts.map +1 -0
  40. package/dist/composition/safetyGate.js +61 -0
  41. package/dist/composition/safetyGate.js.map +1 -0
  42. package/dist/composition/templateUnit.d.ts +95 -0
  43. package/dist/composition/templateUnit.d.ts.map +1 -0
  44. package/dist/composition/templateUnit.js +189 -0
  45. package/dist/composition/templateUnit.js.map +1 -0
  46. package/dist/describeStatement.d.ts +51 -0
  47. package/dist/describeStatement.d.ts.map +1 -0
  48. package/dist/describeStatement.js +19 -0
  49. package/dist/describeStatement.js.map +1 -0
  50. package/dist/fieldSecurity/projectionStars.d.ts +15 -0
  51. package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
  52. package/dist/fieldSecurity/projectionStars.js +116 -0
  53. package/dist/fieldSecurity/projectionStars.js.map +1 -0
  54. package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
  55. package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
  56. package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
  57. package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
  58. package/dist/index.d.ts +7 -0
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +5 -0
  61. package/dist/index.js.map +1 -1
  62. package/dist/pagingLayout.d.ts +68 -0
  63. package/dist/pagingLayout.d.ts.map +1 -0
  64. package/dist/pagingLayout.js +190 -0
  65. package/dist/pagingLayout.js.map +1 -0
  66. package/dist/queryCompositionEngine.d.ts +22 -222
  67. package/dist/queryCompositionEngine.d.ts.map +1 -1
  68. package/dist/queryCompositionEngine.js +35 -729
  69. package/dist/queryCompositionEngine.js.map +1 -1
  70. package/dist/queryPagingEngine.d.ts +26 -5
  71. package/dist/queryPagingEngine.d.ts.map +1 -1
  72. package/dist/queryPagingEngine.js +51 -15
  73. package/dist/queryPagingEngine.js.map +1 -1
  74. package/dist/renderPipeline.d.ts +77 -85
  75. package/dist/renderPipeline.d.ts.map +1 -1
  76. package/dist/renderPipeline.js +70 -220
  77. package/dist/renderPipeline.js.map +1 -1
  78. package/dist/statementMemo.d.ts +29 -0
  79. package/dist/statementMemo.d.ts.map +1 -0
  80. package/dist/statementMemo.js +61 -0
  81. package/dist/statementMemo.js.map +1 -0
  82. package/dist/typedQueryParameter.d.ts +55 -0
  83. package/dist/typedQueryParameter.d.ts.map +1 -0
  84. package/dist/typedQueryParameter.js +122 -0
  85. package/dist/typedQueryParameter.js.map +1 -0
  86. package/package.json +14 -14
@@ -23,7 +23,12 @@ import { createHash } from 'node:crypto';
23
23
  import { v4 as uuidv4 } from 'uuid';
24
24
  import { ApplyStatementTransforms, SqlLoggingSessionImpl } from './SqlLogger.js';
25
25
  import { GetDialect } from '@memberjunction/sql-dialect';
26
- import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
26
+ import { SqlDocument, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
27
+ import { DescribeStatementFailure } from './describeStatement.js';
28
+ import { NamedQueryParameter, TypedBindValue, TypedQueryParameter } from './typedQueryParameter.js';
29
+ import { StatementMemo } from './statementMemo.js';
30
+ import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
31
+ import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './fieldSecurity/queryColumnSecurity.js';
27
32
  // QueryCompositionEngine is now owned by RenderPipeline
28
33
  import { RenderPipeline } from './renderPipeline.js';
29
34
  import { UseJsonArgShape } from './crudSprocFieldRules.js';
@@ -32,7 +37,7 @@ import { AIEngine } from '@memberjunction/aiengine';
32
37
  import { SimpleVectorServiceProvider } from '@memberjunction/ai-vectors-memory';
33
38
  import { QueueManager } from '@memberjunction/queue';
34
39
  import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
35
- import { BuildEntityChangeContext } from '@memberjunction/actions-base';
40
+ import { BuildEntityChangeContext, DurableEntityActionRegistry } from '@memberjunction/actions-base';
36
41
  import { TransactionFrameTracker } from './TransactionFrameTracker.js';
37
42
  import { TransactionAffinity } from './TransactionAffinity.js';
38
43
  import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
@@ -437,7 +442,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
437
442
  * `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
438
443
  * save succeeds is not a durability improvement, it is a different feature.
439
444
  */
440
- async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs) {
445
+ async HandleEntityActions(entity, baseType, before, user, originatingEntityActionIDs, runModeFilter) {
441
446
  const engine = EntityActionEngineServer.Instance;
442
447
  if (engine.Loaded && engine.GetActionsByEntityName(entity.EntityInfo.Name, 'Active').length === 0) {
443
448
  return [];
@@ -470,6 +475,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
470
475
  const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
471
476
  const results = [];
472
477
  for (const a of activeActions) {
478
+ if (runModeFilter === 'DurableOnly' && a.RunMode !== 'Durable') {
479
+ continue;
480
+ }
481
+ if (runModeFilter === 'NonDurableOnly' && a.RunMode === 'Durable') {
482
+ continue;
483
+ }
473
484
  if (guarded && originatingEntityActionIDs?.some((id) => UUIDsEqual(id, a.ID))) {
474
485
  // The caller declared this save IS this action's write-back. Used by work that
475
486
  // detached from the async context the guard tracks — see
@@ -610,11 +621,38 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
610
621
  }
611
622
  }
612
623
  }
613
- OnAfterSaveExecute(entity, user, options, _context) {
624
+ async ShouldEnlistSaveInTransaction(entity, user, options, isNewRecord) {
625
+ if (options.SkipEntityActions === true || options.ReplayOnly === true) {
626
+ return false;
627
+ }
628
+ if (DurableEntityActionRegistry.Instance.Submitter === null) {
629
+ return false;
630
+ }
631
+ const engine = EntityActionEngineServer.Instance;
632
+ if (!engine.Loaded) {
633
+ await engine.Config(false, user);
634
+ }
635
+ const invocationType = isNewRecord ? 'AfterCreate' : 'AfterUpdate';
636
+ const activeActions = engine.GetActionsByEntityNameAndInvocationType(entity.EntityInfo.Name, invocationType, 'Active');
637
+ const originatingSet = options.OriginatingEntityActionIDs && options.OriginatingEntityActionIDs.length > 0
638
+ ? new UUIDSet(options.OriginatingEntityActionIDs)
639
+ : null;
640
+ return activeActions.some((a) => a.RunMode === 'Durable' && !originatingSet?.Has(a.ID));
641
+ }
642
+ async OnDurableAfterSaveExecute(entity, user, options, context) {
643
+ if (options.SkipEntityActions === true) {
644
+ return;
645
+ }
646
+ context.State['durableActionsEnlistedInTx'] = true;
647
+ await this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, 'DurableOnly');
648
+ }
649
+ OnAfterSaveExecute(entity, user, options, context) {
614
650
  if (options.SkipEntityAIActions !== true)
615
651
  this.HandleEntityAIActions(entity, 'save', false, user); // NO AWAIT INTENTIONALLY
616
- if (options.SkipEntityActions !== true)
617
- this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs); // NO AWAIT INTENTIONALLY
652
+ if (options.SkipEntityActions !== true) {
653
+ const filter = context.State['durableActionsEnlistedInTx'] === true ? 'NonDurableOnly' : undefined;
654
+ this.HandleEntityActions(entity, 'save', false, user, options.OriginatingEntityActionIDs, filter); // NO AWAIT INTENTIONALLY
655
+ }
618
656
  }
619
657
  async OnSaveCompleted(entity, saveSQLResult, user, options, context) {
620
658
  const superPatches = await super.OnSaveCompleted(entity, saveSQLResult, user, options, context);
@@ -708,6 +746,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
708
746
  /**************************************************************************/
709
747
  // PostProcessRows — Datetime Adjustment + Encryption Decryption
710
748
  /**************************************************************************/
749
+ /**
750
+ * Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
751
+ * preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
752
+ * Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
753
+ */
754
+ static { this._preDecryptionRowsByResult = new WeakMap(); }
711
755
  /**
712
756
  * Post-processes rows: first applies platform-specific datetime adjustments
713
757
  * via the virtual `AdjustDatetimeFields` hook, then handles field-level
@@ -716,7 +760,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
716
760
  * Subclasses should NOT override this method. Instead, override
717
761
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
718
762
  */
719
- async PostProcessRows(rows, entityInfo, user) {
763
+ async PostProcessRows(rows, entityInfo, user, options) {
720
764
  if (!rows || rows.length === 0)
721
765
  return rows;
722
766
  // Step 0: binary columns → base64. Drivers return varbinary/bytea as byte arrays (Node
@@ -738,11 +782,33 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
738
782
  const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
739
783
  if (encryptedFields.length === 0)
740
784
  return processedRows;
785
+ // Preserve ciphertext-bearing normalized rows for cache storage BEFORE decrypting any fields.
786
+ const ciphertextRowsForCache = processedRows.map(r => ({ ...r }));
787
+ const decryptedRows = await this.decryptRowsForConsumer(processedRows, entityInfo, encryptedFields, user, Boolean(options?.preserveRestrictedApiCiphertext));
788
+ GenericDatabaseProvider._preDecryptionRowsByResult.set(decryptedRows, ciphertextRowsForCache);
789
+ return decryptedRows;
790
+ }
791
+ /**
792
+ * Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
793
+ * When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
794
+ * remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
795
+ * needlessly decrypt values destined for sentinel redaction.
796
+ */
797
+ async decryptRowsForConsumer(rows, entityInfo, encryptedFields, user, preserveRestrictedApiCiphertext) {
798
+ if (!rows || rows.length === 0 || encryptedFields.length === 0) {
799
+ return rows;
800
+ }
801
+ const fieldsToDecrypt = preserveRestrictedApiCiphertext
802
+ ? encryptedFields.filter(f => f.AllowDecryptInAPI)
803
+ : encryptedFields;
804
+ if (fieldsToDecrypt.length === 0) {
805
+ return rows.map(r => ({ ...r }));
806
+ }
741
807
  const encryptionEngine = EncryptionEngine.Instance;
742
808
  await encryptionEngine.Config(false, user);
743
- return Promise.all(processedRows.map(async (row) => {
809
+ return Promise.all(rows.map(async (row) => {
744
810
  const processedRow = { ...row };
745
- for (const field of encryptedFields) {
811
+ for (const field of fieldsToDecrypt) {
746
812
  const fieldValue = processedRow[field.Name];
747
813
  if (fieldValue === null || fieldValue === undefined || fieldValue === '')
748
814
  continue;
@@ -768,6 +834,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
768
834
  return processedRow;
769
835
  }));
770
836
  }
837
+ PrepareRowsForCacheStorage(rows, entityInfo) {
838
+ if (!rows || rows.length === 0)
839
+ return rows;
840
+ const preDecrypted = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
841
+ if (preDecrypted) {
842
+ return preDecrypted;
843
+ }
844
+ if (entityInfo && GenericDatabaseProvider.getEncryptedFields(entityInfo).length > 0) {
845
+ // Rows passed directly without PostProcessRows: returned as-is (LocalCacheManager's
846
+ // server write gate rejects any row carrying plaintext on an encrypted column).
847
+ return rows;
848
+ }
849
+ return rows;
850
+ }
851
+ async MaterializeCachedRowsForCaller(rows, entityInfo, contextUser, preserveRestrictedApiCiphertext) {
852
+ if (!rows || rows.length === 0 || !entityInfo) {
853
+ return rows;
854
+ }
855
+ const encryptedFields = GenericDatabaseProvider.getEncryptedFields(entityInfo);
856
+ if (encryptedFields.length === 0) {
857
+ return rows;
858
+ }
859
+ return this.decryptRowsForConsumer(rows, entityInfo, encryptedFields, contextUser ?? this.CurrentUser, Boolean(preserveRestrictedApiCiphertext));
860
+ }
771
861
  static { this._encryptedFieldsCache = new WeakMap(); }
772
862
  static getEncryptedFields(entityInfo) {
773
863
  let entry = GenericDatabaseProvider._encryptedFieldsCache.get(entityInfo);
@@ -1543,6 +1633,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
1543
1633
  Fields: ['Status', 'ViewName'],
1544
1634
  ResultType: 'simple',
1545
1635
  MaxRows: 1,
1636
+ SkipTotalRowCount: true,
1546
1637
  BypassCache: true,
1547
1638
  }, contextUser);
1548
1639
  // A FAILED lookup must not masquerade as "no materialization exists" — see MaterializationLookupFailed
@@ -2057,7 +2148,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2057
2148
  // Generic-erasure boundary: PostProcessRows operates on Record<string,unknown>[]
2058
2149
  // but Results is typed T[]; the double-cast bridges that erasure (not a lazy `any`).
2059
2150
  const rows = externalResult.Results;
2060
- const processed = (await this.PostProcessRows(rows, entityInfo, user));
2151
+ const processed = (await this.PostProcessRows(rows, entityInfo, user, {
2152
+ preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
2153
+ }));
2061
2154
  externalResult.Results = this.projectExternalRowsForCaller(processed, entityInfo, externalParams, user);
2062
2155
  }
2063
2156
  return externalResult;
@@ -2157,13 +2250,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2157
2250
  if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
2158
2251
  throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
2159
2252
  }
2253
+ // The filter builder saves WhereClauses in SQL Server syntax (`[Field] LIKE ...`), so the
2254
+ // rendered clause gets the same platform rewrite as ExtraFilter. Without it PostgreSQL
2255
+ // rejects every filtered saved view run here: `syntax error at or near "["`.
2256
+ const viewWhereSQL = this.TransformExternalSQLClause(renderedWhere, entityInfo);
2160
2257
  // CustomWhereClause views too: an unbalanced clause would take row-level security
2161
2258
  // out of force for everyone who runs the view. Only their admin-written text may
2162
- // carry comments.
2163
- this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
2259
+ // carry comments. Checked after the rewrite, since that is the text that runs.
2260
+ this.AssertClauseBalanced(viewWhereSQL, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
2164
2261
  AllowComments: isCustomWhereClause,
2165
2262
  });
2166
- whereSQL = `(${renderedWhere})`;
2263
+ whereSQL = `(${viewWhereSQL})`;
2167
2264
  bHasWhere = true;
2168
2265
  }
2169
2266
  // 2. ExtraFilter
@@ -2407,7 +2504,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2407
2504
  // ── Process data rows ──
2408
2505
  let retData = resultMap['data'] || [];
2409
2506
  if (retData.length > 0 && params.ResultType !== 'count_only') {
2410
- retData = await this.PostProcessRows(retData, entityInfo, user);
2507
+ retData = await this.PostProcessRows(retData, entityInfo, user, {
2508
+ preserveRestrictedApiCiphertext: Boolean(params.PreserveRestrictedApiCiphertext),
2509
+ });
2411
2510
  }
2412
2511
  // ── Process count ──
2413
2512
  let rowCount = null;
@@ -2416,34 +2515,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2416
2515
  if (countResult && countResult.length > 0)
2417
2516
  rowCount = countResult[0].TotalRowCount;
2418
2517
  }
2419
- else if (countSQL && maxRowsUsed && maxRowsUsed > 1 && retData.length === maxRowsUsed && !skipCount) {
2518
+ else if (countSQL && maxRowsUsed && retData.length === maxRowsUsed && !skipCount) {
2420
2519
  // A row-limited read that came back FULL may have been truncated, so the total is
2421
2520
  // worth a second round trip: this is what makes Explorer's "100 of 299" correct.
2422
- // `maxRowsUsed > 1` carves out the ONE case where it cannot be: a `MaxRows:1`
2423
- // probe. Those callers ask "does a row exist / give me the one row" — a
2424
- // record-map lookup, a single-key resolve — and never read TotalRowCount. The
2425
- // count they triggered was pure cost, and SEQUENTIAL cost: it runs after the data
2426
- // query has already resolved, so it is a full extra round trip on the critical
2427
- // path, not a parallel one.
2428
- //
2429
- // Measured on a live tenant over a 120-second census: 1,000 record-map lookups
2430
- // fired 721 of these counts and 800 row lookups fired 600 — 1,321 extra round
2431
- // trips totalling 9,760 ms, 11.4% of ALL SQL time in the window. Nothing read a
2432
- // single one of the results.
2433
- //
2434
- // Everything with `maxRowsUsed > 1` is untouched, so the "100 of 299" behaviour
2435
- // is preserved exactly; only the degenerate single-row probe changes.
2436
2521
  //
2437
- // What DOES change for `MaxRows:1`, stated plainly: with no `rowCount`, the return
2438
- // below falls back to `rowCount ?? retData.length`, so a hit now reports
2439
- // `TotalRowCount: 1` instead of the whole view's row count. That is the entire
2440
- // observable difference, and it is confined to a limit of exactly one row — a shape
2441
- // no caller asks for in order to learn a total, because a total is the one thing a
2442
- // single-row limit cannot tell it anything about.
2443
- //
2444
- // `!skipCount`: a caller that never reads TotalRowCount can also opt out of this count
2445
- // on a full multi-row page (RunViewParams.SkipTotalRowCount); the pagination count
2446
- // above honours the same flag.
2522
+ // That round trip is SEQUENTIAL: it runs after the data query has already resolved,
2523
+ // so it is a full extra trip on the critical path, not a parallel one. For a
2524
+ // single-row probe it fires on every hit. Measured on a live tenant over a
2525
+ // 120-second census: 1,000 record-map lookups fired 721 of these counts and 800 row
2526
+ // lookups fired 600 — 1,321 extra round trips totalling 9,760 ms, 11.4% of ALL SQL
2527
+ // time in the window, with nothing reading a single result. Callers that only read
2528
+ // `Results` opt out explicitly with RunViewParams.SkipTotalRowCount; the provider
2529
+ // never infers that from the value of MaxRows.
2447
2530
  const countResult = await this.ExecuteSQL(countSQL, undefined, undefined, contextUser);
2448
2531
  if (countResult && countResult.length > 0)
2449
2532
  rowCount = countResult[0].TotalRowCount;
@@ -2486,7 +2569,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
2486
2569
  }
2487
2570
  return {
2488
2571
  RowCount: params.ResultType === 'count_only' ? rowCount : retData.length,
2489
- TotalRowCount: rowCount ?? retData.length,
2572
+ TotalRowCount: skipCount ? undefined : rowCount ?? retData.length,
2490
2573
  Results: retData,
2491
2574
  UserViewRunID: userViewRunID,
2492
2575
  ExecutionTime: stopTime.getTime() - startTime.getTime(),
@@ -3503,7 +3586,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3503
3586
  fingerprint: resolved.fingerprint,
3504
3587
  });
3505
3588
  }
3589
+ else if (entityInfo.TrackRecordChanges) {
3590
+ // The client's copy is older and the entity tracks record changes: Phase 2 reads
3591
+ // the DB status and sends only the changed rows, not the full cached copy.
3592
+ serverCacheMissItems.push({ index, item, entityInfo });
3593
+ }
3506
3594
  else {
3595
+ LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${resolved.serverCached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
3507
3596
  serverCacheStaleItems.push({ index, item, entityInfo, serverCached: resolved.serverCached });
3508
3597
  }
3509
3598
  }
@@ -3514,6 +3603,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3514
3603
  // Phase 2: For server cache misses and TTL-expired server slots, validate against DB
3515
3604
  const differentialItems = [];
3516
3605
  const staleItemsNoTracking = [];
3606
+ /** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
3607
+ const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus) => {
3608
+ LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
3609
+ differentialItems.push({
3610
+ index, params: item.params, entityInfo, whereSQL,
3611
+ clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
3612
+ clientRowCount: item.cacheStatus.rowCount,
3613
+ serverStatus,
3614
+ });
3615
+ };
3517
3616
  if (serverCacheMissItems.length > 0) {
3518
3617
  // Build WHERE clauses and run batched DB status check only for cache misses / TTL-expired slots
3519
3618
  const itemsForDBCheck = [];
@@ -3548,6 +3647,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3548
3647
  LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
3549
3648
  currentResults.push({ viewIndex: index, status: 'current' });
3550
3649
  }
3650
+ else if (entityInfo.TrackRecordChanges) {
3651
+ queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
3652
+ }
3551
3653
  else {
3552
3654
  LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-VERIFIED-CACHE] "${entityLabel}" — server cache verified against DB, serving ${serverCached.rowCount} rows without full SQL query`, verboseOnly: true });
3553
3655
  serverCacheStaleItems.push({ index, item, entityInfo, serverCached });
@@ -3573,13 +3675,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3573
3675
  currentResults.push({ viewIndex: index, status: 'current' });
3574
3676
  }
3575
3677
  else if (entityInfo.TrackRecordChanges) {
3576
- LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${entityLabel}" — sending only changed rows (from DB)`, verboseOnly: true });
3577
- differentialItems.push({
3578
- index, params: item.params, entityInfo, whereSQL,
3579
- clientMaxUpdatedAt: item.cacheStatus.maxUpdatedAt,
3580
- clientRowCount: item.cacheStatus.rowCount,
3581
- serverStatus,
3582
- });
3678
+ queueDifferential(index, item, entityInfo, whereSQL, serverStatus);
3583
3679
  }
3584
3680
  else {
3585
3681
  LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
@@ -3610,7 +3706,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3610
3706
  if (cached) {
3611
3707
  const entityLabel = entry.item.params.EntityName || 'unknown';
3612
3708
  LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — client has no cache, serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
3613
- noCacheStatusServedFromCache.push({ index: entry.index, serverCached: cached });
3709
+ noCacheStatusServedFromCache.push({ index: entry.index, params: entry.item.params, serverCached: cached });
3614
3710
  continue;
3615
3711
  }
3616
3712
  }
@@ -3622,11 +3718,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3622
3718
  // permission class may read.
3623
3719
  const queryPromises = [
3624
3720
  // Items without cache check — served from server cache
3625
- ...noCacheStatusServedFromCache.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
3721
+ ...noCacheStatusServedFromCache.map(({ index, params: viewParams, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, viewParams, user)),
3626
3722
  // Items without cache check — server cache miss, must hit DB
3627
3723
  ...noCacheStatusNeedsDB.map(({ index, item }) => this.runFullQueryAndCacheResult(item.params, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
3628
- // Server cache stale — serve from server's cached data (zero DB)
3629
- ...serverCacheStaleItems.map(({ index, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null)),
3724
+ // Server cache newer than the client, no change tracking — serve from server's cached data (zero DB)
3725
+ ...serverCacheStaleItems.map(({ index, item, serverCached }) => this.serveFromServerCache(index, serverCached, callerFieldsByIndex.get(index) ?? null, item.params, user)),
3630
3726
  // DB-validated stale items (no change tracking)
3631
3727
  ...staleItemsNoTracking.map(({ index, params: viewParams }) => this.runFullQueryAndCacheResult(viewParams, index, contextUser, callerFieldsByIndex.get(index) ?? null)),
3632
3728
  // DB-validated differential items
@@ -3808,7 +3904,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3808
3904
  async runFullQueryAndReturn(params, viewIndex, contextUser) {
3809
3905
  let result;
3810
3906
  try {
3811
- result = await this.InternalRunView(params, contextUser);
3907
+ result = await this.InternalRunView({ ...params, PreserveRestrictedApiCiphertext: true }, contextUser);
3812
3908
  }
3813
3909
  catch (e) {
3814
3910
  // A field-security refusal fails this item only, as the up-front gate does on this path.
@@ -3847,13 +3943,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3847
3943
  if (ttlMs !== 0) {
3848
3944
  const fingerprint = this.ComputeRunViewCacheFingerprint(params, contextUser);
3849
3945
  const maxUpdatedAt = result.maxUpdatedAt || new Date().toISOString();
3946
+ const cacheEntity = this.resolveEntityForRunViewParams(params);
3850
3947
  // Pass the aggregates (B38-family omission #4). This slot is ALSO written by
3851
3948
  // InternalRunView's normal PostRunView path WITH aggregates — two writers,
3852
3949
  // one slot, and this one dropped them. Whichever write landed last won, so a
3853
3950
  // later server-cache hit served rows with or without aggregates depending on
3854
3951
  // a write race. That is exactly the standalone-passes / aggregator-fails
3855
3952
  // flake client-cache C13 exhibited.
3856
- await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, result.results, maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
3953
+ await LocalCacheManager.Instance.SetRunViewResult(fingerprint, params, this.PrepareRowsForCacheStorage(result.results, cacheEntity), maxUpdatedAt, result.aggregateResults, result.rowCount, this, ttlMs);
3857
3954
  }
3858
3955
  }
3859
3956
  // Project the response down to the caller's requested shape AFTER the
@@ -3967,7 +4064,23 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
3967
4064
  * them: the entity resolved here is named explicitly.
3968
4065
  */
3969
4066
  projectExternalRowsForCaller(rows, entityInfo, params, user) {
3970
- return this.ApplyFieldSecurityProjection(rows, { ...params, EntityName: entityInfo.Name }, user);
4067
+ const entityParams = { ...params, EntityName: entityInfo.Name };
4068
+ const projected = this.ApplyFieldSecurityProjection(rows, entityParams, user);
4069
+ this.carryCiphertextRowsForCache(rows, projected, entityParams, user);
4070
+ return projected;
4071
+ }
4072
+ /**
4073
+ * Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
4074
+ * narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
4075
+ * caller's width instead of finding no copy and falling back to the decrypted rows.
4076
+ */
4077
+ carryCiphertextRowsForCache(rows, projected, params, user) {
4078
+ if (projected === rows)
4079
+ return;
4080
+ const ciphertextRows = GenericDatabaseProvider._preDecryptionRowsByResult.get(rows);
4081
+ if (ciphertextRows) {
4082
+ GenericDatabaseProvider._preDecryptionRowsByResult.set(projected, this.ApplyFieldSecurityProjection(ciphertextRows, params, user));
4083
+ }
3971
4084
  }
3972
4085
  /**
3973
4086
  * Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
@@ -4019,7 +4132,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4019
4132
  }
4020
4133
  /**
4021
4134
  * Checks the server's LocalCacheManager for cached data matching the client's request.
4022
- * Returns the resolution if found ('current', 'stale' server-cached data to serve, or
4135
+ * Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
4023
4136
  * 'needs_verification' when the server slot's freshness window has elapsed),
4024
4137
  * or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
4025
4138
  */
@@ -4070,24 +4183,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4070
4183
  LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches server cache, no DB hit`, verboseOnly: true });
4071
4184
  return { status: 'current', result: { viewIndex: index, status: 'current' } };
4072
4185
  }
4073
- // Server has newer data than client — we can serve it directly from cache
4074
- LogStatusEx({ message: ` 📦 [SmartCache SERVE-FROM-CACHE] "${entityLabel}" — serving ${cached.rowCount} rows from server cache, no DB hit`, verboseOnly: true });
4186
+ // Server has newer data than the client; the caller decides between the cached copy and a differential
4075
4187
  return { status: 'stale', serverCached: cached };
4076
4188
  }
4077
4189
  /**
4078
4190
  * Packages server-cached data as a RunViewWithCacheCheckResult for return to the client.
4079
4191
  */
4080
- async serveFromServerCache(viewIndex, serverCached, callerFields = null) {
4081
- // The server cache stores every field the slot's permission class may read —
4192
+ async serveFromServerCache(viewIndex, serverCached, callerFields = null, viewParams, contextUser) {
4193
+ // The server cache stores every field the slot's permission class may read (with encrypted
4194
+ // fields stored as ciphertext at rest). Materialize allowed API decryptions first, then
4082
4195
  // project down to the caller's requested fields (∪ PK) before returning, exactly like the
4083
- // ProviderBase hit path. Serving unprojected rows here previously leaked
4084
- // whatever shape happened to be cached to every subsequent caller.
4085
- //
4086
- // `serverCached.results` are the cache's shared, deep-frozen rows — the runtime freeze
4087
- // is what actually protects the cache. See ProviderBase's hit path.
4196
+ // ProviderBase hit path.
4197
+ const cacheEntity = viewParams ? this.resolveEntityForRunViewParams(viewParams) : undefined;
4198
+ const materialized = await this.MaterializeCachedRowsForCaller(serverCached.results, cacheEntity, contextUser, true);
4088
4199
  const results = callerFields
4089
- ? ProjectRowsToFields(serverCached.results, callerFields)
4090
- : serverCached.results;
4200
+ ? ProjectRowsToFields(materialized, callerFields)
4201
+ : materialized;
4091
4202
  return {
4092
4203
  viewIndex,
4093
4204
  status: 'stale',
@@ -4104,19 +4215,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4104
4215
  /**
4105
4216
  * Runs a differential query and returns only changes since the client's cached state.
4106
4217
  * Includes updated/created rows and deleted record IDs.
4107
- * Falls back to full query if hidden deletes are detected.
4218
+ * Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
4108
4219
  */
4109
4220
  async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null) {
4110
4221
  try {
4111
- const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, clientMaxUpdatedAt, whereSQL, contextUser);
4112
- const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, clientMaxUpdatedAt, contextUser);
4113
- // Validation: detect hidden deletes not tracked in RecordChanges
4114
4222
  const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
4115
4223
  if (!clientMaxUpdatedDate) {
4116
4224
  // Unparseable client timestamp — can't trust the differential math; fall
4117
4225
  // back to a full refresh (cached wide + projected, like every other leg).
4118
4226
  return this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
4119
4227
  }
4228
+ const since = clientMaxUpdatedDate.toISOString();
4229
+ const updatedRows = await this.getUpdatedRowsSince(params, entityInfo, since, whereSQL, contextUser);
4230
+ const deletedRecordIDs = await this.getDeletedRecordIDsSince(entityInfo.ID, since, contextUser);
4231
+ // Validation: detect hidden deletes not tracked in RecordChanges
4120
4232
  const newInserts = updatedRows.filter(row => {
4121
4233
  const createdAt = row['__mj_CreatedAt'];
4122
4234
  if (!createdAt)
@@ -4182,13 +4294,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4182
4294
  return { viewIndex, status: 'error', errorMessage: e instanceof Error ? e.message : String(e) };
4183
4295
  }
4184
4296
  }
4297
+ /**
4298
+ * Formats a client timestamp as ISO 8601 for a SQL literal.
4299
+ * Throws when the value is not a date.
4300
+ */
4301
+ toSQLTimestamp(raw) {
4302
+ const date = this.parseClientTimestamp(raw);
4303
+ if (!date)
4304
+ throw new Error('Client timestamp is not a valid date');
4305
+ return date.toISOString();
4306
+ }
4185
4307
  /**
4186
4308
  * Gets IDs of records deleted since a given timestamp.
4187
- * Uses dialect-neutral quoting. Subclasses can override for parameterized queries.
4309
+ * Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
4310
+ * Subclasses can override for parameterized queries.
4188
4311
  */
4189
4312
  async getDeletedRecordIDsSince(entityID, sinceTimestamp, contextUser) {
4190
4313
  try {
4191
- const sql = `SELECT DISTINCT ${this.QuoteIdentifier('RecordID')} FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwRecordChanges')} WHERE ${this.QuoteIdentifier('EntityID')} = '${entityID}' AND ${this.QuoteIdentifier('Type')} = 'Delete' AND ${this.QuoteIdentifier('ChangedAt')} > '${sinceTimestamp}'`;
4314
+ const since = this.toSQLTimestamp(sinceTimestamp);
4315
+ const sql = `SELECT DISTINCT ${this.QuoteIdentifier('RecordID')} FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwRecordChanges')} WHERE ${this.QuoteIdentifier('EntityID')} = '${entityID}' AND ${this.QuoteIdentifier('Type')} = 'Delete' AND (${this.QuoteIdentifier('ChangedAt')} > '${since}')`;
4192
4316
  const results = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
4193
4317
  return results.map(r => String(r['RecordID']));
4194
4318
  }
@@ -4199,11 +4323,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4199
4323
  }
4200
4324
  /**
4201
4325
  * Gets rows updated/created since a given timestamp.
4202
- * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy.
4326
+ * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
4327
+ * timestamp in ISO 8601 form as its own predicate group.
4203
4328
  */
4204
4329
  async getUpdatedRowsSince(params, entityInfo, sinceTimestamp, whereSQL, contextUser) {
4205
4330
  try {
4206
- const timestampFilter = `${this.QuoteIdentifier('__mj_UpdatedAt')} > '${sinceTimestamp}'`;
4331
+ const timestampFilter = `(${this.QuoteIdentifier('__mj_UpdatedAt')} > '${this.toSQLTimestamp(sinceTimestamp)}')`;
4207
4332
  const combinedWhere = whereSQL
4208
4333
  ? `(${whereSQL}) AND ${timestampFilter}`
4209
4334
  : timestampFilter;
@@ -4219,7 +4344,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4219
4344
  this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
4220
4345
  sql += ` ORDER BY ${orderBy}`;
4221
4346
  }
4222
- return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
4347
+ const rawRows = await this.ExecuteSQL(sql, undefined, undefined, contextUser);
4348
+ const processed = await this.PostProcessRows(rawRows, entityInfo, (contextUser ?? this.CurrentUser), { preserveRestrictedApiCiphertext: true });
4349
+ return processed;
4223
4350
  }
4224
4351
  catch (e) {
4225
4352
  LogError(e);
@@ -4251,16 +4378,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4251
4378
  const item = params[i];
4252
4379
  const query = this.resolveQuery(item.params);
4253
4380
  if (!query) {
4254
- errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: `Query not found: ${item.params.QueryID || item.params.QueryName}` });
4381
+ errorResults.push({ queryIndex: i, queryId: item.params.QueryID || '', status: 'error', errorMessage: GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params)) });
4255
4382
  continue;
4256
4383
  }
4257
4384
  const definition = this.QueryDefinitionSignatureFor(query);
4258
4385
  const runCheck = this.authorizeCacheCheckedQuery(query, item, definition, user);
4259
4386
  if (!runCheck.canRun) {
4260
- const deniedMsg = runCheck.deniedEntities.length > 0
4261
- ? ` Denied entities: ${runCheck.deniedEntities.join(', ')}.`
4262
- : '';
4263
- const errorMessage = runCheck.renderError ?? `User does not have permission to run query: ${query.Name}.${deniedMsg}`;
4387
+ const errorMessage = runCheck.renderError ?? this.queryRunRefusalMessage(GenericDatabaseProvider.RequestedQueryLabel(item.params));
4264
4388
  errorResults.push({ queryIndex: i, queryId: query.ID, status: 'error', errorMessage });
4265
4389
  continue;
4266
4390
  }
@@ -4338,7 +4462,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4338
4462
  const mayAnswerWithoutRunning = !!item.cacheStatus
4339
4463
  && !this.clientSlotDefinitionDiffers(item.cacheStatus, definition)
4340
4464
  && !!query.CacheValidationSQL;
4341
- return mayAnswerWithoutRunning ? this.authorizeQueryRun(query, item.params.Parameters, user) : query.UserCanRun(user);
4465
+ if (mayAnswerWithoutRunning) {
4466
+ return this.authorizeQueryRun(query, item.params.Parameters, user);
4467
+ }
4468
+ const result = query.UserCanRun(user);
4469
+ if (!result.canRun) {
4470
+ // RunQueriesWithCacheCheck short-circuits on !canRun before reaching
4471
+ // runFullQueryAndReturnForQuery, so this refusal would otherwise never log.
4472
+ this.logQueryRunRefusal(query, user, result);
4473
+ }
4474
+ return result;
4342
4475
  }
4343
4476
  /**
4344
4477
  * B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
@@ -4366,9 +4499,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4366
4499
  if (!query) {
4367
4500
  return { resolvable: false, authorized: false };
4368
4501
  }
4502
+ // Pre-cache probe: a denial here falls through to execution, which logs at its own
4503
+ // gate, so this probe does not log (no duplicate refusal lines on cached runs).
4504
+ const run = user ? this.authorizeQueryRun(query, params.Parameters, user, false) : null;
4369
4505
  return {
4370
4506
  resolvable: true,
4371
- authorized: !user || this.authorizeQueryRun(query, params.Parameters, user).canRun,
4507
+ authorized: !run || run.canRun,
4508
+ // A run that drops denied columns returns rows shaped by the user's denials, so its
4509
+ // slot is the user's field-security segment's alone.
4510
+ fieldSecurityKey: user && run?.needsColumnFiltering ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : undefined,
4372
4511
  categoryPath: query.CategoryPath,
4373
4512
  queryName: query.Name,
4374
4513
  contextTokens: this.queryContextTokens(query),
@@ -4452,14 +4591,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4452
4591
  *
4453
4592
  * @param query - The resolved MJQueryEntityExtended to validate
4454
4593
  * @param contextUser - The user attempting to execute the query
4594
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
4595
+ * refusal echoes it and nothing else. The query's ID when omitted.
4455
4596
  * @throws Error if the user does not have permission to run the query
4456
4597
  */
4457
- ValidateQueryForExecution(query, contextUser) {
4598
+ ValidateQueryForExecution(query, contextUser, requestedLabel = query.ID) {
4458
4599
  const user = contextUser || this.CurrentUser;
4459
4600
  if (user) {
4460
4601
  const result = query.UserCanRun(user);
4461
4602
  if (!result.canRun) {
4462
- throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
4603
+ // This gate, not the rendered-SQL one, is where a role-list denial lands: it
4604
+ // short-circuits before any SQL is rendered.
4605
+ this.logQueryRunRefusal(query, user, result);
4606
+ throw new Error(this.queryRunRefusalMessage(requestedLabel));
4463
4607
  }
4464
4608
  }
4465
4609
  if (query.Status !== 'Approved') {
@@ -4527,44 +4671,130 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4527
4671
  * and field-level security on every column it references. A template that injects an
4528
4672
  * identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
4529
4673
  * render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
4530
- * The refusal does not say which field or clause caused it.
4531
4674
  *
4675
+ * A refusal reads exactly like the message for a query that does not exist
4676
+ * ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
4677
+ *
4678
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
4679
+ * refusal echoes it and nothing else. The query's ID when omitted.
4680
+ * @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
4681
+ * `alias.*` that reaches only the output reads an entity the user is denied a field on.
4532
4682
  * @throws Error when the user may not run this rendering of the query
4533
4683
  */
4534
- ValidateRenderedQueryForExecution(query, renderedSQL, contextUser) {
4684
+ ValidateRenderedQueryForExecution(query, renderedSQL, contextUser, requestedLabel = query.ID) {
4535
4685
  const user = contextUser || this.CurrentUser;
4536
4686
  if (!user) {
4537
- return;
4687
+ return { NeedsColumnFiltering: false };
4538
4688
  }
4539
4689
  const result = this.checkRenderedQuery(query, renderedSQL, user);
4540
4690
  if (!result.canRun) {
4541
- throw new Error(this.queryRunRefusalMessage(query, result.deniedEntities));
4691
+ throw new Error(this.queryRunRefusalMessage(requestedLabel));
4692
+ }
4693
+ return { NeedsColumnFiltering: result.needsColumnFiltering === true };
4694
+ }
4695
+ /**
4696
+ * The message for a saved query that does not exist or that the caller may not run. The two
4697
+ * are worded identically, so a refusal does not confirm that the query, or anything it reads,
4698
+ * exists.
4699
+ *
4700
+ * It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
4701
+ * looked up from the resolved query: a refusal of a request by ID that named the query would
4702
+ * both differ from that request's not-found message and disclose the query's name.
4703
+ *
4704
+ * @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
4705
+ */
4706
+ static QueryUnavailableMessage(label) {
4707
+ return `Query '${label}' does not exist or you do not have permission to run it.`;
4708
+ }
4709
+ /**
4710
+ * The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
4711
+ * name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
4712
+ */
4713
+ static RequestedQueryLabel(params) {
4714
+ if (params.QueryName) {
4715
+ const path = (params.CategoryPath ?? '').split('/').map(s => s.trim()).filter(s => s.length > 0).join('/');
4716
+ return path ? `${path}/${params.QueryName}` : params.QueryName;
4542
4717
  }
4718
+ return params.QueryID ?? '';
4543
4719
  }
4544
- /** The refusal for a user who may not run `query`; names entities the user cannot read, never a field. */
4545
- queryRunRefusalMessage(query, deniedEntities) {
4546
- const deniedMsg = deniedEntities.length > 0 ? ` Denied entities: ${deniedEntities.join(', ')}.` : '';
4547
- return `User does not have permission to run query '${query.Name}' (ID: ${query.ID}).${deniedMsg}`;
4720
+ /** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
4721
+ queryRunRefusalMessage(requestedLabel) {
4722
+ return GenericDatabaseProvider.QueryUnavailableMessage(requestedLabel);
4548
4723
  }
4549
- /** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
4550
- checkRenderedQuery(query, renderedSQL, user) {
4551
- const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey);
4552
- if (result.fieldSecurityViolation) {
4553
- const v = result.fieldSecurityViolation;
4554
- LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}' by field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''}).`, verboseOnly: true });
4724
+ /**
4725
+ * The OPERATOR's record of why a run was refused. The refusal returned to the caller is
4726
+ * {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
4727
+ * that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
4728
+ *
4729
+ * Without it a refusal is unattributable: the query's own role list, SQL the field-security
4730
+ * gate could not read, and a field-security violation all end in the same caller message.
4731
+ *
4732
+ * Previously only the field-security case logged anything, and only at `verboseOnly`, which
4733
+ * CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
4734
+ * bundles refusing together) could not be diagnosed from the logs at all. Called from every
4735
+ * refusal gate, so no path is silent.
4736
+ *
4737
+ * The loaded-role count is here because an empty or undefined `UserRoles` denies every
4738
+ * permission-bearing query at once — exactly the all-or-nothing signature those runs show.
4739
+ * Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
4740
+ * to ask and it costs one integer.
4741
+ */
4742
+ logQueryRunRefusal(query, user, result) {
4743
+ const v = result.fieldSecurityViolation;
4744
+ const queryRoles = (query.QueryPermissions ?? []).map(p => p.Role).join(', ');
4745
+ const reason = v
4746
+ ? `field-level security (${v.Kind}: ${v.Reference}${v.Entity ? ` on ${v.Entity.Name}` : ''})`
4747
+ : result.deniedEntities.length > 0
4748
+ ? `unreadable entities (${result.deniedEntities.join(', ')})`
4749
+ : `the query's own role list (MJ: Query Permissions: [${queryRoles}])`;
4750
+ const userRoles = user.UserRoles
4751
+ ? `${user.UserRoles.length} ([${user.UserRoles.map(r => r.Role).join(', ')}])`
4752
+ : 'undefined';
4753
+ LogStatus(`RunQuery: query '${query.Name}' (${query.ID}) refused for user '${user.Email}' by ${reason}. ` +
4754
+ `Roles loaded for this user: ${userRoles}.`);
4755
+ }
4756
+ /**
4757
+ * The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
4758
+ * refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
4759
+ * projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
4760
+ * its denied columns dropped instead of being refused.
4761
+ */
4762
+ checkRenderedQuery(query, renderedSQL, user, logRefusal = true) {
4763
+ const stars = this.projectionStarOffsets(renderedSQL, user);
4764
+ const result = query.UserCanRunRenderedSQL(user, renderedSQL, this.Entities, this.PlatformKey, stars ? { ProjectionStarOffsets: stars } : undefined);
4765
+ if (!result.canRun && logRefusal) {
4766
+ this.logQueryRunRefusal(query, user, result);
4555
4767
  }
4556
4768
  return result;
4557
4769
  }
4770
+ /** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
4771
+ static { this.projectionStarMemo = new StatementMemo(500); }
4772
+ /**
4773
+ * The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
4774
+ * denied a field on some entity and only when the text holds a `*`; undefined otherwise.
4775
+ */
4776
+ projectionStarOffsets(renderedSQL, user) {
4777
+ if (!renderedSQL.includes('*') || !FieldSecuritySQLGate.CatalogHasDenialsForUser(this.Entities, user)) {
4778
+ return undefined;
4779
+ }
4780
+ const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
4781
+ return GenericDatabaseProvider.projectionStarMemo.GetOrCompute(key, () => FindProjectionStars(renderedSQL, this.Dialect));
4782
+ }
4558
4783
  /**
4559
4784
  * The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
4560
4785
  * and the run-time checks on the query rendered with `parameters`. A rendering that fails
4561
4786
  * refuses, carrying the rendering's error.
4562
4787
  */
4563
- authorizeQueryRun(query, parameters, user) {
4788
+ authorizeQueryRun(query, parameters, user, logRefusal = true) {
4564
4789
  const base = query.UserCanRun(user);
4565
4790
  if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
4566
4791
  // A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
4567
4792
  // already confirmed the user holds one of its roles: nothing to render.
4793
+ if (!base.canRun && logRefusal) {
4794
+ // The batch/cache-checked path returns rather than throws, so this refusal would
4795
+ // otherwise never reach a log at all.
4796
+ this.logQueryRunRefusal(query, user, base);
4797
+ }
4568
4798
  return base;
4569
4799
  }
4570
4800
  let renderedSQL;
@@ -4574,7 +4804,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4574
4804
  catch (e) {
4575
4805
  return { canRun: false, deniedEntities: [], renderError: e instanceof Error ? e.message : String(e) };
4576
4806
  }
4577
- return this.checkRenderedQuery(query, renderedSQL, user);
4807
+ return this.checkRenderedQuery(query, renderedSQL, user, logRefusal);
4578
4808
  }
4579
4809
  /** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
4580
4810
  static roleListGrants(query) {
@@ -4698,102 +4928,48 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4698
4928
  * {@link buildMaterializedReadQuery}).
4699
4929
  */
4700
4930
  static { this.MATERIALIZED_SURROGATE_ORDER_COLUMN = '__mj_MaterializedRowID'; }
4701
- /** Quotes a SQL identifier for the target engine (SQL Server `[x]`, PostgreSQL `"x"`), escaping the closer. */
4702
- static quoteMaterializedIdentifier(name, isPostgres) {
4703
- return isPostgres ? `"${name.replace(/"/g, '""')}"` : `[${name.replace(/]/g, ']]')}]`;
4704
- }
4705
4931
  /**
4706
4932
  * PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
4707
4933
  * output columns, the materialized view (schema + name), the persisted read-filter spec, the caller's
4708
- * parameter values, and the platform, returns `{ sql, parameters }` whose WHERE injects each spec
4709
- * predicate as `column <op> <placeholder>` with the value **bound** (SQL Server `?`, PostgreSQL `$n`) —
4710
- * never interpolating a caller value (SQL-injection-safe by construction).
4934
+ * parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
4935
+ * predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
4936
+ * value (SQL-injection-safe by construction).
4937
+ *
4938
+ * With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
4939
+ * a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
4940
+ * placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
4941
+ * varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
4942
+ * Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
4943
+ * ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
4944
+ * dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
4711
4945
  *
4712
4946
  * Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
4713
4947
  * the caller falls back to running live (always correct): an operator outside the safe set, a spec
4714
4948
  * parameter the caller did not supply (the live query would apply the param's default), a null value,
4715
- * or an empty/non-array value for a list (`IN`/`NOT IN`) predicate. No IO — fully unit-testable.
4716
- */
4717
- /**
4718
- * True if `sql`'s top-level SELECT carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
4719
- * {@link buildMaterializedReadQuery} emits no ORDER BY and the snapshot is built with the source's top-level
4720
- * ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and therefore its
4721
- * pagination under StartRow/MaxRows — is preserved) rather than from the unordered snapshot. Parse failure or
4722
- * an un-reasoned statement shape returns `true` (refuse-to-live: treat unknown as ordered rather than risk
4723
- * serving mis-ordered pages). Mirrors MaterializationRefresher.stripTopLevelOrderBy's AST detection.
4724
- *
4725
- * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
4726
- * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
4949
+ * an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
4950
+ * known type or a value its type cannot hold. No IO — fully unit-testable.
4727
4951
  */
4728
- static queryHasTopLevelOrderBy(sql, platformKey) {
4729
- if (!sql || sql.trim().length === 0)
4730
- return false;
4731
- try {
4732
- const parsed = SQLParser.Astify(sql, GetDialect(platformKey ?? 'sqlserver'));
4733
- if (!parsed.astParsed || parsed.ast == null)
4734
- return true; // unparseable → refuse to live
4735
- const stmtNode = Array.isArray(parsed.ast) ? (parsed.ast.length === 1 ? parsed.ast[0] : null) : parsed.ast;
4736
- if (stmtNode == null || typeof stmtNode !== 'object')
4737
- return true;
4738
- const s = stmtNode;
4739
- if (s.type !== 'select')
4740
- return true; // not a simple SELECT we can reason about → refuse to live
4741
- return s.orderby != null;
4742
- }
4743
- catch {
4744
- return true; // parser threw → refuse to live (safe: served correctly by the live path)
4745
- }
4746
- }
4747
4952
  static buildMaterializedReadQuery(opts) {
4748
- const { outputColumns, schemaName, viewName, spec, paramValues, paramTypes, isPostgres } = opts;
4953
+ const { outputColumns, schemaName, viewName, spec } = opts;
4749
4954
  if (!outputColumns || outputColumns.length === 0)
4750
4955
  return null;
4751
4956
  if (!spec || spec.length === 0)
4752
4957
  return null;
4753
- const q = (name) => GenericDatabaseProvider.quoteMaterializedIdentifier(name, isPostgres);
4754
- const parameters = [];
4958
+ const dialect = opts.dialect ?? GetDialect(opts.isPostgres ? 'postgresql' : 'sqlserver');
4959
+ const binder = GenericDatabaseProvider.materializedBinder(opts, dialect);
4960
+ // A typed binding converts the value itself, so it takes native forms (a boolean, a UTC ISO date with
4961
+ // its 'Z'); so does an untyped one whose driver binds booleans natively (PostgreSQL). SQL Server's
4962
+ // untyped binding takes BIT 1/0 and a zone-less ISO string.
4963
+ const nativeForms = binder.Typed || (opts.dialect ? typeof dialect.Binding.BooleanParameterValue(true) === 'boolean' : opts.isPostgres === true);
4755
4964
  const predicates = [];
4756
- // Placeholder for the NEXT bound value: SQL Server uses positional `?`; PostgreSQL uses `$n` (1-based,
4757
- // computed BEFORE the value is pushed so the index aligns with the array position).
4758
- const nextPlaceholder = () => (isPostgres ? `$${parameters.length + 1}` : '?');
4759
4965
  for (const e of spec) {
4760
- // Defensive: the spec is parsed from a persisted JSON string, so validate each element's shape
4761
- // before use — a malformed element (missing/non-string column/operator/paramName) returns null
4762
- // (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
4763
- if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
4764
- return null;
4765
- if (!GenericDatabaseProvider.RUNTIME_SAFE_READ_FILTER_OPERATORS.has(e.operator))
4966
+ const predicate = GenericDatabaseProvider.materializedPredicate(e, opts, dialect, binder, nativeForms);
4967
+ if (predicate === null)
4766
4968
  return null;
4767
- const val = paramValues ? paramValues[e.paramName] : undefined;
4768
- if (val === undefined || val === null)
4769
- return null; // caller omitted it → live applies the default
4770
- const col = q(e.column);
4771
- const isListOp = e.operator === 'IN' || e.operator === 'NOT IN';
4772
- if (isListOp) {
4773
- if (!Array.isArray(val) || val.length === 0)
4774
- return null; // empty/non-array IN → live
4775
- const phs = val.map((item) => {
4776
- const ph = nextPlaceholder();
4777
- parameters.push(item); // list elements bound as-is (array element type is not declared)
4778
- return ph;
4779
- });
4780
- predicates.push(`${col} ${e.operator} (${phs.join(', ')})`);
4781
- }
4782
- else {
4783
- // Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
4784
- // Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
4785
- // which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
4786
- // than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
4787
- // aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
4788
- const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, paramTypes?.[e.paramName], isPostgres);
4789
- if (!coerced.ok)
4790
- return null;
4791
- const ph = nextPlaceholder();
4792
- parameters.push(coerced.value);
4793
- predicates.push(`${col} ${e.operator} ${ph}`);
4794
- }
4969
+ predicates.push(predicate);
4795
4970
  }
4796
- const cols = outputColumns.map((c) => q(c)).join(', ');
4971
+ const q = (name) => dialect.Writer.QuoteIdentifier(name);
4972
+ const cols = outputColumns.map(c => q(c)).join(', ');
4797
4973
  // Deterministic page order. A materialized read carries no user ORDER BY (an ordered source query falls
4798
4974
  // back to live), so without an explicit order the paging engine would append `ORDER BY (SELECT NULL)` and
4799
4975
  // successive pages could skip or duplicate rows whenever the execution plan differs between calls. The
@@ -4802,7 +4978,90 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4802
4978
  // buildDataSQL detects this ORDER BY and pages against it instead of the dialect default.
4803
4979
  const orderBy = q(GenericDatabaseProvider.MATERIALIZED_SURROGATE_ORDER_COLUMN);
4804
4980
  const sql = `SELECT ${cols} FROM ${q(schemaName)}.${q(viewName)} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`;
4805
- return { sql, parameters };
4981
+ return { sql, parameters: binder.Parameters };
4982
+ }
4983
+ /**
4984
+ * The parameter list one materialized read builds, and how a value joins it: typed by the filtered
4985
+ * column when the snapshot's column types are known, otherwise untyped (the deprecated form).
4986
+ */
4987
+ static materializedBinder(opts, dialect) {
4988
+ const parameters = [];
4989
+ const types = opts.columnTypes
4990
+ ? new Map(Object.entries(opts.columnTypes).map(([name, type]) => [name.toLowerCase(), type]))
4991
+ : null;
4992
+ const untypedPlaceholder = (index) => (opts.isPostgres ? `$${index + 1}` : '?');
4993
+ return {
4994
+ Parameters: parameters,
4995
+ Typed: types !== null,
4996
+ Bind(column, value) {
4997
+ if (types === null && opts.dialect) {
4998
+ return GenericDatabaseProvider.bindNamedParameter(parameters, dialect, value);
4999
+ }
5000
+ if (types === null) {
5001
+ parameters.push(value);
5002
+ return untypedPlaceholder(parameters.length - 1);
5003
+ }
5004
+ const sqlType = types.get(column.toLowerCase());
5005
+ const bound = sqlType === undefined ? undefined : TypedBindValue(value, sqlType);
5006
+ if (sqlType === undefined || bound === undefined)
5007
+ return null;
5008
+ const reference = dialect.Binding.TypedParameter(parameters.length, sqlType);
5009
+ parameters.push(new TypedQueryParameter(reference.Name, sqlType, bound));
5010
+ return reference.Placeholder;
5011
+ },
5012
+ };
5013
+ }
5014
+ /**
5015
+ * Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
5016
+ * it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
5017
+ * provider from rewriting `?` in the statement text, which the legacy positional array form does
5018
+ * everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
5019
+ */
5020
+ static bindNamedParameter(parameters, dialect, value) {
5021
+ const bound = GenericDatabaseProvider.namedParameterValue(value);
5022
+ if (bound === undefined)
5023
+ return null;
5024
+ const placeholder = dialect.Binding.ParameterPlaceholder(parameters.length);
5025
+ parameters.push(new NamedQueryParameter(placeholder.startsWith('@') ? placeholder.slice(1) : placeholder, bound));
5026
+ return placeholder;
5027
+ }
5028
+ /** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
5029
+ static namedParameterValue(value) {
5030
+ if (value === null || value instanceof Date)
5031
+ return value;
5032
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
5033
+ return value;
5034
+ return undefined;
5035
+ }
5036
+ /** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
5037
+ static materializedPredicate(e, opts, dialect, binder, nativeForms) {
5038
+ // Defensive: the spec is parsed from a persisted JSON string, so validate each element's shape
5039
+ // before use — a malformed element (missing/non-string column/operator/paramName) returns null
5040
+ // (→ caller falls back to live), never throws mid-build (Phase 2 §2: any uncertainty → live).
5041
+ if (!e || typeof e.column !== 'string' || typeof e.operator !== 'string' || typeof e.paramName !== 'string')
5042
+ return null;
5043
+ if (!GenericDatabaseProvider.RUNTIME_SAFE_READ_FILTER_OPERATORS.has(e.operator))
5044
+ return null;
5045
+ const val = opts.paramValues ? opts.paramValues[e.paramName] : undefined;
5046
+ if (val === undefined || val === null)
5047
+ return null; // caller omitted it → live applies the default
5048
+ const col = dialect.Writer.QuoteIdentifier(e.column);
5049
+ if (e.operator === 'IN' || e.operator === 'NOT IN') {
5050
+ if (!Array.isArray(val) || val.length === 0)
5051
+ return null; // empty/non-array IN → live
5052
+ const placeholders = val.map(item => binder.Bind(e.column, item));
5053
+ return placeholders.some(p => p === null) ? null : `${col} ${e.operator} (${placeholders.join(', ')})`;
5054
+ }
5055
+ // Bind the value AS ITS DECLARED TYPE. The live path renders params as typed SQL literals via the
5056
+ // Nunjucks pipeline; binding the raw string here would instead make the DB implicitly coerce it,
5057
+ // which can (a) error on PostgreSQL (text vs numeric/date) and (b) silently match DIFFERENT rows
5058
+ // than live on SQL Server for format/whitespace-sensitive values. Coercing to the declared type
5059
+ // aligns the two; an unconvertible value fails closed → live (never a wrong-rows materialized read).
5060
+ const coerced = GenericDatabaseProvider.coerceMaterializedScalarValue(val, opts.paramTypes?.[e.paramName], nativeForms);
5061
+ if (!coerced.ok)
5062
+ return null;
5063
+ const placeholder = binder.Bind(e.column, coerced.value);
5064
+ return placeholder === null ? null : `${col} ${e.operator} ${placeholder}`;
4806
5065
  }
4807
5066
  /**
4808
5067
  * Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
@@ -4818,13 +5077,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4818
5077
  * the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
4819
5078
  * - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
4820
5079
  * - `boolean` → live truthiness: ONLY 'true' (case-insensitive) or a real boolean `true` is true; everything
4821
- * else is false (live never refuses a boolean). SQL Server binds BIT 1/0; PostgreSQL binds bool.
5080
+ * else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
4822
5081
  * - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
4823
5082
  * the naive input string: live applies the local→UTC shift, so binding the raw string would
4824
- * diverge for any timed value. Invalid date → refuse.
5083
+ * diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
5084
+ * suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
5085
+ * (error 241); the zone-less string is the same UTC wall-clock.
4825
5086
  * - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
5087
+ *
5088
+ * @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
4826
5089
  */
4827
- static coerceMaterializedScalarValue(value, type, isPostgres) {
5090
+ static coerceMaterializedScalarValue(value, type, nativeForms) {
4828
5091
  switch (type) {
4829
5092
  case 'number': {
4830
5093
  const n = Number(typeof value === 'string' ? value.trim() : value);
@@ -4832,19 +5095,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4832
5095
  }
4833
5096
  case 'boolean': {
4834
5097
  const b = typeof value === 'boolean' ? value : String(value).toLowerCase() === 'true';
4835
- return { ok: true, value: isPostgres ? b : b ? 1 : 0 };
5098
+ return { ok: true, value: nativeForms ? b : b ? 1 : 0 };
4836
5099
  }
4837
5100
  case 'date': {
4838
5101
  const d = value instanceof Date ? value : new Date(String(value));
4839
5102
  if (Number.isNaN(d.getTime()))
4840
5103
  return { ok: false };
4841
5104
  const iso = d.toISOString();
4842
- // SQL Server rejects the ISO 'Z' zone suffix for datetime2/datetime (error 241 — 'Z' is valid only
4843
- // for datetimeoffset), so binding it would throw and force a fallback to live. Strip it for SS: the
4844
- // value is already the UTC moment and a zone-less ISO string binds as that same datetime2 wall-clock,
4845
- // matching the live path's rendered literal (no row divergence). PostgreSQL's timestamptz accepts
4846
- // 'Z', so keep it there.
4847
- return { ok: true, value: isPostgres ? iso : iso.replace(/Z$/, '') };
5105
+ return { ok: true, value: nativeForms ? iso : iso.replace(/Z$/, '') };
4848
5106
  }
4849
5107
  case 'string':
4850
5108
  return { ok: true, value: String(value) };
@@ -4852,14 +5110,70 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4852
5110
  return { ok: true, value };
4853
5111
  }
4854
5112
  }
5113
+ /**
5114
+ * The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
5115
+ * describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
5116
+ * the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
5117
+ * be described (→ live).
5118
+ */
5119
+ async materializedColumnTypes(mat, contextUser) {
5120
+ const refreshed = mat.LastRefreshedAt instanceof Date ? mat.LastRefreshedAt.toISOString() : String(mat.LastRefreshedAt ?? '');
5121
+ const key = StatementMemo.KeyOf(`${NormalizeUUID(mat.ID)}|${refreshed}|${mat.SchemaName}.${mat.ViewName}`, this.Dialect.Key);
5122
+ const kept = GenericDatabaseProvider.materializedColumnTypeMemo.Get(key);
5123
+ if (kept)
5124
+ return kept;
5125
+ const writer = this.Dialect.Writer;
5126
+ const described = await this.DescribeStatement(`SELECT * FROM ${writer.QuoteIdentifier(mat.SchemaName)}.${writer.QuoteIdentifier(mat.ViewName)}`, contextUser);
5127
+ if (!described.Success) {
5128
+ LogStatusEx({ message: `Materialized read: the column types of ${mat.SchemaName}.${mat.ViewName} could not be read (${described.Diagnostics.join('; ')}) — serving live.`, verboseOnly: true });
5129
+ return null;
5130
+ }
5131
+ const types = {};
5132
+ for (const c of described.Columns)
5133
+ types[c.Name.toLowerCase()] = c.SQLFullType;
5134
+ GenericDatabaseProvider.materializedColumnTypeMemo.Set(key, types);
5135
+ return types;
5136
+ }
5137
+ /** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
5138
+ static { this.materializedColumnTypeMemo = new StatementMemo(500); }
5139
+ /** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
5140
+ static { this.topLevelOrderByMemo = new StatementMemo(1000); }
5141
+ /**
5142
+ * True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
5143
+ * {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
5144
+ * source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
5145
+ * therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
5146
+ * `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
5147
+ * (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
5148
+ * (SQL, dialect) in a bounded memo.
5149
+ *
5150
+ * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
5151
+ * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
5152
+ */
5153
+ static queryHasTopLevelOrderBy(sql, platformKey) {
5154
+ if (!sql || sql.trim().length === 0)
5155
+ return false;
5156
+ const dialect = GetDialect(platformKey ?? 'sqlserver');
5157
+ return GenericDatabaseProvider.topLevelOrderByMemo.GetOrCompute(StatementMemo.KeyOf(sql, dialect.Key), () => {
5158
+ const doc = SqlDocument.Parse(sql, dialect);
5159
+ if (doc.TopLevelQuery() === null || doc.HasStackedStatements().Value)
5160
+ return true;
5161
+ const orderBy = doc.TopLevelOrderBy();
5162
+ return !orderBy.Complete || orderBy.Value !== null;
5163
+ });
5164
+ }
4855
5165
  /**
4856
5166
  * Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
4857
5167
  * `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
4858
5168
  * persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
4859
5169
  * the live query (serving live is always correct — this is a transparent optimization, never a
4860
5170
  * correctness dependency).
5171
+ *
5172
+ * @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
5173
+ * check reads it; without it the check reads the platform SQL, where template syntax makes any
5174
+ * template query read as ordered (→ live).
4861
5175
  */
4862
- async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues) {
5176
+ async tryBuildMaterializedQueryPlan(query, params, contextUser, contextValues, renderedSQL) {
4863
5177
  if (!IsMaterializedDataSource(params.DataSource))
4864
5178
  return null; // not opted in → live
4865
5179
  // A snapshot is shared by every caller and was built without this caller's Context (user, date), so a
@@ -4879,6 +5193,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4879
5193
  Fields: ['MaterializedResultID'],
4880
5194
  ResultType: 'simple',
4881
5195
  MaxRows: 1,
5196
+ SkipTotalRowCount: true,
4882
5197
  }, contextUser);
4883
5198
  // Same failure-vs-absence distinction as the base-view path: a permission/query failure here would
4884
5199
  // otherwise be indistinguishable from "this query is not materialized", silently pinning the caller to
@@ -4894,10 +5209,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4894
5209
  // source's top-level ORDER BY stripped (it has no inherent order). A query that carries a top-level ORDER
4895
5210
  // BY would therefore page differently from the live query. Refuse → live (which preserves the ordering)
4896
5211
  // rather than serve a divergent page order — consistent with this method's "any uncertainty → live".
4897
- // Check the PLATFORM-resolved SQL (the exact SQL the live path executes — GetPlatformSQL, line ~3642),
4898
- // not the base query.SQL: a per-platform QuerySQL variant (e.g. a PostgreSQL variant) may add a top-level
5212
+ // Check the SQL the live path executes: the rendered statement when the caller has it (a template decides
5213
+ // its ORDER BY only when it renders, and the structural reader does not read template syntax, so the
5214
+ // template text of every template query would read as ordered), otherwise the PLATFORM-resolved SQL — not
5215
+ // the base query.SQL: a per-platform QuerySQL variant (e.g. a PostgreSQL variant) may add a top-level
4899
5216
  // ORDER BY the base SQL lacks, and parsing the base SQL would miss it and serve mis-ordered snapshot pages.
4900
- if (GenericDatabaseProvider.queryHasTopLevelOrderBy(query.GetPlatformSQL(this.PlatformKey) ?? '', this.PlatformKey))
5217
+ const orderingSQL = renderedSQL ?? query.GetPlatformSQL(this.PlatformKey) ?? '';
5218
+ if (GenericDatabaseProvider.queryHasTopLevelOrderBy(orderingSQL, this.PlatformKey))
4901
5219
  return null;
4902
5220
  // Load the materialization metadata. matId is our own UUID (from committed metadata), so it is safe
4903
5221
  // to interpolate into ExtraFilter — it never carries caller input.
@@ -4910,9 +5228,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4910
5228
  const res = await rv.RunView({
4911
5229
  EntityName: 'MJ: Materialized Results',
4912
5230
  ExtraFilter: `ID='${matId}'`,
4913
- Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName'],
5231
+ Fields: ['Status', 'ParamMode', 'ReadFilterSpec', 'SchemaName', 'ViewName', 'LastRefreshedAt'],
4914
5232
  ResultType: 'simple',
4915
5233
  MaxRows: 1,
5234
+ SkipTotalRowCount: true,
4916
5235
  BypassCache: true,
4917
5236
  }, contextUser);
4918
5237
  if (this.MaterializationLookupFailed(res, `query "${query.Name}" (materialization metadata)`))
@@ -4955,6 +5274,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4955
5274
  const paramTypes = {};
4956
5275
  for (const p of query.QueryParameters ?? [])
4957
5276
  paramTypes[p.Name] = p.Type;
5277
+ // Each value binds with the type of the snapshot column it is compared with (read once per refresh;
5278
+ // the status read above stays uncached). Unknown types → live.
5279
+ const columnTypes = await this.materializedColumnTypes({ ID: matId, SchemaName: mat.SchemaName, ViewName: mat.ViewName, LastRefreshedAt: mat.LastRefreshedAt ?? null }, contextUser);
5280
+ if (!columnTypes)
5281
+ return null;
4958
5282
  return GenericDatabaseProvider.buildMaterializedReadQuery({
4959
5283
  outputColumns,
4960
5284
  schemaName: mat.SchemaName,
@@ -4964,7 +5288,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4964
5288
  // already refused when the template rendered), so the row filter sees both.
4965
5289
  paramValues: params.ServerParameters ? { ...params.Parameters, ...params.ServerParameters } : params.Parameters,
4966
5290
  paramTypes,
4967
- isPostgres: this.PlatformKey === 'postgresql',
5291
+ dialect: this.Dialect,
5292
+ columnTypes,
4968
5293
  });
4969
5294
  }
4970
5295
  async InternalRunQuery(params, contextUser) {
@@ -4988,8 +5313,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4988
5313
  try {
4989
5314
  // Find and validate query
4990
5315
  const query = this.findAndValidateQuery(params, contextUser);
4991
- // Process parameters (composition + Nunjucks templates)
4992
- const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params);
5316
+ const requestedLabel = GenericDatabaseProvider.RequestedQueryLabel(params);
5317
+ // Process parameters (composition + Nunjucks templates). A query on an external data source
5318
+ // renders its values with that source's dialect, so its literals read as the remote database reads them.
5319
+ const dialectKey = query.ExternalDataSourceID ? await this.externalQueryDialectKey(query, contextUser) : undefined;
5320
+ const resolved = this.processQueryParameters(query, params.Parameters, contextUser, params, dialectKey);
4993
5321
  finalSQL = resolved.finalSQL;
4994
5322
  const appliedParameters = resolved.appliedParameters;
4995
5323
  // Opt-in: the approval must be current for the definition about to run
@@ -4997,13 +5325,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
4997
5325
  await this.ValidateQueryApprovalAsync(query, resolved.renderResult);
4998
5326
  }
4999
5327
  // Authorize what will actually run, before any cache, materialized or external read.
5000
- this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser);
5328
+ const authorization = this.ValidateRenderedQueryForExecution(query, finalSQL, contextUser, requestedLabel);
5329
+ // A projection star over an entity the user is denied a field on: the run drops the denied
5330
+ // columns, chosen by the database's description of the statement. An external source's
5331
+ // statement cannot be described here, so such a run is refused.
5332
+ if (authorization.NeedsColumnFiltering && query.ExternalDataSourceID) {
5333
+ throw new Error(this.queryRunRefusalMessage(requestedLabel));
5334
+ }
5335
+ const columnFilter = authorization.NeedsColumnFiltering ? await this.queryColumnFilter(query, finalSQL, requestedLabel, contextUser) : null;
5336
+ const cacheSlot = this.queryResultCacheSlot(query, finalSQL, authorization.NeedsColumnFiltering, contextUser);
5001
5337
  // ── Phase 2: materialized read redirect (plan §5) ──
5002
5338
  // If the caller opted into DataSource:'Materialized' and this query has a fresh, Active
5003
5339
  // RowFilterBroad materialization, serve from the materialized table with the row-filter params
5004
5340
  // injected as BOUND predicates. On ANY uncertainty tryBuildMaterializedQueryPlan returns null and
5005
5341
  // we fall through to the live execution below — a materialized read can never diverge from live.
5006
- const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues);
5342
+ const matPlan = await this.tryBuildMaterializedQueryPlan(query, params, contextUser, resolved.renderResult.ContextValues, finalSQL);
5007
5343
  if (matPlan) {
5008
5344
  // Use a LOCAL for the materialized SQL — never overwrite `finalSQL` (which stays the
5009
5345
  // live-rendered SQL), so a fallback below runs the live path unchanged.
@@ -5044,6 +5380,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5044
5380
  rows = paginated.paginatedResult;
5045
5381
  matTotalRowCount = paginated.totalRowCount;
5046
5382
  }
5383
+ rows = this.filterQueryRows(rows, columnFilter);
5047
5384
  if (params.Enrichment?.EnricherKey) {
5048
5385
  rows = await this.enrichQueryResults(rows, params, query, contextUser);
5049
5386
  }
@@ -5099,10 +5436,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5099
5436
  let executionTime;
5100
5437
  let fullResult;
5101
5438
  if (useSQLPaging) {
5439
+ // The paging wrapper may order by output position (`ORDER BY 1` on PostgreSQL); a page ordered
5440
+ // by a column the caller is denied would reveal how its values rank, so such a run is refused.
5441
+ if (columnFilter && columnFilter.Columns.length > 0 && columnFilter.Withheld.has(columnFilter.Columns[0].Name)) {
5442
+ throw new Error(this.queryRunRefusalMessage(requestedLabel));
5443
+ }
5102
5444
  // Check paged cache before executing SQL
5103
- const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters);
5445
+ const pagedCacheHit = await this.checkPagedQueryCache(query, params, appliedParameters, cacheSlot.PageKey(params));
5104
5446
  if (pagedCacheHit) {
5105
- return pagedCacheHit;
5447
+ return { ...pagedCacheHit, Results: this.filterQueryRows(pagedCacheHit.Results, columnFilter) };
5106
5448
  }
5107
5449
  const paging = QueryPagingEngine.WrapWithPaging(finalSQL, QueryPagingEngine.ResolveStartRow(params.StartRow), params.MaxRows, this.PlatformKey);
5108
5450
  // Execute data + count queries in parallel
@@ -5114,27 +5456,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5114
5456
  executionTime = Date.now() - start;
5115
5457
  if (!dataResult)
5116
5458
  throw new Error('Error executing paged query SQL');
5117
- paginatedResult = dataResult;
5118
- this.ConvertByteArrayValuesToBase64(paginatedResult);
5459
+ this.ConvertByteArrayValuesToBase64(dataResult);
5460
+ paginatedResult = this.filterQueryRows(dataResult, columnFilter);
5119
5461
  totalRowCount = countResult?.[0]?.TotalRowCount != null
5120
5462
  ? Number(countResult[0].TotalRowCount)
5121
5463
  : paginatedResult.length;
5122
5464
  }
5123
5465
  else {
5124
5466
  // Check full-result cache before executing
5125
- const cachedResult = await this.checkQueryCache(query, params, appliedParameters);
5467
+ const cachedResult = await this.checkQueryCache(query, params, appliedParameters, cacheSlot.Key);
5126
5468
  if (cachedResult) {
5127
- return cachedResult;
5469
+ return { ...cachedResult, Results: this.filterQueryRows(cachedResult.Results, columnFilter) };
5128
5470
  }
5129
5471
  // No paging requested — execute full query, apply in-memory pagination as fallback
5130
5472
  const timing = await this.executeQueryWithTiming(finalSQL, contextUser);
5131
5473
  executionTime = timing.executionTime;
5132
5474
  fullResult = timing.result;
5133
5475
  const paginated = this.applyQueryPagination(fullResult, params);
5134
- paginatedResult = paginated.paginatedResult;
5476
+ paginatedResult = this.filterQueryRows(paginated.paginatedResult, columnFilter);
5135
5477
  totalRowCount = paginated.totalRowCount;
5136
5478
  // Cache full (unpaginated) results if enabled (fire-and-forget)
5137
- void this.cacheQueryResults(query, params.Parameters || {}, fullResult);
5479
+ void this.cacheQueryResults(query, params.Parameters || {}, fullResult, cacheSlot.Key);
5138
5480
  }
5139
5481
  // Optional, additive post-query enrichment (e.g. append an ML prediction
5140
5482
  // column). Awaited so the appended columns are present in the response.
@@ -5184,6 +5526,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5184
5526
  };
5185
5527
  }
5186
5528
  }
5529
+ /** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
5530
+ static { this.describedStatementMemo = new StatementMemo(500, 10 * 60 * 1000); }
5531
+ /**
5532
+ * Describes the result set of `sql` without returning its rows: each output column's name,
5533
+ * position, exact type, nullability and, for a pass-through column, the table or view column it
5534
+ * comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
5535
+ * runs it under `LIMIT 0` in a transaction that is rolled back).
5536
+ *
5537
+ * This base implementation describes nothing: it reports a failure. Providers for a database
5538
+ * that can describe a statement override it.
5539
+ *
5540
+ * @param sql - The rendered statement, in this provider's dialect.
5541
+ * @param _contextUser - The user the description is for.
5542
+ */
5543
+ async DescribeStatement(sql, _contextUser) {
5544
+ return DescribeStatementFailure(`${this.constructor.name} cannot describe a statement.`);
5545
+ }
5546
+ /**
5547
+ * SECURITY — the output columns of `renderedSQL` that `user` must not receive
5548
+ * ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
5549
+ *
5550
+ * @throws Error with the refusal message when the statement cannot be described: without the
5551
+ * description no column can be shown to be safe, so the run is refused.
5552
+ */
5553
+ async queryColumnFilter(query, renderedSQL, requestedLabel, contextUser) {
5554
+ const user = contextUser || this.CurrentUser;
5555
+ const key = StatementMemo.KeyOf(renderedSQL, this.Dialect.Key);
5556
+ let columns = GenericDatabaseProvider.describedStatementMemo.Get(key);
5557
+ if (!columns) {
5558
+ const described = await this.DescribeStatement(renderedSQL, user);
5559
+ if (!described.Success) {
5560
+ LogStatusEx({ message: `RunQuery: query '${query.Name}' refused for user '${user.Email}': its columns could not be described for field-level security (${described.Diagnostics.join('; ')}).`, verboseOnly: true });
5561
+ throw new Error(this.queryRunRefusalMessage(requestedLabel));
5562
+ }
5563
+ columns = described.Columns;
5564
+ GenericDatabaseProvider.describedStatementMemo.Set(key, columns);
5565
+ }
5566
+ const readEntities = [...(FieldSecuritySQLGate.RelationEntities(renderedSQL, this.Entities, this.PlatformKey) ?? []), ...this.declaredQueryEntities(query)];
5567
+ return { Key: key, Columns: columns, Withheld: WithheldColumnNames(columns, this.Entities, readEntities, user) };
5568
+ }
5569
+ /** The catalog entities `query`'s `QueryEntities` rows name. */
5570
+ declaredQueryEntities(query) {
5571
+ const byID = IndexByUUID(this.Entities);
5572
+ return (query.QueryEntities ?? []).map(qe => byID.Get(qe.EntityID)).filter((e) => !!e);
5573
+ }
5574
+ /**
5575
+ * `rows` with the filter's withheld columns dropped, as new row objects. A column the
5576
+ * description does not list is dropped too, and the description is forgotten: the statement's
5577
+ * shape changed since it was described (a view redefined), so the next run describes it again.
5578
+ */
5579
+ filterQueryRows(rows, filter) {
5580
+ if (!filter || rows.length === 0)
5581
+ return rows;
5582
+ const undescribed = UndescribedColumnNames(rows, filter.Columns);
5583
+ if (undescribed.size > 0) {
5584
+ GenericDatabaseProvider.describedStatementMemo.Delete(filter.Key);
5585
+ }
5586
+ return WithholdColumns(rows, undescribed.size > 0 ? new Set([...filter.Withheld, ...undescribed]) : filter.Withheld);
5587
+ }
5187
5588
  /**
5188
5589
  * Batch query execution — runs all queries in parallel.
5189
5590
  */
@@ -5333,22 +5734,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5333
5734
  findAndValidateQuery(params, contextUser) {
5334
5735
  const query = this.resolveQuery(params);
5335
5736
  if (!query) {
5336
- let errorDetails = 'Query not found';
5337
- if (params.QueryName) {
5338
- errorDetails = `Query '${params.QueryName}' not found`;
5339
- if (params.CategoryPath) {
5340
- errorDetails += ` in category path '${params.CategoryPath}'`;
5341
- }
5342
- else if (params.CategoryID) {
5343
- errorDetails += ` in category ID '${params.CategoryID}'`;
5344
- }
5345
- }
5346
- else if (params.QueryID) {
5347
- errorDetails = `Query with ID '${params.QueryID}' not found`;
5348
- }
5349
- throw new Error(errorDetails);
5737
+ // Worded exactly as a refusal (QueryUnavailableMessage), so neither confirms the query exists.
5738
+ throw new Error(GenericDatabaseProvider.QueryUnavailableMessage(GenericDatabaseProvider.RequestedQueryLabel(params)));
5350
5739
  }
5351
- this.ValidateQueryForExecution(query, contextUser);
5740
+ this.ValidateQueryForExecution(query, contextUser, GenericDatabaseProvider.RequestedQueryLabel(params));
5352
5741
  return query;
5353
5742
  }
5354
5743
  /**
@@ -5357,10 +5746,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5357
5746
  *
5358
5747
  * Delegates to {@link RenderPipeline.Run} for the composition → template
5359
5748
  * pipeline. Paging is handled separately by the caller (InternalRunQuery).
5749
+ *
5750
+ * @param dialectKey - The dialect the template's values render for (`sqlString` literals,
5751
+ * booleans); this provider's platform when omitted. An external data source's query passes
5752
+ * the source's dialect.
5360
5753
  */
5361
- processQueryParameters(query, parameters, contextUser, serverSet) {
5754
+ processQueryParameters(query, parameters, contextUser, serverSet, dialectKey) {
5362
5755
  const result = RenderPipeline.Run(query.GetPlatformSQL(this.PlatformKey), {
5363
5756
  Platform: this.PlatformKey,
5757
+ DialectKey: dialectKey,
5758
+ QueryID: query.ID,
5759
+ QueryName: query.Name,
5364
5760
  ContextUser: contextUser ?? this.CurrentUser,
5365
5761
  Parameters: parameters,
5366
5762
  ServerParameters: serverSet?.ServerParameters,
@@ -5377,6 +5773,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5377
5773
  }
5378
5774
  return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
5379
5775
  }
5776
+ /**
5777
+ * The dialect key of the external data source `query` reads, so its template values render as
5778
+ * that database reads literals; undefined when the source has no SQL dialect (a document
5779
+ * store), in which case the query renders with this provider's platform as before.
5780
+ */
5781
+ async externalQueryDialectKey(query, contextUser) {
5782
+ const router = this.resolveExternalReadRouterOrThrow(`Query '${query.Name}'`);
5783
+ const key = await router.GetQueryDialectKey(query.ExternalDataSourceID, contextUser, this);
5784
+ return key ?? undefined;
5785
+ }
5380
5786
  /**
5381
5787
  * Checks the columns an external-data-source query returned against the fields the Query
5382
5788
  * *declares* (its QueryField metadata) and logs a warning naming any declared field that
@@ -5566,19 +5972,46 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5566
5972
  return { finalSQL: result.FinalSQL, appliedParameters: result.AppliedParameters, renderResult: result };
5567
5973
  }
5568
5974
  // wrapWithMaxRows is now handled by RenderPipeline.applyMaxRows
5975
+ /**
5976
+ * Where a server-side result cache keeps this run's rows: one slot per rendered statement and
5977
+ * dialect, and, when the caller is denied a field the statement's projection star reads, per
5978
+ * field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
5979
+ * runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
5980
+ * The rendered statement carries every parameter value, server-set ones included, so they need
5981
+ * no separate part of the key.
5982
+ */
5983
+ queryResultCacheSlot(query, renderedSQL, needsColumnFiltering, contextUser) {
5984
+ const user = contextUser || this.CurrentUser;
5985
+ const profile = needsColumnFiltering && user ? FieldSecuritySQLGate.CatalogDenialProfileKey(this.Entities, user) : '';
5986
+ const key = `${query.ID}|${StatementMemo.KeyOf(renderedSQL, this.Dialect.Key)}|fs:${profile}`;
5987
+ return {
5988
+ Key: key,
5989
+ PageKey: (params) => `${key}|page:${QueryPagingEngine.ResolveStartRow(params.StartRow)}:${params.MaxRows ?? ''}`,
5990
+ };
5991
+ }
5569
5992
  /**
5570
5993
  * Checks the query cache for existing results and returns them if valid.
5571
5994
  * Currently always returns null (query caching is not active).
5995
+ *
5996
+ * An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
5997
+ * stores under: it separates rendered statements and field-security profiles, so a slot never
5998
+ * serves one caller rows shaped for another. The returned rows must be the statement's full
5999
+ * output; the caller's withheld columns are dropped from them after the hit.
5572
6000
  */
5573
- async checkQueryCache(_query, _params, _appliedParameters) {
6001
+ async checkQueryCache(_query, _params, _appliedParameters, _slotKey) {
5574
6002
  return null;
5575
6003
  }
5576
6004
  /**
5577
6005
  * Checks the paged cache for a specific page of query results.
5578
6006
  * Returns a full RunQueryResult on hit, null on miss.
5579
6007
  * Currently always returns null (query caching is not active).
6008
+ *
6009
+ * An override must look the page up by `slotKey` alone: it names the rendered statement, the
6010
+ * caller's field-security profile and the page, so a page cached for a restricted caller is
6011
+ * never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
6012
+ * from the returned rows after the hit.
5580
6013
  */
5581
- async checkPagedQueryCache(_query, _params, _appliedParameters) {
6014
+ async checkPagedQueryCache(_query, _params, _appliedParameters, _slotKey) {
5582
6015
  return null;
5583
6016
  }
5584
6017
  /**
@@ -5690,8 +6123,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
5690
6123
  /**
5691
6124
  * Caches query results if caching is enabled for the query.
5692
6125
  * Currently a no-op (query caching is not active).
6126
+ *
6127
+ * `results` is the statement's full output, before the caller's withheld columns are dropped.
6128
+ * An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
5693
6129
  */
5694
- async cacheQueryResults(_query, _parameters, _results) {
6130
+ async cacheQueryResults(_query, _parameters, _results, _slotKey) {
5695
6131
  // No-op: query caching has been removed
5696
6132
  }
5697
6133
  /**************************************************************************/
@@ -6323,11 +6759,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6323
6759
  }
6324
6760
  if (cached) {
6325
6761
  cacheHitCount++;
6762
+ const materializedDatasetRows = await provider.MaterializeCachedRowsForCaller(cached.results, itemEntity, contextUser, false);
6326
6763
  cachedResults.push({
6327
6764
  EntityID: entityID,
6328
6765
  EntityName: entityName,
6329
6766
  Code: code,
6330
- Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, cached.results, contextUser),
6767
+ Results: this.projectDatasetRowsForCaller(datasetName, itemEntity, materializedDatasetRows, contextUser),
6331
6768
  LatestUpdateDate: latestUpdateDate,
6332
6769
  Success: true,
6333
6770
  });
@@ -6431,7 +6868,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6431
6868
  // item.Results — these very arrays — to every engine subclass), so those slots
6432
6869
  // must stay under the defensive deep-freeze like any RunView result.
6433
6870
  const isMetadataScaffolding = datasetName === ProviderBase._mjMetadataDatasetName;
6434
- await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, itemData, maxUpdatedAt, undefined, undefined, this, undefined, isMetadataScaffolding ? { ProviderInternalScaffolding: true } : undefined);
6871
+ const rowsForCache = isMetadataScaffolding
6872
+ ? itemData
6873
+ : provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName));
6874
+ await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, rowsForCache, maxUpdatedAt, undefined, undefined, this, undefined, isMetadataScaffolding ? { ProviderInternalScaffolding: true } : undefined);
6435
6875
  }
6436
6876
  sqlResults.push({
6437
6877
  EntityID: entityID,
@@ -6760,7 +7200,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6760
7200
  * `AIEngine.Models` to recover the driver class / APIName and call
6761
7201
  * `EmbedText(model, text)` directly. If the EntityDocument does not specify
6762
7202
  * a model (or the model isn't loaded) we fall back to
6763
- * `EmbedTextLocal` (highest-power local model) only as a last resort.
7203
+ * `EmbedTextLocal` (the default local model) only as a last resort. The search
7204
+ * text is embedded as a query (`inputType: 'query'`). The index's
7205
+ * `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
7206
+ * the model's native size.
6764
7207
  *
6765
7208
  * Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
6766
7209
  * which rehydrates the vector pool for `entityDocumentId` from
@@ -6787,15 +7230,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
6787
7230
  LogError(`searchEntitiesSemanticPass: EntityDocument AIModelID="${embeddingAIModelId}" not found in AIEngine.Models. Index/query model mismatch is likely — refusing to fall back silently.`);
6788
7231
  return [];
6789
7232
  }
6790
- const result = await AIEngine.Instance.EmbedText(model, searchText);
7233
+ const result = await AIEngine.Instance.EmbedText(model, searchText, undefined, { inputType: 'query' });
6791
7234
  queryVector = result?.vector ?? null;
6792
7235
  }
6793
7236
  else {
6794
7237
  // No model on the EntityDocument — last-resort fallback to the
6795
7238
  // highest-power local embedder. Logged because this path means
6796
7239
  // indexing-time and query-time models can diverge.
6797
- LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to highest-power local embedding model. Index/query mismatch possible.`);
6798
- const embed = await AIEngine.Instance.EmbedTextLocal(searchText);
7240
+ LogError(`searchEntitiesSemanticPass: no AIModelID on EntityDocument "${entityDocumentId}"; falling back to the default local embedding model. Index/query mismatch possible.`);
7241
+ const embed = await AIEngine.Instance.EmbedTextLocal(searchText, { inputType: 'query' });
6799
7242
  queryVector = embed?.result?.vector ?? null;
6800
7243
  }
6801
7244
  }