@memberjunction/generic-database-provider 6.2.0-edge.2 → 6.2.0-edge.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GenericDatabaseProvider.d.ts +226 -36
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +542 -105
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/SqlLogger.js +2 -2
- package/dist/SqlLogger.js.map +1 -1
- package/dist/TransactionAffinity.d.ts +73 -0
- package/dist/TransactionAffinity.d.ts.map +1 -0
- package/dist/TransactionAffinity.js +120 -0
- package/dist/TransactionAffinity.js.map +1 -0
- package/dist/UserCache.d.ts +277 -11
- package/dist/UserCache.d.ts.map +1 -1
- package/dist/UserCache.js +610 -23
- package/dist/UserCache.js.map +1 -1
- package/dist/countOnlyBatch.d.ts +79 -0
- package/dist/countOnlyBatch.d.ts.map +1 -0
- package/dist/countOnlyBatch.js +153 -0
- package/dist/countOnlyBatch.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/queryCompositionEngine.d.ts +45 -8
- package/dist/queryCompositionEngine.d.ts.map +1 -1
- package/dist/queryCompositionEngine.js +161 -36
- package/dist/queryCompositionEngine.js.map +1 -1
- package/dist/queryPagingEngine.d.ts +147 -95
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +299 -254
- package/dist/queryPagingEngine.js.map +1 -1
- package/dist/renderPipeline.d.ts +24 -1
- package/dist/renderPipeline.d.ts.map +1 -1
- package/dist/renderPipeline.js +33 -4
- package/dist/renderPipeline.js.map +1 -1
- package/package.json +14 -14
|
@@ -16,14 +16,14 @@
|
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
18
18
|
import { SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
|
|
19
|
-
import { MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
|
|
19
|
+
import { BytesToBase64, IsByteArray, MJGlobal, NormalizeUUID, SQLExpressionValidator, UUIDsEqual } from '@memberjunction/global';
|
|
20
20
|
import { QueryPagingEngine } from './queryPagingEngine.js';
|
|
21
21
|
// QueryParameterProcessor is now called internally by RenderPipeline
|
|
22
22
|
import { createHash } from 'node:crypto';
|
|
23
23
|
import { v4 as uuidv4 } from 'uuid';
|
|
24
24
|
import { SqlLoggingSessionImpl } from './SqlLogger.js';
|
|
25
25
|
import { GetDialect } from '@memberjunction/sql-dialect';
|
|
26
|
-
import { SQLParser } from '@memberjunction/sql-parser';
|
|
26
|
+
import { SQLParser, IsReadOnlyQuery, CheckAggregateExpression } from '@memberjunction/sql-parser';
|
|
27
27
|
// QueryCompositionEngine is now owned by RenderPipeline
|
|
28
28
|
import { RenderPipeline } from './renderPipeline.js';
|
|
29
29
|
import { UseJsonArgShape } from './crudSprocFieldRules.js';
|
|
@@ -34,8 +34,15 @@ import { QueueManager } from '@memberjunction/queue';
|
|
|
34
34
|
import { BuildEntityActionDispatchKey, EntityActionDispatchGuard, EntityActionEngineServer } from '@memberjunction/actions';
|
|
35
35
|
import { BuildEntityChangeContext } from '@memberjunction/actions-base';
|
|
36
36
|
import { TransactionFrameTracker } from './TransactionFrameTracker.js';
|
|
37
|
-
import {
|
|
37
|
+
import { TransactionAffinity } from './TransactionAffinity.js';
|
|
38
|
+
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
39
|
+
import { EncryptionEngine, IsEncryptionKeyUnavailable, ReportEncryptionKeyUnavailable } from '@memberjunction/encryption';
|
|
38
40
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
41
|
+
/**
|
|
42
|
+
* Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
|
|
43
|
+
* queries): run it read-only and roll back, so it can neither write nor leave session state behind.
|
|
44
|
+
*/
|
|
45
|
+
const CALLER_SQL_OPTIONS = { readOnlyTransaction: true, description: 'caller-supplied query' };
|
|
39
46
|
/**
|
|
40
47
|
* GenericDatabaseProvider is an intermediate abstract class that implements shared
|
|
41
48
|
* entity action, AI action, encryption, and view WHERE clause rendering logic.
|
|
@@ -89,16 +96,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
89
96
|
* release hands them to the enclosing frame.
|
|
90
97
|
*/
|
|
91
98
|
this._postCommitTasks = [];
|
|
92
|
-
/**
|
|
93
|
-
* Tasks whose own transaction already settled, held back because an UNRELATED transaction is
|
|
94
|
-
* open on this instance. Running them now would enlist their writes in it — on one connection,
|
|
95
|
-
* that means a rollback of work that has nothing to do with them. Drained when this provider
|
|
96
|
-
* goes idle, whichever way that transaction ends.
|
|
97
|
-
*/
|
|
98
|
-
this._idlePostCommitTasks = [];
|
|
99
99
|
/** Identity of each open frame and the fate of recent transactions, for {@link PostCommitToken}s. */
|
|
100
100
|
this._frameTracker = new TransactionFrameTracker();
|
|
101
|
+
/** Which async scope the open transaction belongs to (#4786). See {@link IsCallerInAmbientTransaction}. */
|
|
102
|
+
this._affinity = new TransactionAffinity();
|
|
103
|
+
/** Epoch whose foreign join was already reported, so a transaction reports at most one (#4786). */
|
|
104
|
+
this._foreignJoinReportedEpoch = null;
|
|
101
105
|
this._txMutex = Promise.resolve();
|
|
106
|
+
/**
|
|
107
|
+
* Batch levels this provider has opened and not yet closed.
|
|
108
|
+
*
|
|
109
|
+
* The open happens only after a begin SUCCEEDS, while a commit or rollback closes in a
|
|
110
|
+
* `finally` — so a rollback issued for a begin that threw would close a level it never opened.
|
|
111
|
+
* That happens for real: a nested begin whose savepoint creation fails leaves the caller's
|
|
112
|
+
* catch to roll back, and the seventeen generated cascade-delete overrides are written exactly
|
|
113
|
+
* that way. Closing an outer unit of work's batch early un-batches the rest of its saves, which
|
|
114
|
+
* then write to the shared cache one by one — the uncommitted-rows-in-the-fleet failure the
|
|
115
|
+
* batch exists to prevent.
|
|
116
|
+
*/
|
|
117
|
+
this._openBatchLevels = 0;
|
|
102
118
|
}
|
|
103
119
|
/**
|
|
104
120
|
* Returns the active local storage provider, lazily creating an
|
|
@@ -138,6 +154,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
138
154
|
SetLocalStorageProvider(provider) {
|
|
139
155
|
this._localStorageProvider = provider;
|
|
140
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Installs {@link ProviderConfigDataBase.LocalStorageProvider}, when the configuration carries
|
|
159
|
+
* one, before the base configuration loads metadata. A server fleet passes its shared (Redis)
|
|
160
|
+
* store this way so the metadata load and the engines loaded at startup use it from the first
|
|
161
|
+
* read: the first server to start fills the shared cache, and the others read it instead of
|
|
162
|
+
* each querying the database and broadcasting what they loaded.
|
|
163
|
+
*/
|
|
164
|
+
async Config(data, providerToUse) {
|
|
165
|
+
if (data?.LocalStorageProvider) {
|
|
166
|
+
this.SetLocalStorageProvider(data.LocalStorageProvider);
|
|
167
|
+
}
|
|
168
|
+
return super.Config(data, providerToUse);
|
|
169
|
+
}
|
|
141
170
|
/**************************************************************************/
|
|
142
171
|
// SQL Logging — Session Management & Statement Logging
|
|
143
172
|
/**************************************************************************/
|
|
@@ -634,6 +663,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
634
663
|
async PostProcessRows(rows, entityInfo, user) {
|
|
635
664
|
if (!rows || rows.length === 0)
|
|
636
665
|
return rows;
|
|
666
|
+
// Step 0: binary columns → base64. Drivers return varbinary/bytea as byte arrays (Node
|
|
667
|
+
// Buffers); BaseEntity, the caches and every transport hold binary values as base64
|
|
668
|
+
// strings, so the conversion happens once, here, for every row a provider returns.
|
|
669
|
+
// Applies to external entities too — their drivers return Buffers just the same.
|
|
670
|
+
this.ConvertBinaryFieldsToBase64(rows, entityInfo.BinaryFields);
|
|
637
671
|
// Step 1: Platform-specific datetime adjustment (virtual hook).
|
|
638
672
|
// SKIP for external entities: AdjustDatetimeFields applies THIS provider's platform correction
|
|
639
673
|
// (e.g. SQL Server appends 'Z' to compensate for how tedious marshals datetimes from the LOCAL
|
|
@@ -663,6 +697,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
663
697
|
processedRow[field.Name] = decryptedValue;
|
|
664
698
|
}
|
|
665
699
|
catch (decryptError) {
|
|
700
|
+
// A key this install wasn't given (an app's own key) is configuration, not a
|
|
701
|
+
// fault: one warning per key, and the value stays encrypted.
|
|
702
|
+
if (IsEncryptionKeyUnavailable(decryptError)) {
|
|
703
|
+
ReportEncryptionKeyUnavailable(decryptError);
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
666
706
|
const message = decryptError instanceof Error ? decryptError.message : String(decryptError);
|
|
667
707
|
LogError(`Failed to decrypt field "${field.Name}" on entity "${entityInfo.Name}": ${message}. ` +
|
|
668
708
|
'The encrypted value will be returned unchanged.');
|
|
@@ -672,6 +712,65 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
672
712
|
return processedRow;
|
|
673
713
|
}));
|
|
674
714
|
}
|
|
715
|
+
/**
|
|
716
|
+
* Public entry point to {@link PostProcessRows} for code that runs SQL outside the provider's
|
|
717
|
+
* own read paths but returns entity rows — the transaction groups. Every row a provider hands
|
|
718
|
+
* back must pass through here, so binary columns become base64, datetimes are adjusted and
|
|
719
|
+
* encrypted fields are decrypted no matter which path saved the record.
|
|
720
|
+
*
|
|
721
|
+
* @param rows - Raw rows for `entityInfo`.
|
|
722
|
+
* @param entityInfo - The entity the rows belong to.
|
|
723
|
+
* @param contextUser - The user the rows are processed for (decryption runs as this user).
|
|
724
|
+
* @returns The processed rows.
|
|
725
|
+
*/
|
|
726
|
+
async ProcessEntityRows(rows, entityInfo, contextUser) {
|
|
727
|
+
if (!rows || rows.length === 0)
|
|
728
|
+
return rows;
|
|
729
|
+
return this.PostProcessRows(rows, entityInfo, contextUser);
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Converts the byte-array values of an entity's binary fields to base64 strings, in place.
|
|
733
|
+
*
|
|
734
|
+
* Database drivers return `varbinary` / `binary` / `image` (SQL Server) and `bytea`
|
|
735
|
+
* (PostgreSQL) columns as `Uint8Array`s (Node `Buffer`s). MemberJunction's representation of
|
|
736
|
+
* a binary value above the provider is a base64 string, so it is JSON-safe for dirty tracking,
|
|
737
|
+
* Record Changes, the RunView caches and every transport. Values that are already strings,
|
|
738
|
+
* null or absent are left untouched, which makes the conversion idempotent.
|
|
739
|
+
*
|
|
740
|
+
* @param rows - Rows as returned by the driver; mutated in place.
|
|
741
|
+
* @param binaryFields - The entity's binary fields (`EntityInfo.BinaryFields`).
|
|
742
|
+
*/
|
|
743
|
+
ConvertBinaryFieldsToBase64(rows, binaryFields) {
|
|
744
|
+
if (binaryFields.length === 0)
|
|
745
|
+
return;
|
|
746
|
+
for (const row of rows) {
|
|
747
|
+
for (const field of binaryFields) {
|
|
748
|
+
const value = row[field.Name];
|
|
749
|
+
if (IsByteArray(value))
|
|
750
|
+
row[field.Name] = BytesToBase64(value);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Converts every byte-array value in a set of rows to a base64 string, in place. For results
|
|
756
|
+
* with no entity metadata, such as RunQuery and ad-hoc SQL, where binary columns can only be
|
|
757
|
+
* recognised by value. See {@link ConvertBinaryFieldsToBase64}.
|
|
758
|
+
*
|
|
759
|
+
* @param rows - Rows as returned by the driver; mutated in place.
|
|
760
|
+
*/
|
|
761
|
+
ConvertByteArrayValuesToBase64(rows) {
|
|
762
|
+
if (!rows)
|
|
763
|
+
return;
|
|
764
|
+
for (const row of rows) {
|
|
765
|
+
if (!row || typeof row !== 'object')
|
|
766
|
+
continue;
|
|
767
|
+
for (const key of Object.keys(row)) {
|
|
768
|
+
const value = row[key];
|
|
769
|
+
if (IsByteArray(value))
|
|
770
|
+
row[key] = BytesToBase64(value);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
675
774
|
/**************************************************************************/
|
|
676
775
|
// PreProcessFieldsForSave — Field-Level Encryption Before Save
|
|
677
776
|
/**************************************************************************/
|
|
@@ -953,6 +1052,27 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
953
1052
|
RenderReplaySaveSQL(_binding, _entity, _fieldValues) {
|
|
954
1053
|
return undefined;
|
|
955
1054
|
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Optional replay form of an UPDATE for the SQL log only (never executed). Receives just the
|
|
1057
|
+
* fields this save CHANGED. A recording that carried the whole row would, on replay, overwrite
|
|
1058
|
+
* every column of the target row with the recording database's values — including settings a
|
|
1059
|
+
* deploying application tuned on purpose (an MJ metadata sync that only flipped
|
|
1060
|
+
* `AllowUserSearchAPI` on 'MJ: Content Items' also reset that consumer's
|
|
1061
|
+
* `TrustServerCacheCompletely`). Dialects whose update procs keep unpassed columns override
|
|
1062
|
+
* this. Default: no replay form, the plain save SQL is logged.
|
|
1063
|
+
*/
|
|
1064
|
+
RenderReplayUpdateSQL(_binding, _entity, _changedFieldValues) {
|
|
1065
|
+
return undefined;
|
|
1066
|
+
}
|
|
1067
|
+
/** The entries of a save's parameter map whose fields this save actually changed. */
|
|
1068
|
+
changedFieldValues(entity, fieldValues) {
|
|
1069
|
+
const changed = new Map();
|
|
1070
|
+
for (const [f, value] of fieldValues) {
|
|
1071
|
+
if (entity.GetFieldByName(f.Name)?.Dirty)
|
|
1072
|
+
changed.set(f, value);
|
|
1073
|
+
}
|
|
1074
|
+
return changed;
|
|
1075
|
+
}
|
|
956
1076
|
/**
|
|
957
1077
|
* Concrete implementation of the abstract save-SQL builder defined on
|
|
958
1078
|
* `DatabaseProviderBase`. Iterates fields via the single `IsSPParameter`
|
|
@@ -1017,9 +1137,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1017
1137
|
const baseSaveSQL = this.WrapSaveCallForResult(binding, entity, spName);
|
|
1018
1138
|
let saveSQL = baseSaveSQL;
|
|
1019
1139
|
// A CREATE's logged form is guarded on the primary key so a migration replay of
|
|
1020
|
-
// the recording converges on a database that already holds the row (#4503).
|
|
1021
|
-
//
|
|
1022
|
-
|
|
1140
|
+
// the recording converges on a database that already holds the row (#4503). An
|
|
1141
|
+
// UPDATE's logged form carries only the fields this save changed, so a replay never
|
|
1142
|
+
// resets the target's other columns. A forced save (IgnoreDirtyState, e.g. MetadataSync's
|
|
1143
|
+
// `alwaysPush`) asked to re-impose the whole row, so it keeps the full-row form. Dialects
|
|
1144
|
+
// without a replay form log the plain save SQL.
|
|
1145
|
+
const replaySQL = isNew
|
|
1146
|
+
? this.RenderReplaySaveSQL(binding, entity, fieldValueMap)
|
|
1147
|
+
: options?.IgnoreDirtyState
|
|
1148
|
+
? undefined
|
|
1149
|
+
: this.RenderReplayUpdateSQL(binding, entity, this.changedFieldValues(entity, fieldValueMap));
|
|
1023
1150
|
const simpleSQL = replaySQL ?? baseSaveSQL.sql;
|
|
1024
1151
|
// 5. Optionally wrap with record-change emission.
|
|
1025
1152
|
let overlappingChangeData;
|
|
@@ -1353,6 +1480,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1353
1480
|
* aggregates, parallel query execution, post-processing, and audit logging.
|
|
1354
1481
|
*/
|
|
1355
1482
|
async InternalRunView(params, contextUser) {
|
|
1483
|
+
return this.RunViewCore(params, contextUser);
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* The body of {@link InternalRunView}. `countExecutor`, when supplied, replaces the
|
|
1487
|
+
* direct execution of a `count_only` view's COUNT query — {@link InternalRunViews} uses
|
|
1488
|
+
* it to coalesce an all-`count_only` batch into one statement (see countOnlyBatch.ts).
|
|
1489
|
+
* Everything before that step — permissions, RLS, filter screening — is unchanged.
|
|
1490
|
+
*/
|
|
1491
|
+
async RunViewCore(params, contextUser, countExecutor) {
|
|
1356
1492
|
if (params?.Aggregates?.length) {
|
|
1357
1493
|
LogStatus(`[GenericDatabaseProvider] InternalRunView received aggregates: entityName=${params.EntityName}, viewID=${params.ViewID}, viewName=${params.ViewName}, aggregateCount=${params.Aggregates.length}`);
|
|
1358
1494
|
}
|
|
@@ -1674,7 +1810,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1674
1810
|
const maxRowsUsed = params.MaxRows || entityInfo.UserViewMaxRows;
|
|
1675
1811
|
const willNeedCount = countSQL && (usingPagination || params.ResultType === 'count_only');
|
|
1676
1812
|
if (willNeedCount) {
|
|
1677
|
-
queries.push(
|
|
1813
|
+
queries.push(countExecutor && params.ResultType === 'count_only'
|
|
1814
|
+
? countExecutor(countSQL)
|
|
1815
|
+
: this.ExecuteSQL(countSQL, undefined, undefined, contextUser));
|
|
1678
1816
|
queryKeys.push('count');
|
|
1679
1817
|
}
|
|
1680
1818
|
const aggregateStartTime = Date.now();
|
|
@@ -1771,12 +1909,61 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1771
1909
|
}
|
|
1772
1910
|
}
|
|
1773
1911
|
async InternalRunViews(params, contextUser) {
|
|
1912
|
+
if (IsCoalescibleCountBatch(params)) {
|
|
1913
|
+
return this.RunCoalescedCountBatch(params, contextUser);
|
|
1914
|
+
}
|
|
1774
1915
|
const promises = params.map((p) => this.InternalRunView(p, contextUser));
|
|
1775
1916
|
return Promise.all(promises);
|
|
1776
1917
|
}
|
|
1918
|
+
/**
|
|
1919
|
+
* All-`count_only` batch: every view runs the normal per-view path (so every
|
|
1920
|
+
* security gate applies per view), but their COUNT queries are executed as ONE
|
|
1921
|
+
* `UNION ALL` statement — one database round trip for, e.g., every related-section
|
|
1922
|
+
* badge on a form. A view that fails keeps its own `Success:false` result; a connection
|
|
1923
|
+
* failure is thrown, as on the per-view path.
|
|
1924
|
+
*/
|
|
1925
|
+
async RunCoalescedCountBatch(params, contextUser) {
|
|
1926
|
+
const batch = new CountOnlyBatchCoalescer(params.length, (sql) => this.ExecuteSQL(sql, undefined, undefined, contextUser), (name) => this.QuoteIdentifier(name), (error) => this.isConnectionError(error));
|
|
1927
|
+
return Promise.all(params.map((p, index) => this.RunViewCore(p, contextUser, (countSQL) => batch.Execute(index, countSQL))
|
|
1928
|
+
.finally(() => batch.MarkSettled(index))));
|
|
1929
|
+
}
|
|
1777
1930
|
/**************************************************************************/
|
|
1778
1931
|
// InternalRunView Helpers
|
|
1779
1932
|
/**************************************************************************/
|
|
1933
|
+
/**
|
|
1934
|
+
* Builds the aggregate query without running the caller's text. Each expression must be a single
|
|
1935
|
+
* aggregate function call over this entity's columns: the query runs the SQL that
|
|
1936
|
+
* {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
|
|
1937
|
+
* dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
|
|
1938
|
+
* per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
|
|
1939
|
+
* request order, which is how `RunViewCore` reads their values back.
|
|
1940
|
+
*/
|
|
1941
|
+
BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
|
|
1942
|
+
const columns = entityInfo.Fields.map((f) => f.Name);
|
|
1943
|
+
const items = [];
|
|
1944
|
+
const validationErrors = [];
|
|
1945
|
+
for (const agg of aggregates ?? []) {
|
|
1946
|
+
const screened = this.screenAggregateExpression(agg.expression, columns);
|
|
1947
|
+
if ('SQL' in screened) {
|
|
1948
|
+
items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
|
|
1949
|
+
}
|
|
1950
|
+
else {
|
|
1951
|
+
validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
if (items.length === 0)
|
|
1955
|
+
return { aggregateSQL: null, validationErrors };
|
|
1956
|
+
const where = whereSQL ? ` WHERE ${whereSQL}` : '';
|
|
1957
|
+
return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
|
|
1958
|
+
}
|
|
1959
|
+
/** The SQL to run for one caller aggregate expression, or why it is refused. */
|
|
1960
|
+
screenAggregateExpression(expression, columns) {
|
|
1961
|
+
const check = CheckAggregateExpression(expression, this.Dialect, columns);
|
|
1962
|
+
if (!check.IsAllowed || check.SQL === null)
|
|
1963
|
+
return { Error: `Invalid aggregate expression: ${check.Reason}` };
|
|
1964
|
+
const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
|
|
1965
|
+
return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
|
|
1966
|
+
}
|
|
1780
1967
|
/**
|
|
1781
1968
|
* Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
|
|
1782
1969
|
* the columns this user is allowed to read when field security denies them any.
|
|
@@ -1843,6 +2030,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1843
2030
|
if (!entityInfo)
|
|
1844
2031
|
throw new Error(`Entity ${params.EntityName} not found in metadata`);
|
|
1845
2032
|
}
|
|
2033
|
+
// Binary columns are omitted from every implicit field list (saved-view columns and
|
|
2034
|
+
// the no-Fields wildcard) unless requested; an explicit params.Fields entry is honoured.
|
|
2035
|
+
const includeBinary = params.IncludeBinaryFields === true;
|
|
1846
2036
|
const flsUser = contextUser ?? this.CurrentUser;
|
|
1847
2037
|
const denied = params.ResultType !== 'entity_object' && flsUser && entityInfo.EnableFieldLevelSecurity
|
|
1848
2038
|
? entityInfo.GetDeniedReadFields(flsUser)
|
|
@@ -1868,6 +2058,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1868
2058
|
if (c.EntityField) {
|
|
1869
2059
|
if (denied.has(c.EntityField.Name.trim().toLowerCase()))
|
|
1870
2060
|
return; // silent narrowing
|
|
2061
|
+
if (!includeBinary && c.EntityField.IsBinaryFieldType)
|
|
2062
|
+
return; // binary only on request
|
|
1871
2063
|
fieldList.push(c.EntityField);
|
|
1872
2064
|
}
|
|
1873
2065
|
else {
|
|
@@ -1880,13 +2072,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1880
2072
|
fieldList.push(ef);
|
|
1881
2073
|
}
|
|
1882
2074
|
}
|
|
1883
|
-
else if (denied.size > 0) {
|
|
1884
|
-
// No explicit fields and no saved view would emit `SELECT
|
|
1885
|
-
// user that pulls denied columns out of the database,
|
|
1886
|
-
//
|
|
2075
|
+
else if (denied.size > 0 || (entityInfo.HasBinaryFields && !includeBinary)) {
|
|
2076
|
+
// No explicit fields and no saved view would emit `SELECT *`. For a restricted
|
|
2077
|
+
// user that pulls denied columns out of the database, and for an entity with
|
|
2078
|
+
// binary columns it pulls large values nobody asked for — so emit the explicit
|
|
2079
|
+
// column list instead (PKs are unrestrictable and always included).
|
|
1887
2080
|
for (const ef of entityInfo.Fields) {
|
|
1888
|
-
if (
|
|
1889
|
-
|
|
2081
|
+
if (denied.has(ef.Name.trim().toLowerCase()))
|
|
2082
|
+
continue;
|
|
2083
|
+
if (!includeBinary && ef.IsBinaryFieldType && !ef.IsPrimaryKey)
|
|
2084
|
+
continue;
|
|
2085
|
+
fieldList.push(ef);
|
|
1890
2086
|
}
|
|
1891
2087
|
}
|
|
1892
2088
|
}
|
|
@@ -2204,6 +2400,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2204
2400
|
/**************************************************************************/
|
|
2205
2401
|
// RunViewsWithCacheCheck — Shared Implementation
|
|
2206
2402
|
/**************************************************************************/
|
|
2403
|
+
/**
|
|
2404
|
+
* Row count and newest `__mj_UpdatedAt` for each view, read from the database and never from
|
|
2405
|
+
* a cache. Uses the same WHERE clause (filter, user search, row-level security, pre-run hooks)
|
|
2406
|
+
* and the same batched status query as {@link RunViewsWithCacheCheck}. One entry per param,
|
|
2407
|
+
* in order; a failure is reported per entry.
|
|
2408
|
+
*/
|
|
2409
|
+
async GetRunViewsDatabaseStatus(params, contextUser) {
|
|
2410
|
+
const user = contextUser || this.CurrentUser;
|
|
2411
|
+
const statuses = params.map(() => ({ Success: false, ErrorMessage: 'not checked' }));
|
|
2412
|
+
if (!user) {
|
|
2413
|
+
return statuses.map(() => ({ Success: false, ErrorMessage: 'No user context available' }));
|
|
2414
|
+
}
|
|
2415
|
+
const items = await this.buildDatabaseStatusItems(params, user, statuses);
|
|
2416
|
+
const results = await this.getBatchedServerCacheStatus(items, contextUser);
|
|
2417
|
+
for (const { index } of items) {
|
|
2418
|
+
const status = results.get(index);
|
|
2419
|
+
statuses[index] = status?.success
|
|
2420
|
+
? { Success: true, RowCount: status.rowCount ?? 0, MaxUpdatedAt: status.maxUpdatedAt }
|
|
2421
|
+
: { Success: false, ErrorMessage: status?.errorMessage ?? 'no status returned' };
|
|
2422
|
+
}
|
|
2423
|
+
return statuses;
|
|
2424
|
+
}
|
|
2425
|
+
/** Status-query inputs for {@link GetRunViewsDatabaseStatus}; entries that cannot be built record their error. */
|
|
2426
|
+
async buildDatabaseStatusItems(params, user, statuses) {
|
|
2427
|
+
const items = [];
|
|
2428
|
+
for (let index = 0; index < params.length; index++) {
|
|
2429
|
+
try {
|
|
2430
|
+
const viewParams = { ...params[index] };
|
|
2431
|
+
this.ResolvePlatformSQLInParams(viewParams);
|
|
2432
|
+
const hooked = await this.RunPreRunViewHooks(viewParams, user);
|
|
2433
|
+
const entityInfo = hooked.EntityName ? this.EntityByName(hooked.EntityName) : undefined;
|
|
2434
|
+
if (!entityInfo) {
|
|
2435
|
+
statuses[index] = { Success: false, ErrorMessage: `Entity ${hooked.EntityName ?? '(none)'} not found` };
|
|
2436
|
+
continue;
|
|
2437
|
+
}
|
|
2438
|
+
const whereSQL = await this.buildWhereClauseForCacheCheck(hooked, entityInfo, user);
|
|
2439
|
+
items.push({ index, item: { params: hooked }, entityInfo, whereSQL });
|
|
2440
|
+
}
|
|
2441
|
+
catch (e) {
|
|
2442
|
+
statuses[index] = { Success: false, ErrorMessage: e instanceof Error ? e.message : String(e) };
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
return items;
|
|
2446
|
+
}
|
|
2207
2447
|
/**
|
|
2208
2448
|
* Smart cache validation for batch RunViews.
|
|
2209
2449
|
* For each view request, if cacheStatus is provided, checks if the cache is current
|
|
@@ -2268,7 +2508,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2268
2508
|
// ALL fields, for every user: server slots are full-width and shared, and
|
|
2269
2509
|
// field security narrows per request at read time via
|
|
2270
2510
|
// ApplyFieldSecurityProjection rather than at fetch time.
|
|
2271
|
-
|
|
2511
|
+
this.ResolveIncludeBinaryFields(p, widenEntity);
|
|
2512
|
+
p.Fields = this.ComputeRunViewFetchFields(widenEntity, p);
|
|
2272
2513
|
if (requested) {
|
|
2273
2514
|
callerFieldsByIndex.set(i, ProviderBase.UnionFieldsWithPrimaryKeys(requested, widenEntity));
|
|
2274
2515
|
}
|
|
@@ -2392,6 +2633,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2392
2633
|
const noCacheStatusServedFromCache = [];
|
|
2393
2634
|
const noCacheStatusNeedsDB = [];
|
|
2394
2635
|
for (const entry of itemsWithoutCacheCheck) {
|
|
2636
|
+
// A param carrying BypassCache lands here because it is ineligible for a cache status,
|
|
2637
|
+
// NOT because the caller has nothing cached — and those two must not be treated alike.
|
|
2638
|
+
// Serving it from the server cache is precisely what it asked not to happen: its
|
|
2639
|
+
// documented contract is "the query always hits the database", and it is the only way a
|
|
2640
|
+
// client can escape a server slot that a missed invalidation left stale. The write side
|
|
2641
|
+
// already refuses to store such a result (runViewCacheEligible starts with
|
|
2642
|
+
// !param.BypassCache); this is the matching read-side gate.
|
|
2643
|
+
if (entry.item.params.BypassCache) {
|
|
2644
|
+
LogStatusEx({ message: ` 🚫 [SmartCache BYPASS] "${entry.item.params.EntityName || 'unknown'}" — BypassCache requested, going to the database`, verboseOnly: true });
|
|
2645
|
+
noCacheStatusNeedsDB.push(entry);
|
|
2646
|
+
continue;
|
|
2647
|
+
}
|
|
2395
2648
|
if (LocalCacheManager.Instance.IsInitialized) {
|
|
2396
2649
|
const rlsWhereClause = this.ComputeRunViewRLSWhereClause(entry.item.params, contextUser);
|
|
2397
2650
|
const flsFieldsKey = this.ComputeRunViewFLSFingerprintKey(entry.item.params);
|
|
@@ -2533,6 +2786,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2533
2786
|
}
|
|
2534
2787
|
return whereSQL;
|
|
2535
2788
|
}
|
|
2789
|
+
/**
|
|
2790
|
+
* The freshness probe for one view: a row count, plus the newest `__mj_UpdatedAt` **when the
|
|
2791
|
+
* entity has that column**. Selecting it unconditionally made the probe fail outright for an
|
|
2792
|
+
* entity whose view does not carry it, instead of comparing by count alone the way
|
|
2793
|
+
* `BaseEngine.SweepAgainstDatabase` documents.
|
|
2794
|
+
*/
|
|
2795
|
+
BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL) {
|
|
2796
|
+
const from = `FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, effectiveView)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
2797
|
+
const count = `COUNT(*) AS ${this.QuoteIdentifier('TotalRows')}`;
|
|
2798
|
+
// `Fields` absent (a partial EntityInfo) degrades to the count-only probe rather than
|
|
2799
|
+
// throwing: a freshness check must not be the thing that breaks a sweep.
|
|
2800
|
+
if (!entityInfo.Fields?.some(f => f.IsUpdatedAtField)) {
|
|
2801
|
+
return `SELECT ${count} ${from}`;
|
|
2802
|
+
}
|
|
2803
|
+
return `SELECT ${count}, MAX(${this.QuoteIdentifier('__mj_UpdatedAt')}) AS ${this.QuoteIdentifier('MaxUpdatedAt')} ${from}`;
|
|
2804
|
+
}
|
|
2536
2805
|
/**
|
|
2537
2806
|
* Executes cache status checks for multiple views.
|
|
2538
2807
|
* Default: parallel individual queries (works on all platforms).
|
|
@@ -2551,7 +2820,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2551
2820
|
// (Materialized reads are normally kept out of the client cache by runViewCacheEligible; this
|
|
2552
2821
|
// matches the SQL Server override and is defense-in-depth on the PG/default path.)
|
|
2553
2822
|
const effectiveView = await this.resolveEffectiveBaseView(entityInfo, item.params, contextUser);
|
|
2554
|
-
const statusSQL =
|
|
2823
|
+
const statusSQL = this.BuildCacheStatusSQL(entityInfo, effectiveView, whereSQL);
|
|
2555
2824
|
const rows = await this.ExecuteSQL(statusSQL, undefined, undefined, contextUser);
|
|
2556
2825
|
if (rows && rows.length > 0) {
|
|
2557
2826
|
const row = rows[0];
|
|
@@ -3521,6 +3790,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3521
3790
|
]);
|
|
3522
3791
|
matExecutionTime = Date.now() - start;
|
|
3523
3792
|
rows = dataResult ?? [];
|
|
3793
|
+
this.ConvertByteArrayValuesToBase64(rows);
|
|
3524
3794
|
matTotalRowCount = countResult?.[0]?.TotalRowCount != null ? Number(countResult[0].TotalRowCount) : rows.length;
|
|
3525
3795
|
}
|
|
3526
3796
|
else {
|
|
@@ -3601,6 +3871,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3601
3871
|
if (!dataResult)
|
|
3602
3872
|
throw new Error('Error executing paged query SQL');
|
|
3603
3873
|
paginatedResult = dataResult;
|
|
3874
|
+
this.ConvertByteArrayValuesToBase64(paginatedResult);
|
|
3604
3875
|
totalRowCount = countResult?.[0]?.TotalRowCount != null
|
|
3605
3876
|
? Number(countResult[0].TotalRowCount)
|
|
3606
3877
|
: paginatedResult.length;
|
|
@@ -3683,7 +3954,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3683
3954
|
try {
|
|
3684
3955
|
const validator = SQLExpressionValidator.Instance;
|
|
3685
3956
|
const validation = validator.validateFullQuery(params.SQL);
|
|
3686
|
-
|
|
3957
|
+
const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
|
|
3958
|
+
if (!validation.valid || !statementCheck.IsReadOnly) {
|
|
3687
3959
|
return {
|
|
3688
3960
|
Success: false,
|
|
3689
3961
|
QueryID: '',
|
|
@@ -3692,17 +3964,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3692
3964
|
RowCount: 0,
|
|
3693
3965
|
TotalRowCount: 0,
|
|
3694
3966
|
ExecutionTime: 0,
|
|
3695
|
-
ErrorMessage: validation.
|
|
3967
|
+
ErrorMessage: !validation.valid
|
|
3968
|
+
? validation.error || 'SQL validation failed'
|
|
3969
|
+
: `Ad-hoc SQL must be a single read query: ${statementCheck.Reason}.`,
|
|
3696
3970
|
};
|
|
3697
3971
|
}
|
|
3698
|
-
const {
|
|
3699
|
-
const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
|
|
3972
|
+
const { rows, totalRowCount, executionTime } = await this.runAdhocSQL(params, contextUser);
|
|
3700
3973
|
return {
|
|
3701
3974
|
Success: true,
|
|
3702
3975
|
QueryID: '',
|
|
3703
3976
|
QueryName: 'Ad-Hoc Query',
|
|
3704
|
-
Results:
|
|
3705
|
-
RowCount:
|
|
3977
|
+
Results: rows,
|
|
3978
|
+
RowCount: rows.length,
|
|
3706
3979
|
TotalRowCount: totalRowCount,
|
|
3707
3980
|
ExecutionTime: executionTime,
|
|
3708
3981
|
ErrorMessage: '',
|
|
@@ -3723,6 +3996,60 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3723
3996
|
};
|
|
3724
3997
|
}
|
|
3725
3998
|
}
|
|
3999
|
+
/**
|
|
4000
|
+
* Runs validated ad-hoc SQL. It is rendered the way caller-supplied SQL always is: composition
|
|
4001
|
+
* tokens resolved, comments removed, and a single read query required. With `MaxRows` the
|
|
4002
|
+
* database returns that page and a count runs beside it, as for saved queries, so the server
|
|
4003
|
+
* sends one page rather than every row; without it every row is returned, offset by `StartRow`
|
|
4004
|
+
* when one is given. `TimeoutSeconds` limits every statement the run sends.
|
|
4005
|
+
*/
|
|
4006
|
+
async runAdhocSQL(params, contextUser) {
|
|
4007
|
+
const usePaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
|
|
4008
|
+
const startRow = QueryPagingEngine.ResolveStartRow(params.StartRow);
|
|
4009
|
+
const rendered = RenderPipeline.Run(params.SQL, {
|
|
4010
|
+
Platform: this.PlatformKey,
|
|
4011
|
+
ContextUser: contextUser,
|
|
4012
|
+
RequireReadStatement: true,
|
|
4013
|
+
...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
|
|
4014
|
+
});
|
|
4015
|
+
const options = this.adhocSQLOptions(params);
|
|
4016
|
+
if (!usePaging) {
|
|
4017
|
+
const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
|
|
4018
|
+
const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
|
|
4019
|
+
return { rows: paginatedResult, totalRowCount, executionTime };
|
|
4020
|
+
}
|
|
4021
|
+
const start = Date.now();
|
|
4022
|
+
const [dataResult, total] = await Promise.all([
|
|
4023
|
+
this.ExecuteSQL(rendered.FinalSQL, undefined, options, contextUser),
|
|
4024
|
+
this.countAdhocRows(rendered.PagingResult?.CountSQL ?? null, options, contextUser),
|
|
4025
|
+
]);
|
|
4026
|
+
const rows = dataResult ?? [];
|
|
4027
|
+
return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
|
|
4028
|
+
}
|
|
4029
|
+
/**
|
|
4030
|
+
* The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
|
|
4031
|
+
* fails does not fail the run: some queries page fine but cannot be counted (duplicate column
|
|
4032
|
+
* names are legal in a result but not inside the count's wrap), so the caller reports a lower
|
|
4033
|
+
* bound instead.
|
|
4034
|
+
*/
|
|
4035
|
+
async countAdhocRows(countSQL, options, contextUser) {
|
|
4036
|
+
if (!countSQL)
|
|
4037
|
+
return null;
|
|
4038
|
+
try {
|
|
4039
|
+
const countResult = await this.ExecuteSQL(countSQL, undefined, options, contextUser);
|
|
4040
|
+
const total = Number(countResult?.[0]?.TotalRowCount);
|
|
4041
|
+
return Number.isFinite(total) && total >= 0 ? Math.floor(total) : null;
|
|
4042
|
+
}
|
|
4043
|
+
catch (e) {
|
|
4044
|
+
LogError(`Ad-hoc query row count failed; reporting a lower-bound total. ${e instanceof Error ? e.message : String(e)}`);
|
|
4045
|
+
return null;
|
|
4046
|
+
}
|
|
4047
|
+
}
|
|
4048
|
+
/** The options every statement of an ad-hoc run uses: caller-SQL protections, plus its timeout. */
|
|
4049
|
+
adhocSQLOptions(params) {
|
|
4050
|
+
const seconds = params.TimeoutSeconds;
|
|
4051
|
+
return seconds && seconds > 0 ? { ...CALLER_SQL_OPTIONS, timeoutMs: seconds * 1000 } : CALLER_SQL_OPTIONS;
|
|
4052
|
+
}
|
|
3726
4053
|
/**
|
|
3727
4054
|
* Finds a query from RunQueryParams and validates user permissions.
|
|
3728
4055
|
* Uses `resolveQuery()` for lookup and `ValidateQueryForExecution()` for permissions.
|
|
@@ -3889,7 +4216,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3889
4216
|
const resolved = this.resolveSpecParameters(spec, contextUser);
|
|
3890
4217
|
finalSQL = resolved.finalSQL;
|
|
3891
4218
|
// Execute
|
|
3892
|
-
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser);
|
|
4219
|
+
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
|
|
3893
4220
|
return {
|
|
3894
4221
|
Success: true,
|
|
3895
4222
|
QueryID: '',
|
|
@@ -3939,6 +4266,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3939
4266
|
Dependencies: spec.Dependencies,
|
|
3940
4267
|
OriginalSQL: spec.SQL,
|
|
3941
4268
|
MaxRows: spec.MaxRows,
|
|
4269
|
+
RequireReadStatement: true,
|
|
3942
4270
|
});
|
|
3943
4271
|
if (!result.HasCompositions && !spec.UsesTemplate && spec.Parameters && Object.keys(spec.Parameters).length > 0) {
|
|
3944
4272
|
LogStatus('Warning: Parameters provided but query does not use templates. Parameters will be ignored.');
|
|
@@ -3964,13 +4292,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3964
4292
|
/**
|
|
3965
4293
|
* Executes the query SQL and tracks execution time.
|
|
3966
4294
|
*/
|
|
3967
|
-
async executeQueryWithTiming(sql, contextUser, parameters) {
|
|
4295
|
+
async executeQueryWithTiming(sql, contextUser, parameters, options) {
|
|
3968
4296
|
const start = Date.now();
|
|
3969
|
-
const result = await this.ExecuteSQL(sql, parameters,
|
|
4297
|
+
const result = await this.ExecuteSQL(sql, parameters, options, contextUser);
|
|
3970
4298
|
const executionTime = Date.now() - start;
|
|
3971
4299
|
if (!result) {
|
|
3972
4300
|
throw new Error('Error executing query SQL');
|
|
3973
4301
|
}
|
|
4302
|
+
// Query results carry no entity metadata, so binary columns are found by value.
|
|
4303
|
+
this.ConvertByteArrayValuesToBase64(result);
|
|
3974
4304
|
return { result, executionTime };
|
|
3975
4305
|
}
|
|
3976
4306
|
/**
|
|
@@ -4565,6 +4895,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4565
4895
|
continue;
|
|
4566
4896
|
}
|
|
4567
4897
|
let itemData = batchResults[i] || [];
|
|
4898
|
+
// Binary columns become base64 whether or not the entity post-processing below runs —
|
|
4899
|
+
// at boot there is no context user, and a raw Buffer must never reach the metadata
|
|
4900
|
+
// cache or the wire (it serializes as {"type":"Buffer","data":[...]}).
|
|
4901
|
+
this.ConvertByteArrayValuesToBase64(itemData);
|
|
4568
4902
|
// Post-process rows for encryption/datetime
|
|
4569
4903
|
if (itemData.length > 0) {
|
|
4570
4904
|
const entityInfo = provider.EntityByName(entityName);
|
|
@@ -4769,9 +5103,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4769
5103
|
/**
|
|
4770
5104
|
* Validates columns for a dataset item and returns the column list string.
|
|
4771
5105
|
* Returns null if columns are invalid.
|
|
5106
|
+
*
|
|
5107
|
+
* An item that names no columns selects every column EXCEPT binary ones, matching RunView's
|
|
5108
|
+
* default (binary columns are large and rarely wanted; see guides/BINARY_FIELDS_GUIDE.md). A
|
|
5109
|
+
* binary column can still be named explicitly. When the entity's metadata is not loaded yet —
|
|
5110
|
+
* the first `MJ_Metadata` read at boot — the item falls back to `*`, and the rows' byte arrays
|
|
5111
|
+
* are converted to base64 by the caller.
|
|
4772
5112
|
*/
|
|
4773
5113
|
getColumnsForDatasetItem(item, datasetName) {
|
|
4774
5114
|
const specifiedColumns = item['Columns'] ? String(item['Columns']).split(',').map(col => col.trim()) : [];
|
|
5115
|
+
if (specifiedColumns.length === 0) {
|
|
5116
|
+
const entity = this.EntityByID(item['EntityID']);
|
|
5117
|
+
if (entity?.HasBinaryFields) {
|
|
5118
|
+
return entity.Fields.filter(f => !f.IsBinaryFieldType).map(f => this.QuoteIdentifier(f.Name)).join(',');
|
|
5119
|
+
}
|
|
5120
|
+
}
|
|
4775
5121
|
if (specifiedColumns.length > 0) {
|
|
4776
5122
|
const entity = this.EntityByID(item['EntityID']);
|
|
4777
5123
|
if (!entity && this.Entities.length > 0) {
|
|
@@ -4958,12 +5304,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4958
5304
|
get IsDoomed() {
|
|
4959
5305
|
return this._doomed;
|
|
4960
5306
|
}
|
|
4961
|
-
/**
|
|
4962
|
-
* Throw if a statement would run on the pool while frames are still open
|
|
4963
|
-
* after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
|
|
4964
|
-
* — outermost begin has depth 1 before the handle is published, and
|
|
4965
|
-
* concurrent reads on SQL Server legitimately use the pool in that window.
|
|
4966
|
-
*/
|
|
4967
5307
|
/**
|
|
4968
5308
|
* A debounced metadata refresh is timer-driven, so it can fire at any point of a caller's
|
|
4969
5309
|
* unit of work — including the microtask window while the ambient transaction is being
|
|
@@ -4973,21 +5313,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4973
5313
|
* Metadata reads are not part of anyone's unit of work, so wait for the transaction to end
|
|
4974
5314
|
* before starting one (#4486).
|
|
4975
5315
|
*
|
|
4976
|
-
*
|
|
4977
|
-
*
|
|
4978
|
-
*
|
|
4979
|
-
*
|
|
4980
|
-
*
|
|
4981
|
-
*
|
|
5316
|
+
* Under scope affinity (#4786) the timer inherits the membership of the code that scheduled it
|
|
5317
|
+
* (re-arms included), so the refresh can only ever join the transaction whose scope scheduled
|
|
5318
|
+
* it — and only if that transaction is still open when the batch is issued, several round trips
|
|
5319
|
+
* after this check ran. It never joins a transaction someone else begins later. That remaining
|
|
5320
|
+
* window is harmless to the process — the batch fails, the dataset reports it, and the loaded
|
|
5321
|
+
* metadata stays — but the refresh itself is lost until the next member write. The check is
|
|
5322
|
+
* instance-wide, so an unrelated transaction also defers the refresh. Running the metadata
|
|
5323
|
+
* batch on the pool regardless of the ambient transaction is #4514 (alongside #4454, the
|
|
5324
|
+
* commit-side half of the same window).
|
|
4982
5325
|
*/
|
|
4983
5326
|
get MetadataMemberRefreshMustWait() {
|
|
4984
5327
|
return this.CurrentTransactionDepth > 0 || this.HasPhysicalTransaction;
|
|
4985
5328
|
}
|
|
5329
|
+
/**
|
|
5330
|
+
* Throw if a statement from a member of the ambient transaction would run on the pool while its
|
|
5331
|
+
* frames are still open after a server abort. Keyed on `_doomed`, not "depth > 0 with no handle"
|
|
5332
|
+
* — outermost begin has depth 1 before the handle is published, and concurrent reads on SQL
|
|
5333
|
+
* Server legitimately use the pool in that window. Callers outside the transaction's scope
|
|
5334
|
+
* (see {@link IsCallerInAmbientTransaction}) do not use its handle, so a subclass should apply
|
|
5335
|
+
* this check only to members' statements.
|
|
5336
|
+
*/
|
|
4986
5337
|
AssertAmbientTransactionUsable() {
|
|
4987
5338
|
if (this._doomed) {
|
|
4988
5339
|
throw new DoomedTransactionError(`SQL issued at depth ${this._transactionDepth} while the ambient transaction is doomed would autocommit on the pool`);
|
|
4989
5340
|
}
|
|
4990
5341
|
}
|
|
5342
|
+
/**
|
|
5343
|
+
* Whether the calling async scope is part of this provider's ambient transaction (#4786). A shared
|
|
5344
|
+
* provider's open transaction belongs to the scope that began it and its descendants; every other
|
|
5345
|
+
* caller must run on the pool, as if no transaction were open. Subclasses consult this — not merely
|
|
5346
|
+
* "is a handle open" — before routing a statement to the transaction handle.
|
|
5347
|
+
*/
|
|
5348
|
+
IsCallerInAmbientTransaction() {
|
|
5349
|
+
return this._affinity.IsCallerMember;
|
|
5350
|
+
}
|
|
5351
|
+
/** Members of the open transaction share RunViews only with each other (see {@link ProviderBase.RunViewDedupScope}). */
|
|
5352
|
+
get RunViewDedupScope() {
|
|
5353
|
+
return this.IsCallerInAmbientTransaction() ? `tx:${this._affinity.CurrentEpoch}` : '';
|
|
5354
|
+
}
|
|
4991
5355
|
/**
|
|
4992
5356
|
* Drop a dead physical handle without going through public RollbackTransaction.
|
|
4993
5357
|
* Default is RollbackPhysicalTransaction if one is open. Subclasses override
|
|
@@ -5021,8 +5385,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5021
5385
|
}
|
|
5022
5386
|
}
|
|
5023
5387
|
/**
|
|
5024
|
-
* Queue `task` until the outermost commit of the
|
|
5025
|
-
* there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract.
|
|
5388
|
+
* Queue `task` until the outermost commit of the caller's transaction, or start it now when
|
|
5389
|
+
* there is none. See {@link DatabaseProviderBase.RunAfterCommit} for the contract. Work
|
|
5390
|
+
* registered by a caller outside the open transaction's scope (#4786) is not tied to that
|
|
5391
|
+
* transaction: it starts now, detached, on the pool, whether or not that transaction is open.
|
|
5026
5392
|
*
|
|
5027
5393
|
* - Queued tasks run once, in registration order, after the outermost commit succeeds and the
|
|
5028
5394
|
* transaction lock is released — so a task may begin its own transaction. The committer
|
|
@@ -5036,26 +5402,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5036
5402
|
* token was captured in, rolled back — including a savepoint rolled back inside a transaction
|
|
5037
5403
|
* that went on to commit — or if the token matches nothing this provider knows; otherwise it
|
|
5038
5404
|
* is queued at the deepest captured frame that is still open. A token captured outside any
|
|
5039
|
-
* transaction always runs.
|
|
5040
|
-
*
|
|
5405
|
+
* transaction always runs.
|
|
5406
|
+
* - "Starts now" means fire-and-forget under {@link TransactionAffinity.RunDetached}: the task is
|
|
5407
|
+
* in no transaction on this provider (its statements run on the pool), the caller never awaits
|
|
5408
|
+
* it, and a `BeginTransaction` in the task's synchronous prefix stays in the task's own scope.
|
|
5409
|
+
* If the task begins a transaction while another is open on this instance, it joins that one as
|
|
5410
|
+
* a savepoint (logged) — a task that needs its own transaction belongs on an independent instance.
|
|
5041
5411
|
*/
|
|
5042
5412
|
RunAfterCommit(task, description = 'post-commit task', token) {
|
|
5043
5413
|
if (token) {
|
|
5044
5414
|
this.registerPostCommitTaskWithToken(task, description, token);
|
|
5045
5415
|
return;
|
|
5046
5416
|
}
|
|
5047
|
-
if (
|
|
5048
|
-
|
|
5417
|
+
if (!this.IsCallerInAmbientTransaction()) {
|
|
5418
|
+
// No transaction open, or not the caller's: either way the task is not tied to one.
|
|
5419
|
+
this.runDetachedTask(task, description);
|
|
5049
5420
|
return;
|
|
5050
5421
|
}
|
|
5051
5422
|
this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
|
|
5052
5423
|
}
|
|
5053
5424
|
/**
|
|
5054
|
-
* Snapshot of the
|
|
5055
|
-
* outside a transaction it returns a token whose epoch is `null`, which says the work
|
|
5056
|
-
* durable rather than saying nothing. See
|
|
5425
|
+
* Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
|
|
5426
|
+
* provider: outside a transaction it returns a token whose epoch is `null`, which says the work
|
|
5427
|
+
* is already durable rather than saying nothing. See
|
|
5428
|
+
* {@link DatabaseProviderBase.CapturePostCommitToken}. Work registered by a caller outside the
|
|
5429
|
+
* open transaction's scope (#4786) is not tied to that transaction, so such a caller gets the
|
|
5430
|
+
* same `null`-epoch token.
|
|
5057
5431
|
*/
|
|
5058
5432
|
CapturePostCommitToken() {
|
|
5433
|
+
if (!this.IsCallerInAmbientTransaction()) {
|
|
5434
|
+
return { Epoch: null, FrameIds: [] };
|
|
5435
|
+
}
|
|
5059
5436
|
return this._frameTracker.Capture();
|
|
5060
5437
|
}
|
|
5061
5438
|
registerPostCommitTaskWithToken(task, description, token) {
|
|
@@ -5083,33 +5460,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5083
5460
|
get PendingPostCommitTaskCount() {
|
|
5084
5461
|
return this._postCommitTasks.length;
|
|
5085
5462
|
}
|
|
5086
|
-
/**
|
|
5463
|
+
/**
|
|
5464
|
+
* @deprecated Always 0. Post-commit work not tied to the caller's transaction used to be held
|
|
5465
|
+
* until this provider went idle; with scope affinity (#4786) it starts immediately on the pool, so
|
|
5466
|
+
* there is no idle queue left to count. Kept for one release.
|
|
5467
|
+
*/
|
|
5087
5468
|
get PendingIdlePostCommitTaskCount() {
|
|
5088
|
-
return
|
|
5469
|
+
return 0;
|
|
5089
5470
|
}
|
|
5090
5471
|
/**
|
|
5091
|
-
*
|
|
5092
|
-
*
|
|
5093
|
-
* transaction
|
|
5472
|
+
* Start work that is not tied to the caller's transaction now, fire-and-forget; never throws.
|
|
5473
|
+
* Detached so it is in no transaction on this provider — its statements run on the pool, even
|
|
5474
|
+
* while an unrelated transaction is open — and so a begin in its synchronous prefix cannot make
|
|
5475
|
+
* the caller a member (see {@link TransactionAffinity.Claim}).
|
|
5094
5476
|
*/
|
|
5095
5477
|
runDetachedTask(task, description) {
|
|
5096
|
-
|
|
5097
|
-
super.RunAfterCommit(task, description);
|
|
5098
|
-
return;
|
|
5099
|
-
}
|
|
5100
|
-
this._idlePostCommitTasks.push({ Task: task, Description: description, Depth: 0 });
|
|
5101
|
-
}
|
|
5102
|
-
/** Run everything that was waiting for this provider to go idle. Never throws. */
|
|
5103
|
-
async drainIdlePostCommitTasks() {
|
|
5104
|
-
if (this._idlePostCommitTasks.length === 0 || this._transactionDepth > 0 || this.HasPhysicalTransaction) {
|
|
5105
|
-
return;
|
|
5106
|
-
}
|
|
5107
|
-
const tasks = this._idlePostCommitTasks;
|
|
5108
|
-
this._idlePostCommitTasks = [];
|
|
5109
|
-
LogStatus(`Running ${tasks.length} post-commit task(s) held back by an unrelated transaction`);
|
|
5110
|
-
for (const entry of tasks) {
|
|
5111
|
-
await this.RunPostCommitTaskSafely(entry.Task, entry.Description);
|
|
5112
|
-
}
|
|
5478
|
+
void this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(task, description));
|
|
5113
5479
|
}
|
|
5114
5480
|
/** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
|
|
5115
5481
|
async runPostCommitTasks(tasks) {
|
|
@@ -5118,7 +5484,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5118
5484
|
}
|
|
5119
5485
|
LogStatus(`Running ${tasks.length} post-commit task(s) after transaction commit`);
|
|
5120
5486
|
for (const entry of tasks) {
|
|
5121
|
-
|
|
5487
|
+
// Detached from the committer's (now stale) membership explicitly, not merely by epoch mismatch.
|
|
5488
|
+
await this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(entry.Task, entry.Description));
|
|
5122
5489
|
}
|
|
5123
5490
|
}
|
|
5124
5491
|
/** Detach the whole queue (outermost commit succeeded). */
|
|
@@ -5176,29 +5543,79 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5176
5543
|
*/
|
|
5177
5544
|
async ResetTransactionState() {
|
|
5178
5545
|
await this.WithTransactionLock(() => this.abandonDoomedTransaction());
|
|
5179
|
-
|
|
5546
|
+
// The frames are gone, so no settle will ever close this instance's batch. Drop it here or
|
|
5547
|
+
// its entities count as pending forever and every cached read of them misses.
|
|
5548
|
+
this._openBatchLevels = 0;
|
|
5549
|
+
await LocalCacheManager.Instance.AbandonEntityEventBatch(this);
|
|
5180
5550
|
}
|
|
5551
|
+
/**
|
|
5552
|
+
* Cache maintenance for the saves inside a transaction waits for the outermost settle: one
|
|
5553
|
+
* rewrite per cached slot on commit instead of one per save, and nothing written for work that
|
|
5554
|
+
* is rolled back.
|
|
5555
|
+
*
|
|
5556
|
+
* The batch is opened HERE, on the raw primitive, not only in
|
|
5557
|
+
* `DatabaseProviderBase.BeginEntityTransaction` — 41 call sites across the repo use
|
|
5558
|
+
* `BeginTransaction()` directly, including new-user creation on first login, the magic-link
|
|
5559
|
+
* service, the roles/users sync resolver, `MergeRecords` and every generated cascade-delete
|
|
5560
|
+
* override. Those saves each published their own cache write, and a rollback left rows in the
|
|
5561
|
+
* shared cache that were never committed. `BeginEntityTransaction` still opens
|
|
5562
|
+
* its own level on top; the levels are depth-counted, so the batch applies once, at the
|
|
5563
|
+
* outermost settle, either way.
|
|
5564
|
+
*/
|
|
5181
5565
|
async BeginTransaction() {
|
|
5182
|
-
|
|
5566
|
+
// Claimed before the first await (the lock's): see TransactionAffinity.Claim for why.
|
|
5567
|
+
const membership = this._affinity.Claim();
|
|
5568
|
+
try {
|
|
5569
|
+
await this.WithTransactionLock(() => this.beginTransactionCore(membership));
|
|
5570
|
+
}
|
|
5571
|
+
catch (e) {
|
|
5572
|
+
// Every failure path, including a begin refused while doomed. A no-op for a membership
|
|
5573
|
+
// already bound (a member's failed nested begin): see TransactionAffinity.Release.
|
|
5574
|
+
this._affinity.Release(membership);
|
|
5575
|
+
throw e;
|
|
5576
|
+
}
|
|
5577
|
+
LocalCacheManager.Instance.BeginEntityEventBatch(this);
|
|
5578
|
+
this._openBatchLevels++;
|
|
5579
|
+
}
|
|
5580
|
+
/** Closes one batch level, but only if this provider opened one. @internal */
|
|
5581
|
+
async endBatchLevelIfOpen(succeeded) {
|
|
5582
|
+
if (this._openBatchLevels <= 0) {
|
|
5583
|
+
return;
|
|
5584
|
+
}
|
|
5585
|
+
this._openBatchLevels--;
|
|
5586
|
+
await LocalCacheManager.Instance.EndEntityEventBatch(this, succeeded);
|
|
5183
5587
|
}
|
|
5184
5588
|
async CommitTransaction() {
|
|
5185
5589
|
// null = not the outermost commit, so nothing drains and the subclass hook does not run.
|
|
5186
|
-
|
|
5187
|
-
|
|
5188
|
-
|
|
5189
|
-
|
|
5190
|
-
|
|
5590
|
+
let committedTasks;
|
|
5591
|
+
try {
|
|
5592
|
+
committedTasks = await this.WithTransactionLock(async () => {
|
|
5593
|
+
const outermost = this._transactionDepth === 1;
|
|
5594
|
+
const tasks = await this.commitTransactionCore();
|
|
5595
|
+
return outermost ? tasks : null;
|
|
5596
|
+
});
|
|
5597
|
+
}
|
|
5598
|
+
catch (e) {
|
|
5599
|
+
// The commit failed: the rows may not be in the database, so the batch settles as a
|
|
5600
|
+
// failure (its slots are invalidated) rather than being left open.
|
|
5601
|
+
await this.endBatchLevelIfOpen(false);
|
|
5602
|
+
throw e;
|
|
5603
|
+
}
|
|
5604
|
+
await this.endBatchLevelIfOpen(true);
|
|
5191
5605
|
if (committedTasks) {
|
|
5192
5606
|
await this.runPostCommitTasks(committedTasks);
|
|
5193
5607
|
await this.AfterPhysicalCommit();
|
|
5194
5608
|
}
|
|
5195
|
-
await this.drainIdlePostCommitTasks();
|
|
5196
5609
|
}
|
|
5197
5610
|
async RollbackTransaction() {
|
|
5198
|
-
|
|
5199
|
-
|
|
5611
|
+
try {
|
|
5612
|
+
await this.WithTransactionLock(() => this.rollbackTransactionCore());
|
|
5613
|
+
}
|
|
5614
|
+
finally {
|
|
5615
|
+
await this.endBatchLevelIfOpen(false);
|
|
5616
|
+
}
|
|
5200
5617
|
}
|
|
5201
|
-
async beginTransactionCore() {
|
|
5618
|
+
async beginTransactionCore(membership) {
|
|
5202
5619
|
if (this._doomed) {
|
|
5203
5620
|
throw new DoomedTransactionError();
|
|
5204
5621
|
}
|
|
@@ -5208,6 +5625,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5208
5625
|
if (this._transactionDepth === 1) {
|
|
5209
5626
|
this._abandonedByFailedCommit = false;
|
|
5210
5627
|
await this.BeginPhysicalTransaction();
|
|
5628
|
+
this._affinity.OpenEpoch();
|
|
5629
|
+
this._affinity.Bind(membership);
|
|
5211
5630
|
return;
|
|
5212
5631
|
}
|
|
5213
5632
|
if (!this.HasPhysicalTransaction) {
|
|
@@ -5223,6 +5642,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5223
5642
|
this._savepointCounter--;
|
|
5224
5643
|
throw savepointError;
|
|
5225
5644
|
}
|
|
5645
|
+
// Only once the savepoint exists (as the outermost binds only after BEGIN): a begin that
|
|
5646
|
+
// failed to join must not leave its caller's statements routed to the transaction handle.
|
|
5647
|
+
this.bindJoiningMembership(membership);
|
|
5226
5648
|
}
|
|
5227
5649
|
catch (e) {
|
|
5228
5650
|
if (this._transactionDepth > 0) {
|
|
@@ -5241,14 +5663,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5241
5663
|
throw e;
|
|
5242
5664
|
}
|
|
5243
5665
|
}
|
|
5666
|
+
/**
|
|
5667
|
+
* A nested begin joins the open transaction as a savepoint. When the caller was not already part of
|
|
5668
|
+
* it, that is an unrelated unit of work entangling itself with someone else's transaction on a shared
|
|
5669
|
+
* instance: its savepoint commits only if the owner commits, and settling out of order corrupts both.
|
|
5670
|
+
* Joining keeps pre-#4786 behaviour — waiting for the owner instead can deadlock when the owner is
|
|
5671
|
+
* itself waiting on this work (a coalesced entity-action rerun) — so it is reported, once per
|
|
5672
|
+
* transaction, instead of silently happening. The joiner stays bound to the owner's transaction
|
|
5673
|
+
* after its own savepoint is released: its later plain statements keep running on that
|
|
5674
|
+
* transaction until the owner ends it.
|
|
5675
|
+
*/
|
|
5676
|
+
bindJoiningMembership(membership) {
|
|
5677
|
+
const epoch = this._affinity.CurrentEpoch;
|
|
5678
|
+
if (membership.Epoch !== epoch && this._foreignJoinReportedEpoch !== epoch) {
|
|
5679
|
+
this._foreignJoinReportedEpoch = epoch;
|
|
5680
|
+
LogError(`${this.constructor.name}: a transaction was begun by code outside the async scope of the transaction ` +
|
|
5681
|
+
`already open on this provider instance, so it joins that transaction as a savepoint. Its writes now ` +
|
|
5682
|
+
`commit or roll back with a unit of work it is not part of, and its later statements keep running ` +
|
|
5683
|
+
`in that transaction until its owner ends it. Run independent units of work on ` +
|
|
5684
|
+
`CreateIndependentInstance() or a per-request provider (#4786).`);
|
|
5685
|
+
}
|
|
5686
|
+
this._affinity.Bind(membership);
|
|
5687
|
+
}
|
|
5688
|
+
/** Savepoint SQL is the provider's own bookkeeping: it must reach the handle whichever scope settles the frame. */
|
|
5689
|
+
async executeTransactionControlSQL(sql, description) {
|
|
5690
|
+
await this._affinity.RunAsMember(() => this.ExecuteSQL(sql, undefined, { description, ignoreLogging: true }));
|
|
5691
|
+
}
|
|
5244
5692
|
async createSavepoint(savepointName) {
|
|
5245
5693
|
const sql = this.Dialect.CreateSavepointSQL(savepointName);
|
|
5246
|
-
const options = {
|
|
5247
|
-
description: `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`,
|
|
5248
|
-
ignoreLogging: true,
|
|
5249
|
-
};
|
|
5250
5694
|
try {
|
|
5251
|
-
await this.
|
|
5695
|
+
await this.executeTransactionControlSQL(sql, `Creating savepoint ${savepointName} at depth ${this._transactionDepth}`);
|
|
5252
5696
|
}
|
|
5253
5697
|
catch (savepointError) {
|
|
5254
5698
|
if (this.HasPhysicalTransaction && this.isDoomedPhysicalTransactionError(savepointError)) {
|
|
@@ -5324,10 +5768,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5324
5768
|
const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
|
|
5325
5769
|
if (releaseSQL) {
|
|
5326
5770
|
try {
|
|
5327
|
-
await this.
|
|
5328
|
-
description: `Releasing savepoint ${savepointName}`,
|
|
5329
|
-
ignoreLogging: true,
|
|
5330
|
-
});
|
|
5771
|
+
await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName}`);
|
|
5331
5772
|
}
|
|
5332
5773
|
catch (e) {
|
|
5333
5774
|
await this.AbandonPhysicalTransaction();
|
|
@@ -5372,16 +5813,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5372
5813
|
throw new Error('Savepoint stack mismatch - no savepoint to rollback to');
|
|
5373
5814
|
}
|
|
5374
5815
|
try {
|
|
5375
|
-
await this.
|
|
5376
|
-
description: `Rolling back to savepoint ${savepointName}`,
|
|
5377
|
-
ignoreLogging: true,
|
|
5378
|
-
});
|
|
5816
|
+
await this.executeTransactionControlSQL(this.Dialect.RollbackToSavepointSQL(savepointName), `Rolling back to savepoint ${savepointName}`);
|
|
5379
5817
|
const releaseSQL = this.Dialect.ReleaseSavepointSQL(savepointName);
|
|
5380
5818
|
if (releaseSQL) {
|
|
5381
|
-
await this.
|
|
5382
|
-
description: `Releasing savepoint ${savepointName} after rollback`,
|
|
5383
|
-
ignoreLogging: true,
|
|
5384
|
-
});
|
|
5819
|
+
await this.executeTransactionControlSQL(releaseSQL, `Releasing savepoint ${savepointName} after rollback`);
|
|
5385
5820
|
}
|
|
5386
5821
|
this.discardPostCommitTasks(this._transactionDepth, `savepoint ${savepointName} was rolled back`);
|
|
5387
5822
|
this._savepointStack.pop();
|
|
@@ -5412,10 +5847,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5412
5847
|
this._savepointCounter = 0;
|
|
5413
5848
|
}
|
|
5414
5849
|
/**
|
|
5415
|
-
* Back to depth 0
|
|
5416
|
-
*
|
|
5850
|
+
* Back to depth 0 — every ending of the transaction goes through here, so it is also where the
|
|
5851
|
+
* transaction's memberships go stale. A successful commit detaches the post-commit queue first, so
|
|
5852
|
+
* anything still queued here belongs to a transaction that rolled back, failed, or was abandoned.
|
|
5417
5853
|
*/
|
|
5418
5854
|
clearTransactionState() {
|
|
5855
|
+
this._affinity.CloseEpoch();
|
|
5419
5856
|
this._transactionDepth = 0;
|
|
5420
5857
|
this._doomed = false;
|
|
5421
5858
|
this.clearSavepointState();
|