@memberjunction/generic-database-provider 6.3.0-edge.0 → 6.3.0-edge.1
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 +114 -6
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +806 -105
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/UserCache.d.ts +32 -0
- package/dist/UserCache.d.ts.map +1 -1
- package/dist/UserCache.js +111 -12
- package/dist/UserCache.js.map +1 -1
- package/dist/clientClauseScreen.d.ts.map +1 -1
- package/dist/clientClauseScreen.js +4 -1
- package/dist/clientClauseScreen.js.map +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/recordChangeSnapshot.d.ts +28 -0
- package/dist/recordChangeSnapshot.d.ts.map +1 -1
- package/dist/recordChangeSnapshot.js +66 -0
- package/dist/recordChangeSnapshot.js.map +1 -1
- package/dist/rowFilterParameters.d.ts +22 -0
- package/dist/rowFilterParameters.d.ts.map +1 -0
- package/dist/rowFilterParameters.js +23 -0
- package/dist/rowFilterParameters.js.map +1 -0
- package/dist/serverPrincipal.d.ts +45 -0
- package/dist/serverPrincipal.d.ts.map +1 -0
- package/dist/serverPrincipal.js +46 -0
- package/dist/serverPrincipal.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +14 -14
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
18
|
-
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProjectEntityValueRowsForUser, FieldSecurityError, FieldSecuritySQLGate, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride, NormalizeAlternateBaseViewName, ResolveAlternateBaseView, LocalCacheManager, LogError, LogErrorEx, LogStatus, LogStatusEx, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, ServerOperationScopeManager, NormalizeRunViewParameters, CompositeFilterSQLCompiler, } from '@memberjunction/core';
|
|
19
|
-
import { BytesToBase64, GroupByUUID, IndexByUUID, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UnwrapPhraseQuotes, UUIDsEqual, UUIDSet } from '@memberjunction/global';
|
|
18
|
+
import { BaseEntity, SerializeCloneChangeContext, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProjectEntityValueRowsForUser, FieldSecurityError, FieldSecuritySQLGate, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, GetEffectiveAlternateBaseViewName, IsExplicitBaseViewOverride, NormalizeAlternateBaseViewName, ResolveAlternateBaseView, LocalCacheManager, LogError, LogErrorEx, LogStatus, LogStatusEx, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, FindQueryContextTokens, ValidateUserViewProperties, ResolveViewPropertyValues, BuildViewPropertyFilter, ServerOperationScopeManager, NormalizeRunViewParameters, CompositeFilterSQLCompiler, IsPostRunViewProtectedEntity, WellKnownUserSource, } from '@memberjunction/core';
|
|
19
|
+
import { BytesToBase64, EscapeSQLString, GroupByUUID, IndexByUUID, IsByteArray, IsValidUUID, MJGlobal, NormalizeUUID, SQLExpressionValidator, UnwrapPhraseQuotes, UUIDsEqual, UUIDSet } 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';
|
|
@@ -26,6 +26,7 @@ import { GetDialect } from '@memberjunction/sql-dialect';
|
|
|
26
26
|
import { SqlDocument, EditSet, SqlTokens, IsReadOnlyQuery, CheckAggregateExpression, IsBalancedSQLFragment, SplitTopLevelAndTerms } from '@memberjunction/sql-parser';
|
|
27
27
|
import { DescribeStatementFailure } from './describeStatement.js';
|
|
28
28
|
import { NamedQueryParameter, TypedBindValue, TypedQueryParameter } from './typedQueryParameter.js';
|
|
29
|
+
import { RowFilterParameterCollector } from './rowFilterParameters.js';
|
|
29
30
|
import { StatementMemo } from './statementMemo.js';
|
|
30
31
|
import { FindProjectionStars } from './fieldSecurity/projectionStars.js';
|
|
31
32
|
import { UndescribedColumnNames, WithheldColumnNames, WithholdColumns } from './fieldSecurity/queryColumnSecurity.js';
|
|
@@ -44,7 +45,7 @@ import { TransactionAffinity } from './TransactionAffinity.js';
|
|
|
44
45
|
import { CountOnlyBatchCoalescer, IsCoalescibleCountBatch } from './countOnlyBatch.js';
|
|
45
46
|
import { ClientClauseScreen } from './clientClauseScreen.js';
|
|
46
47
|
import { IsSystemUser } from './systemUser.js';
|
|
47
|
-
import { CreateSnapshots, FieldsLackingStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots } from './recordChangeSnapshot.js';
|
|
48
|
+
import { CreateSnapshots, FieldsLackingStoredValue, FieldsWrittenWithoutStoredValue, WidenDeleteSnapshot, WidenUpdateSnapshots, } from './recordChangeSnapshot.js';
|
|
48
49
|
import { NodeAsyncServerOperationScopeTracker } from './NodeAsyncServerOperationScopeTracker.js';
|
|
49
50
|
// Install Node AsyncLocalStorage-backed authority scope tracker on server startup so concurrent
|
|
50
51
|
// in-flight requests / remote operations maintain isolated ServerOperationScopeFrame stacks.
|
|
@@ -344,7 +345,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
344
345
|
*/
|
|
345
346
|
get LocalStorageProvider() {
|
|
346
347
|
if (!this._localStorageProvider) {
|
|
347
|
-
this._localStorageProvider = new InMemoryLocalStorageProvider();
|
|
348
|
+
this._localStorageProvider = this.ConfigData?.LocalStorageProvider ?? new InMemoryLocalStorageProvider();
|
|
348
349
|
}
|
|
349
350
|
return this._localStorageProvider;
|
|
350
351
|
}
|
|
@@ -885,7 +886,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
885
886
|
if (!this.ShouldCheckUpdateConcurrency(entity, options)) {
|
|
886
887
|
return true;
|
|
887
888
|
}
|
|
888
|
-
const
|
|
889
|
+
const values = this.collectConcurrencyCheckValues(entity, options);
|
|
890
|
+
return this.runLockedConcurrencyCheck(entity, user, this.getEffectiveConcurrencyCheckMode(options), values, entityResult);
|
|
891
|
+
}
|
|
892
|
+
PrepareQueuedUpdateConcurrencyCheck(entity, user, options, entityResult) {
|
|
893
|
+
if (!this.ShouldCheckUpdateConcurrency(entity, options)) {
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
const values = this.collectConcurrencyCheckValues(entity, options);
|
|
897
|
+
if (Object.keys(values.baselineValues).length === 0) {
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
const mode = this.getEffectiveConcurrencyCheckMode(options);
|
|
901
|
+
return () => this.runLockedConcurrencyCheck(entity, user, mode, values, entityResult);
|
|
902
|
+
}
|
|
903
|
+
/**
|
|
904
|
+
* Collects, for each field the save changes, the value the caller believes the database holds
|
|
905
|
+
* (the `ConcurrencyBaseline` entry when one is supplied, otherwise the field's `OldValue`) and the
|
|
906
|
+
* value the save writes.
|
|
907
|
+
*/
|
|
908
|
+
collectConcurrencyCheckValues(entity, options) {
|
|
889
909
|
const baselineValues = {};
|
|
890
910
|
const newValues = {};
|
|
891
911
|
if (options?.ConcurrencyBaseline) {
|
|
@@ -915,6 +935,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
915
935
|
newValues[f.Name] = entityField.Value;
|
|
916
936
|
}
|
|
917
937
|
}
|
|
938
|
+
return { baselineValues, newValues };
|
|
939
|
+
}
|
|
940
|
+
/**
|
|
941
|
+
* Reads the stored values of the changed columns under a row lock held by the current
|
|
942
|
+
* transaction, and compares them with the caller's baseline. A conflict is logged; in
|
|
943
|
+
* `'enforce'` mode it also fails `entityResult` and returns `false`.
|
|
944
|
+
*/
|
|
945
|
+
async runLockedConcurrencyCheck(entity, user, effectiveMode, values, entityResult) {
|
|
946
|
+
const { baselineValues, newValues } = values;
|
|
918
947
|
const columnsToRead = Object.keys(baselineValues);
|
|
919
948
|
if (columnsToRead.length === 0) {
|
|
920
949
|
return true;
|
|
@@ -991,14 +1020,41 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
991
1020
|
// Build parallel post-save tasks — geocoding and ISA sibling propagation
|
|
992
1021
|
// are independent (write to RecordGeoCode and RecordChange respectively).
|
|
993
1022
|
let geoResult = null;
|
|
994
|
-
// Geocoding:
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1023
|
+
// Geocoding: outside an ambient/group transaction, await inline so the SP result
|
|
1024
|
+
// can be patched immediately. Inside an open transaction, defer external HTTP
|
|
1025
|
+
// geocoding I/O via RunAfterCommit so exclusive SQL X-locks are never held across
|
|
1026
|
+
// network round-trips (and rolled-back saves never call external geocoding APIs).
|
|
1027
|
+
let geoPromise = null;
|
|
1028
|
+
if (context.State['geoSyncNeeded']) {
|
|
1029
|
+
if (this.IsCallerInAmbientTransaction()) {
|
|
1030
|
+
this.RunAfterCommit(async () => {
|
|
1031
|
+
const deferredGeo = await GeoCodeSyncService.Instance.SyncIfChanged(entity, user).catch(e => {
|
|
1032
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1033
|
+
LogError(`GenericDatabaseProvider: Geo sync failed for ${entity.EntityInfo.Name}: ${msg}`);
|
|
1034
|
+
return null;
|
|
1035
|
+
});
|
|
1036
|
+
if (deferredGeo) {
|
|
1037
|
+
const latField = entity.Fields.find(f => f.Name === '__mj_Latitude');
|
|
1038
|
+
if (latField) {
|
|
1039
|
+
latField.Value = deferredGeo.Latitude;
|
|
1040
|
+
latField.ResetOldValue();
|
|
1041
|
+
}
|
|
1042
|
+
const lngField = entity.Fields.find(f => f.Name === '__mj_Longitude');
|
|
1043
|
+
if (lngField) {
|
|
1044
|
+
lngField.Value = deferredGeo.Longitude;
|
|
1045
|
+
lngField.ResetOldValue();
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
}, `GeoCodeSyncService(${entity.EntityInfo.Name})`);
|
|
1049
|
+
}
|
|
1050
|
+
else {
|
|
1051
|
+
geoPromise = GeoCodeSyncService.Instance.SyncIfChanged(entity, user).catch(e => {
|
|
1052
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
1053
|
+
LogError(`GenericDatabaseProvider: Geo sync failed for ${entity.EntityInfo.Name}: ${msg}`);
|
|
1054
|
+
return null;
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1002
1058
|
// ISA sibling record-change propagation — when saving an overlapping-subtype entity,
|
|
1003
1059
|
// propagate the record change to sibling branches so their change history stays in sync.
|
|
1004
1060
|
const overlappingChangeData = saveSQLResult.extraData?.overlappingChangeData;
|
|
@@ -1062,7 +1118,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1062
1118
|
const rv = new RunView();
|
|
1063
1119
|
const result = await rv.RunView({
|
|
1064
1120
|
EntityName: 'MJ: Record Geo Codes',
|
|
1065
|
-
ExtraFilter: `EntityID='${entity.EntityInfo.ID}' AND RecordID='${recordId}'`,
|
|
1121
|
+
ExtraFilter: `EntityID='${entity.EntityInfo.ID}' AND RecordID='${EscapeSQLString(recordId)}'`,
|
|
1066
1122
|
ResultType: 'entity_object'
|
|
1067
1123
|
}, contextUser);
|
|
1068
1124
|
if (result.Success && result.Results.length > 0) {
|
|
@@ -1393,6 +1449,36 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1393
1449
|
getDialect() {
|
|
1394
1450
|
return null;
|
|
1395
1451
|
}
|
|
1452
|
+
/**
|
|
1453
|
+
* The binder a RunView's row filter binds the user's values into (#5713), or null to keep them
|
|
1454
|
+
* literal. The default binds untyped named parameters with the dialect's placeholders (`$n` on
|
|
1455
|
+
* PostgreSQL); a provider with no dialect keeps literals. Providers override it to choose the
|
|
1456
|
+
* parameter type.
|
|
1457
|
+
*/
|
|
1458
|
+
CreateRowFilterParameterBinder() {
|
|
1459
|
+
const dialect = this.getDialect();
|
|
1460
|
+
if (!dialect) {
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
return new RowFilterParameterCollector((index, value) => {
|
|
1464
|
+
const placeholder = dialect.Binding.ParameterPlaceholder(index);
|
|
1465
|
+
return { Placeholder: placeholder, Parameter: new NamedQueryParameter(placeholder.startsWith('@') ? placeholder.slice(1) : placeholder, value) };
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
/**
|
|
1469
|
+
* Runs several statements that all reference the same `parameters` (one RunView's data, count
|
|
1470
|
+
* and aggregate statements share its WHERE, row-filter parameters included). The default runs
|
|
1471
|
+
* each with the full list; SQL Server overrides it to send one batch that declares them once.
|
|
1472
|
+
*/
|
|
1473
|
+
async ExecuteSQLBatchWithSharedParameters(queries, parameters, options, contextUser) {
|
|
1474
|
+
const execOptions = options ? {
|
|
1475
|
+
description: options.description,
|
|
1476
|
+
ignoreLogging: options.ignoreLogging,
|
|
1477
|
+
isMutation: options.isMutation,
|
|
1478
|
+
ignoreAmbientTransaction: options.ignoreAmbientTransaction,
|
|
1479
|
+
} : undefined;
|
|
1480
|
+
return Promise.all(queries.map(query => this.ExecuteSQL(query, parameters, execOptions, contextUser)));
|
|
1481
|
+
}
|
|
1396
1482
|
/**
|
|
1397
1483
|
* Detects infrastructure-level connection errors (timeout, refused, pool closed)
|
|
1398
1484
|
* as opposed to query-level errors (bad SQL, constraint violations).
|
|
@@ -1731,8 +1817,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1731
1817
|
// Per-save suppression: a high-volume machine writer (integration sync) opts out of the
|
|
1732
1818
|
// audit row for ITS writes only — the entity keeps TrackRecordChanges for everyone else.
|
|
1733
1819
|
if (this.ShouldTrackRecordChanges(entity.EntityInfo) && options?.SkipRecordChanges !== true) {
|
|
1734
|
-
const
|
|
1735
|
-
const
|
|
1820
|
+
const snapshotFromRow = this.BuildsFullRecordJSONFromResultRow(entity, returnContext);
|
|
1821
|
+
const { NewData: newData, OldData: oldData } = await this.BuildRecordChangeSnapshots(entity, isUpdate, user, snapshotFromRow);
|
|
1822
|
+
const payload = this.BuildRecordChangePayload(newData, oldData, '', entity.EntityInfo, isNew ? 'Create' : 'Update', user, entity.RestoreContext, "'", entity.CloneContext, snapshotFromRow);
|
|
1736
1823
|
if (payload) {
|
|
1737
1824
|
// ISA propagation hook: reuse the diff already computed by BuildRecordChangePayload
|
|
1738
1825
|
// for SS subtype propagation without running DiffObjects + JSON.stringify twice.
|
|
@@ -1766,6 +1853,16 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1766
1853
|
}
|
|
1767
1854
|
return result;
|
|
1768
1855
|
}
|
|
1856
|
+
/**
|
|
1857
|
+
* True when the dialect builds this save's Record Change `FullRecordJSON` in SQL from the row the
|
|
1858
|
+
* save returned, instead of serializing the payload's snapshot. That row is what the database
|
|
1859
|
+
* stored, including columns another writer changed after this object was loaded, so the snapshot
|
|
1860
|
+
* cannot go stale. The base implementation never does; a dialect that can overrides this and
|
|
1861
|
+
* renders the snapshot in `WrapSaveCallWithRecordChange` under the same conditions.
|
|
1862
|
+
*/
|
|
1863
|
+
BuildsFullRecordJSONFromResultRow(_entity, _returnContext) {
|
|
1864
|
+
return false;
|
|
1865
|
+
}
|
|
1769
1866
|
/**
|
|
1770
1867
|
* The old and new snapshots a save's Record Change is built from. The audit trail stores
|
|
1771
1868
|
* whole payloads and projects them per reader, so both snapshots describe the whole record
|
|
@@ -1780,17 +1877,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1780
1877
|
* - **Create**: there is no stored row yet. A field the INSERT omits because the user may
|
|
1781
1878
|
* not supply it is left out rather than recorded with a value the record never got.
|
|
1782
1879
|
*
|
|
1880
|
+
* With `snapshotFromRow` (see {@link BuildsFullRecordJSONFromResultRow}) the snapshots feed only
|
|
1881
|
+
* the diff, so a restricted user's update reads stored values only for the fields their object
|
|
1882
|
+
* wrote without having read them.
|
|
1883
|
+
*
|
|
1783
1884
|
* The read runs on the save's connection: inside an open transaction it reads that
|
|
1784
1885
|
* transaction's state. A save queued in a transaction group is generated when `Save()` is
|
|
1785
1886
|
* called, so its snapshot reflects the row as of then — the same moment the object's own
|
|
1786
1887
|
* old values describe.
|
|
1787
1888
|
*/
|
|
1788
|
-
async BuildRecordChangeSnapshots(entity, isUpdate, user) {
|
|
1889
|
+
async BuildRecordChangeSnapshots(entity, isUpdate, user, snapshotFromRow = false) {
|
|
1789
1890
|
if (!isUpdate) {
|
|
1790
1891
|
return CreateSnapshots(entity);
|
|
1791
1892
|
}
|
|
1792
1893
|
const narrow = { NewData: entity.GetAll(false), OldData: entity.GetAll(true) };
|
|
1793
|
-
|
|
1894
|
+
// When the dialect builds FullRecordJSON from the returned row, the snapshots feed only the
|
|
1895
|
+
// diff, which needs a stored value only for a field the object wrote without having read it.
|
|
1896
|
+
const allLacking = FieldsLackingStoredValue(entity, user);
|
|
1897
|
+
const lacking = snapshotFromRow ? FieldsWrittenWithoutStoredValue(entity, allLacking) : allLacking;
|
|
1794
1898
|
if (lacking.size === 0) {
|
|
1795
1899
|
return narrow;
|
|
1796
1900
|
}
|
|
@@ -1927,11 +2031,307 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1927
2031
|
* `QuoteIdentifier` produces `"TotalRowCount"` on PG and `[TotalRowCount]` on SQL
|
|
1928
2032
|
* Server — both preserve case.
|
|
1929
2033
|
*/
|
|
1930
|
-
|
|
2034
|
+
/**
|
|
2035
|
+
* Determines whether a count query can be safely executed against the entity's physical
|
|
2036
|
+
* `BaseTable` instead of the generated `BaseView`.
|
|
2037
|
+
*
|
|
2038
|
+
* Generated `BaseView`s only `LEFT OUTER JOIN` related lookup tables on single-row primary
|
|
2039
|
+
* keys and do not alter row cardinality. When 100% of columns referenced in `whereSQL`
|
|
2040
|
+
* are physical non-virtual columns on `BaseTable`, counting directly from `BaseTable`
|
|
2041
|
+
* bypasses expensive joins, outer applies, and view expansion while returning identical counts.
|
|
2042
|
+
*/
|
|
2043
|
+
CanCountFromBaseTable(entityInfo, whereSQL) {
|
|
2044
|
+
if (!entityInfo) {
|
|
2045
|
+
return false;
|
|
2046
|
+
}
|
|
2047
|
+
// 1) BaseView must be generated by CodeGen (hand-written custom views may filter rows)
|
|
2048
|
+
if (entityInfo.BaseViewGenerated !== true) {
|
|
2049
|
+
return false;
|
|
2050
|
+
}
|
|
2051
|
+
// 2) Must have a physical BaseTable and not be a virtual entity
|
|
2052
|
+
if (entityInfo.VirtualEntity || !entityInfo.BaseTable) {
|
|
2053
|
+
return false;
|
|
2054
|
+
}
|
|
2055
|
+
// 3) IS-A child entities join parent tables and inherit columns — never rewrite IS-A child entities
|
|
2056
|
+
if (entityInfo.IsChildType || Boolean(entityInfo.ParentID) || Boolean(entityInfo.ParentEntityInfo)) {
|
|
2057
|
+
return false;
|
|
2058
|
+
}
|
|
2059
|
+
// 4) Layered base views have an application-owned outer view that might filter rows
|
|
2060
|
+
if (entityInfo.HasLayeredBaseView) {
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
// 5) Soft-delete entities have `WHERE [DeletedAt] IS NULL` in the view; base table contains deleted rows
|
|
2064
|
+
if (entityInfo.DeleteType === 'Soft') {
|
|
2065
|
+
return false;
|
|
2066
|
+
}
|
|
2067
|
+
const trimmed = (whereSQL ?? '').trim();
|
|
2068
|
+
if (!trimmed) {
|
|
2069
|
+
return true;
|
|
2070
|
+
}
|
|
2071
|
+
if (!entityInfo.Fields || entityInfo.Fields.length === 0) {
|
|
2072
|
+
return false;
|
|
2073
|
+
}
|
|
2074
|
+
const tokens = GenericDatabaseProvider.extractWhereTokens(trimmed);
|
|
2075
|
+
if (tokens === null) {
|
|
2076
|
+
return false;
|
|
2077
|
+
}
|
|
2078
|
+
const physicalColumns = new Set(entityInfo.Fields
|
|
2079
|
+
.filter(f => !f.IsVirtual)
|
|
2080
|
+
.map(f => f.Name.toLowerCase()));
|
|
2081
|
+
const virtualColumns = new Set(entityInfo.Fields
|
|
2082
|
+
.filter(f => f.IsVirtual)
|
|
2083
|
+
.map(f => f.Name.toLowerCase()));
|
|
2084
|
+
const schemaLower = (entityInfo.SchemaName ?? '').trim().toLowerCase();
|
|
2085
|
+
const baseTableLower = entityInfo.BaseTable.trim().toLowerCase();
|
|
2086
|
+
const baseViewLower = (entityInfo.BaseView ?? '').trim().toLowerCase();
|
|
2087
|
+
let parenDepth = 0;
|
|
2088
|
+
const subqueryStartDepths = [];
|
|
2089
|
+
for (let idx = 0; idx < tokens.length; idx++) {
|
|
2090
|
+
const t = tokens[idx];
|
|
2091
|
+
if (t.kind === 'lparen') {
|
|
2092
|
+
parenDepth++;
|
|
2093
|
+
const next = tokens[idx + 1];
|
|
2094
|
+
if (next && next.kind === 'ident' && (next.value === 'select' || next.value === 'with')) {
|
|
2095
|
+
subqueryStartDepths.push(parenDepth);
|
|
2096
|
+
}
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
if (t.kind === 'rparen') {
|
|
2100
|
+
if (parenDepth === 0) {
|
|
2101
|
+
return false;
|
|
2102
|
+
}
|
|
2103
|
+
if (subqueryStartDepths.length > 0 && subqueryStartDepths[subqueryStartDepths.length - 1] === parenDepth) {
|
|
2104
|
+
subqueryStartDepths.pop();
|
|
2105
|
+
}
|
|
2106
|
+
parenDepth--;
|
|
2107
|
+
continue;
|
|
2108
|
+
}
|
|
2109
|
+
if (t.kind !== 'ident' && t.kind !== 'quoted') {
|
|
2110
|
+
continue;
|
|
2111
|
+
}
|
|
2112
|
+
const inSubquery = subqueryStartDepths.length > 0;
|
|
2113
|
+
const prev = tokens[idx - 1];
|
|
2114
|
+
const next = tokens[idx + 1];
|
|
2115
|
+
const isAfterDot = prev?.kind === 'dot';
|
|
2116
|
+
const isBeforeDot = next?.kind === 'dot';
|
|
2117
|
+
if (inSubquery) {
|
|
2118
|
+
if (baseViewLower && t.value === baseViewLower) {
|
|
2119
|
+
return false;
|
|
2120
|
+
}
|
|
2121
|
+
if (!isAfterDot && !isBeforeDot && next?.kind !== 'lparen' &&
|
|
2122
|
+
virtualColumns.has(t.value) && !physicalColumns.has(t.value)) {
|
|
2123
|
+
return false;
|
|
2124
|
+
}
|
|
2125
|
+
continue;
|
|
2126
|
+
}
|
|
2127
|
+
// Outer WHERE level: forbid joins/set-ops/bare SELECT; allow EXISTS (SELECT ...)
|
|
2128
|
+
if (t.kind === 'ident') {
|
|
2129
|
+
if (t.value === 'exists') {
|
|
2130
|
+
const afterParen = tokens[idx + 2];
|
|
2131
|
+
if (next?.kind === 'lparen' && afterParen?.kind === 'ident' &&
|
|
2132
|
+
(afterParen.value === 'select' || afterParen.value === 'with')) {
|
|
2133
|
+
continue;
|
|
2134
|
+
}
|
|
2135
|
+
return false;
|
|
2136
|
+
}
|
|
2137
|
+
if (GenericDatabaseProvider._forbiddenCountKeywords.has(t.value)) {
|
|
2138
|
+
return false;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
if (isBeforeDot) {
|
|
2142
|
+
const isBaseTableQualifier = t.value === baseTableLower;
|
|
2143
|
+
const isSchemaForBaseTable = Boolean(schemaLower) && t.value === schemaLower &&
|
|
2144
|
+
(tokens[idx + 2]?.kind === 'ident' || tokens[idx + 2]?.kind === 'quoted') &&
|
|
2145
|
+
tokens[idx + 2].value === baseTableLower;
|
|
2146
|
+
if (!isBaseTableQualifier && !isSchemaForBaseTable) {
|
|
2147
|
+
return false;
|
|
2148
|
+
}
|
|
2149
|
+
continue;
|
|
2150
|
+
}
|
|
2151
|
+
if (isAfterDot) {
|
|
2152
|
+
if (t.value !== baseTableLower && !physicalColumns.has(t.value)) {
|
|
2153
|
+
return false;
|
|
2154
|
+
}
|
|
2155
|
+
continue;
|
|
2156
|
+
}
|
|
2157
|
+
if (t.kind === 'ident' && GenericDatabaseProvider._allowedCountKeywords.has(t.value)) {
|
|
2158
|
+
continue;
|
|
2159
|
+
}
|
|
2160
|
+
if (!physicalColumns.has(t.value)) {
|
|
2161
|
+
return false;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
return parenDepth === 0;
|
|
2165
|
+
}
|
|
2166
|
+
static { this._forbiddenCountKeywords = new Set([
|
|
2167
|
+
'select', 'from', 'join', 'exists', 'apply', 'with', 'union', 'intersect', 'except',
|
|
2168
|
+
]); }
|
|
2169
|
+
static { this._allowedCountKeywords = new Set([
|
|
2170
|
+
'and', 'or', 'not', 'is', 'null', 'in', 'between', 'like', 'ilike', 'escape',
|
|
2171
|
+
'true', 'false', 'asc', 'desc', 'cast', 'convert', 'coalesce', 'isnull', 'nullif',
|
|
2172
|
+
'lower', 'upper', 'ltrim', 'rtrim', 'trim', 'len', 'length',
|
|
2173
|
+
'getdate', 'getutcdate', 'sysdatetime', 'sysutcdatetime', 'now', 'current_timestamp', 'current_date',
|
|
2174
|
+
'dateadd', 'datediff', 'year', 'month', 'day', 'hour', 'minute', 'second',
|
|
2175
|
+
'at', 'time', 'zone', 'interval', 'extract', 'date_trunc', 'date_part', 'epoch',
|
|
2176
|
+
'as', 'case', 'when', 'then', 'else', 'end', 'where',
|
|
2177
|
+
'int', 'integer', 'bigint', 'smallint', 'tinyint',
|
|
2178
|
+
'varchar', 'nvarchar', 'char', 'nchar', 'text',
|
|
2179
|
+
'date', 'time', 'datetime', 'datetime2', 'datetimeoffset', 'timestamptz', 'decimal', 'numeric',
|
|
2180
|
+
'float', 'real', 'bit', 'boolean', 'uuid', 'uniqueidentifier', 'max',
|
|
2181
|
+
]); }
|
|
2182
|
+
/**
|
|
2183
|
+
* Linear O(N) character scanner (zero regexes — immune to ReDoS) that strips single-quoted
|
|
2184
|
+
* SQL string literals and `@p` / `$n` parameter placeholders, tokenizes bracketed `[Col]`,
|
|
2185
|
+
* double-quoted `"Col"`, bare identifiers, parentheses, and dots, and returns `null` if an
|
|
2186
|
+
* unclosed quote/bracket or comment token (`--`, `/*`) is encountered.
|
|
2187
|
+
*/
|
|
2188
|
+
static extractWhereTokens(sql) {
|
|
2189
|
+
const tokens = [];
|
|
2190
|
+
const len = sql.length;
|
|
2191
|
+
let i = 0;
|
|
2192
|
+
const isIdentStart = (ch) => (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch === 95;
|
|
2193
|
+
const isIdentPart = (ch) => isIdentStart(ch) || (ch >= 48 && ch <= 57);
|
|
2194
|
+
const isDigit = (ch) => ch >= 48 && ch <= 57;
|
|
2195
|
+
while (i < len) {
|
|
2196
|
+
const code = sql.charCodeAt(i);
|
|
2197
|
+
// Reject SQL line/block comments conservatively
|
|
2198
|
+
if ((code === 45 && i + 1 < len && sql.charCodeAt(i + 1) === 45) ||
|
|
2199
|
+
(code === 47 && i + 1 < len && sql.charCodeAt(i + 1) === 42)) {
|
|
2200
|
+
return null;
|
|
2201
|
+
}
|
|
2202
|
+
// N'...' national string literal prefix
|
|
2203
|
+
if ((code === 78 || code === 110) && i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2204
|
+
i += 2;
|
|
2205
|
+
let closed = false;
|
|
2206
|
+
while (i < len) {
|
|
2207
|
+
if (sql.charCodeAt(i) === 39) {
|
|
2208
|
+
if (i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2209
|
+
i += 2;
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
i++;
|
|
2213
|
+
closed = true;
|
|
2214
|
+
break;
|
|
2215
|
+
}
|
|
2216
|
+
i++;
|
|
2217
|
+
}
|
|
2218
|
+
if (!closed)
|
|
2219
|
+
return null;
|
|
2220
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2221
|
+
continue;
|
|
2222
|
+
}
|
|
2223
|
+
// '...' single-quoted string literal
|
|
2224
|
+
if (code === 39) {
|
|
2225
|
+
i++;
|
|
2226
|
+
let closed = false;
|
|
2227
|
+
while (i < len) {
|
|
2228
|
+
if (sql.charCodeAt(i) === 39) {
|
|
2229
|
+
if (i + 1 < len && sql.charCodeAt(i + 1) === 39) {
|
|
2230
|
+
i += 2;
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
i++;
|
|
2234
|
+
closed = true;
|
|
2235
|
+
break;
|
|
2236
|
+
}
|
|
2237
|
+
i++;
|
|
2238
|
+
}
|
|
2239
|
+
if (!closed)
|
|
2240
|
+
return null;
|
|
2241
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2242
|
+
continue;
|
|
2243
|
+
}
|
|
2244
|
+
// @param token
|
|
2245
|
+
if (code === 64) {
|
|
2246
|
+
i++;
|
|
2247
|
+
while (i < len && isIdentPart(sql.charCodeAt(i))) {
|
|
2248
|
+
i++;
|
|
2249
|
+
}
|
|
2250
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2251
|
+
continue;
|
|
2252
|
+
}
|
|
2253
|
+
// $1 positional parameter token
|
|
2254
|
+
if (code === 36 && i + 1 < len && isDigit(sql.charCodeAt(i + 1))) {
|
|
2255
|
+
i += 2;
|
|
2256
|
+
while (i < len && isDigit(sql.charCodeAt(i))) {
|
|
2257
|
+
i++;
|
|
2258
|
+
}
|
|
2259
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2260
|
+
continue;
|
|
2261
|
+
}
|
|
2262
|
+
// [Identifier] bracketed column
|
|
2263
|
+
if (code === 91) {
|
|
2264
|
+
const start = i + 1;
|
|
2265
|
+
const end = sql.indexOf(']', start);
|
|
2266
|
+
if (end === -1)
|
|
2267
|
+
return null;
|
|
2268
|
+
const ident = sql.slice(start, end).trim().toLowerCase();
|
|
2269
|
+
if (ident.length > 0) {
|
|
2270
|
+
tokens.push({ kind: 'quoted', value: ident });
|
|
2271
|
+
}
|
|
2272
|
+
i = end + 1;
|
|
2273
|
+
continue;
|
|
2274
|
+
}
|
|
2275
|
+
// "Identifier" double-quoted column
|
|
2276
|
+
if (code === 34) {
|
|
2277
|
+
const start = i + 1;
|
|
2278
|
+
const end = sql.indexOf('"', start);
|
|
2279
|
+
if (end === -1)
|
|
2280
|
+
return null;
|
|
2281
|
+
const ident = sql.slice(start, end).trim().toLowerCase();
|
|
2282
|
+
if (ident.length > 0) {
|
|
2283
|
+
tokens.push({ kind: 'quoted', value: ident });
|
|
2284
|
+
}
|
|
2285
|
+
i = end + 1;
|
|
2286
|
+
continue;
|
|
2287
|
+
}
|
|
2288
|
+
// Numeric literal (skip digits so e.g. 1e5 isn't treated as identifier e5)
|
|
2289
|
+
if (isDigit(code)) {
|
|
2290
|
+
i++;
|
|
2291
|
+
while (i < len && (isIdentPart(sql.charCodeAt(i)) || sql.charCodeAt(i) === 46)) {
|
|
2292
|
+
i++;
|
|
2293
|
+
}
|
|
2294
|
+
tokens.push({ kind: 'other', value: '' });
|
|
2295
|
+
continue;
|
|
2296
|
+
}
|
|
2297
|
+
// Bare identifier or keyword
|
|
2298
|
+
if (isIdentStart(code)) {
|
|
2299
|
+
const start = i;
|
|
2300
|
+
i++;
|
|
2301
|
+
while (i < len && isIdentPart(sql.charCodeAt(i))) {
|
|
2302
|
+
i++;
|
|
2303
|
+
}
|
|
2304
|
+
tokens.push({ kind: 'ident', value: sql.slice(start, i).toLowerCase() });
|
|
2305
|
+
continue;
|
|
2306
|
+
}
|
|
2307
|
+
if (code === 40) {
|
|
2308
|
+
tokens.push({ kind: 'lparen', value: '(' });
|
|
2309
|
+
}
|
|
2310
|
+
else if (code === 41) {
|
|
2311
|
+
tokens.push({ kind: 'rparen', value: ')' });
|
|
2312
|
+
}
|
|
2313
|
+
else if (code === 46) {
|
|
2314
|
+
tokens.push({ kind: 'dot', value: '.' });
|
|
2315
|
+
}
|
|
2316
|
+
else if (code > 32) {
|
|
2317
|
+
tokens.push({ kind: 'other', value: sql[i] });
|
|
2318
|
+
}
|
|
2319
|
+
i++;
|
|
2320
|
+
}
|
|
2321
|
+
return tokens;
|
|
2322
|
+
}
|
|
2323
|
+
BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, baseViewOverride, schemaNameOverride, whereSQL) {
|
|
1931
2324
|
const rowsAreLimited = usingPagination || maxRowsForQuery > 0;
|
|
1932
2325
|
if (!rowsAreLimited)
|
|
1933
2326
|
return null;
|
|
1934
|
-
|
|
2327
|
+
const effectiveBaseView = baseViewOverride ?? entityInfo.BaseView;
|
|
2328
|
+
const effectiveSchema = schemaNameOverride ?? entityInfo.SchemaName;
|
|
2329
|
+
const isStandardBaseView = !baseViewOverride ||
|
|
2330
|
+
(entityInfo.BaseView && baseViewOverride.trim().toLowerCase() === entityInfo.BaseView.trim().toLowerCase());
|
|
2331
|
+
const target = (isStandardBaseView && this.CanCountFromBaseTable(entityInfo, whereSQL ?? ''))
|
|
2332
|
+
? this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseTable)
|
|
2333
|
+
: this.QuoteSchemaAndView(effectiveSchema, effectiveBaseView);
|
|
2334
|
+
return `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${target}`;
|
|
1935
2335
|
}
|
|
1936
2336
|
/**
|
|
1937
2337
|
* Resolves the effective semantic `AlternateBaseView` name for a `RunViewParams` object and
|
|
@@ -2618,9 +3018,21 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2618
3018
|
entityInfo = this.EntityByID(viewEntity.EntityID) ?? null;
|
|
2619
3019
|
if (!entityInfo)
|
|
2620
3020
|
throw new Error(`Entity ID: ${viewEntity.EntityID} not found in metadata`);
|
|
3021
|
+
if (typeof params.EntityName === 'string' && params.EntityName.trim().length > 0) {
|
|
3022
|
+
const requestedEntity = this.EntityByName(params.EntityName.trim());
|
|
3023
|
+
if (!requestedEntity || !UUIDsEqual(requestedEntity.ID, entityInfo.ID)) {
|
|
3024
|
+
throw new Error(`EntityName '${params.EntityName}' does not match view '${viewEntity.Name ?? viewEntity.ID}' target entity '${entityInfo.Name}'.`);
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
2621
3027
|
}
|
|
2622
3028
|
this.CheckUserReadPermissions(entityInfo.Name, user);
|
|
2623
3029
|
resolvedEntity = entityInfo;
|
|
3030
|
+
if (params.Aggregates &&
|
|
3031
|
+
params.Aggregates.length > 0 &&
|
|
3032
|
+
this.IsPostRunViewProtectedEntity(entityInfo.Name) &&
|
|
3033
|
+
!this.isSystemCaller(user)) {
|
|
3034
|
+
throw new Error(`Access denied: aggregate queries are not allowed on PostRunView-protected entity '${entityInfo.Name}' because PostRunView hooks cannot filter SQL aggregates.`);
|
|
3035
|
+
}
|
|
2624
3036
|
// A stored view's properties: refused here (Success:false, naming the property) before any SQL runs.
|
|
2625
3037
|
const propertyFilter = this.BuildViewPropertyFilter(viewEntity, entityInfo, params, user);
|
|
2626
3038
|
// ── External data source dispatch ──
|
|
@@ -2725,12 +3137,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2725
3137
|
const effectiveSchemaName = effectiveTarget.schemaName;
|
|
2726
3138
|
const topFragment = topSQL ? topSQL + ' ' : '';
|
|
2727
3139
|
let viewSQL = `SELECT ${topFragment}${fields} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`;
|
|
2728
|
-
|
|
2729
|
-
// it when rows are limited (its pagination purpose), which previously left
|
|
2730
|
-
// count_only with no COUNT at all (silently returned TotalRowCount 0).
|
|
2731
|
-
let countSQL = params.ResultType === 'count_only'
|
|
2732
|
-
? `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView)}`
|
|
2733
|
-
: this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName);
|
|
3140
|
+
let countSQL = null;
|
|
2734
3141
|
// ── WHERE clause assembly ──
|
|
2735
3142
|
let whereSQL = '';
|
|
2736
3143
|
let bHasWhere = false;
|
|
@@ -2823,7 +3230,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2823
3230
|
// SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
|
|
2824
3231
|
if (!IsValidUUID(String(viewEntity?.ID ?? '')))
|
|
2825
3232
|
throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
|
|
2826
|
-
sExcludeSQL += ` UserViewID
|
|
3233
|
+
sExcludeSQL += ` UserViewID='${viewEntity?.ID}')`;
|
|
2827
3234
|
}
|
|
2828
3235
|
else {
|
|
2829
3236
|
// SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
|
|
@@ -2835,7 +3242,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2835
3242
|
// anything that is not a well-formed GUID before it reaches the query.
|
|
2836
3243
|
if (!/^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/.test(excludeUserViewRunID))
|
|
2837
3244
|
throw new Error(`Invalid ExcludeUserViewRunID: must be a GUID`);
|
|
2838
|
-
sExcludeSQL += ` UserViewRunID
|
|
3245
|
+
sExcludeSQL += ` UserViewRunID='${excludeUserViewRunID}')`;
|
|
2839
3246
|
}
|
|
2840
3247
|
if (overrideExcludeFilter.length > 0) {
|
|
2841
3248
|
if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
|
|
@@ -2847,7 +3254,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2847
3254
|
bHasWhere = true;
|
|
2848
3255
|
}
|
|
2849
3256
|
// 5. Row-Level Security — role RLS AND API-key row filters (GetEffectiveRowFilterWhereClause; the role-RLS exemption applies only to the role layer)
|
|
2850
|
-
|
|
3257
|
+
// The user's values bind as parameters (#5713), so every user runs the same SQL text and
|
|
3258
|
+
// the database reuses one plan per query shape. Two paths keep literals because their
|
|
3259
|
+
// statement cannot carry parameters: the coalesced count batch (one UNION ALL across
|
|
3260
|
+
// views) and view-run logging (which rebuilds the statement around this WHERE). A
|
|
3261
|
+
// parameterized ExtraFilter also keeps them literal: its placeholders are numbered from
|
|
3262
|
+
// the same dialect sequence, and one statement binds a single parameter list.
|
|
3263
|
+
const logsViewRun = !!(viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user);
|
|
3264
|
+
const rlsBinder = countExecutor || logsViewRun || queryParameters.length > 0
|
|
3265
|
+
? null
|
|
3266
|
+
: this.CreateRowFilterParameterBinder();
|
|
3267
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '', rlsBinder ?? undefined);
|
|
3268
|
+
const rlsParameters = rlsBinder?.Parameters ?? [];
|
|
3269
|
+
const boundParameters = rlsParameters.length > 0 ? rlsParameters : undefined;
|
|
2851
3270
|
if (rlsWhereClause && rlsWhereClause.length > 0) {
|
|
2852
3271
|
whereSQL = bHasWhere ? `${whereSQL} AND (${rlsWhereClause})` : `(${rlsWhereClause})`;
|
|
2853
3272
|
bHasWhere = true;
|
|
@@ -2856,6 +3275,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2856
3275
|
// The count is the total matching the user-visible filters; the seek predicate is
|
|
2857
3276
|
// a pagination cursor, conceptually distinct from "how many records match overall".
|
|
2858
3277
|
const seekPredicateForData = usingKeyset ? keysetSeekPredicate : '';
|
|
3278
|
+
// ── COUNT query assembly (with automatic BaseTable rewrite when safe) ──
|
|
3279
|
+
const isCountOnly = params.ResultType === 'count_only';
|
|
3280
|
+
if (isCountOnly) {
|
|
3281
|
+
const isStandardBaseView = !effectiveBaseView ||
|
|
3282
|
+
(entityInfo.BaseView && effectiveBaseView.trim().toLowerCase() === entityInfo.BaseView.trim().toLowerCase());
|
|
3283
|
+
const countTarget = (isStandardBaseView && this.CanCountFromBaseTable(entityInfo, whereSQL))
|
|
3284
|
+
? this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseTable)
|
|
3285
|
+
: this.QuoteSchemaAndView(effectiveSchemaName, effectiveBaseView);
|
|
3286
|
+
countSQL = `SELECT COUNT(*) AS ${this.QuoteIdentifier('TotalRowCount')} FROM ${countTarget}`;
|
|
3287
|
+
}
|
|
3288
|
+
else {
|
|
3289
|
+
countSQL = this.BuildTotalRowCountSQL(entityInfo, usingPagination, maxRowsForQuery, effectiveBaseView, effectiveSchemaName, whereSQL);
|
|
3290
|
+
}
|
|
2859
3291
|
if (bHasWhere) {
|
|
2860
3292
|
viewSQL += ` WHERE ${whereSQL}`;
|
|
2861
3293
|
if (countSQL)
|
|
@@ -2989,12 +3421,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2989
3421
|
sqlQueries.push(aggregateSQL);
|
|
2990
3422
|
sqlQueryKeys.push('aggregate');
|
|
2991
3423
|
}
|
|
2992
|
-
|
|
3424
|
+
// At most one of the two lists is non-empty: row-filter values stay literal when the
|
|
3425
|
+
// ExtraFilter binds parameters (step 5).
|
|
3426
|
+
const boundParams = queryParameters.length > 0 ? queryParameters : boundParameters;
|
|
2993
3427
|
const boundBatchParams = queryParameters.length > 0 ? sqlQueries.map(() => queryParameters) : undefined;
|
|
2994
3428
|
const resultMap = {};
|
|
2995
3429
|
if (sqlQueries.length === 1 && !countExecutorPromise) {
|
|
2996
3430
|
resultMap[sqlQueryKeys[0]] = await this.ExecuteSQL(sqlQueries[0], boundParams, undefined, contextUser);
|
|
2997
3431
|
}
|
|
3432
|
+
else if (sqlQueries.length > 1 && boundParameters) {
|
|
3433
|
+
const batchResults = await this.ExecuteSQLBatchWithSharedParameters(sqlQueries, boundParameters, undefined, contextUser);
|
|
3434
|
+
sqlQueryKeys.forEach((key, index) => { resultMap[key] = batchResults[index]; });
|
|
3435
|
+
}
|
|
2998
3436
|
else if (sqlQueries.length > 0 && countExecutorPromise) {
|
|
2999
3437
|
const [batchResults, countRes] = await Promise.all([
|
|
3000
3438
|
sqlQueries.length === 1
|
|
@@ -3117,6 +3555,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3117
3555
|
};
|
|
3118
3556
|
}
|
|
3119
3557
|
}
|
|
3558
|
+
/** Returns true when `entityName` is registered as requiring PostRunView row-level ACL hooks. */
|
|
3559
|
+
IsPostRunViewProtectedEntity(entityName) {
|
|
3560
|
+
return IsPostRunViewProtectedEntity(entityName);
|
|
3561
|
+
}
|
|
3562
|
+
/** Returns true when `user` represents the trusted internal server system identity. */
|
|
3563
|
+
isSystemCaller(user) {
|
|
3564
|
+
if (!user) {
|
|
3565
|
+
return false;
|
|
3566
|
+
}
|
|
3567
|
+
return IsSystemUser(user) || WellKnownUserSource.Instance.IsSystemUser(user);
|
|
3568
|
+
}
|
|
3120
3569
|
/** The stored view a run names (ViewEntity, else ViewID, else ViewName), or null for an entity run. */
|
|
3121
3570
|
async LoadRunViewEntity(params, contextUser) {
|
|
3122
3571
|
if (params.ViewEntity)
|
|
@@ -3332,7 +3781,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3332
3781
|
}
|
|
3333
3782
|
/**
|
|
3334
3783
|
* Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
|
|
3335
|
-
* the columns this user is allowed to read when field security denies them any.
|
|
3784
|
+
* the columns this user is allowed to read when field security denies them any. With
|
|
3785
|
+
* `tableAlias`, every column (or the `*`) is qualified with it.
|
|
3336
3786
|
*
|
|
3337
3787
|
* Deliberately NOT routed through RunView, which is the other way to get this behavior.
|
|
3338
3788
|
* That reroute is the tidier long-term shape and is planned separately (it must pass
|
|
@@ -3340,19 +3790,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3340
3790
|
* — and it changes relationship loading, which stays on its current path). Filtering the
|
|
3341
3791
|
* column list here buys the same protection without touching either.
|
|
3342
3792
|
*/
|
|
3343
|
-
buildFieldSecuritySelectList(entityInfo, user) {
|
|
3793
|
+
buildFieldSecuritySelectList(entityInfo, user, tableAlias) {
|
|
3794
|
+
const prefix = tableAlias ? `${tableAlias}.` : '';
|
|
3344
3795
|
if (!user || !entityInfo.FieldLevelSecurityApplies) {
|
|
3345
|
-
return
|
|
3796
|
+
return `${prefix}*`; // the overwhelmingly common case — one boolean, unchanged SQL
|
|
3346
3797
|
}
|
|
3347
3798
|
const denied = entityInfo.GetDeniedReadFields(user);
|
|
3348
3799
|
if (denied.size === 0) {
|
|
3349
|
-
return
|
|
3800
|
+
return `${prefix}*`;
|
|
3350
3801
|
}
|
|
3351
3802
|
const allowed = entityInfo.Fields.filter(f => !denied.has(f.Name.trim().toLowerCase()));
|
|
3352
3803
|
if (allowed.length === 0) {
|
|
3353
|
-
return
|
|
3804
|
+
return `${prefix}*`; // degenerate; PKs are unrestrictable so this should be unreachable
|
|
3354
3805
|
}
|
|
3355
|
-
return allowed.map(f => this.QuoteIdentifier(f.Name)).join(', ');
|
|
3806
|
+
return allowed.map(f => `${prefix}${this.QuoteIdentifier(f.Name)}`).join(', ');
|
|
3356
3807
|
}
|
|
3357
3808
|
/**
|
|
3358
3809
|
* Builds the SQL field list string for a view query, using dialect-neutral quoting.
|
|
@@ -4059,7 +4510,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4059
4510
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: gateRejection });
|
|
4060
4511
|
continue;
|
|
4061
4512
|
}
|
|
4062
|
-
const entityInfo = item.params.EntityName
|
|
4513
|
+
const entityInfo = item.params.EntityName
|
|
4514
|
+
? this.EntityByName(item.params.EntityName)
|
|
4515
|
+
: (item.params.ViewEntity && item.params.ViewEntity.EntityID
|
|
4516
|
+
? this.EntityByID(item.params.ViewEntity.EntityID)
|
|
4517
|
+
: undefined);
|
|
4063
4518
|
// Read-permission gate for EVERY item whose entity is known, before any leg can answer:
|
|
4064
4519
|
// an item with no cache status, and an external entity, are served from the server cache
|
|
4065
4520
|
// on a hit WITHOUT re-entering InternalRunView, so a CanRead check that lived only on the
|
|
@@ -4070,6 +4525,17 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4070
4525
|
errorResults.push({ viewIndex: i, status: 'error', errorMessage: permissionError });
|
|
4071
4526
|
continue;
|
|
4072
4527
|
}
|
|
4528
|
+
if (item.params.Aggregates &&
|
|
4529
|
+
item.params.Aggregates.length > 0 &&
|
|
4530
|
+
this.IsPostRunViewProtectedEntity(entityInfo.Name) &&
|
|
4531
|
+
!this.isSystemCaller(user)) {
|
|
4532
|
+
errorResults.push({
|
|
4533
|
+
viewIndex: i,
|
|
4534
|
+
status: 'error',
|
|
4535
|
+
errorMessage: `Access denied: aggregate queries are not allowed on PostRunView-protected entity '${entityInfo.Name}' because PostRunView hooks cannot filter SQL aggregates.`,
|
|
4536
|
+
});
|
|
4537
|
+
continue;
|
|
4538
|
+
}
|
|
4073
4539
|
}
|
|
4074
4540
|
// Keyset queries bypass the cache entirely (per the AfterKey API contract):
|
|
4075
4541
|
// each call uses a different seek key, so cached entries would never be
|
|
@@ -4090,11 +4556,20 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4090
4556
|
itemsWithoutCacheCheck.push({ index: i, item });
|
|
4091
4557
|
continue;
|
|
4092
4558
|
}
|
|
4559
|
+
// PostRunView-protected entities enforce per-caller ACL filtering inside PostRunView
|
|
4560
|
+
// hooks driven by sibling permission tables (e.g., ArtifactPermission / CollectionPermission).
|
|
4561
|
+
// Global COUNT(*)/MAX(__mj_UpdatedAt) checks cannot detect ACL revocations on sibling tables,
|
|
4562
|
+
// so never return status: 'current'; always run the full query + PostRunView hook.
|
|
4563
|
+
if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4564
|
+
itemsWithoutCacheCheck.push({ index: i, item });
|
|
4565
|
+
continue;
|
|
4566
|
+
}
|
|
4093
4567
|
itemsNeedingValidation.push({ index: i, item, entityInfo });
|
|
4094
4568
|
}
|
|
4095
4569
|
// Phase 1: Check server's LocalCacheManager first (zero DB hits when within freshness window)
|
|
4096
4570
|
const currentResults = [];
|
|
4097
4571
|
const serverCacheStaleItems = [];
|
|
4572
|
+
const staleItemsNoTracking = [];
|
|
4098
4573
|
const serverCacheMissItems = [];
|
|
4099
4574
|
for (const { index, item, entityInfo } of itemsNeedingValidation) {
|
|
4100
4575
|
const entityLabel = item.params.EntityName || 'unknown';
|
|
@@ -4112,6 +4587,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4112
4587
|
fingerprint: resolved.fingerprint,
|
|
4113
4588
|
});
|
|
4114
4589
|
}
|
|
4590
|
+
else if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4591
|
+
// PostRunView-protected entities bypass differential / cached delta transport and run full query + PostRunView.
|
|
4592
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
4593
|
+
}
|
|
4115
4594
|
else if (entityInfo.TrackRecordChanges) {
|
|
4116
4595
|
// The client's copy is older and the entity tracks record changes: Phase 2 reads
|
|
4117
4596
|
// the DB status and sends only the changed rows, not the full cached copy.
|
|
@@ -4128,7 +4607,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4128
4607
|
}
|
|
4129
4608
|
// Phase 2: For server cache misses and TTL-expired server slots, validate against DB
|
|
4130
4609
|
const differentialItems = [];
|
|
4131
|
-
const staleItemsNoTracking = [];
|
|
4132
4610
|
/** Queues a differential reply: the rows changed since the client's copy, and the deleted IDs. */
|
|
4133
4611
|
const queueDifferential = (index, item, entityInfo, whereSQL, serverStatus, queryParameters) => {
|
|
4134
4612
|
LogStatusEx({ message: ` 🔄 [SmartCache DIFFERENTIAL] "${item.params.EntityName || 'unknown'}" — sending only changed rows (from DB)`, verboseOnly: true });
|
|
@@ -4178,10 +4656,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4178
4656
|
if (this.isCacheCurrent(cachedSlotStatus, serverStatus)) {
|
|
4179
4657
|
// Server cache slot is confirmed current against SQL — refresh its verification timestamp in O(1)
|
|
4180
4658
|
LocalCacheManager.Instance.TouchRunViewResultVerifiedAt(fingerprint);
|
|
4181
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4659
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4182
4660
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — server cache verified against DB and matches client cache`, verboseOnly: true });
|
|
4183
4661
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
4184
4662
|
}
|
|
4663
|
+
else if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4664
|
+
staleItemsNoTracking.push({ index, params: item.params });
|
|
4665
|
+
}
|
|
4185
4666
|
else if (entityInfo.TrackRecordChanges) {
|
|
4186
4667
|
queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
|
|
4187
4668
|
}
|
|
@@ -4196,7 +4677,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4196
4677
|
// Evict the stale server slot and refresh from DB so LocalCacheManager and the client self-heal.
|
|
4197
4678
|
LogStatusEx({ message: ` ♻️ [SmartCache RECONCILE-EVICT] "${entityLabel}" — server cache slot disagreed with DB status; invalidating and refreshing from DB`, verboseOnly: true });
|
|
4198
4679
|
await LocalCacheManager.Instance.InvalidateRunViewResult(fingerprint);
|
|
4199
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4680
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4200
4681
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
4201
4682
|
}
|
|
4202
4683
|
else {
|
|
@@ -4205,15 +4686,15 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4205
4686
|
continue;
|
|
4206
4687
|
}
|
|
4207
4688
|
}
|
|
4208
|
-
if (this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4689
|
+
if (!this.IsPostRunViewProtectedEntity(entityInfo.Name) && this.isCacheCurrent(item.cacheStatus, serverStatus)) {
|
|
4209
4690
|
LogStatusEx({ message: ` ✅ [SmartCache CURRENT] "${entityLabel}" — client cache matches DB (server cache miss)`, verboseOnly: true });
|
|
4210
4691
|
currentResults.push({ viewIndex: index, status: 'current' });
|
|
4211
4692
|
}
|
|
4212
|
-
else if (entityInfo.TrackRecordChanges) {
|
|
4693
|
+
else if (entityInfo.TrackRecordChanges && !this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
4213
4694
|
queueDifferential(index, item, entityInfo, whereSQL, serverStatus, queryParameters);
|
|
4214
4695
|
}
|
|
4215
4696
|
else {
|
|
4216
|
-
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking)`, verboseOnly: true });
|
|
4697
|
+
LogStatusEx({ message: ` 🔍 [SmartCache STALE] "${entityLabel}" — full refresh from DB (no change tracking or PostRunView-protected)`, verboseOnly: true });
|
|
4217
4698
|
staleItemsNoTracking.push({ index, params: item.params });
|
|
4218
4699
|
}
|
|
4219
4700
|
}
|
|
@@ -4331,6 +4812,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4331
4812
|
}, user);
|
|
4332
4813
|
if (hooked && Array.isArray(hooked.Results)) {
|
|
4333
4814
|
rowBearing.results = hooked.Results;
|
|
4815
|
+
if (typeof hooked.TotalRowCount === 'number') {
|
|
4816
|
+
rowBearing.rowCount = hooked.TotalRowCount;
|
|
4817
|
+
}
|
|
4818
|
+
else {
|
|
4819
|
+
rowBearing.rowCount = hooked.Results.length;
|
|
4820
|
+
}
|
|
4334
4821
|
}
|
|
4335
4822
|
}
|
|
4336
4823
|
const entities = params.map(p => p.params.EntityName || 'unknown').join(', ');
|
|
@@ -4697,6 +5184,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4697
5184
|
async resolveFromServerCache(item, index, entityLabel, contextUser) {
|
|
4698
5185
|
if (!LocalCacheManager.Instance.IsInitialized)
|
|
4699
5186
|
return null;
|
|
5187
|
+
if (item.params.EntityName && this.IsPostRunViewProtectedEntity(item.params.EntityName)) {
|
|
5188
|
+
return null;
|
|
5189
|
+
}
|
|
4700
5190
|
if (!this.runViewCacheEligible(item.params) || this.cacheDeniedForViewOnlyRequest(item.params, contextUser)) {
|
|
4701
5191
|
return null;
|
|
4702
5192
|
}
|
|
@@ -4755,7 +5245,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4755
5245
|
const cacheEntity = viewParams ? this.resolveEntityForRunViewParams(viewParams) : undefined;
|
|
4756
5246
|
const materialized = await this.MaterializeCachedRowsForCaller(serverCached.results, cacheEntity, contextUser, true);
|
|
4757
5247
|
const results = callerFields
|
|
4758
|
-
? ProjectRowsToFields(materialized, callerFields)
|
|
5248
|
+
? ProjectRowsToFields(materialized, callerFields, { PreserveFrozen: true })
|
|
4759
5249
|
: materialized;
|
|
4760
5250
|
return {
|
|
4761
5251
|
viewIndex,
|
|
@@ -4777,6 +5267,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4777
5267
|
*/
|
|
4778
5268
|
async runDifferentialQueryAndReturn(params, entityInfo, clientMaxUpdatedAt, clientRowCount, serverStatus, whereSQL, viewIndex, contextUser, callerFields = null, queryParameters) {
|
|
4779
5269
|
try {
|
|
5270
|
+
if (this.IsPostRunViewProtectedEntity(entityInfo.Name)) {
|
|
5271
|
+
return await this.runFullQueryAndCacheResult(params, viewIndex, contextUser, callerFields);
|
|
5272
|
+
}
|
|
4780
5273
|
const clientMaxUpdatedDate = this.parseClientTimestamp(clientMaxUpdatedAt);
|
|
4781
5274
|
if (!clientMaxUpdatedDate) {
|
|
4782
5275
|
// Unparseable client timestamp — can't trust the differential math; fall
|
|
@@ -5154,9 +5647,32 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5154
5647
|
* refusal echoes it and nothing else. The query's ID when omitted.
|
|
5155
5648
|
* @throws Error if the user does not have permission to run the query
|
|
5156
5649
|
*/
|
|
5650
|
+
static { this.RESTRICTED_MAGIC_LINK_ARTIFACT_QUERY_IDS = new Set([
|
|
5651
|
+
'34d2d4d2-c727-4366-996f-3aaf87fc103e', // GetArtifactVersionsByID
|
|
5652
|
+
'8f84dfb4-c38e-4b8d-80e7-9ccf30039e77', // GetConversationComplete
|
|
5653
|
+
'ee272535-9d1d-4e4b-8613-1332cb564501', // GetConversationArtifactsMap
|
|
5654
|
+
'a1b2c3d4-e5f6-4789-abcd-123456789abc', // GetConversationArtifactsForAgent
|
|
5655
|
+
]); }
|
|
5656
|
+
static isMagicLinkRestrictedArtifactQuery(query, user) {
|
|
5657
|
+
if (!user || (!user.IsMagicLinkAnonymous && !user.MagicLinkScope)) {
|
|
5658
|
+
return false;
|
|
5659
|
+
}
|
|
5660
|
+
if (query.ID && GenericDatabaseProvider.RESTRICTED_MAGIC_LINK_ARTIFACT_QUERY_IDS.has(NormalizeUUID(query.ID))) {
|
|
5661
|
+
return true;
|
|
5662
|
+
}
|
|
5663
|
+
const normalized = (query.Name ?? '').trim().toLowerCase();
|
|
5664
|
+
return (normalized === 'getartifactversionsbyid' ||
|
|
5665
|
+
normalized === 'getconversationcomplete' ||
|
|
5666
|
+
normalized === 'getconversationartifactsmap' ||
|
|
5667
|
+
normalized === 'getconversationartifactsforagent');
|
|
5668
|
+
}
|
|
5157
5669
|
ValidateQueryForExecution(query, contextUser, requestedLabel = query.ID) {
|
|
5158
5670
|
const user = contextUser || this.CurrentUser;
|
|
5159
5671
|
if (user) {
|
|
5672
|
+
if (GenericDatabaseProvider.isMagicLinkRestrictedArtifactQuery(query, user)) {
|
|
5673
|
+
this.logQueryRunRefusal(query, user, { deniedEntities: ['MJ: Artifacts', 'MJ: Conversations'] });
|
|
5674
|
+
throw new Error(this.queryRunRefusalMessage(requestedLabel));
|
|
5675
|
+
}
|
|
5160
5676
|
const result = query.UserCanRun(user);
|
|
5161
5677
|
if (!result.canRun) {
|
|
5162
5678
|
// This gate, not the rendered-SQL one, is where a role-list denial lands: it
|
|
@@ -5345,6 +5861,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5345
5861
|
* refuses, carrying the rendering's error.
|
|
5346
5862
|
*/
|
|
5347
5863
|
authorizeQueryRun(query, parameters, user, logRefusal = true) {
|
|
5864
|
+
if (GenericDatabaseProvider.isMagicLinkRestrictedArtifactQuery(query, user)) {
|
|
5865
|
+
const refusal = { canRun: false, deniedEntities: ['MJ: Artifacts', 'MJ: Conversations'] };
|
|
5866
|
+
if (logRefusal) {
|
|
5867
|
+
this.logQueryRunRefusal(query, user, refusal);
|
|
5868
|
+
}
|
|
5869
|
+
return refusal;
|
|
5870
|
+
}
|
|
5348
5871
|
const base = query.UserCanRun(user);
|
|
5349
5872
|
if (!base.canRun || GenericDatabaseProvider.roleListGrants(query)) {
|
|
5350
5873
|
// A role list authorizes on its own, whatever the SQL reads, and UserCanRun has
|
|
@@ -5371,7 +5894,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5371
5894
|
return !!permissions && permissions.length > 0;
|
|
5372
5895
|
}
|
|
5373
5896
|
/**
|
|
5374
|
-
* Resolves a category path string to a
|
|
5897
|
+
* Resolves a category path string to a query category ID, from `QueryEngine`.
|
|
5375
5898
|
*/
|
|
5376
5899
|
resolveCategoryPath(categoryPath) {
|
|
5377
5900
|
if (!categoryPath)
|
|
@@ -5379,10 +5902,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
5379
5902
|
const segments = categoryPath.split('/').map(s => s.trim()).filter(s => s.length > 0);
|
|
5380
5903
|
if (segments.length === 0)
|
|
5381
5904
|
return null;
|
|
5905
|
+
const categories = QueryEngine.Instance.QueryCategories;
|
|
5382
5906
|
let currentCategory = null;
|
|
5383
5907
|
for (const segment of segments) {
|
|
5384
5908
|
const parentId = currentCategory !== null ? currentCategory.ID : null;
|
|
5385
|
-
currentCategory =
|
|
5909
|
+
currentCategory = categories.find(cat => cat.Name.trim().toLowerCase() === segment.toLowerCase() && UUIDsEqual(cat.ParentID, parentId)) ?? null;
|
|
5386
5910
|
if (!currentCategory)
|
|
5387
5911
|
return null;
|
|
5388
5912
|
}
|
|
@@ -6637,13 +7161,14 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6637
7161
|
// No enricher registered under this key (providing package not loaded) — no-op.
|
|
6638
7162
|
return rows;
|
|
6639
7163
|
}
|
|
6640
|
-
//
|
|
6641
|
-
//
|
|
6642
|
-
const queryInfo = this.Queries.find(q => UUIDsEqual(q.ID, query.ID));
|
|
7164
|
+
// The QueryInfo metadata exists only when this provider loads query metadata; the ID
|
|
7165
|
+
// always reaches the enricher, which can resolve the query from QueryEngine.
|
|
7166
|
+
const queryInfo = this.LoadsQueryMetadata ? this.Queries.find(q => UUIDsEqual(q.ID, query.ID)) : undefined;
|
|
6643
7167
|
return await enricher.EnrichResults({
|
|
6644
7168
|
rows,
|
|
6645
7169
|
config: enrichment.Config ?? {},
|
|
6646
7170
|
query: queryInfo,
|
|
7171
|
+
queryID: query.ID,
|
|
6647
7172
|
contextUser,
|
|
6648
7173
|
provider: this,
|
|
6649
7174
|
});
|
|
@@ -6703,11 +7228,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6703
7228
|
const pk = entityInfo.PrimaryKeys.find(p => p.Name.trim().toLowerCase() === val.FieldName.trim().toLowerCase());
|
|
6704
7229
|
if (!pk)
|
|
6705
7230
|
throw new Error(`Primary key ${val.FieldName} not found in entity ${entityInfo.Name}`);
|
|
6706
|
-
|
|
6707
|
-
const safeVal = quotes ? String(val.Value).replace(/'/g, "''") : val.Value;
|
|
6708
|
-
return `${this.QuoteIdentifier(pk.CodeName)}=${quotes}${safeVal}${quotes}`;
|
|
7231
|
+
return `${this.QuoteIdentifier(pk.CodeName)}=${this.RenderPrimaryKeyLiteral(pk, val.Value, entityInfo.Name)}`;
|
|
6709
7232
|
}).join(' AND ');
|
|
6710
7233
|
}
|
|
7234
|
+
/**
|
|
7235
|
+
* A primary key value as a SQL literal: quoted with embedded quotes escaped, or a plain number
|
|
7236
|
+
* for a key that takes no quotes. These statements are built as text, and a key value can come
|
|
7237
|
+
* from the client, so an unquoted value that isn't a number throws.
|
|
7238
|
+
*/
|
|
7239
|
+
RenderPrimaryKeyLiteral(field, value, entityName) {
|
|
7240
|
+
return this.RenderKeyLiteral(value, field?.NeedsQuotes ?? false, field?.Name, entityName);
|
|
7241
|
+
}
|
|
7242
|
+
/**
|
|
7243
|
+
* {@link RenderPrimaryKeyLiteral} for a caller that has the key's quoting rule but not its field.
|
|
7244
|
+
*/
|
|
7245
|
+
RenderKeyLiteral(value, needsQuotes, fieldName, entityName) {
|
|
7246
|
+
if (needsQuotes) {
|
|
7247
|
+
return `'${String(value).replace(/'/g, "''")}'`;
|
|
7248
|
+
}
|
|
7249
|
+
const raw = String(value);
|
|
7250
|
+
if (!/^-?\d+(\.\d+)?$/.test(raw)) {
|
|
7251
|
+
throw new Error(`Invalid non-numeric value provided for numeric key field ${fieldName} on entity ${entityName}`);
|
|
7252
|
+
}
|
|
7253
|
+
return raw;
|
|
7254
|
+
}
|
|
6711
7255
|
/**
|
|
6712
7256
|
* Trims the trailing pad from fixed-width char fields (char/nchar pad with spaces on both SQL
|
|
6713
7257
|
* Server and PostgreSQL), in place, and returns the row.
|
|
@@ -6756,8 +7300,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6756
7300
|
const where = this.BuildPrimaryKeyWhereClause(entityInfo, compositeKey);
|
|
6757
7301
|
// Append Read row filters — role RLS AND API-key filters (GetEffectiveRowFilterWhereClause)
|
|
6758
7302
|
let fullWhere = where;
|
|
7303
|
+
let rlsParameters = [];
|
|
6759
7304
|
if (user) {
|
|
6760
|
-
const
|
|
7305
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7306
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '', rlsBinder ?? undefined);
|
|
7307
|
+
if (rlsBinder?.Parameters?.length) {
|
|
7308
|
+
rlsParameters = rlsBinder.Parameters;
|
|
7309
|
+
}
|
|
6761
7310
|
if (rlsWhereClause && rlsWhereClause.length > 0) {
|
|
6762
7311
|
fullWhere = `${where} AND (${rlsWhereClause})`;
|
|
6763
7312
|
}
|
|
@@ -6773,7 +7322,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6773
7322
|
// Unrestricted users keep the literal `SELECT *` — byte-identical SQL, no plan churn.
|
|
6774
7323
|
const selectList = this.buildFieldSecuritySelectList(entityInfo, user);
|
|
6775
7324
|
const sql = `SELECT ${selectList} FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${fullWhere}`;
|
|
6776
|
-
const
|
|
7325
|
+
const queryParams = rlsParameters.length > 0 ? rlsParameters : undefined;
|
|
7326
|
+
const rawData = await this.ExecuteSQL(sql, queryParams, undefined, user);
|
|
6777
7327
|
const d = await this.PostProcessRows(rawData, entityInfo, user);
|
|
6778
7328
|
if (d && d.length > 0) {
|
|
6779
7329
|
const ret = this.TrimFixedWidthValues(entityInfo, d[0]);
|
|
@@ -6797,15 +7347,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6797
7347
|
}
|
|
6798
7348
|
// An EntityRelationship joins on ONE column (RelatedEntityJoinField / JoinEntityJoinField)
|
|
6799
7349
|
// that references this entity's key — a single-column foreign-key target by metadata design.
|
|
6800
|
-
const
|
|
6801
|
-
|
|
6802
|
-
|
|
6803
|
-
if (
|
|
6804
|
-
|
|
6805
|
-
|
|
6806
|
-
else {
|
|
6807
|
-
// many to many — use join view
|
|
6808
|
-
relSql = `SELECT _theview.* FROM ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.RelatedEntityBaseView)} _theview INNER JOIN ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.JoinView)} _jv ON _theview.${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = _jv.${this.QuoteIdentifier(relInfo.JoinEntityInverseJoinField)} WHERE _jv.${this.QuoteIdentifier(relInfo.JoinEntityJoinField)} = ${quotes}${pkValue}${quotes}`;
|
|
7350
|
+
const relSql = this.BuildRelatedRowsLoadSQL(relInfo, relEntityInfo, ret[entity.FirstPrimaryKey.Name], // first-pk-ok: relationship join field is a single-column FK target
|
|
7351
|
+
entity.FirstPrimaryKey.NeedsQuotes, // first-pk-ok: relationship join field is a single-column FK target
|
|
7352
|
+
user);
|
|
7353
|
+
if (relSql === null) {
|
|
7354
|
+
LogStatus(`[GenericDatabaseProvider] Skipping relationship '${rel}' on '${entityInfo.Name}': the user cannot read '${relEntityInfo.Name}'.`);
|
|
7355
|
+
continue;
|
|
6809
7356
|
}
|
|
6810
7357
|
const rawRelData = await this.ExecuteSQL(relSql, undefined, undefined, user);
|
|
6811
7358
|
if (rawRelData && rawRelData.length > 0) {
|
|
@@ -6817,6 +7364,34 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6817
7364
|
}
|
|
6818
7365
|
return null;
|
|
6819
7366
|
}
|
|
7367
|
+
/**
|
|
7368
|
+
* Builds the SELECT for one relationship of a single-record load, or returns null when the
|
|
7369
|
+
* user may not read the related entity at all (the caller skips the relationship).
|
|
7370
|
+
*
|
|
7371
|
+
* The related rows get the same protection the parent row gets: the column list leaves out
|
|
7372
|
+
* fields the user may not read, and the user's Read row filter narrows the rows. A user with
|
|
7373
|
+
* no field denials and no row filter gets the same SQL as before. With no user (server-side
|
|
7374
|
+
* system work) nothing is narrowed, which matches the parent load.
|
|
7375
|
+
*
|
|
7376
|
+
* For a many-to-many relationship the row filter is applied inside a derived table over the
|
|
7377
|
+
* related view, so its column names cannot clash with the join view's.
|
|
7378
|
+
*/
|
|
7379
|
+
BuildRelatedRowsLoadSQL(relInfo, relEntityInfo, pkValue, pkNeedsQuotes, user) {
|
|
7380
|
+
if (user && !relEntityInfo.GetUserPermisions(user)?.CanRead) {
|
|
7381
|
+
return null;
|
|
7382
|
+
}
|
|
7383
|
+
const keyLiteral = this.RenderKeyLiteral(pkValue, pkNeedsQuotes, relInfo.RelatedEntityJoinField, relEntityInfo.Name);
|
|
7384
|
+
const rowFilter = user ? relEntityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Read, '') : '';
|
|
7385
|
+
const relatedView = this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.RelatedEntityBaseView);
|
|
7386
|
+
if (relInfo.Type.trim().toLowerCase() === 'one to many') {
|
|
7387
|
+
const filterClause = rowFilter ? ` AND (${rowFilter})` : '';
|
|
7388
|
+
return `SELECT ${this.buildFieldSecuritySelectList(relEntityInfo, user)} FROM ${relatedView} WHERE ${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = ${keyLiteral}${filterClause}`;
|
|
7389
|
+
}
|
|
7390
|
+
// many to many — through the join view
|
|
7391
|
+
const columns = this.buildFieldSecuritySelectList(relEntityInfo, user, '_theview');
|
|
7392
|
+
const source = rowFilter ? `(SELECT * FROM ${relatedView} WHERE (${rowFilter}))` : relatedView;
|
|
7393
|
+
return `SELECT ${columns} FROM ${source} _theview INNER JOIN ${this.QuoteSchemaAndView(relEntityInfo.SchemaName, relInfo.JoinView)} _jv ON _theview.${this.QuoteIdentifier(relInfo.RelatedEntityJoinField)} = _jv.${this.QuoteIdentifier(relInfo.JoinEntityInverseJoinField)} WHERE _jv.${this.QuoteIdentifier(relInfo.JoinEntityJoinField)} = ${keyLiteral}`;
|
|
7394
|
+
}
|
|
6820
7395
|
/**************************************************************************/
|
|
6821
7396
|
// Row-Level Security Checks
|
|
6822
7397
|
/**************************************************************************/
|
|
@@ -6827,23 +7402,22 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6827
7402
|
*/
|
|
6828
7403
|
async CheckRecordRLS(entity, user, type) {
|
|
6829
7404
|
const entityInfo = entity.EntityInfo;
|
|
6830
|
-
const
|
|
7405
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7406
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, type, '', rlsBinder ?? undefined);
|
|
6831
7407
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6832
7408
|
return true;
|
|
6833
7409
|
}
|
|
6834
7410
|
const pkWhere = entity.PrimaryKeys.map(pk => {
|
|
6835
7411
|
const fieldInfo = entityInfo.FieldByName(pk.Name);
|
|
6836
|
-
|
|
6837
|
-
//
|
|
6838
|
-
//
|
|
6839
|
-
//
|
|
6840
|
-
|
|
6841
|
-
// pass RLS on rows the caller cannot see.
|
|
6842
|
-
const safeVal = quotes ? String(pk.Value).replace(/'/g, "''") : pk.Value;
|
|
6843
|
-
return `${this.QuoteIdentifier(pk.Name)}=${quotes}${safeVal}${quotes}`;
|
|
7412
|
+
// Rendered as on the Load()-by-PK path above. The PK value can be CLIENT-SUPPLIED here
|
|
7413
|
+
// (the update resolver loads OldValues from the client for entities without record
|
|
7414
|
+
// tracking), and this method's only job is an authorization decision — a crafted PK
|
|
7415
|
+
// must not make the COUNT(*) pass RLS on rows the caller cannot see.
|
|
7416
|
+
return `${this.QuoteIdentifier(pk.Name)}=${this.RenderPrimaryKeyLiteral(fieldInfo, pk.Value, entityInfo.Name)}`;
|
|
6844
7417
|
}).join(' AND ');
|
|
6845
7418
|
const sql = `SELECT COUNT(*) AS cnt FROM ${this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseView)} WHERE ${pkWhere} AND (${rlsWhereClause})`;
|
|
6846
|
-
const
|
|
7419
|
+
const queryParams = rlsBinder?.Parameters?.length ? rlsBinder.Parameters : undefined;
|
|
7420
|
+
const result = await this.ExecuteSQL(sql, queryParams, undefined, user);
|
|
6847
7421
|
return result && result.length > 0 && Number(result[0]['cnt']) > 0;
|
|
6848
7422
|
}
|
|
6849
7423
|
/**
|
|
@@ -6856,13 +7430,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6856
7430
|
*/
|
|
6857
7431
|
async CheckCreateRLS(entity, user) {
|
|
6858
7432
|
const entityInfo = entity.EntityInfo;
|
|
6859
|
-
const
|
|
7433
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7434
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Create, '', rlsBinder ?? undefined);
|
|
6860
7435
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6861
7436
|
return true;
|
|
6862
7437
|
}
|
|
6863
|
-
const
|
|
6864
|
-
const
|
|
6865
|
-
|
|
7438
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, false, rlsBinder?.Parameters?.length ?? 0);
|
|
7439
|
+
const allParams = [
|
|
7440
|
+
...(rlsBinder?.Parameters ?? []),
|
|
7441
|
+
...syntheticRow.parameters
|
|
7442
|
+
];
|
|
7443
|
+
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
7444
|
+
const result = await this.ExecuteSQL(sql, allParams.length > 0 ? allParams : undefined, undefined, user);
|
|
6866
7445
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
6867
7446
|
}
|
|
6868
7447
|
/**
|
|
@@ -6881,7 +7460,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6881
7460
|
*/
|
|
6882
7461
|
async CheckUpdateRLSPostImage(entity, user) {
|
|
6883
7462
|
const entityInfo = entity.EntityInfo;
|
|
6884
|
-
const
|
|
7463
|
+
const rlsBinder = this.CreateRowFilterParameterBinder();
|
|
7464
|
+
const rlsWhereClause = entityInfo.GetEffectiveRowFilterWhereClause(user, EntityPermissionType.Update, '', rlsBinder ?? undefined);
|
|
6885
7465
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
6886
7466
|
return true;
|
|
6887
7467
|
}
|
|
@@ -6893,9 +7473,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6893
7473
|
return true; // pre-image check already passed and no filter-referenced column changed
|
|
6894
7474
|
}
|
|
6895
7475
|
}
|
|
6896
|
-
const
|
|
6897
|
-
const
|
|
6898
|
-
|
|
7476
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, false, rlsBinder?.Parameters?.length ?? 0);
|
|
7477
|
+
const allParams = [
|
|
7478
|
+
...(rlsBinder?.Parameters ?? []),
|
|
7479
|
+
...syntheticRow.parameters
|
|
7480
|
+
];
|
|
7481
|
+
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
7482
|
+
const result = await this.ExecuteSQL(sql, allParams.length > 0 ? allParams : undefined, undefined, user);
|
|
6899
7483
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
6900
7484
|
}
|
|
6901
7485
|
/**
|
|
@@ -6933,10 +7517,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6933
7517
|
}
|
|
6934
7518
|
}
|
|
6935
7519
|
}
|
|
6936
|
-
const
|
|
6937
|
-
const sql = `SELECT CASE WHEN (${trimmed}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
|
|
7520
|
+
const syntheticRow = this.BuildRLSSyntheticRowProjectionsParameterized(entity, entity.EntityInfo, true);
|
|
7521
|
+
const sql = `SELECT CASE WHEN (${trimmed}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${syntheticRow.projections}) AS newrow`;
|
|
6938
7522
|
try {
|
|
6939
|
-
const result = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
7523
|
+
const result = await this.ExecuteSQL(sql, syntheticRow.parameters.length > 0 ? syntheticRow.parameters : undefined, undefined, user);
|
|
6940
7524
|
return Boolean(result && result.length > 0 && Number(result[0]['pass']) === 1);
|
|
6941
7525
|
}
|
|
6942
7526
|
catch (err) {
|
|
@@ -6971,6 +7555,67 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
6971
7555
|
}
|
|
6972
7556
|
return columns.length > 0 ? columns : null;
|
|
6973
7557
|
}
|
|
7558
|
+
/**
|
|
7559
|
+
* Builds field projections and query parameters for an RLS synthetic-row subquery.
|
|
7560
|
+
* Null fields are projected as typed `CAST(NULL AS <sqltype>)`.
|
|
7561
|
+
* Non-null fields are bound as query parameters rather than interpolated literals.
|
|
7562
|
+
*/
|
|
7563
|
+
BuildRLSSyntheticRowProjectionsParameterized(entity, entityInfo, includeISAParentFields = false, paramStartIndex = 0) {
|
|
7564
|
+
const dialect = this.getDialect();
|
|
7565
|
+
const parts = [];
|
|
7566
|
+
const parameters = [];
|
|
7567
|
+
const parentFieldNames = includeISAParentFields ? entityInfo.ParentEntityFieldNames : undefined;
|
|
7568
|
+
for (const field of entityInfo.Fields) {
|
|
7569
|
+
if (field.IsVirtual && !parentFieldNames?.has(field.Name))
|
|
7570
|
+
continue;
|
|
7571
|
+
const val = entity.Get(field.Name);
|
|
7572
|
+
if (val == null) {
|
|
7573
|
+
parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7574
|
+
}
|
|
7575
|
+
else if (val instanceof Uint8Array) {
|
|
7576
|
+
const hex = Buffer.from(val).toString('hex');
|
|
7577
|
+
const hexExpr = dialect?.BinaryTypeNames.includes('bytea')
|
|
7578
|
+
? `decode('${hex}', 'hex')`
|
|
7579
|
+
: (hex.length > 0 ? `0x${hex}` : '0x');
|
|
7580
|
+
parts.push(`${hexExpr} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7581
|
+
}
|
|
7582
|
+
else {
|
|
7583
|
+
const paramIdx = paramStartIndex + parameters.length;
|
|
7584
|
+
const placeholder = dialect ? dialect.Binding.ParameterPlaceholder(paramIdx) : `@_syn_p${paramIdx}`;
|
|
7585
|
+
const paramName = placeholder.startsWith('@') ? placeholder.slice(1) : placeholder;
|
|
7586
|
+
let boundValue;
|
|
7587
|
+
if (typeof val === 'boolean' || val instanceof Date || typeof val === 'number') {
|
|
7588
|
+
boundValue = val;
|
|
7589
|
+
}
|
|
7590
|
+
else if (field.NeedsQuotes) {
|
|
7591
|
+
boundValue = String(val);
|
|
7592
|
+
}
|
|
7593
|
+
else {
|
|
7594
|
+
const num = Number(String(val));
|
|
7595
|
+
if (!Number.isFinite(num)) {
|
|
7596
|
+
throw new Error(`Cannot build RLS projection: value for numeric field ${field.Name} does not parse as a number`);
|
|
7597
|
+
}
|
|
7598
|
+
boundValue = num;
|
|
7599
|
+
}
|
|
7600
|
+
parameters.push(new NamedQueryParameter(paramName, boundValue));
|
|
7601
|
+
const baseType = field.Type;
|
|
7602
|
+
if (baseType && baseType.trim().length > 0) {
|
|
7603
|
+
const isBinary = /^(var)?binary$/i.test(baseType.trim());
|
|
7604
|
+
const charLength = field.Length === -1 || isBinary ? field.Length : field.MaxLength;
|
|
7605
|
+
const mapped = dialect?.MapDataTypeToString(baseType, charLength, field.Precision, field.Scale);
|
|
7606
|
+
const mappedType = mapped ?? field.SQLFullType ?? baseType;
|
|
7607
|
+
parts.push(`CAST(${placeholder} AS ${mappedType}) AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7608
|
+
}
|
|
7609
|
+
else if (field.SQLFullType && field.SQLFullType.trim().length > 0) {
|
|
7610
|
+
parts.push(`CAST(${placeholder} AS ${field.SQLFullType}) AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7611
|
+
}
|
|
7612
|
+
else {
|
|
7613
|
+
parts.push(`${placeholder} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
7614
|
+
}
|
|
7615
|
+
}
|
|
7616
|
+
}
|
|
7617
|
+
return { projections: parts.join(', '), parameters };
|
|
7618
|
+
}
|
|
6974
7619
|
/**
|
|
6975
7620
|
* Builds field projections for an RLS synthetic-row subquery (Create post-image and
|
|
6976
7621
|
* Update post-image checks).
|
|
@@ -7495,21 +8140,11 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
7495
8140
|
? this.extractMaxUpdatedAtFromRows(itemData, dateFieldToCheck)
|
|
7496
8141
|
: new Date(0).toISOString();
|
|
7497
8142
|
const syntheticParams = { EntityName: entityName };
|
|
7498
|
-
//
|
|
7499
|
-
//
|
|
7500
|
-
//
|
|
7501
|
-
//
|
|
7502
|
-
|
|
7503
|
-
// Freezing them makes metadata bootstrap throw and the process starts blind.
|
|
7504
|
-
//
|
|
7505
|
-
// Every OTHER dataset is served to arbitrary consumers (BaseEngine.Load hands
|
|
7506
|
-
// item.Results — these very arrays — to every engine subclass), so those slots
|
|
7507
|
-
// must stay under the defensive deep-freeze like any RunView result.
|
|
7508
|
-
const isMetadataScaffolding = datasetName === ProviderBase._mjMetadataDatasetName;
|
|
7509
|
-
const rowsForCache = isMetadataScaffolding
|
|
7510
|
-
? itemData
|
|
7511
|
-
: provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName));
|
|
7512
|
-
await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, rowsForCache, maxUpdatedAt, undefined, undefined, this, undefined, isMetadataScaffolding ? { ProviderInternalScaffolding: true } : undefined);
|
|
8143
|
+
// Every dataset's slots — MJ_Metadata's included — hold rows that later readers are
|
|
8144
|
+
// served (BaseEngine.Load hands item.Results to every engine subclass; the GraphQL
|
|
8145
|
+
// dataset resolver hands MJ_Metadata to every client), so they are frozen like any
|
|
8146
|
+
// RunView result. The metadata assembly copies the rows it writes to.
|
|
8147
|
+
await cache.SetRunViewResult(uncachedFingerprints[i], syntheticParams, provider.PrepareRowsForCacheStorage(itemData, provider.EntityByName(entityName)), maxUpdatedAt, undefined, undefined, this);
|
|
7513
8148
|
}
|
|
7514
8149
|
sqlResults.push({
|
|
7515
8150
|
EntityID: entityID,
|
|
@@ -8047,6 +8682,37 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
8047
8682
|
}
|
|
8048
8683
|
this._postCommitTasks.push({ Task: task, Description: description, Depth: this._transactionDepth });
|
|
8049
8684
|
}
|
|
8685
|
+
/**
|
|
8686
|
+
* Savepoint- and token-aware coalesced post-commit scheduling.
|
|
8687
|
+
*
|
|
8688
|
+
* Entries recorded inside an open transaction retain their owning depth so savepoint rollbacks
|
|
8689
|
+
* drop rolled-back registrations without touching earlier frames' registrations under the same
|
|
8690
|
+
* key; surviving entries deduplicate once at outermost commit (`'last-wins'` or `'first-wins'`).
|
|
8691
|
+
*/
|
|
8692
|
+
ScheduleAfterCommit(coalesceKey, task, description = 'post-commit task', token, mode = 'last-wins') {
|
|
8693
|
+
if (!coalesceKey) {
|
|
8694
|
+
this.RunAfterCommit(task, description, token);
|
|
8695
|
+
return;
|
|
8696
|
+
}
|
|
8697
|
+
if (token) {
|
|
8698
|
+
this.registerPostCommitTaskWithToken(task, description, token, coalesceKey, mode);
|
|
8699
|
+
return;
|
|
8700
|
+
}
|
|
8701
|
+
if (!this.IsCallerInAmbientTransaction()) {
|
|
8702
|
+
this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, mode);
|
|
8703
|
+
return;
|
|
8704
|
+
}
|
|
8705
|
+
this._postCommitTasks.push({
|
|
8706
|
+
Task: task,
|
|
8707
|
+
Description: description,
|
|
8708
|
+
Depth: this._transactionDepth,
|
|
8709
|
+
CoalesceKey: coalesceKey,
|
|
8710
|
+
CoalesceMode: mode,
|
|
8711
|
+
});
|
|
8712
|
+
}
|
|
8713
|
+
ExecuteDetachedPostCommitTask(task, description) {
|
|
8714
|
+
this.runDetachedTask(task, description);
|
|
8715
|
+
}
|
|
8050
8716
|
/**
|
|
8051
8717
|
* Snapshot of the caller's transaction frames. Synchronous, and never `undefined` on this
|
|
8052
8718
|
* provider: outside a transaction it returns a token whose epoch is `null`, which says the work
|
|
@@ -8061,14 +8727,24 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
8061
8727
|
}
|
|
8062
8728
|
return this._frameTracker.Capture();
|
|
8063
8729
|
}
|
|
8064
|
-
registerPostCommitTaskWithToken(task, description, token) {
|
|
8730
|
+
registerPostCommitTaskWithToken(task, description, token, coalesceKey, coalesceMode) {
|
|
8065
8731
|
const resolution = this._frameTracker.Resolve(token, this._doomed);
|
|
8066
8732
|
switch (resolution.Kind) {
|
|
8067
8733
|
case 'run':
|
|
8068
|
-
|
|
8734
|
+
if (coalesceKey) {
|
|
8735
|
+
this.EnqueueDetachedCoalescedTask(coalesceKey, task, description, coalesceMode ?? 'last-wins');
|
|
8736
|
+
}
|
|
8737
|
+
else {
|
|
8738
|
+
this.runDetachedTask(task, description);
|
|
8739
|
+
}
|
|
8069
8740
|
return;
|
|
8070
8741
|
case 'queue':
|
|
8071
|
-
this._postCommitTasks.push({
|
|
8742
|
+
this._postCommitTasks.push({
|
|
8743
|
+
Task: task,
|
|
8744
|
+
Description: description,
|
|
8745
|
+
Depth: resolution.Depth,
|
|
8746
|
+
...(coalesceKey ? { CoalesceKey: coalesceKey, CoalesceMode: coalesceMode ?? 'last-wins' } : {}),
|
|
8747
|
+
});
|
|
8072
8748
|
return;
|
|
8073
8749
|
case 'drop':
|
|
8074
8750
|
if (resolution.Unknown) {
|
|
@@ -8105,15 +8781,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
8105
8781
|
}
|
|
8106
8782
|
/** Run tasks detached from a committed transaction, one at a time, in order. Never throws. */
|
|
8107
8783
|
async runPostCommitTasks(tasks) {
|
|
8108
|
-
|
|
8784
|
+
const effectiveTasks = this.coalescePostCommitTasks(tasks);
|
|
8785
|
+
if (effectiveTasks.length === 0) {
|
|
8109
8786
|
return;
|
|
8110
8787
|
}
|
|
8111
|
-
LogStatus(`Running ${
|
|
8112
|
-
for (const entry of
|
|
8788
|
+
LogStatus(`Running ${effectiveTasks.length} post-commit task(s) after transaction commit`);
|
|
8789
|
+
for (const entry of effectiveTasks) {
|
|
8113
8790
|
// Detached from the committer's (now stale) membership explicitly, not merely by epoch mismatch.
|
|
8114
8791
|
await this._affinity.RunDetached(() => this.RunPostCommitTaskSafely(entry.Task, entry.Description));
|
|
8115
8792
|
}
|
|
8116
8793
|
}
|
|
8794
|
+
/** Deduplicates entries sharing a `CoalesceKey` after savepoint rollbacks have already been pruned. */
|
|
8795
|
+
coalescePostCommitTasks(tasks) {
|
|
8796
|
+
let hasCoalesced = false;
|
|
8797
|
+
const winnerIndex = new Map();
|
|
8798
|
+
for (let i = 0; i < tasks.length; i++) {
|
|
8799
|
+
const entry = tasks[i];
|
|
8800
|
+
if (!entry.CoalesceKey) {
|
|
8801
|
+
continue;
|
|
8802
|
+
}
|
|
8803
|
+
hasCoalesced = true;
|
|
8804
|
+
if ((entry.CoalesceMode ?? 'last-wins') === 'first-wins') {
|
|
8805
|
+
if (!winnerIndex.has(entry.CoalesceKey)) {
|
|
8806
|
+
winnerIndex.set(entry.CoalesceKey, i);
|
|
8807
|
+
}
|
|
8808
|
+
}
|
|
8809
|
+
else {
|
|
8810
|
+
winnerIndex.set(entry.CoalesceKey, i);
|
|
8811
|
+
}
|
|
8812
|
+
}
|
|
8813
|
+
if (!hasCoalesced) {
|
|
8814
|
+
return tasks;
|
|
8815
|
+
}
|
|
8816
|
+
return tasks.filter((entry, idx) => !entry.CoalesceKey || winnerIndex.get(entry.CoalesceKey) === idx);
|
|
8817
|
+
}
|
|
8117
8818
|
/** Detach the whole queue (outermost commit succeeded). */
|
|
8118
8819
|
takePostCommitTasks() {
|
|
8119
8820
|
const tasks = this._postCommitTasks;
|