@memberjunction/generic-database-provider 6.2.0-edge.3 → 6.2.0-edge.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,18 +15,20 @@
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, RunViewsWithCacheCheckResponse, RunViewWithCacheCheckResult, RunQueryParams, RunQueryResult, RunQueryWithCacheCheckParams, RunQueriesWithCacheCheckResponse, RunQueryWithCacheCheckResult, QueryCacheAuthorization, CompositeKey, DatasetItemFilterType, DatasetResultType, DatasetStatusResultType, IMetadataProvider, 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 } 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';
30
32
  /**
31
33
  * Configuration options for batch SQL execution.
32
34
  * Shared between GenericDatabaseProvider and platform-specific providers.
@@ -60,7 +62,7 @@ export declare class DoomedTransactionError extends Error {
60
62
  cause?: unknown;
61
63
  });
62
64
  }
63
- export declare abstract class GenericDatabaseProvider extends DatabaseProviderBase {
65
+ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBase implements ClientClauseScreeningProvider {
64
66
  /**************************************************************************/
65
67
  /**************************************************************************/
66
68
  /**
@@ -111,10 +113,23 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
111
113
  * ```
112
114
  */
113
115
  SetLocalStorageProvider(provider: ILocalStorageProvider): void;
116
+ /**
117
+ * Installs {@link ProviderConfigDataBase.LocalStorageProvider}, when the configuration carries
118
+ * one, before the base configuration loads metadata. A server fleet passes its shared (Redis)
119
+ * store this way so the metadata load and the engines loaded at startup use it from the first
120
+ * read: the first server to start fills the shared cache, and the others read it instead of
121
+ * each querying the database and broadcasting what they loaded.
122
+ */
123
+ Config(data: ProviderConfigDataBase, providerToUse?: IMetadataProvider): Promise<boolean>;
114
124
  /**************************************************************************/
115
125
  /**************************************************************************/
116
126
  private static _sqlLoggingSessionsKey;
127
+ private static _cachedSqlLoggingSessions;
117
128
  private get _sqlLoggingSessions();
129
+ /**
130
+ * Fast O(1) check for whether any SQL logging sessions are currently active.
131
+ */
132
+ protected get HasActiveSqlLoggingSessions(): boolean;
118
133
  /**
119
134
  * Creates a new SQL logging session that will capture all SQL operations to a file.
120
135
  * Returns a disposable session object that must be disposed to stop logging.
@@ -262,6 +277,8 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
262
277
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
263
278
  */
264
279
  protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo): Promise<Record<string, unknown>[]>;
280
+ private static _encryptedFieldsCache;
281
+ private static getEncryptedFields;
265
282
  /**
266
283
  * Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
267
284
  * own read paths but returns entity rows — the transaction groups. Every row a provider hands
@@ -488,12 +505,44 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
488
505
  * orchestrator preserves.
489
506
  */
490
507
  protected abstract RenderSaveCallBinding(entity: BaseEntity, fieldValues: Map<EntityFieldInfo, unknown>, isUpdate: boolean, spName: string): SaveCallBinding;
508
+ /**
509
+ * Builds the dialect-quoted, comma-separated column list for {@link EntityInfo.DatestampReturnFields}
510
+ * (primary key column(s) followed by `__mj_CreatedAt` and `__mj_UpdatedAt`) using {@link QuoteIdentifier}.
511
+ *
512
+ * Examples:
513
+ * - SQL Server: `[ID], [__mj_CreatedAt], [__mj_UpdatedAt]`
514
+ * - PostgreSQL: `"ID", "__mj_CreatedAt", "__mj_UpdatedAt"`
515
+ */
516
+ protected GetDatestampSelectColumnsSQL(entityInfo: EntityInfo): string;
517
+ /**
518
+ * Resolves the compile-time vs. effective runtime {@link SaveReturnContext} for a save operation.
519
+ *
520
+ * Centralizes the `SaveReturnMode` decision logic in `GenericDatabaseProvider` so dialect providers
521
+ * (`SQLServerDataProvider`, `PostgreSQLDataProvider`, and future providers) never duplicate the
522
+ * rules for:
523
+ * - `spReturnMode`: the return shape compiled into the stored procedure / function (`EntityInfo.SaveReturnMode`).
524
+ * - `effectiveReturnMode`: the return shape requested for this call (`options?.SaveReturnMode ?? spReturnMode`).
525
+ * - `needsDatestampProjection`: `true` when the compiled routine returns the full row (`spReturnMode === 'full'`)
526
+ * but the caller requested `'datestamps_only'` at runtime, requiring the provider to project the result down
527
+ * to `datestampSelectColumnsSQL` before wire transmission.
528
+ */
529
+ protected ResolveSaveReturnContext(entity: BaseEntity, options?: EntitySaveOptions): SaveReturnContext;
491
530
  /**
492
531
  * Wraps the bare SP-call binding with the dialect's result-capture
493
532
  * pattern. SQL Server emits `DECLARE @ResultTable + INSERT INTO @ResultTable EXEC + SELECT * FROM @ResultTable`;
494
533
  * PostgreSQL emits the bare `SELECT * FROM schema."fn"(...)`.
495
534
  */
496
- protected abstract WrapSaveCallForResult(binding: SaveCallBinding, entity: BaseEntity, spName: string): SaveSQLFragment;
535
+ protected abstract WrapSaveCallForResult(binding: SaveCallBinding, entity: BaseEntity, spName: string, options?: EntitySaveOptions, returnContext?: SaveReturnContext): SaveSQLFragment;
536
+ /**
537
+ * Projects a save call's result set down to {@link SaveReturnContext.datestampSelectColumnsSQL}
538
+ * when a caller requests `SaveReturnMode: 'datestamps_only'` at runtime on an entity whose
539
+ * compiled stored procedure / function returns the full row (`returnContext.needsDatestampProjection === true`).
540
+ *
541
+ * - SQL Server captures `EXEC` into `DECLARE @ResultTable TABLE (...)` and emits
542
+ * `SELECT [ID], [__mj_CreatedAt], [__mj_UpdatedAt] FROM @ResultTable;`.
543
+ * - PostgreSQL emits `SELECT "ID", "__mj_CreatedAt", "__mj_UpdatedAt" FROM schema."fn"(...)`.
544
+ */
545
+ protected abstract ProjectSaveCallToDatestamps(binding: SaveCallBinding, entity: BaseEntity, spName: string, returnContext: SaveReturnContext): SaveSQLFragment;
497
546
  /**
498
547
  * Wraps an already-result-captured save SQL with the dialect's
499
548
  * record-change emission. SQL Server inlines `EXEC spCreateRecordChange_Internal`
@@ -503,7 +552,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
503
552
  * Orchestrator only calls this when `ShouldTrackRecordChanges` is true
504
553
  * and `BuildRecordChangePayload` returned a non-null payload.
505
554
  */
506
- protected abstract WrapSaveCallWithRecordChange(saveSQL: SaveSQLFragment, binding: SaveCallBinding, payload: RecordChangePayload, entity: BaseEntity): SaveSQLFragment;
555
+ protected abstract WrapSaveCallWithRecordChange(saveSQL: SaveSQLFragment, binding: SaveCallBinding, payload: RecordChangePayload, entity: BaseEntity, options?: EntitySaveOptions, returnContext?: SaveReturnContext): SaveSQLFragment;
507
556
  /**
508
557
  * Optional replay form of a CREATE for the SQL log only (never executed). Dialects that
509
558
  * record saves for migration replay (SQL Server's Metadata_Sync migrations) override
@@ -512,6 +561,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
512
561
  * (MemberJunction/MJ#4503). Default: no replay form, the plain save SQL is logged.
513
562
  */
514
563
  protected RenderReplaySaveSQL(_binding: SaveCallBinding, _entity: BaseEntity, _fieldValues: Map<EntityFieldInfo, unknown>): string | undefined;
564
+ /**
565
+ * Optional replay form of an UPDATE for the SQL log only (never executed). Receives just the
566
+ * fields this save CHANGED. A recording that carried the whole row would, on replay, overwrite
567
+ * every column of the target row with the recording database's values — including settings a
568
+ * deploying application tuned on purpose (an MJ metadata sync that only flipped
569
+ * `AllowUserSearchAPI` on 'MJ: Content Items' also reset that consumer's
570
+ * `TrustServerCacheCompletely`). Dialects whose update procs keep unpassed columns override
571
+ * this. Default: no replay form, the plain save SQL is logged.
572
+ */
573
+ protected RenderReplayUpdateSQL(_binding: SaveCallBinding, _entity: BaseEntity, _changedFieldValues: Map<EntityFieldInfo, unknown>): string | undefined;
574
+ /** The entries of a save's parameter map whose fields this save actually changed. */
575
+ private changedFieldValues;
515
576
  /**
516
577
  * Concrete implementation of the abstract save-SQL builder defined on
517
578
  * `DatabaseProviderBase`. Iterates fields via the single `IsSPParameter`
@@ -660,6 +721,24 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
660
721
  * Default: returns the clause unchanged.
661
722
  */
662
723
  protected TransformExternalSQLClause(clause: string, _entityInfo: EntityInfo): string;
724
+ /**
725
+ * Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
726
+ * WhereClause) stays inside the parentheses this provider puts around it, read with this
727
+ * provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
728
+ * security, which also carries API-key row filters and guest scope; a piece that closes its
729
+ * parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
730
+ * caller controls.
731
+ */
732
+ protected AssertClauseBalanced(clause: string, label: string, options?: BalancedFragmentOptions): void;
733
+ /**
734
+ * Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
735
+ * {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
736
+ * top-level AND terms, each term is transformed, checked and parenthesized on its own. A
737
+ * PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
738
+ * runs before this transform, so a rewrite that changes the caller's term cannot reach the
739
+ * hook's term.
740
+ */
741
+ protected PrepareExtraFilterSQL(extraFilter: string, entityInfo: EntityInfo): string;
663
742
  /**
664
743
  * Optionally wraps a view query with user view run logging.
665
744
  * SQL Server overrides to use spCreateUserViewRunWithDetail.
@@ -694,6 +773,23 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
694
773
  protected RunCoalescedCountBatch<T = unknown>(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewResult<T>[]>;
695
774
  /**************************************************************************/
696
775
  /**************************************************************************/
776
+ /**
777
+ * Builds the aggregate query without running the caller's text. Each expression must be a single
778
+ * aggregate function call over this entity's columns: the query runs the SQL that
779
+ * {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
780
+ * dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
781
+ * per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
782
+ * request order, which is how `RunViewCore` reads their values back.
783
+ */
784
+ protected BuildAggregateSQL(aggregates: {
785
+ expression: string;
786
+ alias?: string;
787
+ }[], entityInfo: EntityInfo, schemaName: string, baseView: string, whereSQL: string): {
788
+ aggregateSQL: string | null;
789
+ validationErrors: AggregateResult[];
790
+ };
791
+ /** The SQL to run for one caller aggregate expression, or why it is refused. */
792
+ private screenAggregateExpression;
697
793
  /**
698
794
  * Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
699
795
  * the columns this user is allowed to read when field security denies them any.
@@ -796,6 +892,37 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
796
892
  protected isTextSearchableType(field: EntityFieldInfo): boolean;
797
893
  /**************************************************************************/
798
894
  /**************************************************************************/
895
+ /**
896
+ * SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
897
+ * Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
898
+ * fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
899
+ */
900
+ protected AssertClauseFragmentIsSingleStatement(clause: string, label: string): void;
901
+ /**
902
+ * SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
903
+ * against this provider's entities and dialect, with `contextUser` as the acting user. With
904
+ * `entityInfo`, the clause is screened in the form this provider runs a client clause for that
905
+ * entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
906
+ * outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
907
+ * saved-view save gate (`MJUserViewEntityServer`).
908
+ */
909
+ ScreenClientClause(clause: string | null | undefined, label: string, contextUser?: UserInfo, entityInfo?: EntityInfo): void;
910
+ /**
911
+ * SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
912
+ * Any user who can save a view can write its WhereClause, directly or through FilterState or a
913
+ * Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
914
+ * can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
915
+ * request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
916
+ * `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
917
+ */
918
+ protected ScreenStoredViewWhereClause(viewEntity: MJUserViewEntityExtended, renderedWhere: string, user: UserInfo): void;
919
+ /**
920
+ * SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
921
+ * the full client-clause screen. Any user who can save a view can write those.
922
+ */
923
+ protected ScreenStoredViewOrderBy(orderBy: string, user: UserInfo): void;
924
+ /**************************************************************************/
925
+ /**************************************************************************/
799
926
  /**
800
927
  * Renders the WHERE clause for a saved view, replacing template variables
801
928
  * like {%UserView "viewId"%} with subquery SQL. Handles nested/recursive
@@ -832,6 +959,15 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
832
959
  }): boolean;
833
960
  /**************************************************************************/
834
961
  /**************************************************************************/
962
+ /**
963
+ * Row count and newest `__mj_UpdatedAt` for each view, read from the database and never from
964
+ * a cache. Uses the same WHERE clause (filter, user search, row-level security, pre-run hooks)
965
+ * and the same batched status query as {@link RunViewsWithCacheCheck}. One entry per param,
966
+ * in order; a failure is reported per entry.
967
+ */
968
+ GetRunViewsDatabaseStatus(params: RunViewParams[], contextUser?: UserInfo): Promise<RunViewDatabaseStatus[]>;
969
+ /** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
970
+ private buildDatabaseStatusItems;
835
971
  /**
836
972
  * Smart cache validation for batch RunViews.
837
973
  * For each view request, if cacheStatus is provided, checks if the cache is current
@@ -846,6 +982,13 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
846
982
  * Subclasses can override to add platform-specific SQL transformations (e.g., identifier quoting).
847
983
  */
848
984
  protected buildWhereClauseForCacheCheck(params: RunViewParams, entityInfo: EntityInfo, user: UserInfo): Promise<string>;
985
+ /**
986
+ * The freshness probe for one view: a row count, plus the newest `__mj_UpdatedAt` **when the
987
+ * entity has that column**. Selecting it unconditionally made the probe fail outright for an
988
+ * entity whose view does not carry it, instead of comparing by count alone the way
989
+ * `BaseEngine.SweepAgainstDatabase` documents.
990
+ */
991
+ protected BuildCacheStatusSQL(entityInfo: EntityInfo, effectiveView: string, whereSQL: string): string;
849
992
  /**
850
993
  * Executes cache status checks for multiple views.
851
994
  * Default: parallel individual queries (works on all platforms).
@@ -963,6 +1106,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
963
1106
  * unauthorized serve and never a crashed cache path.
964
1107
  */
965
1108
  protected ResolveQueryCacheAuthorization(params: RunQueryParams, user?: UserInfo): QueryCacheAuthorization;
1109
+ /**
1110
+ * The definition signature of `query` on this provider's platform: what a RunQuery cache slot
1111
+ * of the query must have been written under to be served. Computed by `QueryEngine` from the
1112
+ * same metadata this provider executes. Undefined when the engine cannot compute it, which
1113
+ * disables the definition check for that read rather than failing it.
1114
+ */
1115
+ protected QueryDefinitionSignatureFor(query: MJQueryEntityExtended): QueryDefinitionSignature | undefined;
1116
+ /**
1117
+ * True when a client sent the definition hash its slot was written under and it is not this
1118
+ * server's. A client that sends none (a release before the hash existed) gets no definition check.
1119
+ */
1120
+ private clientSlotDefinitionDiffers;
966
1121
  /**
967
1122
  * Resolves a query from RunQueryParams (by ID or Name+CategoryPath).
968
1123
  * Uses QueryEngine as the single source of truth for query metadata.
@@ -997,6 +1152,22 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
997
1152
  rowCount?: number;
998
1153
  errorMessage?: string;
999
1154
  }>>;
1155
+ /**
1156
+ * Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
1157
+ * an empty result: zero rows, no timestamp.
1158
+ *
1159
+ * Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
1160
+ * tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
1161
+ * of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
1162
+ * validate, and NaN is then written back into the client's cache entry where `??` cannot clear
1163
+ * it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
1164
+ * batch the validation SQL read their rows through this too.
1165
+ */
1166
+ protected QueryCacheStatusFromRow(row: Record<string, unknown> | undefined): {
1167
+ success: boolean;
1168
+ maxUpdatedAt?: string;
1169
+ rowCount?: number;
1170
+ };
1000
1171
  /**
1001
1172
  * Runs a full query and returns results with cache metadata.
1002
1173
  */
@@ -1274,6 +1445,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1274
1445
  /**
1275
1446
  * Checks whether a new record's field values pass the Create RLS filter.
1276
1447
  * Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
1448
+ * Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
1449
+ * filter that references a column the new row leaves NULL evaluates instead of failing to bind.
1450
+ * The row is what the caller sends: a column the database fills on insert (a non-literal default
1451
+ * or a trigger) is seen as NULL here.
1277
1452
  */
1278
1453
  protected CheckCreateRLS(entity: BaseEntity, user: UserInfo): Promise<boolean>;
1279
1454
  /**
@@ -1304,15 +1479,14 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1304
1479
  * Builds field projections for an RLS synthetic-row subquery (Create post-image and
1305
1480
  * Update post-image checks).
1306
1481
  *
1307
- * @param includeNulls - The Update post-image REQUIRES null fields to be projected as
1308
- * typed NULLs: a filter referencing a column the caller just nulled must see SQL NULL,
1309
- * not a missing column. A bare `SELECT NULL AS Col` is untyped and can evaluate
1310
- * differently from a real row, so nulls are emitted as `CAST(NULL AS <sqltype>)` using
1311
- * the field's metadata-resolved type. An unresolvable type fails the save (throw)
1312
- * rather than emitting an untyped NULL. The Create check keeps its historical
1313
- * skip-nulls behavior (includeNulls=false).
1482
+ * Every non-virtual field is projected, null fields included: a filter referencing a
1483
+ * column the row leaves NULL must see SQL NULL, not a missing column (which fails to
1484
+ * bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
1485
+ * untyped and can evaluate differently from a real row, so nulls are emitted as
1486
+ * `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
1487
+ * type fails the save (throw) rather than emitting an untyped NULL.
1314
1488
  */
1315
- protected BuildRLSSyntheticRowProjections(entity: BaseEntity, entityInfo: EntityInfo, includeNulls: boolean): string;
1489
+ protected BuildRLSSyntheticRowProjections(entity: BaseEntity, entityInfo: EntityInfo): string;
1316
1490
  /**
1317
1491
  * Renders one field value for the RLS synthetic row. Every branch either escapes or
1318
1492
  * validates: quoted values are `''`-escaped, booleans render as 1/0, and non-quoted
@@ -1340,12 +1514,30 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1340
1514
  * Default: PG-style ($1, $2, ...). SQL Server overrides to @p0, @p1, etc.
1341
1515
  */
1342
1516
  BuildParameterPlaceholder(index: number): string;
1517
+ /**
1518
+ * Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
1519
+ * denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
1520
+ * that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
1521
+ * user checks: every authenticated client loads it to learn the schema, including principals
1522
+ * (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
1523
+ */
1524
+ private resolveDatasetItemScope;
1525
+ /**
1526
+ * The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
1527
+ * item's filter sits two parentheses deep because a client ItemFilter is screened inside one
1528
+ * level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
1529
+ */
1530
+ private datasetItemWhereClause;
1343
1531
  /**
1344
1532
  * Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
1345
1533
  * and aggregating results. Uses dialect-neutral quoting for all SQL construction.
1346
1534
  *
1347
1535
  * ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
1348
1536
  * while PG (and the default) use parallel individual queries.
1537
+ *
1538
+ * An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
1539
+ * CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
1540
+ * item runs no SQL and fails the dataset.
1349
1541
  */
1350
1542
  GetDatasetByName(datasetName: string, itemFilters?: DatasetItemFilterType[], contextUser?: UserInfo, providerToUse?: IMetadataProvider, forceRefresh?: boolean): Promise<DatasetResultType>;
1351
1543
  /**************************************************************************/
@@ -1353,6 +1545,9 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1353
1545
  /**
1354
1546
  * Retrieves status information for a dataset by name: per-entity row count and
1355
1547
  * latest update date. Uses ExecuteSQLBatch for per-item status queries.
1548
+ *
1549
+ * Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
1550
+ * status fails with the refusal and no status SQL runs.
1356
1551
  */
1357
1552
  GetDatasetStatusByName(datasetName: string, itemFilters?: DatasetItemFilterType[], contextUser?: UserInfo, providerToUse?: IMetadataProvider): Promise<DatasetStatusResultType>;
1358
1553
  /**************************************************************************/
@@ -1442,15 +1637,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1442
1637
  * release hands them to the enclosing frame.
1443
1638
  */
1444
1639
  private _postCommitTasks;
1445
- /**
1446
- * Tasks whose own transaction already settled, held back because an UNRELATED transaction is
1447
- * open on this instance. Running them now would enlist their writes in it — on one connection,
1448
- * that means a rollback of work that has nothing to do with them. Drained when this provider
1449
- * goes idle, whichever way that transaction ends.
1450
- */
1451
- private _idlePostCommitTasks;
1452
1640
  /** Identity of each open frame and the fate of recent transactions, for {@link PostCommitToken}s. */
1453
1641
  private readonly _frameTracker;
1642
+ /** Which async scope the open transaction belongs to (#4786). See {@link IsCallerInAmbientTransaction}. */
1643
+ private readonly _affinity;
1644
+ /** Epoch whose foreign join was already reported, so a transaction reports at most one (#4786). */
1645
+ private _foreignJoinReportedEpoch;
1454
1646
  protected get CurrentTransactionDepth(): number;
1455
1647
  /** Copy of the savepoint stack, outermost first. */
1456
1648
  get SavepointStack(): string[];
@@ -1458,12 +1650,6 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1458
1650
  get savepointStack(): string[];
1459
1651
  /** True after the ambient physical TX was abandoned and frames are still settling. */
1460
1652
  protected get IsDoomed(): boolean;
1461
- /**
1462
- * Throw if a statement would run on the pool while frames are still open
1463
- * after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
1464
- * — outermost begin has depth 1 before the handle is published, and
1465
- * concurrent reads on SQL Server legitimately use the pool in that window.
1466
- */
1467
1653
  /**
1468
1654
  * A debounced metadata refresh is timer-driven, so it can fire at any point of a caller's
1469
1655
  * unit of work — including the microtask window while the ambient transaction is being
@@ -1473,15 +1659,35 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1473
1659
  * Metadata reads are not part of anyone's unit of work, so wait for the transaction to end
1474
1660
  * before starting one (#4486).
1475
1661
  *
1476
- * This narrows the window rather than closing it: the check runs when the timer fires, and
1477
- * the batch is issued several round trips later, so a transaction that begins in between
1478
- * is still joined. That case is now harmless to the process — the batch fails, the dataset
1479
- * reports it, and the loaded metadata stays — but the refresh itself is lost until the next
1480
- * member write. Running the metadata batch on the pool regardless of the ambient
1481
- * transaction is #4514 (alongside #4454, the commit-side half of the same window).
1662
+ * Under scope affinity (#4786) the timer inherits the membership of the code that scheduled it
1663
+ * (re-arms included), so the refresh can only ever join the transaction whose scope scheduled
1664
+ * it — and only if that transaction is still open when the batch is issued, several round trips
1665
+ * after this check ran. It never joins a transaction someone else begins later. That remaining
1666
+ * window is harmless to the process — the batch fails, the dataset reports it, and the loaded
1667
+ * metadata stays — but the refresh itself is lost until the next member write. The check is
1668
+ * instance-wide, so an unrelated transaction also defers the refresh. Running the metadata
1669
+ * batch on the pool regardless of the ambient transaction is #4514 (alongside #4454, the
1670
+ * commit-side half of the same window).
1482
1671
  */
1483
1672
  protected get MetadataMemberRefreshMustWait(): boolean;
1673
+ /**
1674
+ * Throw if a statement from a member of the ambient transaction would run on the pool while its
1675
+ * frames are still open after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
1676
+ * — outermost begin has depth 1 before the handle is published, and concurrent reads on SQL
1677
+ * Server legitimately use the pool in that window. Callers outside the transaction's scope
1678
+ * (see {@link IsCallerInAmbientTransaction}) do not use its handle, so a subclass should apply
1679
+ * this check only to members' statements.
1680
+ */
1484
1681
  protected AssertAmbientTransactionUsable(): void;
1682
+ /**
1683
+ * Whether the calling async scope is part of this provider's ambient transaction (#4786). A shared
1684
+ * provider's open transaction belongs to the scope that began it and its descendants; every other
1685
+ * caller must run on the pool, as if no transaction were open. Subclasses consult this — not merely
1686
+ * "is a handle open" — before routing a statement to the transaction handle.
1687
+ */
1688
+ protected IsCallerInAmbientTransaction(): boolean;
1689
+ /** Members of the open transaction share RunViews only with each other (see {@link ProviderBase.RunViewDedupScope}). */
1690
+ protected get RunViewDedupScope(): string;
1485
1691
  /**
1486
1692
  * True when the driver has a begun physical transaction object.
1487
1693
  * Must be truthful: a published-but-unbegun handle is a poison state.
@@ -1513,8 +1719,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1513
1719
  /** Serialize begin/commit/rollback so depth/stack mutations cannot interleave. */
1514
1720
  protected WithTransactionLock<T>(fn: () => Promise<T>): Promise<T>;
1515
1721
  /**
1516
- * Queue `task` until the outermost commit of the ambient transaction, or start it now when
1517
- * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract.
1722
+ * Queue `task` until the outermost commit of the caller's transaction, or start it now when
1723
+ * there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract. Work
1724
+ * registered by a caller outside the open transaction's scope (#4786) is not tied to that
1725
+ * transaction: it starts now, detached, on the pool, whether or not that transaction is open.
1518
1726
  *
1519
1727
  * - Queued tasks run once, in registration order, after the outermost commit succeeds and the
1520
1728
  * transaction lock is released — so a task may begin its own transaction. The committer
@@ -1528,29 +1736,39 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1528
1736
  * token was captured in, rolled back — including a savepoint rolled back inside a transaction
1529
1737
  * that went on to commit — or if the token matches nothing this provider knows; otherwise it
1530
1738
  * is queued at the deepest captured frame that is still open. A token captured outside any
1531
- * transaction always runs. "Runs" means immediately when this provider is idle, and otherwise
1532
- * once it is: a task must never have its own writes rolled back by an unrelated transaction.
1739
+ * transaction always runs.
1740
+ * - "Starts now" means fire-and-forget under {@link TransactionAffinity.RunDetached}: the task is
1741
+ * in no transaction on this provider (its statements run on the pool), the caller never awaits
1742
+ * it, and a `BeginTransaction` in the task's synchronous prefix stays in the task's own scope.
1743
+ * If the task begins a transaction while another is open on this instance, it joins that one as
1744
+ * a savepoint (logged) — a task that needs its own transaction belongs on an independent instance.
1533
1745
  */
1534
1746
  RunAfterCommit(task: PostCommitTask, description?: string, token?: PostCommitToken): void;
1535
1747
  /**
1536
- * Snapshot of the open transaction frames. Synchronous, and never `undefined` on this provider:
1537
- * outside a transaction it returns a token whose epoch is `null`, which says the work is already
1538
- * durable rather than saying nothing. See {@link DatabaseProviderBase.CapturePostCommitToken}.
1748
+ * Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
1749
+ * provider: outside a transaction it returns a token whose epoch is `null`, which says the work
1750
+ * is already durable rather than saying nothing. See
1751
+ * {@link DatabaseProviderBase.CapturePostCommitToken}. Work registered by a caller outside the
1752
+ * open transaction's scope (#4786) is not tied to that transaction, so such a caller gets the
1753
+ * same `null`-epoch token.
1539
1754
  */
1540
1755
  CapturePostCommitToken(): PostCommitToken;
1541
1756
  private registerPostCommitTaskWithToken;
1542
1757
  /** Number of tasks waiting for the outermost commit. */
1543
1758
  get PendingPostCommitTaskCount(): number;
1544
- /** Number of tasks waiting only for this provider to go idle. */
1759
+ /**
1760
+ * @deprecated Always 0. Post-commit work not tied to the caller's transaction used to be held
1761
+ * until this provider went idle; with scope affinity (#4786) it starts immediately on the pool, so
1762
+ * there is no idle queue left to count. Kept for one release.
1763
+ */
1545
1764
  get PendingIdlePostCommitTaskCount(): number;
1546
1765
  /**
1547
- * Run work whose own transaction has already settled. Immediate when this provider is idle;
1548
- * otherwise held until it is, so the task's writes cannot join — and be rolled back with — a
1549
- * transaction it has nothing to do with.
1766
+ * Start work that is not tied to the caller's transaction now, fire-and-forget; never throws.
1767
+ * Detached so it is in no transaction on this provider — its statements run on the pool, even
1768
+ * while an unrelated transaction is open — and so a begin in its synchronous prefix cannot make
1769
+ * the caller a member (see {@link TransactionAffinity.Claim}).
1550
1770
  */
1551
1771
  private runDetachedTask;
1552
- /** Run everything that was waiting for this provider to go idle. Never throws. */
1553
- private drainIdlePostCommitTasks;
1554
1772
  /** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
1555
1773
  private runPostCommitTasks;
1556
1774
  /** Detach the whole queue (outermost commit succeeded). */
@@ -1578,10 +1796,51 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1578
1796
  * (that would re-enter the mutex).
1579
1797
  */
1580
1798
  ResetTransactionState(): Promise<void>;
1799
+ /**
1800
+ * Cache maintenance for the saves inside a transaction waits for the outermost settle: one
1801
+ * rewrite per cached slot on commit instead of one per save, and nothing written for work that
1802
+ * is rolled back.
1803
+ *
1804
+ * The batch is opened HERE, on the raw primitive, not only in
1805
+ * `DatabaseProviderBase.BeginEntityTransaction` — 41 call sites across the repo use
1806
+ * `BeginTransaction()` directly, including new-user creation on first login, the magic-link
1807
+ * service, the roles/users sync resolver, `MergeRecords` and every generated cascade-delete
1808
+ * override. Those saves each published their own cache write, and a rollback left rows in the
1809
+ * shared cache that were never committed. `BeginEntityTransaction` still opens
1810
+ * its own level on top; the levels are depth-counted, so the batch applies once, at the
1811
+ * outermost settle, either way.
1812
+ */
1581
1813
  BeginTransaction(): Promise<void>;
1814
+ /**
1815
+ * Batch levels this provider has opened and not yet closed.
1816
+ *
1817
+ * The open happens only after a begin SUCCEEDS, while a commit or rollback closes in a
1818
+ * `finally` — so a rollback issued for a begin that threw would close a level it never opened.
1819
+ * That happens for real: a nested begin whose savepoint creation fails leaves the caller's
1820
+ * catch to roll back, and the seventeen generated cascade-delete overrides are written exactly
1821
+ * that way. Closing an outer unit of work's batch early un-batches the rest of its saves, which
1822
+ * then write to the shared cache one by one — the uncommitted-rows-in-the-fleet failure the
1823
+ * batch exists to prevent.
1824
+ */
1825
+ private _openBatchLevels;
1826
+ /** Closes one batch level, but only if this provider opened one. @internal */
1827
+ private endBatchLevelIfOpen;
1582
1828
  CommitTransaction(): Promise<void>;
1583
1829
  RollbackTransaction(): Promise<void>;
1584
1830
  private beginTransactionCore;
1831
+ /**
1832
+ * A nested begin joins the open transaction as a savepoint. When the caller was not already part of
1833
+ * it, that is an unrelated unit of work entangling itself with someone else's transaction on a shared
1834
+ * instance: its savepoint commits only if the owner commits, and settling out of order corrupts both.
1835
+ * Joining keeps pre-#4786 behaviour — waiting for the owner instead can deadlock when the owner is
1836
+ * itself waiting on this work (a coalesced entity-action rerun) — so it is reported, once per
1837
+ * transaction, instead of silently happening. The joiner stays bound to the owner's transaction
1838
+ * after its own savepoint is released: its later plain statements keep running on that
1839
+ * transaction until the owner ends it.
1840
+ */
1841
+ private bindJoiningMembership;
1842
+ /** Savepoint SQL is the provider's own bookkeeping: it must reach the handle whichever scope settles the frame. */
1843
+ private executeTransactionControlSQL;
1585
1844
  private createSavepoint;
1586
1845
  /**
1587
1846
  * Driver codes for a server-aborted ambient TX. Walk `cause` because some
@@ -1601,8 +1860,9 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1601
1860
  private popDoomedFrame;
1602
1861
  private clearSavepointState;
1603
1862
  /**
1604
- * Back to depth 0. A successful commit detaches the post-commit queue first, so anything still
1605
- * queued here belongs to a transaction that rolled back, failed, or was abandoned.
1863
+ * Back to depth 0 — every ending of the transaction goes through here, so it is also where the
1864
+ * transaction's memberships go stale. A successful commit detaches the post-commit queue first, so
1865
+ * anything still queued here belongs to a transaction that rolled back, failed, or was abandoned.
1606
1866
  */
1607
1867
  private clearTransactionState;
1608
1868
  }