@memberjunction/generic-database-provider 6.2.0-edge.5 → 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 (100) hide show
  1. package/README.md +165 -1
  2. package/dist/GenericDatabaseProvider.d.ts +599 -69
  3. package/dist/GenericDatabaseProvider.d.ts.map +1 -1
  4. package/dist/GenericDatabaseProvider.js +2055 -403
  5. package/dist/GenericDatabaseProvider.js.map +1 -1
  6. package/dist/SqlLogger.d.ts +26 -0
  7. package/dist/SqlLogger.d.ts.map +1 -1
  8. package/dist/SqlLogger.js +77 -20
  9. package/dist/SqlLogger.js.map +1 -1
  10. package/dist/clientClauseScreen.d.ts +44 -75
  11. package/dist/clientClauseScreen.d.ts.map +1 -1
  12. package/dist/clientClauseScreen.js +129 -267
  13. package/dist/clientClauseScreen.js.map +1 -1
  14. package/dist/composition/compositionAssembler.d.ts +33 -0
  15. package/dist/composition/compositionAssembler.d.ts.map +1 -0
  16. package/dist/composition/compositionAssembler.js +270 -0
  17. package/dist/composition/compositionAssembler.js.map +1 -0
  18. package/dist/composition/compositionInfo.d.ts +7 -0
  19. package/dist/composition/compositionInfo.d.ts.map +1 -0
  20. package/dist/composition/compositionInfo.js +31 -0
  21. package/dist/composition/compositionInfo.js.map +1 -0
  22. package/dist/composition/compositionLookup.d.ts +44 -0
  23. package/dist/composition/compositionLookup.d.ts.map +1 -0
  24. package/dist/composition/compositionLookup.js +122 -0
  25. package/dist/composition/compositionLookup.js.map +1 -0
  26. package/dist/composition/compositionRender.d.ts +136 -0
  27. package/dist/composition/compositionRender.d.ts.map +1 -0
  28. package/dist/composition/compositionRender.js +264 -0
  29. package/dist/composition/compositionRender.js.map +1 -0
  30. package/dist/composition/compositionTypes.d.ts +40 -0
  31. package/dist/composition/compositionTypes.d.ts.map +1 -0
  32. package/dist/composition/compositionTypes.js +2 -0
  33. package/dist/composition/compositionTypes.js.map +1 -0
  34. package/dist/composition/quotedTagRefusal.d.ts +44 -0
  35. package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
  36. package/dist/composition/quotedTagRefusal.js +132 -0
  37. package/dist/composition/quotedTagRefusal.js.map +1 -0
  38. package/dist/composition/renderSteps.d.ts +16 -0
  39. package/dist/composition/renderSteps.d.ts.map +1 -0
  40. package/dist/composition/renderSteps.js +42 -0
  41. package/dist/composition/renderSteps.js.map +1 -0
  42. package/dist/composition/safetyGate.d.ts +46 -0
  43. package/dist/composition/safetyGate.d.ts.map +1 -0
  44. package/dist/composition/safetyGate.js +61 -0
  45. package/dist/composition/safetyGate.js.map +1 -0
  46. package/dist/composition/templateUnit.d.ts +95 -0
  47. package/dist/composition/templateUnit.d.ts.map +1 -0
  48. package/dist/composition/templateUnit.js +189 -0
  49. package/dist/composition/templateUnit.js.map +1 -0
  50. package/dist/describeStatement.d.ts +51 -0
  51. package/dist/describeStatement.d.ts.map +1 -0
  52. package/dist/describeStatement.js +19 -0
  53. package/dist/describeStatement.js.map +1 -0
  54. package/dist/fieldSecurity/projectionStars.d.ts +15 -0
  55. package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
  56. package/dist/fieldSecurity/projectionStars.js +116 -0
  57. package/dist/fieldSecurity/projectionStars.js.map +1 -0
  58. package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
  59. package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
  60. package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
  61. package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
  62. package/dist/index.d.ts +9 -2
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +6 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/pagingLayout.d.ts +68 -0
  67. package/dist/pagingLayout.d.ts.map +1 -0
  68. package/dist/pagingLayout.js +190 -0
  69. package/dist/pagingLayout.js.map +1 -0
  70. package/dist/queryCompositionEngine.d.ts +22 -222
  71. package/dist/queryCompositionEngine.d.ts.map +1 -1
  72. package/dist/queryCompositionEngine.js +35 -729
  73. package/dist/queryCompositionEngine.js.map +1 -1
  74. package/dist/queryPagingEngine.d.ts +26 -5
  75. package/dist/queryPagingEngine.d.ts.map +1 -1
  76. package/dist/queryPagingEngine.js +51 -15
  77. package/dist/queryPagingEngine.js.map +1 -1
  78. package/dist/recordChangeSnapshot.d.ts +43 -0
  79. package/dist/recordChangeSnapshot.d.ts.map +1 -0
  80. package/dist/recordChangeSnapshot.js +85 -0
  81. package/dist/recordChangeSnapshot.js.map +1 -0
  82. package/dist/renderPipeline.d.ts +91 -72
  83. package/dist/renderPipeline.d.ts.map +1 -1
  84. package/dist/renderPipeline.js +71 -179
  85. package/dist/renderPipeline.js.map +1 -1
  86. package/dist/statementMemo.d.ts +29 -0
  87. package/dist/statementMemo.d.ts.map +1 -0
  88. package/dist/statementMemo.js +61 -0
  89. package/dist/statementMemo.js.map +1 -0
  90. package/dist/systemUserFieldAccess.d.ts +16 -1
  91. package/dist/systemUserFieldAccess.d.ts.map +1 -1
  92. package/dist/systemUserFieldAccess.js +39 -8
  93. package/dist/systemUserFieldAccess.js.map +1 -1
  94. package/dist/typedQueryParameter.d.ts +55 -0
  95. package/dist/typedQueryParameter.d.ts.map +1 -0
  96. package/dist/typedQueryParameter.js +122 -0
  97. package/dist/typedQueryParameter.js.map +1 -0
  98. package/dist/types.d.ts +47 -2
  99. package/dist/types.d.ts.map +1 -1
  100. package/package.json +14 -14
@@ -15,10 +15,11 @@
15
15
  *
16
16
  * @module @memberjunction/generic-database-provider
17
17
  */
18
- import { BaseEntity, DatabaseProviderBase, EntityInfo, EntityFieldInfo, EntitySaveOptions, EntityDeleteOptions, EntityPermissionType, ExecuteSQLOptions, ILocalStorageProvider, RunViewParams, RunViewResult, RunViewWithCacheCheckParams, RunViewDatabaseStatus, RunViewsWithCacheCheckResponse, RunViewWithCacheCheckResult, RunQueryParams, RunQueryResult, RunQueryWithCacheCheckParams, RunQueriesWithCacheCheckResponse, RunQueryWithCacheCheckResult, QueryCacheAuthorization, QueryDefinitionSignature, AggregateResult, CompositeKey, DatasetItemFilterType, DatasetResultType, DatasetStatusResultType, IMetadataProvider, ProviderConfigDataBase, UserInfo, PostCommitTask, PostCommitToken, QueryExecutionSpec, SaveContext, SaveSQLResult, ExternalDataSourceReadRouter } from '@memberjunction/core';
18
+ import { BaseEntity, DatabaseProviderBase, EntityInfo, EntityFieldInfo, EntitySaveOptions, EntityDeleteOptions, EntityPermissionType, ExecuteSQLOptions, ILocalStorageProvider, RunViewParams, RunViewResult, RunViewWithCacheCheckParams, RunViewDatabaseStatus, RunViewsWithCacheCheckResponse, RunViewWithCacheCheckResult, RunQueryParams, RunQueryResult, RunQueryWithCacheCheckParams, RunQueriesWithCacheCheckResponse, RunQueryWithCacheCheckResult, QueryCacheAuthorization, QueryDefinitionSignature, AggregateResult, CompositeKey, DatasetItemFilterType, DatasetResultType, DatasetStatusResultType, IMetadataProvider, ProviderConfigDataBase, UserInfo, PostCommitTask, PostCommitToken, QueryExecutionSpec, SaveContext, SaveSQLResult, ExternalDataSourceReadRouter, UserViewProperty, ViewPropertyValues } from '@memberjunction/core';
19
19
  import { SqlLoggingOptions, SqlLoggingSession } from './types.js';
20
20
  import { SQLDialect } from '@memberjunction/sql-dialect';
21
21
  import { type BalancedFragmentOptions } from '@memberjunction/sql-parser';
22
+ import { type DescribeStatementResult } from './describeStatement.js';
22
23
  import { type RenderResult } from './renderPipeline.js';
23
24
  import { CRUDSprocType } from './crudSprocFieldRules.js';
24
25
  import { SaveCoercedValue, SaveCallBinding, SaveSQLFragment, SaveReturnContext } from './saveTypes.js';
@@ -29,6 +30,7 @@ import { ScoredCandidate } from '@memberjunction/core';
29
30
  import { ActionResult } from '@memberjunction/actions-base';
30
31
  import { CountOnlyRow } from './countOnlyBatch.js';
31
32
  import { type ClientClauseScreeningProvider } from './clientClauseScreen.js';
33
+ import { RecordChangeSnapshots } from './recordChangeSnapshot.js';
32
34
  /**
33
35
  * Configuration options for batch SQL execution.
34
36
  * Shared between GenericDatabaseProvider and platform-specific providers.
@@ -121,6 +123,28 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
121
123
  * each querying the database and broadcasting what they loaded.
122
124
  */
123
125
  Config(data: ProviderConfigDataBase, providerToUse?: IMetadataProvider): Promise<boolean>;
126
+ /**
127
+ * Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
128
+ * and Dataset slots. Within this window after a slot was written or last verified against
129
+ * SQL, `RunViewsWithCacheCheck` and `GetDatasetByName` can trust the in-memory slot with
130
+ * zero DB hits. Once this window elapses, the next check performs a lightweight batched
131
+ * SQL status probe (`COUNT(*)` + `MAX(__mj_UpdatedAt)`) to auto-reconcile any out-of-band
132
+ * SQL mutations (e.g., migrations, `mj sync push`, external scripts) without requiring a
133
+ * server restart.
134
+ */
135
+ protected ServerCacheVerificationTTLMs: number;
136
+ /**
137
+ * Public accessor for {@link ServerCacheVerificationTTLMs}.
138
+ * Set to `0` to force SQL status verification on every cache check.
139
+ */
140
+ get ServerCacheVerificationTTL(): number;
141
+ set ServerCacheVerificationTTL(value: number);
142
+ /**
143
+ * Most recent authoritative SQL status result per dataset key (`datasetName + filterKey`),
144
+ * populated by `GetDatasetStatusByName` and consumed by `GetDatasetByName` to reconcile
145
+ * cached dataset item slots against live SQL row counts and timestamps.
146
+ */
147
+ private _lastDatasetStatusByName;
124
148
  /**************************************************************************/
125
149
  /**************************************************************************/
126
150
  private static _sqlLoggingSessionsKey;
@@ -234,7 +258,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
234
258
  * `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
235
259
  * save succeeds is not a durability improvement, it is a different feature.
236
260
  */
237
- protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[]): Promise<ActionResult[]>;
261
+ protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[], runModeFilter?: 'DurableOnly' | 'NonDurableOnly'): Promise<ActionResult[]>;
238
262
  /**
239
263
  * Handles Entity AI Actions for save or delete operations.
240
264
  *
@@ -258,7 +282,9 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
258
282
  /**************************************************************************/
259
283
  protected OnValidateBeforeSave(entity: BaseEntity, user: UserInfo): Promise<string | null>;
260
284
  protected OnBeforeSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
261
- protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, _context: SaveContext): void;
285
+ protected ShouldEnlistSaveInTransaction(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, isNewRecord: boolean): Promise<boolean>;
286
+ protected OnDurableAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
287
+ protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): void;
262
288
  protected OnSaveCompleted(entity: BaseEntity, saveSQLResult: SaveSQLResult, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<Record<string, unknown> | null>;
263
289
  protected OnBeforeDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): Promise<void>;
264
290
  protected OnAfterDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): void;
@@ -268,6 +294,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
268
294
  private cleanupGeoCodesForDeletedRecord;
269
295
  /**************************************************************************/
270
296
  /**************************************************************************/
297
+ /**
298
+ * Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
299
+ * preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
300
+ * Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
301
+ */
302
+ private static readonly _preDecryptionRowsByResult;
271
303
  /**
272
304
  * Post-processes rows: first applies platform-specific datetime adjustments
273
305
  * via the virtual `AdjustDatetimeFields` hook, then handles field-level
@@ -276,7 +308,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
276
308
  * Subclasses should NOT override this method. Instead, override
277
309
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
278
310
  */
279
- protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo): Promise<Record<string, unknown>[]>;
311
+ protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo, options?: {
312
+ preserveRestrictedApiCiphertext?: boolean;
313
+ }): Promise<Record<string, unknown>[]>;
314
+ /**
315
+ * Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
316
+ * When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
317
+ * remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
318
+ * needlessly decrypt values destined for sentinel redaction.
319
+ */
320
+ private decryptRowsForConsumer;
321
+ protected PrepareRowsForCacheStorage(rows: unknown[], entityInfo?: EntityInfo): unknown[];
322
+ protected MaterializeCachedRowsForCaller(rows: Record<string, unknown>[], entityInfo?: EntityInfo, contextUser?: UserInfo, preserveRestrictedApiCiphertext?: boolean): Promise<Record<string, unknown>[]>;
280
323
  private static _encryptedFieldsCache;
281
324
  private static getEncryptedFields;
282
325
  /**
@@ -584,6 +627,67 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
584
627
  * the design and the rev-3 lesson that motivated this shape.
585
628
  */
586
629
  protected GenerateSaveSQL(entity: BaseEntity, isNew: boolean, user: UserInfo, options?: EntitySaveOptions): Promise<SaveSQLResult>;
630
+ /**
631
+ * The old and new snapshots a save's Record Change is built from. The audit trail stores
632
+ * whole payloads and projects them per reader, so both snapshots describe the whole record
633
+ * whoever saves it.
634
+ *
635
+ * - **A user denied nothing** (unrestricted and system-user saves): the object's own values.
636
+ * No query, even when the object was loaded without some columns.
637
+ * - **A restricted user's update** (their object never holds the fields they cannot read):
638
+ * the stored values of those fields are read once and the snapshots are widened with them.
639
+ * The diff is unchanged, because a field the object never held has the same stored value
640
+ * on both sides.
641
+ * - **Create**: there is no stored row yet. A field the INSERT omits because the user may
642
+ * not supply it is left out rather than recorded with a value the record never got.
643
+ *
644
+ * The read runs on the save's connection: inside an open transaction it reads that
645
+ * transaction's state. A save queued in a transaction group is generated when `Save()` is
646
+ * called, so its snapshot reflects the row as of then — the same moment the object's own
647
+ * old values describe.
648
+ */
649
+ protected BuildRecordChangeSnapshots(entity: BaseEntity, isUpdate: boolean, user: UserInfo): Promise<RecordChangeSnapshots>;
650
+ /**
651
+ * Connections a save's SQL is being generated for, by entity object: the transaction a
652
+ * transaction group runs its items on. Set only for the duration of
653
+ * {@link GenerateSaveSQLReadingOn}.
654
+ */
655
+ private readonly _snapshotConnections;
656
+ /**
657
+ * Generates a save's SQL with any stored-row read its Record Change snapshot needs run on
658
+ * `connectionSource`. A transaction group that regenerates an item's SQL while its own
659
+ * transaction is open passes that transaction, so the read sees the group's earlier writes and
660
+ * never waits on the locks the group itself holds.
661
+ */
662
+ protected GenerateSaveSQLReadingOn(entity: BaseEntity, isNew: boolean, user: UserInfo, connectionSource?: object): Promise<SaveSQLResult>;
663
+ /** Full-width delete snapshots captured by {@link Delete}, consumed by `GenerateDeleteSQL`. */
664
+ private readonly _deleteSnapshots;
665
+ /**
666
+ * Deletes a record. Before the shared orchestration runs, a restricted user's delete reads the
667
+ * stored values of the fields their object never held, so the delete's `FullRecordJSON` — the
668
+ * snapshot a deleted record is restored from — is full width. `GenerateDeleteSQL` is
669
+ * synchronous, so the snapshot is captured here and handed to it through
670
+ * {@link RecordChangeDeleteSnapshot}. A user denied nothing costs no extra query.
671
+ */
672
+ Delete(entity: BaseEntity, options: EntityDeleteOptions, user: UserInfo): Promise<boolean>;
673
+ /** Reads and stores the full-width delete snapshot when one is needed; true when it stored one. */
674
+ private captureDeleteSnapshot;
675
+ /**
676
+ * The record snapshot a delete's Record Change carries: the full-width snapshot {@link Delete}
677
+ * captured, else `narrow` (the object's own values, which are already full width whenever no
678
+ * snapshot was needed).
679
+ */
680
+ protected RecordChangeDeleteSnapshot(entity: BaseEntity, narrow: Record<string, unknown>): Record<string, unknown>;
681
+ /**
682
+ * Reads the stored values of `columns` — the fields a snapshot lacks — for a Record Change
683
+ * snapshot. Provider-internal: no row-level filter and no field-security check, because the
684
+ * payload is stored unprojected and projected for each reader. The row gets the same
685
+ * post-processing as a `Load` (binary to base64, datetime adjustment, decryption,
686
+ * fixed-width trimming). Runs on the connection the save is generated for when one was named
687
+ * ({@link GenerateSaveSQLReadingOn}), else on the save's usual connection. Kept out of the SQL
688
+ * log, which records the save itself.
689
+ */
690
+ protected ReadStoredRowForRecordChange(entity: BaseEntity, user: UserInfo, columns: ReadonlySet<string>): Promise<Record<string, unknown> | null>;
587
691
  /**
588
692
  * Builds a platform-specific pagination clause.
589
693
  * SQL Server: `OFFSET X ROWS FETCH NEXT Y ROWS ONLY`
@@ -626,37 +730,34 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
626
730
  * `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
627
731
  * Server — both preserve case.
628
732
  */
629
- protected BuildTotalRowCountSQL(entityInfo: EntityInfo, usingPagination: boolean, maxRowsForQuery: number, baseViewOverride?: string): string | null;
733
+ protected BuildTotalRowCountSQL(entityInfo: EntityInfo, usingPagination: boolean, maxRowsForQuery: number, baseViewOverride?: string, schemaNameOverride?: string): string | null;
630
734
  /**
631
- * Resolves the view a RunView reads from: the entity's live base view by default, or its materialized
632
- * wrapper view when the caller opts into the snapshot via `DataSource: 'Materialized'` (plan §7). The
633
- * choice is explicit (never silent), so the same RLS/paging/field-selection apply against the identical shape.
634
- *
635
- * Two materialization shapes:
636
- * - **Base-view materialization** reuses the SOURCE entity, whose `BaseView` stays the LIVE view; the
637
- * snapshot lives beside it as `materialized_vw<CodeName>` (the name CodeGen's base-view path emits).
638
- * `'Materialized'` swaps the live view for that snapshot.
639
- * - **Query materialization** mints a NEW entity whose `BaseView` ALREADY IS the materialized wrapper
640
- * view (`materialized_vw<...>`), so there is no separate live source to swap — `'Materialized'` is a
641
- * no-op and we return the entity's own base view. (Deriving `materialized_vw<CodeName>` here would be
642
- * wrong: the minted entity's CodeName need not match the query-derived view name.)
643
- *
644
- * Convention-based for the base-view case: if the entity has no such materialization the wrapper view
645
- * won't exist and the read will error — opting into `'Materialized'` asserts the snapshot exists.
735
+ * Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
736
+ * optional loaded `MJUserViewEntityExtended`. An explicit empty string (`""`) on
737
+ * `params.AlternateBaseView` overrides any saved view pin back to `BaseView` (`undefined`).
738
+ */
739
+ protected resolveEffectiveAbvNameFromParams(params: RunViewParams | undefined, viewEntity?: MJUserViewEntityExtended | null): string | undefined;
740
+ /**
741
+ * Resolves the view a RunView reads from: an explicit or pinned `AlternateBaseView` when present,
742
+ * the entity's materialized wrapper view when `DataSource: 'Materialized'`, or the entity's live
743
+ * `BaseView` by default.
646
744
  */
647
- protected GetEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams): string;
745
+ protected GetEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, viewEntity?: MJUserViewEntityExtended | null, suppressDeprecationWarning?: boolean): string;
648
746
  /**
649
747
  * Async status-aware wrapper around {@link GetEffectiveBaseView} for the BASE-VIEW materialization case.
650
- * `GetEffectiveBaseView` name-swaps unconditionally, which (a) serves a `Building`/`DriftHold`/`Disabled`
651
- * snapshot — defeating "flag and hold" (§13/§17.2), since a base-view materialization reuses the source
652
- * entity and thus has no read-permission revoke to fall back on the way a minted query entity does — and
653
- * (b) hard-errors on a `Materialized` read of a non-materialized entity (missing view). This gates the swap
654
- * on an ACTIVE `MaterializedResult` and otherwise returns the LIVE base view (graceful fallback). The status
655
- * read uses `BypassCache` because DriftHold/Disabled are written by CodeGen via direct SQL (no BaseEntity
656
- * cache-invalidation event), so a cached status could otherwise be stale. Non-materialized reads and minted
657
- * query virtual entities (BaseView already `materialized_vw…`) skip the lookup entirely (no extra query).
658
748
  */
659
- protected resolveEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo): Promise<string>;
749
+ protected resolveEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo, viewEntity?: MJUserViewEntityExtended | null): Promise<string>;
750
+ /**
751
+ * Resolves both the effective `{ schemaName, viewName }` for a RunView call, honoring:
752
+ * 1. Explicit `params.AlternateBaseView` (including `""` to force `BaseView` over a saved view pin)
753
+ * 2. Saved `UserView.DisplayState.alternateBaseView` (from `viewEntity`, `params.ViewEntity`, or loaded by `ViewID`/`ViewName`)
754
+ * 3. `DataSource: 'Materialized'`
755
+ * 4. `entityInfo.BaseView`
756
+ */
757
+ protected resolveEffectiveBaseViewTarget(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo, viewEntity?: MJUserViewEntityExtended | null): Promise<{
758
+ schemaName: string;
759
+ viewName: string;
760
+ }>;
660
761
  /**
661
762
  * Reports whether a materialization-metadata `RunView` FAILED, logging the failure when it did.
662
763
  *
@@ -744,10 +845,29 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
744
845
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
745
846
  * Default: returns null (no view run logging).
746
847
  */
747
- protected executeSQLForUserViewRunLogging(_viewId: number, _entityInfo: EntityInfo, _effectiveBaseView: string, _whereSQL: string, _orderBySQL: string, _user: UserInfo): Promise<{
848
+ protected executeSQLForUserViewRunLogging(_viewId: number, _entityInfo: EntityInfo, _effectiveBaseView: string, _whereSQL: string, _orderBySQL: string, _user: UserInfo, _schemaNameOverride?: string): Promise<{
748
849
  executeViewSQL: string;
749
850
  runID: string;
750
851
  } | null>;
852
+ /**
853
+ * Maximum number of concurrent database view executions allowed within a single
854
+ * {@link InternalRunViews} batch. Prevents large `RunViews` batches from exhausting
855
+ * the connection pool in a single tick. Set to 0 or Infinity to disable the cap.
856
+ * Default: 8.
857
+ */
858
+ static MaxConcurrentViewsPerBatch: number;
859
+ /**
860
+ * Process-wide single-flight coalescing registry for in-flight read-only RunView executions.
861
+ * When multiple concurrent requests (across any per-request provider instance on the same
862
+ * server process) execute an identical non-transactional RunView simultaneously, only the
863
+ * first caller queries the database; joiners await the same promise and receive a shallow-cloned
864
+ * result object and Results array.
865
+ */
866
+ private static readonly _inFlightRunViews;
867
+ /**
868
+ * Number of currently in-flight coalesced RunView executions across this process.
869
+ */
870
+ static get InFlightRunViewCount(): number;
751
871
  /**
752
872
  * Shared InternalRunView implementation.
753
873
  * Handles: view resolution, permissions, field selection, WHERE clause building
@@ -755,6 +875,28 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
755
875
  * aggregates, parallel query execution, post-processing, and audit logging.
756
876
  */
757
877
  protected InternalRunView<T = unknown>(params: RunViewParams, contextUser?: UserInfo): Promise<RunViewResult<T>>;
878
+ /**
879
+ * Determines whether a RunView invocation is eligible for process-wide single-flight
880
+ * coalescing across concurrent requests.
881
+ */
882
+ protected canCoalesceRunViewInFlight(params: RunViewParams | null | undefined, countExecutor?: (countSQL: string) => Promise<CountOnlyRow[]>): boolean;
883
+ /**
884
+ * Builds the deterministic single-flight key for an in-flight RunView execution.
885
+ * Includes connection string, entity/view identity, filter, orderBy, fields, resultType,
886
+ * pagination/keyset cursor, aggregates, and effective user role/row-filter security context.
887
+ */
888
+ protected buildSingleFlightRunViewKey(params: RunViewParams, contextUser?: UserInfo): string | null;
889
+ /**
890
+ * Shallow-clones a shared single-flight RunViewResult and its row objects so concurrent
891
+ * callers cannot mutate each other's result arrays or row properties in place.
892
+ */
893
+ protected cloneSingleFlightRunViewResult<T>(result: RunViewResult<unknown>): RunViewResult<T>;
894
+ /**
895
+ * Returns true when an identical read-only RunView is already in flight in the process-wide
896
+ * single-flight registry. Used by {@link InternalRunViews} so duplicate views in a batch can
897
+ * join an active query immediately without consuming a concurrency slot.
898
+ */
899
+ protected hasInFlightSingleFlightView(params: RunViewParams, contextUser?: UserInfo): boolean;
758
900
  /**
759
901
  * The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
760
902
  * direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
@@ -762,6 +904,35 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
762
904
  * Everything before that step — permissions, RLS, filter screening — is unchanged.
763
905
  */
764
906
  protected RunViewCore<T = unknown>(params: RunViewParams, contextUser?: UserInfo, countExecutor?: (countSQL: string) => Promise<CountOnlyRow[]>): Promise<RunViewResult<T>>;
907
+ private executeRunViewCore;
908
+ /** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
909
+ protected LoadRunViewEntity(params: RunViewParams, contextUser?: UserInfo): Promise<MJUserViewEntityExtended | null>;
910
+ /**
911
+ * Works out a stored view's property values before the cache lookup (see
912
+ * {@link ProviderBase.PrepareRunViewProperties}). The resolved values, token defaults included,
913
+ * replace `Properties` and `ServerProperties`, so the fingerprint keys on what the run will use,
914
+ * and RunViewCore resolving them again yields the same predicates. A run that would be refused
915
+ * is left as it is and kept out of the cache; RunViewCore refuses it with its message. A view
916
+ * that cannot be loaded is left to RunViewCore too, which reports it as it always has.
917
+ */
918
+ protected PrepareRunViewProperties(params: RunViewParams, contextUser?: UserInfo): Promise<void>;
919
+ /**
920
+ * Checks a stored view's declared properties and works out each one's value for this run.
921
+ * @returns null when the view declares none and the run sends none
922
+ * @throws on a malformed definition, any refusal {@link ResolveViewPropertyValues} makes, or a
923
+ * property with a value whose target field the user cannot read
924
+ */
925
+ protected ResolveRunViewPropertyValues(viewEntity: MJUserViewEntityExtended | null, entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): {
926
+ Declared: UserViewProperty[];
927
+ Values: ViewPropertyValues;
928
+ } | null;
929
+ /**
930
+ * The WHERE clause a stored view's properties add to this run: '' when there are none.
931
+ * Screened like any caller clause, though it is built only from typed literals.
932
+ */
933
+ protected BuildViewPropertyFilter(viewEntity: MJUserViewEntityExtended | null, entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): string;
934
+ /** The field-security check other predicates get: a property with a value may not filter a field the user cannot read. */
935
+ private assertViewPropertyFieldsReadable;
765
936
  protected InternalRunViews<T = unknown>(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewResult<T>[]>;
766
937
  /**
767
938
  * All-`count_only` batch: every view runs the normal per-view path (so every
@@ -771,6 +942,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
771
942
  * failure is thrown, as on the per-view path.
772
943
  */
773
944
  protected RunCoalescedCountBatch<T = unknown>(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewResult<T>[]>;
945
+ /**
946
+ * One view of a `RunViews` batch. A field-security refusal of this view becomes this view's
947
+ * `Success: false` result, carrying the refusal's message, so it does not fail the views
948
+ * batched with it. Any other error is thrown, as a single RunView throws it.
949
+ */
950
+ protected runBatchedView<T = unknown>(params: RunViewParams, contextUser?: UserInfo): Promise<RunViewResult<T>>;
774
951
  /**************************************************************************/
775
952
  /**************************************************************************/
776
953
  /**
@@ -832,8 +1009,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
832
1009
  * - escapes LIKE metacharacters (%, _, [, ]) in user input with ESCAPE '\\',
833
1010
  * - skips fields that are not sensible text-search targets (non-text types,
834
1011
  * unbounded text columns when FTX is off).
1012
+ *
1013
+ * @param deniedFields - The request's denied set (see ResolveRequestDeniedReadFields), so the
1014
+ * searched columns match the ones its cache key and SELECT list were built from. Read from
1015
+ * the entity for `contextUser` when omitted.
835
1016
  */
836
- protected createViewUserSearchSQL(entityInfo: EntityInfo, userSearchString: string, contextUser?: UserInfo): string;
1017
+ protected createViewUserSearchSQL(entityInfo: EntityInfo, userSearchString: string, contextUser?: UserInfo, deniedFields?: Set<string>): string;
837
1018
  /**
838
1019
  * ORDER BY column list covering EVERY primary key column of the entity, quoted for the dialect
839
1020
  * — `[ID]` for a single-column key, `[OrderID], [LineNo]` for a composite one. Used as the
@@ -907,6 +1088,19 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
907
1088
  * saved-view save gate (`MJUserViewEntityServer`).
908
1089
  */
909
1090
  ScreenClientClause(clause: string | null | undefined, label: string, contextUser?: UserInfo, entityInfo?: EntityInfo): void;
1091
+ /**
1092
+ * The field-security error a failed RunView must raise, or null to report the failure as
1093
+ * usual: a {@link FieldSecurityError} raised along the way, or — for a caller denied fields on
1094
+ * `entity` — a database "no such column" rejection, rewritten into the error a denied column
1095
+ * gets ({@link FieldSecuritySQLGate.ErrorForInvalidColumn}).
1096
+ */
1097
+ protected fieldSecurityErrorFor(error: unknown, entity: EntityInfo | null, user: UserInfo | undefined): Error | null;
1098
+ /**
1099
+ * For a caller denied fields on `entity`, throws the field-security error when an aggregate was
1100
+ * refused because it names a column the entity does not have. A denied column in an aggregate is
1101
+ * refused by the gate with that error, so an unknown one must not answer differently.
1102
+ */
1103
+ protected assertAggregateRefusalsAreNotColumnProbes(errors: AggregateResult[], entity: EntityInfo, user: UserInfo): void;
910
1104
  /**
911
1105
  * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
912
1106
  * Any user who can save a view can write its WhereClause, directly or through FilterState or a
@@ -968,6 +1162,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
968
1162
  GetRunViewsDatabaseStatus(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewDatabaseStatus[]>;
969
1163
  /** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
970
1164
  private buildDatabaseStatusItems;
1165
+ /**
1166
+ * The field-security key of one request, built once per request (`params` object) and user.
1167
+ * A smart-cache-check item asks for it from each leg — its browser freshness check, the
1168
+ * server-cache lookup and the cache write — and the answer cannot change within the request:
1169
+ * the denied set it is built from is already resolved once per request.
1170
+ */
1171
+ protected ComputeRunViewFLSFingerprintKey(params: RunViewParams, contextUser?: UserInfo): string;
1172
+ private readonly _requestFLSKeys;
1173
+ /** What a request's field-security key is about: its entity, or the saved view it names. */
1174
+ private static flsKeyTarget;
1175
+ /** The message refusing `user` Read on `entityInfo`, or null when the user may read it. */
1176
+ private readPermissionError;
971
1177
  /**
972
1178
  * Smart cache validation for batch RunViews.
973
1179
  * For each view request, if cacheStatus is provided, checks if the cache is current
@@ -988,7 +1194,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
988
1194
  * entity whose view does not carry it, instead of comparing by count alone the way
989
1195
  * `BaseEngine.SweepAgainstDatabase` documents.
990
1196
  */
991
- protected BuildCacheStatusSQL(entityInfo: EntityInfo, effectiveView: string, whereSQL: string): string;
1197
+ protected BuildCacheStatusSQL(entityInfo: EntityInfo, effectiveView: string, whereSQL: string, schemaNameOverride?: string): string;
992
1198
  /**
993
1199
  * Executes cache status checks for multiple views.
994
1200
  * Default: parallel individual queries (works on all platforms).
@@ -1044,7 +1250,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1044
1250
  * infinite loop / duplicate processing in deep-pagination jobs. Aggregates and a non-empty
1045
1251
  * UserSearchString likewise can't be evaluated remotely. Throws a clear error naming the param.
1046
1252
  */
1047
- protected assertExternalRunViewParamsSupported(params: RunViewParams, entityName: string): void;
1253
+ protected assertExternalRunViewParamsSupported(params: RunViewParams, entityName: string, viewEntity?: MJUserViewEntityExtended | null): void;
1254
+ /**
1255
+ * Field-level security on the clauses an external-data-source read hands its driver: the
1256
+ * caller's own, merged with a saved view's stored ones. The same gates the SQL path applies to
1257
+ * the clauses it runs; the external dispatch returns before that path, and the driver runs
1258
+ * the clauses remotely, where nothing else checks them.
1259
+ */
1260
+ protected assertExternalClausesRespectFieldSecurity(entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): void;
1261
+ /**
1262
+ * An external driver's rows without the columns `user` may not read. The driver returns the
1263
+ * entity's columns at full width, and the result-path projection resolves the entity only from
1264
+ * an `EntityName` or a loaded `ViewEntity`, so a request naming only a `ViewID` would keep
1265
+ * them: the entity resolved here is named explicitly.
1266
+ */
1267
+ protected projectExternalRowsForCaller<T>(rows: T[], entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): T[];
1268
+ /**
1269
+ * Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
1270
+ * narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
1271
+ * caller's width instead of finding no copy and falling back to the decrypted rows.
1272
+ */
1273
+ private carryCiphertextRowsForCache;
1048
1274
  /**
1049
1275
  * Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
1050
1276
  * external dispatch. The external branch returns before the normal SQL path that applies
@@ -1054,10 +1280,19 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1054
1280
  * when there is no saved view.
1055
1281
  */
1056
1282
  protected mergeExternalViewParams(params: RunViewParams, viewEntity: MJUserViewEntityExtended | null, user: UserInfo): Promise<RunViewParams>;
1283
+ /**
1284
+ * True when a browser's cache status carries a field-security key (see
1285
+ * `ProviderBase.ComputeFieldSecurityCacheStatusKey`) other than the one this server computes
1286
+ * for `user` and `params`: the browser's slot was filled for a different set of columns, so
1287
+ * its row count and newest timestamp say nothing about whether it is current. False when the
1288
+ * status carries no key.
1289
+ */
1290
+ private cacheStatusFieldSecurityDiffers;
1057
1291
  /**
1058
1292
  * Checks the server's LocalCacheManager for cached data matching the client's request.
1059
- * Returns the resolution if found (either 'current' or server-cached data to serve),
1060
- * or null if the server cache doesn't have this data.
1293
+ * Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
1294
+ * 'needs_verification' when the server slot's freshness window has elapsed),
1295
+ * or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
1061
1296
  */
1062
1297
  private resolveFromServerCache;
1063
1298
  /**
@@ -1067,20 +1302,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1067
1302
  /**
1068
1303
  * Runs a differential query and returns only changes since the client's cached state.
1069
1304
  * Includes updated/created rows and deleted record IDs.
1070
- * Falls back to full query if hidden deletes are detected.
1305
+ * Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
1071
1306
  */
1072
1307
  protected runDifferentialQueryAndReturn<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, clientMaxUpdatedAt: string, clientRowCount: number, serverStatus: {
1073
1308
  maxUpdatedAt?: string;
1074
1309
  rowCount?: number;
1075
1310
  }, whereSQL: string, viewIndex: number, contextUser?: UserInfo, callerFields?: string[] | null): Promise<RunViewWithCacheCheckResult<T>>;
1311
+ /**
1312
+ * Formats a client timestamp as ISO 8601 for a SQL literal.
1313
+ * Throws when the value is not a date.
1314
+ */
1315
+ private toSQLTimestamp;
1076
1316
  /**
1077
1317
  * Gets IDs of records deleted since a given timestamp.
1078
- * Uses dialect-neutral quoting. Subclasses can override for parameterized queries.
1318
+ * Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
1319
+ * Subclasses can override for parameterized queries.
1079
1320
  */
1080
1321
  protected getDeletedRecordIDsSince(entityID: string, sinceTimestamp: string, contextUser?: UserInfo): Promise<string[]>;
1081
1322
  /**
1082
1323
  * Gets rows updated/created since a given timestamp.
1083
- * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy.
1324
+ * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
1325
+ * timestamp in ISO 8601 form as its own predicate group.
1084
1326
  */
1085
1327
  protected getUpdatedRowsSince<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, sinceTimestamp: string, whereSQL: string, contextUser?: UserInfo): Promise<T[]>;
1086
1328
  /**************************************************************************/
@@ -1092,6 +1334,14 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1092
1334
  * the query has no CacheValidationSQL configured.
1093
1335
  */
1094
1336
  RunQueriesWithCacheCheck<T = unknown>(params: RunQueryWithCacheCheckParams[], contextUser?: UserInfo): Promise<RunQueriesWithCacheCheckResponse<T>>;
1337
+ /**
1338
+ * The authorization of one {@link RunQueriesWithCacheCheck} item before it is routed. An item
1339
+ * that may be answered "current" without running — it carries a cache status for this
1340
+ * definition and the query has validation SQL — is checked in full on its rendering here. Every
1341
+ * other item runs, and the run checks the rendering it executes, so only the render-free part
1342
+ * is checked here rather than rendering the query twice.
1343
+ */
1344
+ private authorizeCacheCheckedQuery;
1095
1345
  /**
1096
1346
  * B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
1097
1347
  * cache HIT that the miss path enforces. Resolution uses `resolveQuery()` (QueryEngine as
@@ -1101,6 +1351,13 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1101
1351
  * applies before a real execution. The base's roles-only check would let a user read cached
1102
1352
  * rows of a query whose underlying entities they cannot read.
1103
1353
  *
1354
+ * The run-time checks (`UserCanRunRenderedSQL`: entities read by the SQL itself, and field-level
1355
+ * security) run against the query rendered with the request's own parameters: the SQL the miss
1356
+ * path would check and execute for this slot, since the slot's fingerprint carries those
1357
+ * parameters and its definition hash the query's SQL. A user the miss path would refuse is never
1358
+ * served the slot; a rendering that fails is treated as not authorized, so the request falls
1359
+ * through to execution and gets that path's error.
1360
+ *
1104
1361
  * Non-throwing by contract: any resolution error degrades to `resolvable: false`, which the
1105
1362
  * gate treats as "fall through to authorized execution" — one extra query run, never an
1106
1363
  * unauthorized serve and never a crashed cache path.
@@ -1131,9 +1388,101 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1131
1388
  *
1132
1389
  * @param query - The resolved MJQueryEntityExtended to validate
1133
1390
  * @param contextUser - The user attempting to execute the query
1391
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1392
+ * refusal echoes it and nothing else. The query's ID when omitted.
1134
1393
  * @throws Error if the user does not have permission to run the query
1135
1394
  */
1136
- protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo): void;
1395
+ protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo, requestedLabel?: string): void;
1396
+ /**
1397
+ * For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
1398
+ * current approval — status Approved and a stored fingerprint equal to the fingerprint of the
1399
+ * definition this run executes. The fingerprint is worked out here, from the same
1400
+ * `QueryEngine` metadata the run renders, never from a caller's value.
1401
+ *
1402
+ * @throws Error naming the first query whose approval is not current
1403
+ */
1404
+ protected ValidateQueryApprovalAsync(query: MJQueryEntityExtended, render: RenderResult): Promise<void>;
1405
+ /** The context tokens a query reads, with every query it composes, as the `QueryEngine` holds them. */
1406
+ private queryContextTokens;
1407
+ /**
1408
+ * SECURITY — authorizes a saved query against the SQL the run will execute (fully composed and
1409
+ * rendered), after {@link ValidateQueryForExecution} has passed: the entities that SQL reads,
1410
+ * and field-level security on every column it references. A template that injects an
1411
+ * identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
1412
+ * render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
1413
+ *
1414
+ * A refusal reads exactly like the message for a query that does not exist
1415
+ * ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
1416
+ *
1417
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1418
+ * refusal echoes it and nothing else. The query's ID when omitted.
1419
+ * @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
1420
+ * `alias.*` that reaches only the output reads an entity the user is denied a field on.
1421
+ * @throws Error when the user may not run this rendering of the query
1422
+ */
1423
+ protected ValidateRenderedQueryForExecution(query: MJQueryEntityExtended, renderedSQL: string, contextUser?: UserInfo, requestedLabel?: string): {
1424
+ NeedsColumnFiltering: boolean;
1425
+ };
1426
+ /**
1427
+ * The message for a saved query that does not exist or that the caller may not run. The two
1428
+ * are worded identically, so a refusal does not confirm that the query, or anything it reads,
1429
+ * exists.
1430
+ *
1431
+ * It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
1432
+ * looked up from the resolved query: a refusal of a request by ID that named the query would
1433
+ * both differ from that request's not-found message and disclose the query's name.
1434
+ *
1435
+ * @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
1436
+ */
1437
+ static QueryUnavailableMessage(label: string): string;
1438
+ /**
1439
+ * The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
1440
+ * name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
1441
+ */
1442
+ static RequestedQueryLabel(params: Pick<RunQueryParams, 'QueryID' | 'QueryName' | 'CategoryPath'>): string;
1443
+ /** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
1444
+ private queryRunRefusalMessage;
1445
+ /**
1446
+ * The OPERATOR's record of why a run was refused. The refusal returned to the caller is
1447
+ * {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
1448
+ * that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
1449
+ *
1450
+ * Without it a refusal is unattributable: the query's own role list, SQL the field-security
1451
+ * gate could not read, and a field-security violation all end in the same caller message.
1452
+ *
1453
+ * Previously only the field-security case logged anything, and only at `verboseOnly`, which
1454
+ * CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
1455
+ * bundles refusing together) could not be diagnosed from the logs at all. Called from every
1456
+ * refusal gate, so no path is silent.
1457
+ *
1458
+ * The loaded-role count is here because an empty or undefined `UserRoles` denies every
1459
+ * permission-bearing query at once — exactly the all-or-nothing signature those runs show.
1460
+ * Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
1461
+ * to ask and it costs one integer.
1462
+ */
1463
+ private logQueryRunRefusal;
1464
+ /**
1465
+ * The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
1466
+ * refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
1467
+ * projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
1468
+ * its denied columns dropped instead of being refused.
1469
+ */
1470
+ private checkRenderedQuery;
1471
+ /** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
1472
+ private static readonly projectionStarMemo;
1473
+ /**
1474
+ * The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
1475
+ * denied a field on some entity and only when the text holds a `*`; undefined otherwise.
1476
+ */
1477
+ private projectionStarOffsets;
1478
+ /**
1479
+ * The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
1480
+ * and the run-time checks on the query rendered with `parameters`. A rendering that fails
1481
+ * refuses, carrying the rendering's error.
1482
+ */
1483
+ private authorizeQueryRun;
1484
+ /** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
1485
+ private static roleListGrants;
1137
1486
  /**
1138
1487
  * Resolves a category path string to a QueryCategoryInfo ID.
1139
1488
  */
@@ -1196,32 +1545,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1196
1545
  * {@link buildMaterializedReadQuery}).
1197
1546
  */
1198
1547
  private static readonly MATERIALIZED_SURROGATE_ORDER_COLUMN;
1199
- /** Quotes a SQL identifier for the target engine (SQL Server `[x]`, PostgreSQL `"x"`), escaping the closer. */
1200
- private static quoteMaterializedIdentifier;
1201
1548
  /**
1202
1549
  * PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
1203
1550
  * output columns, the materialized view (schema + name), the persisted read-filter spec, the caller's
1204
- * parameter values, and the platform, returns `{ sql, parameters }` whose WHERE injects each spec
1205
- * predicate as `column <op> <placeholder>` with the value **bound** (SQL Server `?`, PostgreSQL `$n`) —
1206
- * never interpolating a caller value (SQL-injection-safe by construction).
1551
+ * parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
1552
+ * predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
1553
+ * value (SQL-injection-safe by construction).
1554
+ *
1555
+ * With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
1556
+ * a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
1557
+ * placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
1558
+ * varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
1559
+ * Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
1560
+ * ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
1561
+ * dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
1207
1562
  *
1208
1563
  * Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
1209
1564
  * the caller falls back to running live (always correct): an operator outside the safe set, a spec
1210
1565
  * parameter the caller did not supply (the live query would apply the param's default), a null value,
1211
- * or an empty/non-array value for a list (`IN`/`NOT IN`) predicate. No IO — fully unit-testable.
1566
+ * an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
1567
+ * known type or a value its type cannot hold. No IO — fully unit-testable.
1212
1568
  */
1213
- /**
1214
- * True if `sql`'s top-level SELECT carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
1215
- * {@link buildMaterializedReadQuery} emits no ORDER BY and the snapshot is built with the source's top-level
1216
- * ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and therefore its
1217
- * pagination under StartRow/MaxRows — is preserved) rather than from the unordered snapshot. Parse failure or
1218
- * an un-reasoned statement shape returns `true` (refuse-to-live: treat unknown as ordered rather than risk
1219
- * serving mis-ordered pages). Mirrors MaterializationRefresher.stripTopLevelOrderBy's AST detection.
1220
- *
1221
- * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
1222
- * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
1223
- */
1224
- static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1225
1569
  static buildMaterializedReadQuery(opts: {
1226
1570
  outputColumns: string[];
1227
1571
  schemaName: string;
@@ -1236,11 +1580,32 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1236
1580
  /** Declared parameter type per paramName (from MJ: Query Parameters). Drives type-faithful binding so a
1237
1581
  * scalar value matches the live path's typed literal instead of a raw string the DB implicitly coerces. */
1238
1582
  paramTypes?: Record<string, string>;
1239
- isPostgres: boolean;
1583
+ /** The dialect the read runs in: identifier quoting and parameter references. */
1584
+ dialect?: SQLDialect;
1585
+ /** @deprecated Pass {@link dialect}. True for PostgreSQL when no dialect is given. */
1586
+ isPostgres?: boolean;
1587
+ /** The snapshot's column types, column name → SQL type (`varchar(50)`, `datetime2(7)`). Names match ignoring case. */
1588
+ columnTypes?: Record<string, string>;
1240
1589
  }): {
1241
1590
  sql: string;
1242
1591
  parameters: unknown[];
1243
1592
  } | null;
1593
+ /**
1594
+ * The parameter list one materialized read builds, and how a value joins it: typed by the filtered
1595
+ * column when the snapshot's column types are known, otherwise untyped (the deprecated form).
1596
+ */
1597
+ private static materializedBinder;
1598
+ /**
1599
+ * Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
1600
+ * it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
1601
+ * provider from rewriting `?` in the statement text, which the legacy positional array form does
1602
+ * everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
1603
+ */
1604
+ private static bindNamedParameter;
1605
+ /** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
1606
+ private static namedParameterValue;
1607
+ /** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
1608
+ private static materializedPredicate;
1244
1609
  /**
1245
1610
  * Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
1246
1611
  * (see {@link buildMaterializedReadQuery}). This mirrors the TYPE-CONVERSION SWITCH of the live path's
@@ -1255,25 +1620,88 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1255
1620
  * the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
1256
1621
  * - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
1257
1622
  * - `boolean` → live truthiness: ONLY 'true' (case-insensitive) or a real boolean `true` is true; everything
1258
- * else is false (live never refuses a boolean). SQL Server binds BIT 1/0; PostgreSQL binds bool.
1623
+ * else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
1259
1624
  * - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
1260
1625
  * the naive input string: live applies the local→UTC shift, so binding the raw string would
1261
- * diverge for any timed value. Invalid date → refuse.
1626
+ * diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
1627
+ * suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
1628
+ * (error 241); the zone-less string is the same UTC wall-clock.
1262
1629
  * - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
1630
+ *
1631
+ * @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
1263
1632
  */
1264
1633
  private static coerceMaterializedScalarValue;
1634
+ /**
1635
+ * The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
1636
+ * describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
1637
+ * the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
1638
+ * be described (→ live).
1639
+ */
1640
+ private materializedColumnTypes;
1641
+ /** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
1642
+ private static readonly materializedColumnTypeMemo;
1643
+ /** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
1644
+ private static readonly topLevelOrderByMemo;
1645
+ /**
1646
+ * True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
1647
+ * {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
1648
+ * source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
1649
+ * therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
1650
+ * `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
1651
+ * (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
1652
+ * (SQL, dialect) in a bounded memo.
1653
+ *
1654
+ * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
1655
+ * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
1656
+ */
1657
+ static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1265
1658
  /**
1266
1659
  * Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
1267
1660
  * `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
1268
1661
  * persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
1269
1662
  * the live query (serving live is always correct — this is a transparent optimization, never a
1270
1663
  * correctness dependency).
1664
+ *
1665
+ * @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
1666
+ * check reads it; without it the check reads the platform SQL, where template syntax makes any
1667
+ * template query read as ordered (→ live).
1271
1668
  */
1272
- protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo): Promise<{
1669
+ protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>, renderedSQL?: string): Promise<{
1273
1670
  sql: string;
1274
1671
  parameters: unknown[];
1275
1672
  } | null>;
1276
1673
  protected InternalRunQuery(params: RunQueryParams, contextUser?: UserInfo): Promise<RunQueryResult>;
1674
+ /** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
1675
+ private static readonly describedStatementMemo;
1676
+ /**
1677
+ * Describes the result set of `sql` without returning its rows: each output column's name,
1678
+ * position, exact type, nullability and, for a pass-through column, the table or view column it
1679
+ * comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
1680
+ * runs it under `LIMIT 0` in a transaction that is rolled back).
1681
+ *
1682
+ * This base implementation describes nothing: it reports a failure. Providers for a database
1683
+ * that can describe a statement override it.
1684
+ *
1685
+ * @param sql - The rendered statement, in this provider's dialect.
1686
+ * @param _contextUser - The user the description is for.
1687
+ */
1688
+ DescribeStatement(sql: string, _contextUser?: UserInfo): Promise<DescribeStatementResult>;
1689
+ /**
1690
+ * SECURITY — the output columns of `renderedSQL` that `user` must not receive
1691
+ * ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
1692
+ *
1693
+ * @throws Error with the refusal message when the statement cannot be described: without the
1694
+ * description no column can be shown to be safe, so the run is refused.
1695
+ */
1696
+ private queryColumnFilter;
1697
+ /** The catalog entities `query`'s `QueryEntities` rows name. */
1698
+ private declaredQueryEntities;
1699
+ /**
1700
+ * `rows` with the filter's withheld columns dropped, as new row objects. A column the
1701
+ * description does not list is dropped too, and the description is forgotten: the statement's
1702
+ * shape changed since it was described (a view redefined), so the next run describes it again.
1703
+ */
1704
+ private filterQueryRows;
1277
1705
  /**
1278
1706
  * Batch query execution — runs all queries in parallel.
1279
1707
  */
@@ -1291,6 +1719,19 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1291
1719
  * when one is given. `TimeoutSeconds` limits every statement the run sends.
1292
1720
  */
1293
1721
  private runAdhocSQL;
1722
+ /**
1723
+ * SECURITY — what ad-hoc SQL may read, checked in the provider so that every in-process caller
1724
+ * (agents, data contexts, actions) is covered, not only the API's resolvers. `sql` is the
1725
+ * rendered statement, before the server's own paging wrap. Every table it reads must be an
1726
+ * entity base view the caller can read unscoped: CanRead with no row-level filter and no denied
1727
+ * field, because raw SQL applies neither ({@link ClientClauseScreen.AssertStatementReadsUnscopedEntityViews}).
1728
+ * The system user runs the server's own SQL and is not checked, but only when passed
1729
+ * explicitly: no user at all refuses, rather than falling back to the provider's own user,
1730
+ * which on a server is the system user.
1731
+ *
1732
+ * @throws Error when the caller may not run `sql`
1733
+ */
1734
+ protected AssertAdhocReadAllowed(sql: string, contextUser?: UserInfo): void;
1294
1735
  /**
1295
1736
  * The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
1296
1737
  * fails does not fail the run: some queries page fine but cannot be counted (duplicate column
@@ -1317,12 +1758,22 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1317
1758
  *
1318
1759
  * Delegates to {@link RenderPipeline.Run} for the composition → template
1319
1760
  * pipeline. Paging is handled separately by the caller (InternalRunQuery).
1761
+ *
1762
+ * @param dialectKey - The dialect the template's values render for (`sqlString` literals,
1763
+ * booleans); this provider's platform when omitted. An external data source's query passes
1764
+ * the source's dialect.
1320
1765
  */
1321
- protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo): {
1766
+ protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>, dialectKey?: string): {
1322
1767
  finalSQL: string;
1323
1768
  appliedParameters: Record<string, string>;
1324
1769
  renderResult: RenderResult;
1325
1770
  };
1771
+ /**
1772
+ * The dialect key of the external data source `query` reads, so its template values render as
1773
+ * that database reads literals; undefined when the source has no SQL dialect (a document
1774
+ * store), in which case the query renders with this provider's platform as before.
1775
+ */
1776
+ private externalQueryDialectKey;
1326
1777
  /**
1327
1778
  * Checks the columns an external-data-source query returned against the fields the Query
1328
1779
  * *declares* (its QueryField metadata) and logs a warning naming any declared field that
@@ -1345,7 +1796,13 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1345
1796
  * truth (a TTL of <= 0 disables caching for the source); field-drift warnings still apply to
1346
1797
  * freshly-fetched rows. Ad-hoc SQL (params.SQL) is never cached.
1347
1798
  */
1348
- protected runExternalQueryWithCache(query: MJQueryEntityExtended, finalSQL: string, params: RunQueryParams, router: ExternalDataSourceReadRouter, contextUser?: UserInfo): Promise<RunQueryResult>;
1799
+ protected runExternalQueryWithCache(query: MJQueryEntityExtended, finalSQL: string, params: RunQueryParams, router: ExternalDataSourceReadRouter, contextUser?: UserInfo, contextValues?: Record<string, string>): Promise<RunQueryResult>;
1800
+ /**
1801
+ * The result-cache fingerprint segment for what the server set on a run: its `ServerParameters`
1802
+ * and the `Context` values the template read. Empty when there are neither, so the fingerprint
1803
+ * is exactly what it was before either existed.
1804
+ */
1805
+ private serverSetFingerprintSegment;
1349
1806
  protected warnIfExternalQueryFieldsMissing(query: MJQueryEntityExtended, result: RunQueryResult): RunQueryResult;
1350
1807
  /**
1351
1808
  * Lower-layer execution: resolves composition, processes templates, executes SQL.
@@ -1367,17 +1824,36 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1367
1824
  * pipeline. Supports inline dependencies for transient query testing.
1368
1825
  */
1369
1826
  private resolveSpecParameters;
1827
+ /**
1828
+ * Where a server-side result cache keeps this run's rows: one slot per rendered statement and
1829
+ * dialect, and, when the caller is denied a field the statement's projection star reads, per
1830
+ * field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
1831
+ * runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
1832
+ * The rendered statement carries every parameter value, server-set ones included, so they need
1833
+ * no separate part of the key.
1834
+ */
1835
+ private queryResultCacheSlot;
1370
1836
  /**
1371
1837
  * Checks the query cache for existing results and returns them if valid.
1372
1838
  * Currently always returns null (query caching is not active).
1839
+ *
1840
+ * An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
1841
+ * stores under: it separates rendered statements and field-security profiles, so a slot never
1842
+ * serves one caller rows shaped for another. The returned rows must be the statement's full
1843
+ * output; the caller's withheld columns are dropped from them after the hit.
1373
1844
  */
1374
- protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1845
+ protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1375
1846
  /**
1376
1847
  * Checks the paged cache for a specific page of query results.
1377
1848
  * Returns a full RunQueryResult on hit, null on miss.
1378
1849
  * Currently always returns null (query caching is not active).
1850
+ *
1851
+ * An override must look the page up by `slotKey` alone: it names the rendered statement, the
1852
+ * caller's field-security profile and the page, so a page cached for a restricted caller is
1853
+ * never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
1854
+ * from the returned rows after the hit.
1379
1855
  */
1380
- protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1856
+ protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1381
1857
  /**
1382
1858
  * Executes the query SQL and tracks execution time.
1383
1859
  */
@@ -1425,10 +1901,25 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1425
1901
  /**
1426
1902
  * Caches query results if caching is enabled for the query.
1427
1903
  * Currently a no-op (query caching is not active).
1904
+ *
1905
+ * `results` is the statement's full output, before the caller's withheld columns are dropped.
1906
+ * An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
1428
1907
  */
1429
- protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[]): Promise<void>;
1908
+ protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[], _slotKey: string): Promise<void>;
1430
1909
  /**************************************************************************/
1431
1910
  /**************************************************************************/
1911
+ /**
1912
+ * The `WHERE` predicate that selects one record by its composite key, using dialect-neutral
1913
+ * quoting. Quoted key values have embedded single quotes escaped: a key value can contain
1914
+ * apostrophes (an object-valued soft key whose JSON carries free text), and an unescaped quote
1915
+ * both breaks the statement and is an injection vector.
1916
+ */
1917
+ protected BuildPrimaryKeyWhereClause(entityInfo: EntityInfo, compositeKey: CompositeKey): string;
1918
+ /**
1919
+ * Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
1920
+ * Server and PostgreSQL), in place, and returns the row.
1921
+ */
1922
+ protected TrimFixedWidthValues(entityInfo: EntityInfo, row: Record<string, unknown>): Record<string, unknown>;
1432
1923
  /**
1433
1924
  * Loads a single entity record by composite key, with optional relationship loading.
1434
1925
  * Uses dialect-neutral quoting for all SQL construction.
@@ -1522,6 +2013,30 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1522
2013
  * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
1523
2014
  */
1524
2015
  private resolveDatasetItemScope;
2016
+ /**
2017
+ * Why a caller's ItemFilter is refused by the field-level security gate — the same gate every
2018
+ * RunView filter passes — or null when it may run. The item's stored WhereClause is
2019
+ * administrator-defined dataset metadata, not a predicate the caller chose, so it is not checked.
2020
+ */
2021
+ private datasetItemFilterFieldSecurityRefusal;
2022
+ /**
2023
+ * The fields of a dataset item's entity the caller may not read, lowercased; empty when none,
2024
+ * when there is no caller, or for MJ_Metadata, which every principal loads to learn the schema.
2025
+ */
2026
+ private datasetItemDeniedFields;
2027
+ /**
2028
+ * The error a failed dataset batch reports to the caller. When the caller is denied fields on
2029
+ * an item's entity and the database rejected a column that does not exist, every item reports
2030
+ * the field-security error a denied column gets instead, so the two cannot be told apart.
2031
+ */
2032
+ private datasetBatchErrorForCaller;
2033
+ /**
2034
+ * Dataset item rows as the caller may see them: denied columns removed, and Record Changes
2035
+ * payloads narrowed. Cached rows are shared and full width, so this always builds new rows
2036
+ * rather than narrowing the cached ones. MJ_Metadata is exempt for the reason given on
2037
+ * {@link datasetItemDeniedFields}.
2038
+ */
2039
+ private projectDatasetRowsForCaller;
1525
2040
  /**
1526
2041
  * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
1527
2042
  * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
@@ -1550,6 +2065,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1550
2065
  * status fails with the refusal and no status SQL runs.
1551
2066
  */
1552
2067
  GetDatasetStatusByName(datasetName: string, itemFilters?: DatasetItemFilterType[], contextUser?: UserInfo, providerToUse?: IMetadataProvider): Promise<DatasetStatusResultType>;
2068
+ /**
2069
+ * Builds the lookup key for {@link _lastDatasetStatusByName} from dataset name and item filters.
2070
+ */
2071
+ private buildDatasetStatusCacheKey;
1553
2072
  /**************************************************************************/
1554
2073
  /**************************************************************************/
1555
2074
  /**
@@ -1561,8 +2080,16 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1561
2080
  * binary column can still be named explicitly. When the entity's metadata is not loaded yet —
1562
2081
  * the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
1563
2082
  * are converted to base64 by the caller.
2083
+ *
2084
+ * `deniedFields` (lowercased) are the columns the caller may not read. They are never
2085
+ * selected: a named one is dropped, and an item that names none selects every readable column.
2086
+ */
2087
+ protected getColumnsForDatasetItem(item: Record<string, unknown>, datasetName: string, deniedFields?: Set<string>): string | null;
2088
+ /**
2089
+ * `columns` without the denied ones, quoted and joined. When every one is denied, the primary
2090
+ * key columns are selected instead, which are never denied, so the read still has a shape.
1564
2091
  */
1565
- protected getColumnsForDatasetItem(item: Record<string, unknown>, datasetName: string): string | null;
2092
+ private readableDatasetColumns;
1566
2093
  /**************************************************************************/
1567
2094
  /**************************************************************************/
1568
2095
  /**
@@ -1609,7 +2136,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1609
2136
  * `AIEngine.Models` to recover the driver class / APIName and call
1610
2137
  * `EmbedText(model, text)` directly. If the EntityDocument does not specify
1611
2138
  * a model (or the model isn't loaded) we fall back to
1612
- * `EmbedTextLocal` (highest-power local model) only as a last resort.
2139
+ * `EmbedTextLocal` (the default local model) only as a last resort. The search
2140
+ * text is embedded as a query (`inputType: 'query'`). The index's
2141
+ * `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
2142
+ * the model's native size.
1613
2143
  *
1614
2144
  * Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
1615
2145
  * which rehydrates the vector pool for `entityDocumentId` from