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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,18 +15,21 @@
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, 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
+ import { type BalancedFragmentOptions } from '@memberjunction/sql-parser';
21
22
  import { type RenderResult } from './renderPipeline.js';
22
23
  import { CRUDSprocType } from './crudSprocFieldRules.js';
23
- import { SaveCoercedValue, SaveCallBinding, SaveSQLFragment } from './saveTypes.js';
24
+ import { SaveCoercedValue, SaveCallBinding, SaveSQLFragment, SaveReturnContext } from './saveTypes.js';
24
25
  import type { RecordChangePayload } from '@memberjunction/core';
25
26
  import { MJEntityAIActionEntity, MJQueryEntityExtended, MJUserViewEntityExtended } from '@memberjunction/core-entities';
26
27
  import { EntityAIActionParams } from '@memberjunction/aiengine';
27
28
  import { ScoredCandidate } from '@memberjunction/core';
28
29
  import { ActionResult } from '@memberjunction/actions-base';
29
30
  import { CountOnlyRow } from './countOnlyBatch.js';
31
+ import { type ClientClauseScreeningProvider } from './clientClauseScreen.js';
32
+ import { RecordChangeSnapshots } from './recordChangeSnapshot.js';
30
33
  /**
31
34
  * Configuration options for batch SQL execution.
32
35
  * Shared between GenericDatabaseProvider and platform-specific providers.
@@ -60,7 +63,7 @@ export declare class DoomedTransactionError extends Error {
60
63
  cause?: unknown;
61
64
  });
62
65
  }
63
- export declare abstract class GenericDatabaseProvider extends DatabaseProviderBase {
66
+ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBase implements ClientClauseScreeningProvider {
64
67
  /**************************************************************************/
65
68
  /**************************************************************************/
66
69
  /**
@@ -119,10 +122,37 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
119
122
  * each querying the database and broadcasting what they loaded.
120
123
  */
121
124
  Config(data: ProviderConfigDataBase, providerToUse?: IMetadataProvider): Promise<boolean>;
125
+ /**
126
+ * Bounded freshness window (in milliseconds) for server-side `LocalCacheManager` RunView
127
+ * and Dataset slots. Within this window after a slot was written or last verified against
128
+ * SQL, `RunViewsWithCacheCheck` and `GetDatasetByName` can trust the in-memory slot with
129
+ * zero DB hits. Once this window elapses, the next check performs a lightweight batched
130
+ * SQL status probe (`COUNT(*)` + `MAX(__mj_UpdatedAt)`) to auto-reconcile any out-of-band
131
+ * SQL mutations (e.g., migrations, `mj sync push`, external scripts) without requiring a
132
+ * server restart.
133
+ */
134
+ protected ServerCacheVerificationTTLMs: number;
135
+ /**
136
+ * Public accessor for {@link ServerCacheVerificationTTLMs}.
137
+ * Set to `0` to force SQL status verification on every cache check.
138
+ */
139
+ get ServerCacheVerificationTTL(): number;
140
+ set ServerCacheVerificationTTL(value: number);
141
+ /**
142
+ * Most recent authoritative SQL status result per dataset key (`datasetName + filterKey`),
143
+ * populated by `GetDatasetStatusByName` and consumed by `GetDatasetByName` to reconcile
144
+ * cached dataset item slots against live SQL row counts and timestamps.
145
+ */
146
+ private _lastDatasetStatusByName;
122
147
  /**************************************************************************/
123
148
  /**************************************************************************/
124
149
  private static _sqlLoggingSessionsKey;
150
+ private static _cachedSqlLoggingSessions;
125
151
  private get _sqlLoggingSessions();
152
+ /**
153
+ * Fast O(1) check for whether any SQL logging sessions are currently active.
154
+ */
155
+ protected get HasActiveSqlLoggingSessions(): boolean;
126
156
  /**
127
157
  * Creates a new SQL logging session that will capture all SQL operations to a file.
128
158
  * Returns a disposable session object that must be disposed to stop logging.
@@ -270,6 +300,8 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
270
300
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
271
301
  */
272
302
  protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo): Promise<Record<string, unknown>[]>;
303
+ private static _encryptedFieldsCache;
304
+ private static getEncryptedFields;
273
305
  /**
274
306
  * Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
275
307
  * own read paths but returns entity rows — the transaction groups. Every row a provider hands
@@ -496,12 +528,44 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
496
528
  * orchestrator preserves.
497
529
  */
498
530
  protected abstract RenderSaveCallBinding(entity: BaseEntity, fieldValues: Map<EntityFieldInfo, unknown>, isUpdate: boolean, spName: string): SaveCallBinding;
531
+ /**
532
+ * Builds the dialect-quoted, comma-separated column list for {@link EntityInfo.DatestampReturnFields}
533
+ * (primary key column(s) followed by `__mj_CreatedAt` and `__mj_UpdatedAt`) using {@link QuoteIdentifier}.
534
+ *
535
+ * Examples:
536
+ * - SQL Server: `[ID], [__mj_CreatedAt], [__mj_UpdatedAt]`
537
+ * - PostgreSQL: `"ID", "__mj_CreatedAt", "__mj_UpdatedAt"`
538
+ */
539
+ protected GetDatestampSelectColumnsSQL(entityInfo: EntityInfo): string;
540
+ /**
541
+ * Resolves the compile-time vs. effective runtime {@link SaveReturnContext} for a save operation.
542
+ *
543
+ * Centralizes the `SaveReturnMode` decision logic in `GenericDatabaseProvider` so dialect providers
544
+ * (`SQLServerDataProvider`, `PostgreSQLDataProvider`, and future providers) never duplicate the
545
+ * rules for:
546
+ * - `spReturnMode`: the return shape compiled into the stored procedure / function (`EntityInfo.SaveReturnMode`).
547
+ * - `effectiveReturnMode`: the return shape requested for this call (`options?.SaveReturnMode ?? spReturnMode`).
548
+ * - `needsDatestampProjection`: `true` when the compiled routine returns the full row (`spReturnMode === 'full'`)
549
+ * but the caller requested `'datestamps_only'` at runtime, requiring the provider to project the result down
550
+ * to `datestampSelectColumnsSQL` before wire transmission.
551
+ */
552
+ protected ResolveSaveReturnContext(entity: BaseEntity, options?: EntitySaveOptions): SaveReturnContext;
499
553
  /**
500
554
  * Wraps the bare SP-call binding with the dialect's result-capture
501
555
  * pattern. SQL Server emits `DECLARE @ResultTable + INSERT INTO @ResultTable EXEC + SELECT * FROM @ResultTable`;
502
556
  * PostgreSQL emits the bare `SELECT * FROM schema."fn"(...)`.
503
557
  */
504
- protected abstract WrapSaveCallForResult(binding: SaveCallBinding, entity: BaseEntity, spName: string): SaveSQLFragment;
558
+ protected abstract WrapSaveCallForResult(binding: SaveCallBinding, entity: BaseEntity, spName: string, options?: EntitySaveOptions, returnContext?: SaveReturnContext): SaveSQLFragment;
559
+ /**
560
+ * Projects a save call's result set down to {@link SaveReturnContext.datestampSelectColumnsSQL}
561
+ * when a caller requests `SaveReturnMode: 'datestamps_only'` at runtime on an entity whose
562
+ * compiled stored procedure / function returns the full row (`returnContext.needsDatestampProjection === true`).
563
+ *
564
+ * - SQL Server captures `EXEC` into `DECLARE @ResultTable TABLE (...)` and emits
565
+ * `SELECT [ID], [__mj_CreatedAt], [__mj_UpdatedAt] FROM @ResultTable;`.
566
+ * - PostgreSQL emits `SELECT "ID", "__mj_CreatedAt", "__mj_UpdatedAt" FROM schema."fn"(...)`.
567
+ */
568
+ protected abstract ProjectSaveCallToDatestamps(binding: SaveCallBinding, entity: BaseEntity, spName: string, returnContext: SaveReturnContext): SaveSQLFragment;
505
569
  /**
506
570
  * Wraps an already-result-captured save SQL with the dialect's
507
571
  * record-change emission. SQL Server inlines `EXEC spCreateRecordChange_Internal`
@@ -511,7 +575,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
511
575
  * Orchestrator only calls this when `ShouldTrackRecordChanges` is true
512
576
  * and `BuildRecordChangePayload` returned a non-null payload.
513
577
  */
514
- protected abstract WrapSaveCallWithRecordChange(saveSQL: SaveSQLFragment, binding: SaveCallBinding, payload: RecordChangePayload, entity: BaseEntity): SaveSQLFragment;
578
+ protected abstract WrapSaveCallWithRecordChange(saveSQL: SaveSQLFragment, binding: SaveCallBinding, payload: RecordChangePayload, entity: BaseEntity, options?: EntitySaveOptions, returnContext?: SaveReturnContext): SaveSQLFragment;
515
579
  /**
516
580
  * Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
517
581
  * record saves for migration replay (SQL Server's Metadata_Sync migrations) override
@@ -543,6 +607,67 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
543
607
  * the design and the rev-3 lesson that motivated this shape.
544
608
  */
545
609
  protected GenerateSaveSQL(entity: BaseEntity, isNew: boolean, user: UserInfo, options?: EntitySaveOptions): Promise<SaveSQLResult>;
610
+ /**
611
+ * The old and new snapshots a save's Record Change is built from. The audit trail stores
612
+ * whole payloads and projects them per reader, so both snapshots describe the whole record
613
+ * whoever saves it.
614
+ *
615
+ * - **A user denied nothing** (unrestricted and system-user saves): the object's own values.
616
+ * No query, even when the object was loaded without some columns.
617
+ * - **A restricted user's update** (their object never holds the fields they cannot read):
618
+ * the stored values of those fields are read once and the snapshots are widened with them.
619
+ * The diff is unchanged, because a field the object never held has the same stored value
620
+ * on both sides.
621
+ * - **Create**: there is no stored row yet. A field the INSERT omits because the user may
622
+ * not supply it is left out rather than recorded with a value the record never got.
623
+ *
624
+ * The read runs on the save's connection: inside an open transaction it reads that
625
+ * transaction's state. A save queued in a transaction group is generated when `Save()` is
626
+ * called, so its snapshot reflects the row as of then — the same moment the object's own
627
+ * old values describe.
628
+ */
629
+ protected BuildRecordChangeSnapshots(entity: BaseEntity, isUpdate: boolean, user: UserInfo): Promise<RecordChangeSnapshots>;
630
+ /**
631
+ * Connections a save's SQL is being generated for, by entity object: the transaction a
632
+ * transaction group runs its items on. Set only for the duration of
633
+ * {@link GenerateSaveSQLReadingOn}.
634
+ */
635
+ private readonly _snapshotConnections;
636
+ /**
637
+ * Generates a save's SQL with any stored-row read its Record Change snapshot needs run on
638
+ * `connectionSource`. A transaction group that regenerates an item's SQL while its own
639
+ * transaction is open passes that transaction, so the read sees the group's earlier writes and
640
+ * never waits on the locks the group itself holds.
641
+ */
642
+ protected GenerateSaveSQLReadingOn(entity: BaseEntity, isNew: boolean, user: UserInfo, connectionSource?: object): Promise<SaveSQLResult>;
643
+ /** Full-width delete snapshots captured by {@link Delete}, consumed by `GenerateDeleteSQL`. */
644
+ private readonly _deleteSnapshots;
645
+ /**
646
+ * Deletes a record. Before the shared orchestration runs, a restricted user's delete reads the
647
+ * stored values of the fields their object never held, so the delete's `FullRecordJSON` — the
648
+ * snapshot a deleted record is restored from — is full width. `GenerateDeleteSQL` is
649
+ * synchronous, so the snapshot is captured here and handed to it through
650
+ * {@link RecordChangeDeleteSnapshot}. A user denied nothing costs no extra query.
651
+ */
652
+ Delete(entity: BaseEntity, options: EntityDeleteOptions, user: UserInfo): Promise<boolean>;
653
+ /** Reads and stores the full-width delete snapshot when one is needed; true when it stored one. */
654
+ private captureDeleteSnapshot;
655
+ /**
656
+ * The record snapshot a delete's Record Change carries: the full-width snapshot {@link Delete}
657
+ * captured, else `narrow` (the object's own values, which are already full width whenever no
658
+ * snapshot was needed).
659
+ */
660
+ protected RecordChangeDeleteSnapshot(entity: BaseEntity, narrow: Record<string, unknown>): Record<string, unknown>;
661
+ /**
662
+ * Reads the stored values of `columns` — the fields a snapshot lacks — for a Record Change
663
+ * snapshot. Provider-internal: no row-level filter and no field-security check, because the
664
+ * payload is stored unprojected and projected for each reader. The row gets the same
665
+ * post-processing as a `Load` (binary to base64, datetime adjustment, decryption,
666
+ * fixed-width trimming). Runs on the connection the save is generated for when one was named
667
+ * ({@link GenerateSaveSQLReadingOn}), else on the save's usual connection. Kept out of the SQL
668
+ * log, which records the save itself.
669
+ */
670
+ protected ReadStoredRowForRecordChange(entity: BaseEntity, user: UserInfo, columns: ReadonlySet<string>): Promise<Record<string, unknown> | null>;
546
671
  /**
547
672
  * Builds a platform-specific pagination clause.
548
673
  * SQL Server: `OFFSET X ROWS FETCH NEXT Y ROWS ONLY`
@@ -585,37 +710,34 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
585
710
  * `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
586
711
  * Server — both preserve case.
587
712
  */
588
- protected BuildTotalRowCountSQL(entityInfo: EntityInfo, usingPagination: boolean, maxRowsForQuery: number, baseViewOverride?: string): string | null;
713
+ protected BuildTotalRowCountSQL(entityInfo: EntityInfo, usingPagination: boolean, maxRowsForQuery: number, baseViewOverride?: string, schemaNameOverride?: string): string | null;
589
714
  /**
590
- * Resolves the view a RunView reads from: the entity's live base view by default, or its materialized
591
- * wrapper view when the caller opts into the snapshot via `DataSource: 'Materialized'` (plan §7). The
592
- * choice is explicit (never silent), so the same RLS/paging/field-selection apply against the identical shape.
593
- *
594
- * Two materialization shapes:
595
- * - **Base-view materialization** reuses the SOURCE entity, whose `BaseView` stays the LIVE view; the
596
- * snapshot lives beside it as `materialized_vw<CodeName>` (the name CodeGen's base-view path emits).
597
- * `'Materialized'` swaps the live view for that snapshot.
598
- * - **Query materialization** mints a NEW entity whose `BaseView` ALREADY IS the materialized wrapper
599
- * view (`materialized_vw<...>`), so there is no separate live source to swap — `'Materialized'` is a
600
- * no-op and we return the entity's own base view. (Deriving `materialized_vw<CodeName>` here would be
601
- * wrong: the minted entity's CodeName need not match the query-derived view name.)
602
- *
603
- * Convention-based for the base-view case: if the entity has no such materialization the wrapper view
604
- * won't exist and the read will error — opting into `'Materialized'` asserts the snapshot exists.
715
+ * Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
716
+ * optional loaded `MJUserViewEntityExtended`. An explicit empty string (`""`) on
717
+ * `params.AlternateBaseView` overrides any saved view pin back to `BaseView` (`undefined`).
718
+ */
719
+ protected resolveEffectiveAbvNameFromParams(params: RunViewParams | undefined, viewEntity?: MJUserViewEntityExtended | null): string | undefined;
720
+ /**
721
+ * Resolves the view a RunView reads from: an explicit or pinned `AlternateBaseView` when present,
722
+ * the entity's materialized wrapper view when `DataSource: 'Materialized'`, or the entity's live
723
+ * `BaseView` by default.
605
724
  */
606
- protected GetEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams): string;
725
+ protected GetEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, viewEntity?: MJUserViewEntityExtended | null, suppressDeprecationWarning?: boolean): string;
607
726
  /**
608
727
  * Async status-aware wrapper around {@link GetEffectiveBaseView} for the BASE-VIEW materialization case.
609
- * `GetEffectiveBaseView` name-swaps unconditionally, which (a) serves a `Building`/`DriftHold`/`Disabled`
610
- * snapshot — defeating "flag and hold" (§13/§17.2), since a base-view materialization reuses the source
611
- * entity and thus has no read-permission revoke to fall back on the way a minted query entity does — and
612
- * (b) hard-errors on a `Materialized` read of a non-materialized entity (missing view). This gates the swap
613
- * on an ACTIVE `MaterializedResult` and otherwise returns the LIVE base view (graceful fallback). The status
614
- * read uses `BypassCache` because DriftHold/Disabled are written by CodeGen via direct SQL (no BaseEntity
615
- * cache-invalidation event), so a cached status could otherwise be stale. Non-materialized reads and minted
616
- * query virtual entities (BaseView already `materialized_vw…`) skip the lookup entirely (no extra query).
617
728
  */
618
- protected resolveEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo): Promise<string>;
729
+ protected resolveEffectiveBaseView(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo, viewEntity?: MJUserViewEntityExtended | null): Promise<string>;
730
+ /**
731
+ * Resolves both the effective `{ schemaName, viewName }` for a RunView call, honoring:
732
+ * 1. Explicit `params.AlternateBaseView` (including `""` to force `BaseView` over a saved view pin)
733
+ * 2. Saved `UserView.DisplayState.alternateBaseView` (from `viewEntity`, `params.ViewEntity`, or loaded by `ViewID`/`ViewName`)
734
+ * 3. `DataSource: 'Materialized'`
735
+ * 4. `entityInfo.BaseView`
736
+ */
737
+ protected resolveEffectiveBaseViewTarget(entityInfo: EntityInfo, params: RunViewParams, contextUser?: UserInfo, viewEntity?: MJUserViewEntityExtended | null): Promise<{
738
+ schemaName: string;
739
+ viewName: string;
740
+ }>;
619
741
  /**
620
742
  * Reports whether a materialization-metadata `RunView` FAILED, logging the failure when it did.
621
743
  *
@@ -680,15 +802,52 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
680
802
  * Default: returns the clause unchanged.
681
803
  */
682
804
  protected TransformExternalSQLClause(clause: string, _entityInfo: EntityInfo): string;
805
+ /**
806
+ * Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
807
+ * WhereClause) stays inside the parentheses this provider puts around it, read with this
808
+ * provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
809
+ * security, which also carries API-key row filters and guest scope; a piece that closes its
810
+ * parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
811
+ * caller controls.
812
+ */
813
+ protected AssertClauseBalanced(clause: string, label: string, options?: BalancedFragmentOptions): void;
814
+ /**
815
+ * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
816
+ * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
817
+ * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
818
+ * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
819
+ * runs before this transform, so a rewrite that changes the caller's term cannot reach the
820
+ * hook's term.
821
+ */
822
+ protected PrepareExtraFilterSQL(extraFilter: string, entityInfo: EntityInfo): string;
683
823
  /**
684
824
  * Optionally wraps a view query with user view run logging.
685
825
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
686
826
  * Default: returns null (no view run logging).
687
827
  */
688
- protected executeSQLForUserViewRunLogging(_viewId: number, _entityInfo: EntityInfo, _effectiveBaseView: string, _whereSQL: string, _orderBySQL: string, _user: UserInfo): Promise<{
828
+ protected executeSQLForUserViewRunLogging(_viewId: number, _entityInfo: EntityInfo, _effectiveBaseView: string, _whereSQL: string, _orderBySQL: string, _user: UserInfo, _schemaNameOverride?: string): Promise<{
689
829
  executeViewSQL: string;
690
830
  runID: string;
691
831
  } | null>;
832
+ /**
833
+ * Maximum number of concurrent database view executions allowed within a single
834
+ * {@link InternalRunViews} batch. Prevents large `RunViews` batches from exhausting
835
+ * the connection pool in a single tick. Set to 0 or Infinity to disable the cap.
836
+ * Default: 8.
837
+ */
838
+ static MaxConcurrentViewsPerBatch: number;
839
+ /**
840
+ * Process-wide single-flight coalescing registry for in-flight read-only RunView executions.
841
+ * When multiple concurrent requests (across any per-request provider instance on the same
842
+ * server process) execute an identical non-transactional RunView simultaneously, only the
843
+ * first caller queries the database; joiners await the same promise and receive a shallow-cloned
844
+ * result object and Results array.
845
+ */
846
+ private static readonly _inFlightRunViews;
847
+ /**
848
+ * Number of currently in-flight coalesced RunView executions across this process.
849
+ */
850
+ static get InFlightRunViewCount(): number;
692
851
  /**
693
852
  * Shared InternalRunView implementation.
694
853
  * Handles: view resolution, permissions, field selection, WHERE clause building
@@ -696,6 +855,28 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
696
855
  * aggregates, parallel query execution, post-processing, and audit logging.
697
856
  */
698
857
  protected InternalRunView<T = unknown>(params: RunViewParams, contextUser?: UserInfo): Promise<RunViewResult<T>>;
858
+ /**
859
+ * Determines whether a RunView invocation is eligible for process-wide single-flight
860
+ * coalescing across concurrent requests.
861
+ */
862
+ protected canCoalesceRunViewInFlight(params: RunViewParams | null | undefined, countExecutor?: (countSQL: string) => Promise<CountOnlyRow[]>): boolean;
863
+ /**
864
+ * Builds the deterministic single-flight key for an in-flight RunView execution.
865
+ * Includes connection string, entity/view identity, filter, orderBy, fields, resultType,
866
+ * pagination/keyset cursor, aggregates, and effective user role/row-filter security context.
867
+ */
868
+ protected buildSingleFlightRunViewKey(params: RunViewParams, contextUser?: UserInfo): string | null;
869
+ /**
870
+ * Shallow-clones a shared single-flight RunViewResult and its row objects so concurrent
871
+ * callers cannot mutate each other's result arrays or row properties in place.
872
+ */
873
+ protected cloneSingleFlightRunViewResult<T>(result: RunViewResult<unknown>): RunViewResult<T>;
874
+ /**
875
+ * Returns true when an identical read-only RunView is already in flight in the process-wide
876
+ * single-flight registry. Used by {@link InternalRunViews} so duplicate views in a batch can
877
+ * join an active query immediately without consuming a concurrency slot.
878
+ */
879
+ protected hasInFlightSingleFlightView(params: RunViewParams, contextUser?: UserInfo): boolean;
699
880
  /**
700
881
  * The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
701
882
  * direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
@@ -703,6 +884,35 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
703
884
  * Everything before that step — permissions, RLS, filter screening — is unchanged.
704
885
  */
705
886
  protected RunViewCore<T = unknown>(params: RunViewParams, contextUser?: UserInfo, countExecutor?: (countSQL: string) => Promise<CountOnlyRow[]>): Promise<RunViewResult<T>>;
887
+ private executeRunViewCore;
888
+ /** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
889
+ protected LoadRunViewEntity(params: RunViewParams, contextUser?: UserInfo): Promise<MJUserViewEntityExtended | null>;
890
+ /**
891
+ * Works out a stored view's property values before the cache lookup (see
892
+ * {@link ProviderBase.PrepareRunViewProperties}). The resolved values, token defaults included,
893
+ * replace `Properties` and `ServerProperties`, so the fingerprint keys on what the run will use,
894
+ * and RunViewCore resolving them again yields the same predicates. A run that would be refused
895
+ * is left as it is and kept out of the cache; RunViewCore refuses it with its message. A view
896
+ * that cannot be loaded is left to RunViewCore too, which reports it as it always has.
897
+ */
898
+ protected PrepareRunViewProperties(params: RunViewParams, contextUser?: UserInfo): Promise<void>;
899
+ /**
900
+ * Checks a stored view's declared properties and works out each one's value for this run.
901
+ * @returns null when the view declares none and the run sends none
902
+ * @throws on a malformed definition, any refusal {@link ResolveViewPropertyValues} makes, or a
903
+ * property with a value whose target field the user cannot read
904
+ */
905
+ protected ResolveRunViewPropertyValues(viewEntity: MJUserViewEntityExtended | null, entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): {
906
+ Declared: UserViewProperty[];
907
+ Values: ViewPropertyValues;
908
+ } | null;
909
+ /**
910
+ * The WHERE clause a stored view's properties add to this run: '' when there are none.
911
+ * Screened like any caller clause, though it is built only from typed literals.
912
+ */
913
+ protected BuildViewPropertyFilter(viewEntity: MJUserViewEntityExtended | null, entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): string;
914
+ /** The field-security check other predicates get: a property with a value may not filter a field the user cannot read. */
915
+ private assertViewPropertyFieldsReadable;
706
916
  protected InternalRunViews<T = unknown>(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewResult<T>[]>;
707
917
  /**
708
918
  * All-`count_only` batch: every view runs the normal per-view path (so every
@@ -712,6 +922,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
712
922
  * failure is thrown, as on the per-view path.
713
923
  */
714
924
  protected RunCoalescedCountBatch<T = unknown>(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewResult<T>[]>;
925
+ /**
926
+ * One view of a `RunViews` batch. A field-security refusal of this view becomes this view's
927
+ * `Success: false` result, carrying the refusal's message, so it does not fail the views
928
+ * batched with it. Any other error is thrown, as a single RunView throws it.
929
+ */
930
+ protected runBatchedView<T = unknown>(params: RunViewParams, contextUser?: UserInfo): Promise<RunViewResult<T>>;
715
931
  /**************************************************************************/
716
932
  /**************************************************************************/
717
933
  /**
@@ -773,8 +989,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
773
989
  * - escapes LIKE metacharacters (%, _, [, ]) in user input with ESCAPE '\\',
774
990
  * - skips fields that are not sensible text-search targets (non-text types,
775
991
  * unbounded text columns when FTX is off).
992
+ *
993
+ * @param deniedFields - The request's denied set (see ResolveRequestDeniedReadFields), so the
994
+ * searched columns match the ones its cache key and SELECT list were built from. Read from
995
+ * the entity for `contextUser` when omitted.
776
996
  */
777
- protected createViewUserSearchSQL(entityInfo: EntityInfo, userSearchString: string, contextUser?: UserInfo): string;
997
+ protected createViewUserSearchSQL(entityInfo: EntityInfo, userSearchString: string, contextUser?: UserInfo, deniedFields?: Set<string>): string;
778
998
  /**
779
999
  * ORDER BY column list covering EVERY primary key column of the entity, quoted for the dialect
780
1000
  * — `[ID]` for a single-column key, `[OrderID], [LineNo]` for a composite one. Used as the
@@ -833,6 +1053,50 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
833
1053
  protected isTextSearchableType(field: EntityFieldInfo): boolean;
834
1054
  /**************************************************************************/
835
1055
  /**************************************************************************/
1056
+ /**
1057
+ * SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
1058
+ * Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
1059
+ * fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
1060
+ */
1061
+ protected AssertClauseFragmentIsSingleStatement(clause: string, label: string): void;
1062
+ /**
1063
+ * SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
1064
+ * against this provider's entities and dialect, with `contextUser` as the acting user. With
1065
+ * `entityInfo`, the clause is screened in the form this provider runs a client clause for that
1066
+ * entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
1067
+ * outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
1068
+ * saved-view save gate (`MJUserViewEntityServer`).
1069
+ */
1070
+ ScreenClientClause(clause: string | null | undefined, label: string, contextUser?: UserInfo, entityInfo?: EntityInfo): void;
1071
+ /**
1072
+ * The field-security error a failed RunView must raise, or null to report the failure as
1073
+ * usual: a {@link FieldSecurityError} raised along the way, or — for a caller denied fields on
1074
+ * `entity` — a database "no such column" rejection, rewritten into the error a denied column
1075
+ * gets ({@link FieldSecuritySQLGate.ErrorForInvalidColumn}).
1076
+ */
1077
+ protected fieldSecurityErrorFor(error: unknown, entity: EntityInfo | null, user: UserInfo | undefined): Error | null;
1078
+ /**
1079
+ * For a caller denied fields on `entity`, throws the field-security error when an aggregate was
1080
+ * refused because it names a column the entity does not have. A denied column in an aggregate is
1081
+ * refused by the gate with that error, so an unknown one must not answer differently.
1082
+ */
1083
+ protected assertAggregateRefusalsAreNotColumnProbes(errors: AggregateResult[], entity: EntityInfo, user: UserInfo): void;
1084
+ /**
1085
+ * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
1086
+ * Any user who can save a view can write its WhereClause, directly or through FilterState or a
1087
+ * Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
1088
+ * can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
1089
+ * request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
1090
+ * `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
1091
+ */
1092
+ protected ScreenStoredViewWhereClause(viewEntity: MJUserViewEntityExtended, renderedWhere: string, user: UserInfo): void;
1093
+ /**
1094
+ * SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
1095
+ * the full client-clause screen. Any user who can save a view can write those.
1096
+ */
1097
+ protected ScreenStoredViewOrderBy(orderBy: string, user: UserInfo): void;
1098
+ /**************************************************************************/
1099
+ /**************************************************************************/
836
1100
  /**
837
1101
  * Renders the WHERE clause for a saved view, replacing template variables
838
1102
  * like {%UserView "viewId"%} with subquery SQL. Handles nested/recursive
@@ -878,6 +1142,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
878
1142
  GetRunViewsDatabaseStatus(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewDatabaseStatus[]>;
879
1143
  /** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
880
1144
  private buildDatabaseStatusItems;
1145
+ /**
1146
+ * The field-security key of one request, built once per request (`params` object) and user.
1147
+ * A smart-cache-check item asks for it from each leg — its browser freshness check, the
1148
+ * server-cache lookup and the cache write — and the answer cannot change within the request:
1149
+ * the denied set it is built from is already resolved once per request.
1150
+ */
1151
+ protected ComputeRunViewFLSFingerprintKey(params: RunViewParams, contextUser?: UserInfo): string;
1152
+ private readonly _requestFLSKeys;
1153
+ /** What a request's field-security key is about: its entity, or the saved view it names. */
1154
+ private static flsKeyTarget;
1155
+ /** The message refusing `user` Read on `entityInfo`, or null when the user may read it. */
1156
+ private readPermissionError;
881
1157
  /**
882
1158
  * Smart cache validation for batch RunViews.
883
1159
  * For each view request, if cacheStatus is provided, checks if the cache is current
@@ -898,7 +1174,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
898
1174
  * entity whose view does not carry it, instead of comparing by count alone the way
899
1175
  * `BaseEngine.SweepAgainstDatabase` documents.
900
1176
  */
901
- protected BuildCacheStatusSQL(entityInfo: EntityInfo, effectiveView: string, whereSQL: string): string;
1177
+ protected BuildCacheStatusSQL(entityInfo: EntityInfo, effectiveView: string, whereSQL: string, schemaNameOverride?: string): string;
902
1178
  /**
903
1179
  * Executes cache status checks for multiple views.
904
1180
  * Default: parallel individual queries (works on all platforms).
@@ -954,7 +1230,21 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
954
1230
  * infinite loop / duplicate processing in deep-pagination jobs. Aggregates and a non-empty
955
1231
  * UserSearchString likewise can't be evaluated remotely. Throws a clear error naming the param.
956
1232
  */
957
- protected assertExternalRunViewParamsSupported(params: RunViewParams, entityName: string): void;
1233
+ protected assertExternalRunViewParamsSupported(params: RunViewParams, entityName: string, viewEntity?: MJUserViewEntityExtended | null): void;
1234
+ /**
1235
+ * Field-level security on the clauses an external-data-source read hands its driver: the
1236
+ * caller's own, merged with a saved view's stored ones. The same gates the SQL path applies to
1237
+ * the clauses it runs; the external dispatch returns before that path, and the driver runs
1238
+ * the clauses remotely, where nothing else checks them.
1239
+ */
1240
+ protected assertExternalClausesRespectFieldSecurity(entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): void;
1241
+ /**
1242
+ * An external driver's rows without the columns `user` may not read. The driver returns the
1243
+ * entity's columns at full width, and the result-path projection resolves the entity only from
1244
+ * an `EntityName` or a loaded `ViewEntity`, so a request naming only a `ViewID` would keep
1245
+ * them: the entity resolved here is named explicitly.
1246
+ */
1247
+ protected projectExternalRowsForCaller<T>(rows: T[], entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): T[];
958
1248
  /**
959
1249
  * Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
960
1250
  * external dispatch. The external branch returns before the normal SQL path that applies
@@ -964,10 +1254,19 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
964
1254
  * when there is no saved view.
965
1255
  */
966
1256
  protected mergeExternalViewParams(params: RunViewParams, viewEntity: MJUserViewEntityExtended | null, user: UserInfo): Promise<RunViewParams>;
1257
+ /**
1258
+ * True when a browser's cache status carries a field-security key (see
1259
+ * `ProviderBase.ComputeFieldSecurityCacheStatusKey`) other than the one this server computes
1260
+ * for `user` and `params`: the browser's slot was filled for a different set of columns, so
1261
+ * its row count and newest timestamp say nothing about whether it is current. False when the
1262
+ * status carries no key.
1263
+ */
1264
+ private cacheStatusFieldSecurityDiffers;
967
1265
  /**
968
1266
  * Checks the server's LocalCacheManager for cached data matching the client's request.
969
- * Returns the resolution if found (either 'current' or server-cached data to serve),
970
- * or null if the server cache doesn't have this data.
1267
+ * Returns the resolution if found ('current', 'stale' server-cached data to serve, or
1268
+ * 'needs_verification' when the server slot's freshness window has elapsed),
1269
+ * or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
971
1270
  */
972
1271
  private resolveFromServerCache;
973
1272
  /**
@@ -1002,6 +1301,14 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1002
1301
  * the query has no CacheValidationSQL configured.
1003
1302
  */
1004
1303
  RunQueriesWithCacheCheck<T = unknown>(params: RunQueryWithCacheCheckParams[], contextUser?: UserInfo): Promise<RunQueriesWithCacheCheckResponse<T>>;
1304
+ /**
1305
+ * The authorization of one {@link RunQueriesWithCacheCheck} item before it is routed. An item
1306
+ * that may be answered "current" without running — it carries a cache status for this
1307
+ * definition and the query has validation SQL — is checked in full on its rendering here. Every
1308
+ * other item runs, and the run checks the rendering it executes, so only the render-free part
1309
+ * is checked here rather than rendering the query twice.
1310
+ */
1311
+ private authorizeCacheCheckedQuery;
1005
1312
  /**
1006
1313
  * B45 override of the RunQuery cache-serve seam — enforce the SAME authorization on a
1007
1314
  * cache HIT that the miss path enforces. Resolution uses `resolveQuery()` (QueryEngine as
@@ -1011,11 +1318,30 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1011
1318
  * applies before a real execution. The base's roles-only check would let a user read cached
1012
1319
  * rows of a query whose underlying entities they cannot read.
1013
1320
  *
1321
+ * The run-time checks (`UserCanRunRenderedSQL`: entities read by the SQL itself, and field-level
1322
+ * security) run against the query rendered with the request's own parameters: the SQL the miss
1323
+ * path would check and execute for this slot, since the slot's fingerprint carries those
1324
+ * parameters and its definition hash the query's SQL. A user the miss path would refuse is never
1325
+ * served the slot; a rendering that fails is treated as not authorized, so the request falls
1326
+ * through to execution and gets that path's error.
1327
+ *
1014
1328
  * Non-throwing by contract: any resolution error degrades to `resolvable: false`, which the
1015
1329
  * gate treats as "fall through to authorized execution" — one extra query run, never an
1016
1330
  * unauthorized serve and never a crashed cache path.
1017
1331
  */
1018
1332
  protected ResolveQueryCacheAuthorization(params: RunQueryParams, user?: UserInfo): QueryCacheAuthorization;
1333
+ /**
1334
+ * The definition signature of `query` on this provider's platform: what a RunQuery cache slot
1335
+ * of the query must have been written under to be served. Computed by `QueryEngine` from the
1336
+ * same metadata this provider executes. Undefined when the engine cannot compute it, which
1337
+ * disables the definition check for that read rather than failing it.
1338
+ */
1339
+ protected QueryDefinitionSignatureFor(query: MJQueryEntityExtended): QueryDefinitionSignature | undefined;
1340
+ /**
1341
+ * True when a client sent the definition hash its slot was written under and it is not this
1342
+ * server's. A client that sends none (a release before the hash existed) gets no definition check.
1343
+ */
1344
+ private clientSlotDefinitionDiffers;
1019
1345
  /**
1020
1346
  * Resolves a query from RunQueryParams (by ID or Name+CategoryPath).
1021
1347
  * Uses QueryEngine as the single source of truth for query metadata.
@@ -1032,6 +1358,40 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1032
1358
  * @throws Error if the user does not have permission to run the query
1033
1359
  */
1034
1360
  protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo): void;
1361
+ /**
1362
+ * For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
1363
+ * current approval — status Approved and a stored fingerprint equal to the fingerprint of the
1364
+ * definition this run executes. The fingerprint is worked out here, from the same
1365
+ * `QueryEngine` metadata the run renders, never from a caller's value.
1366
+ *
1367
+ * @throws Error naming the first query whose approval is not current
1368
+ */
1369
+ protected ValidateQueryApprovalAsync(query: MJQueryEntityExtended, render: RenderResult): Promise<void>;
1370
+ /** The context tokens a query reads, with every query it composes, as the `QueryEngine` holds them. */
1371
+ private queryContextTokens;
1372
+ /**
1373
+ * SECURITY — authorizes a saved query against the SQL the run will execute (fully composed and
1374
+ * rendered), after {@link ValidateQueryForExecution} has passed: the entities that SQL reads,
1375
+ * and field-level security on every column it references. A template that injects an
1376
+ * identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
1377
+ * render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
1378
+ * The refusal does not say which field or clause caused it.
1379
+ *
1380
+ * @throws Error when the user may not run this rendering of the query
1381
+ */
1382
+ protected ValidateRenderedQueryForExecution(query: MJQueryEntityExtended, renderedSQL: string, contextUser?: UserInfo): void;
1383
+ /** The refusal for a user who may not run `query`; names entities the user cannot read, never a field. */
1384
+ private queryRunRefusalMessage;
1385
+ /** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
1386
+ private checkRenderedQuery;
1387
+ /**
1388
+ * The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
1389
+ * and the run-time checks on the query rendered with `parameters`. A rendering that fails
1390
+ * refuses, carrying the rendering's error.
1391
+ */
1392
+ private authorizeQueryRun;
1393
+ /** True when the query carries a role list (`MJ: Query Permissions` rows), which authorizes a run by itself. */
1394
+ private static roleListGrants;
1035
1395
  /**
1036
1396
  * Resolves a category path string to a QueryCategoryInfo ID.
1037
1397
  */
@@ -1050,6 +1410,22 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1050
1410
  rowCount?: number;
1051
1411
  errorMessage?: string;
1052
1412
  }>>;
1413
+ /**
1414
+ * Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
1415
+ * an empty result: zero rows, no timestamp.
1416
+ *
1417
+ * Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
1418
+ * tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
1419
+ * of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
1420
+ * validate, and NaN is then written back into the client's cache entry where `??` cannot clear
1421
+ * it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
1422
+ * batch the validation SQL read their rows through this too.
1423
+ */
1424
+ protected QueryCacheStatusFromRow(row: Record<string, unknown> | undefined): {
1425
+ success: boolean;
1426
+ maxUpdatedAt?: string;
1427
+ rowCount?: number;
1428
+ };
1053
1429
  /**
1054
1430
  * Runs a full query and returns results with cache metadata.
1055
1431
  */
@@ -1151,7 +1527,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1151
1527
  * the live query (serving live is always correct — this is a transparent optimization, never a
1152
1528
  * correctness dependency).
1153
1529
  */
1154
- protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo): Promise<{
1530
+ protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>): Promise<{
1155
1531
  sql: string;
1156
1532
  parameters: unknown[];
1157
1533
  } | null>;
@@ -1173,6 +1549,19 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1173
1549
  * when one is given. `TimeoutSeconds` limits every statement the run sends.
1174
1550
  */
1175
1551
  private runAdhocSQL;
1552
+ /**
1553
+ * SECURITY — what ad-hoc SQL may read, checked in the provider so that every in-process caller
1554
+ * (agents, data contexts, actions) is covered, not only the API's resolvers. `sql` is the
1555
+ * rendered statement, before the server's own paging wrap. Every table it reads must be an
1556
+ * entity base view the caller can read unscoped: CanRead with no row-level filter and no denied
1557
+ * field, because raw SQL applies neither ({@link ClientClauseScreen.AssertStatementReadsUnscopedEntityViews}).
1558
+ * The system user runs the server's own SQL and is not checked, but only when passed
1559
+ * explicitly: no user at all refuses, rather than falling back to the provider's own user,
1560
+ * which on a server is the system user.
1561
+ *
1562
+ * @throws Error when the caller may not run `sql`
1563
+ */
1564
+ protected AssertAdhocReadAllowed(sql: string, contextUser?: UserInfo): void;
1176
1565
  /**
1177
1566
  * The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
1178
1567
  * fails does not fail the run: some queries page fine but cannot be counted (duplicate column
@@ -1200,7 +1589,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1200
1589
  * Delegates to {@link RenderPipeline.Run} for the composition → template
1201
1590
  * pipeline. Paging is handled separately by the caller (InternalRunQuery).
1202
1591
  */
1203
- protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo): {
1592
+ protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>): {
1204
1593
  finalSQL: string;
1205
1594
  appliedParameters: Record<string, string>;
1206
1595
  renderResult: RenderResult;
@@ -1227,7 +1616,13 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1227
1616
  * truth (a TTL of <= 0 disables caching for the source); field-drift warnings still apply to
1228
1617
  * freshly-fetched rows. Ad-hoc SQL (params.SQL) is never cached.
1229
1618
  */
1230
- protected runExternalQueryWithCache(query: MJQueryEntityExtended, finalSQL: string, params: RunQueryParams, router: ExternalDataSourceReadRouter, contextUser?: UserInfo): Promise<RunQueryResult>;
1619
+ protected runExternalQueryWithCache(query: MJQueryEntityExtended, finalSQL: string, params: RunQueryParams, router: ExternalDataSourceReadRouter, contextUser?: UserInfo, contextValues?: Record<string, string>): Promise<RunQueryResult>;
1620
+ /**
1621
+ * The result-cache fingerprint segment for what the server set on a run: its `ServerParameters`
1622
+ * and the `Context` values the template read. Empty when there are neither, so the fingerprint
1623
+ * is exactly what it was before either existed.
1624
+ */
1625
+ private serverSetFingerprintSegment;
1231
1626
  protected warnIfExternalQueryFieldsMissing(query: MJQueryEntityExtended, result: RunQueryResult): RunQueryResult;
1232
1627
  /**
1233
1628
  * Lower-layer execution: resolves composition, processes templates, executes SQL.
@@ -1311,6 +1706,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1311
1706
  protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[]): Promise<void>;
1312
1707
  /**************************************************************************/
1313
1708
  /**************************************************************************/
1709
+ /**
1710
+ * The `WHERE` predicate that selects one record by its composite key, using dialect-neutral
1711
+ * quoting. Quoted key values have embedded single quotes escaped: a key value can contain
1712
+ * apostrophes (an object-valued soft key whose JSON carries free text), and an unescaped quote
1713
+ * both breaks the statement and is an injection vector.
1714
+ */
1715
+ protected BuildPrimaryKeyWhereClause(entityInfo: EntityInfo, compositeKey: CompositeKey): string;
1716
+ /**
1717
+ * Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
1718
+ * Server and PostgreSQL), in place, and returns the row.
1719
+ */
1720
+ protected TrimFixedWidthValues(entityInfo: EntityInfo, row: Record<string, unknown>): Record<string, unknown>;
1314
1721
  /**
1315
1722
  * Loads a single entity record by composite key, with optional relationship loading.
1316
1723
  * Uses dialect-neutral quoting for all SQL construction.
@@ -1327,6 +1734,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1327
1734
  /**
1328
1735
  * Checks whether a new record's field values pass the Create RLS filter.
1329
1736
  * Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
1737
+ * Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
1738
+ * filter that references a column the new row leaves NULL evaluates instead of failing to bind.
1739
+ * The row is what the caller sends: a column the database fills on insert (a non-literal default
1740
+ * or a trigger) is seen as NULL here.
1330
1741
  */
1331
1742
  protected CheckCreateRLS(entity: BaseEntity, user: UserInfo): Promise<boolean>;
1332
1743
  /**
@@ -1357,15 +1768,14 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1357
1768
  * Builds field projections for an RLS synthetic-row subquery (Create post-image and
1358
1769
  * Update post-image checks).
1359
1770
  *
1360
- * @param includeNulls - The Update post-image REQUIRES null fields to be projected as
1361
- * typed NULLs: a filter referencing a column the caller just nulled must see SQL NULL,
1362
- * not a missing column. A bare `SELECT NULL AS Col` is untyped and can evaluate
1363
- * differently from a real row, so nulls are emitted as `CAST(NULL AS <sqltype>)` using
1364
- * the field's metadata-resolved type. An unresolvable type fails the save (throw)
1365
- * rather than emitting an untyped NULL. The Create check keeps its historical
1366
- * skip-nulls behavior (includeNulls=false).
1771
+ * Every non-virtual field is projected, null fields included: a filter referencing a
1772
+ * column the row leaves NULL must see SQL NULL, not a missing column (which fails to
1773
+ * bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
1774
+ * untyped and can evaluate differently from a real row, so nulls are emitted as
1775
+ * `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
1776
+ * type fails the save (throw) rather than emitting an untyped NULL.
1367
1777
  */
1368
- protected BuildRLSSyntheticRowProjections(entity: BaseEntity, entityInfo: EntityInfo, includeNulls: boolean): string;
1778
+ protected BuildRLSSyntheticRowProjections(entity: BaseEntity, entityInfo: EntityInfo): string;
1369
1779
  /**
1370
1780
  * Renders one field value for the RLS synthetic row. Every branch either escapes or
1371
1781
  * validates: quoted values are `''`-escaped, booleans render as 1/0, and non-quoted
@@ -1393,12 +1803,54 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1393
1803
  * Default: PG-style ($1, $2, ...). SQL Server overrides to @p0, @p1, etc.
1394
1804
  */
1395
1805
  BuildParameterPlaceholder(index: number): string;
1806
+ /**
1807
+ * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
1808
+ * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
1809
+ * that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
1810
+ * user checks: every authenticated client loads it to learn the schema, including principals
1811
+ * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
1812
+ */
1813
+ private resolveDatasetItemScope;
1814
+ /**
1815
+ * Why a caller's ItemFilter is refused by the field-level security gate — the same gate every
1816
+ * RunView filter passes — or null when it may run. The item's stored WhereClause is
1817
+ * administrator-defined dataset metadata, not a predicate the caller chose, so it is not checked.
1818
+ */
1819
+ private datasetItemFilterFieldSecurityRefusal;
1820
+ /**
1821
+ * The fields of a dataset item's entity the caller may not read, lowercased; empty when none,
1822
+ * when there is no caller, or for MJ_Metadata, which every principal loads to learn the schema.
1823
+ */
1824
+ private datasetItemDeniedFields;
1825
+ /**
1826
+ * The error a failed dataset batch reports to the caller. When the caller is denied fields on
1827
+ * an item's entity and the database rejected a column that does not exist, every item reports
1828
+ * the field-security error a denied column gets instead, so the two cannot be told apart.
1829
+ */
1830
+ private datasetBatchErrorForCaller;
1831
+ /**
1832
+ * Dataset item rows as the caller may see them: denied columns removed, and Record Changes
1833
+ * payloads narrowed. Cached rows are shared and full width, so this always builds new rows
1834
+ * rather than narrowing the cached ones. MJ_Metadata is exempt for the reason given on
1835
+ * {@link datasetItemDeniedFields}.
1836
+ */
1837
+ private projectDatasetRowsForCaller;
1838
+ /**
1839
+ * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
1840
+ * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
1841
+ * level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
1842
+ */
1843
+ private datasetItemWhereClause;
1396
1844
  /**
1397
1845
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
1398
1846
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
1399
1847
  *
1400
1848
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
1401
1849
  * while PG (and the default) use parallel individual queries.
1850
+ *
1851
+ * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
1852
+ * CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
1853
+ * item runs no SQL and fails the dataset.
1402
1854
  */
1403
1855
  GetDatasetByName(datasetName: string, itemFilters?: DatasetItemFilterType[], contextUser?: UserInfo, providerToUse?: IMetadataProvider, forceRefresh?: boolean): Promise<DatasetResultType>;
1404
1856
  /**************************************************************************/
@@ -1406,8 +1858,15 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1406
1858
  /**
1407
1859
  * Retrieves status information for a dataset by name: per-entity row count and
1408
1860
  * latest update date. Uses ExecuteSQLBatch for per-item status queries.
1861
+ *
1862
+ * Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
1863
+ * status fails with the refusal and no status SQL runs.
1409
1864
  */
1410
1865
  GetDatasetStatusByName(datasetName: string, itemFilters?: DatasetItemFilterType[], contextUser?: UserInfo, providerToUse?: IMetadataProvider): Promise<DatasetStatusResultType>;
1866
+ /**
1867
+ * Builds the lookup key for {@link _lastDatasetStatusByName} from dataset name and item filters.
1868
+ */
1869
+ private buildDatasetStatusCacheKey;
1411
1870
  /**************************************************************************/
1412
1871
  /**************************************************************************/
1413
1872
  /**
@@ -1419,8 +1878,16 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1419
1878
  * binary column can still be named explicitly. When the entity's metadata is not loaded yet —
1420
1879
  * the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
1421
1880
  * are converted to base64 by the caller.
1881
+ *
1882
+ * `deniedFields` (lowercased) are the columns the caller may not read. They are never
1883
+ * selected: a named one is dropped, and an item that names none selects every readable column.
1884
+ */
1885
+ protected getColumnsForDatasetItem(item: Record<string, unknown>, datasetName: string, deniedFields?: Set<string>): string | null;
1886
+ /**
1887
+ * `columns` without the denied ones, quoted and joined. When every one is denied, the primary
1888
+ * key columns are selected instead, which are never denied, so the read still has a shape.
1422
1889
  */
1423
- protected getColumnsForDatasetItem(item: Record<string, unknown>, datasetName: string): string | null;
1890
+ private readableDatasetColumns;
1424
1891
  /**************************************************************************/
1425
1892
  /**************************************************************************/
1426
1893
  /**