@memberjunction/generic-database-provider 6.1.4 → 6.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GenericDatabaseProvider.d.ts +136 -11
- package/dist/GenericDatabaseProvider.d.ts.map +1 -1
- package/dist/GenericDatabaseProvider.js +371 -90
- package/dist/GenericDatabaseProvider.js.map +1 -1
- package/dist/clientClauseScreen.d.ts +259 -0
- package/dist/clientClauseScreen.d.ts.map +1 -0
- package/dist/clientClauseScreen.js +531 -0
- package/dist/clientClauseScreen.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 +127 -95
- package/dist/queryPagingEngine.d.ts.map +1 -1
- package/dist/queryPagingEngine.js +241 -260
- 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
|
@@ -15,15 +15,15 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module @memberjunction/generic-database-provider
|
|
17
17
|
*/
|
|
18
|
-
import { 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';
|
|
18
|
+
import { BaseEntity, DatabaseProviderBase, EntityFieldTSType, ProjectRowsToFields, ProviderBase, EntityPermissionType, InMemoryLocalStorageProvider, Metadata, RunView, IsMaterializedDataSource, LocalCacheManager, LogError, LogStatus, LogStatusEx, StripStopWords, AfterKeyNotSupportedError, IsKeysetPaginationOrderableType, ExternalDataSourceReadRouter, resolveQueryResultEnricher, } from '@memberjunction/core';
|
|
19
|
+
import { IsValidUUID, 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, IsBalancedSQLFragment, SplitTopLevelAndTerms } 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,14 @@ 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 { ClientClauseScreen } from './clientClauseScreen.js';
|
|
37
38
|
import { EncryptionEngine } from '@memberjunction/encryption';
|
|
38
39
|
import { GeoCodeSyncService } from '@memberjunction/geo-core';
|
|
40
|
+
/**
|
|
41
|
+
* Execution options for SQL a caller supplied rather than a saved query (ad-hoc SQL, transient test
|
|
42
|
+
* queries): run it read-only and roll back, so it can neither write nor leave session state behind.
|
|
43
|
+
*/
|
|
44
|
+
const CALLER_SQL_OPTIONS = { readOnlyTransaction: true, description: 'caller-supplied query' };
|
|
39
45
|
/**
|
|
40
46
|
* GenericDatabaseProvider is an intermediate abstract class that implements shared
|
|
41
47
|
* entity action, AI action, encryption, and view WHERE clause rendering logic.
|
|
@@ -1323,6 +1329,45 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1323
1329
|
TransformExternalSQLClause(clause, _entityInfo) {
|
|
1324
1330
|
return clause;
|
|
1325
1331
|
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Throws unless a caller-supplied WHERE piece (ExtraFilter, OverrideExcludeFilter, a stored view
|
|
1334
|
+
* WhereClause) stays inside the parentheses this provider puts around it, read with this
|
|
1335
|
+
* provider's SQL dialect (see `IsBalancedSQLFragment`). The pieces are ANDed with row-level
|
|
1336
|
+
* security, which also carries API-key row filters and guest scope; a piece that closes its
|
|
1337
|
+
* parentheses early, such as `1=1) OR (1=1`, would leave those filters on one side of an OR the
|
|
1338
|
+
* caller controls.
|
|
1339
|
+
*/
|
|
1340
|
+
AssertClauseBalanced(clause, label, options) {
|
|
1341
|
+
const check = IsBalancedSQLFragment(clause, this.Dialect, options);
|
|
1342
|
+
if (!check.IsBalanced) {
|
|
1343
|
+
throw new Error(`Invalid ${label}: ${check.Reason}`);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
/**
|
|
1347
|
+
* Applies {@link TransformExternalSQLClause} to a caller's ExtraFilter and checks the result with
|
|
1348
|
+
* {@link AssertClauseBalanced}. When the transform changes the text and the filter is a chain of
|
|
1349
|
+
* top-level AND terms, each term is transformed, checked and parenthesized on its own. A
|
|
1350
|
+
* PreRunView hook that ANDs a server predicate (such as tenant scope) onto the caller's filter
|
|
1351
|
+
* runs before this transform, so a rewrite that changes the caller's term cannot reach the
|
|
1352
|
+
* hook's term.
|
|
1353
|
+
*/
|
|
1354
|
+
PrepareExtraFilterSQL(extraFilter, entityInfo) {
|
|
1355
|
+
if (!extraFilter)
|
|
1356
|
+
return '';
|
|
1357
|
+
const transformed = this.TransformExternalSQLClause(extraFilter, entityInfo);
|
|
1358
|
+
const terms = transformed === extraFilter ? null : SplitTopLevelAndTerms(extraFilter, this.Dialect);
|
|
1359
|
+
if (!terms || terms.length < 2) {
|
|
1360
|
+
this.AssertClauseBalanced(transformed, 'ExtraFilter');
|
|
1361
|
+
return transformed;
|
|
1362
|
+
}
|
|
1363
|
+
return terms
|
|
1364
|
+
.map((term) => {
|
|
1365
|
+
const termSQL = this.TransformExternalSQLClause(term.trim(), entityInfo);
|
|
1366
|
+
this.AssertClauseBalanced(termSQL, 'ExtraFilter');
|
|
1367
|
+
return `(${termSQL})`;
|
|
1368
|
+
})
|
|
1369
|
+
.join(' AND ');
|
|
1370
|
+
}
|
|
1326
1371
|
/**
|
|
1327
1372
|
* Optionally wraps a view query with user view run logging.
|
|
1328
1373
|
* SQL Server overrides to use spCreateUserViewRunWithDetail.
|
|
@@ -1398,11 +1443,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1398
1443
|
return externalResult;
|
|
1399
1444
|
}
|
|
1400
1445
|
// ── Parameters (transform user-provided SQL clauses for platform compatibility) ──
|
|
1401
|
-
const extraFilter = this.
|
|
1446
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
|
|
1402
1447
|
const userSearchString = params.UserSearchString ?? '';
|
|
1403
1448
|
const excludeUserViewRunID = params.ExcludeUserViewRunID ?? '';
|
|
1404
1449
|
const overrideExcludeFilter = params.OverrideExcludeFilter ?? '';
|
|
1405
1450
|
const saveViewResults = params.SaveViewResults ?? false;
|
|
1451
|
+
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
1452
|
+
this.AssertClauseFragmentIsSingleStatement(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
1406
1453
|
// ── TOP / pagination mode ──
|
|
1407
1454
|
// Keyset (AfterKey) takes precedence: validate now so failures are early, predictable,
|
|
1408
1455
|
// and never silently degrade to OFFSET. Throws AfterKeyNotSupportedError if invalid.
|
|
@@ -1463,18 +1510,25 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1463
1510
|
// 1. View where clause
|
|
1464
1511
|
if (viewEntity?.WhereClause && viewEntity.WhereClause.length > 0) {
|
|
1465
1512
|
const renderedWhere = await this.RenderViewWhereClause(viewEntity, user);
|
|
1466
|
-
// SECURITY: a stored view WhereClause originates from a client save, so
|
|
1467
|
-
//
|
|
1468
|
-
//
|
|
1469
|
-
//
|
|
1470
|
-
//
|
|
1471
|
-
//
|
|
1472
|
-
//
|
|
1473
|
-
//
|
|
1513
|
+
// SECURITY: a stored view WhereClause originates from a client save, so the rendered
|
|
1514
|
+
// clause passes the full client-clause screen (ScreenStoredViewWhereClause) and the
|
|
1515
|
+
// keyword denylist ExtraFilter gets. The one exemption is CustomWhereClause views:
|
|
1516
|
+
// those are admin-authored (MJUserViewEntityServer's save gate restricts setting/
|
|
1517
|
+
// changing them to Owner-type users) and may legitimately contain constructs the
|
|
1518
|
+
// screens block. Auto-generated clauses (FilterState / SmartFilter / nested
|
|
1519
|
+
// {%UserView%} templates) are written against entity base views, which the screens
|
|
1520
|
+
// permit when the running user reads each of those entities unscoped.
|
|
1521
|
+
this.ScreenStoredViewWhereClause(viewEntity, renderedWhere, user);
|
|
1474
1522
|
const isCustomWhereClause = !!viewEntity.CustomWhereClause; // truthy — the DB may hand back true or 1
|
|
1475
1523
|
if (!isCustomWhereClause && !this.ValidateUserProvidedSQLClause(renderedWhere)) {
|
|
1476
1524
|
throw new Error(`Invalid view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}': contains one or more forbidden keywords`);
|
|
1477
1525
|
}
|
|
1526
|
+
// CustomWhereClause views too: an unbalanced clause would take row-level security
|
|
1527
|
+
// out of force for everyone who runs the view. Only their admin-written text may
|
|
1528
|
+
// carry comments.
|
|
1529
|
+
this.AssertClauseBalanced(renderedWhere, `view WhereClause for view '${viewEntity.Name ?? viewEntity.ID}'`, {
|
|
1530
|
+
AllowComments: isCustomWhereClause,
|
|
1531
|
+
});
|
|
1478
1532
|
whereSQL = `(${renderedWhere})`;
|
|
1479
1533
|
bHasWhere = true;
|
|
1480
1534
|
}
|
|
@@ -1519,8 +1573,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1519
1573
|
// first column's value with a prior run — refuse rather than return the wrong rows.
|
|
1520
1574
|
this.assertSingleColumnPrimaryKey(entityInfo, 'ExcludeUserViewRunID / ExcludeDataFromAllPriorViewRuns');
|
|
1521
1575
|
let sExcludeSQL = `${this.QuoteIdentifier(entityInfo.FirstPrimaryKey.Name)} NOT IN (SELECT RecordID FROM ${this.QuoteSchemaAndView(this.MJCoreSchemaName, 'vwUserViewRunDetails')} WHERE EntityID='${viewEntity?.EntityID}' AND`; // first-pk-ok: guarded above — view-run RecordID is a single bare key value, PrimaryKeys.length === 1 enforced
|
|
1522
|
-
if (params.ExcludeDataFromAllPriorViewRuns === true)
|
|
1576
|
+
if (params.ExcludeDataFromAllPriorViewRuns === true) {
|
|
1577
|
+
// SECURITY: the view ID is interpolated; a loaded view's ID is always a GUID.
|
|
1578
|
+
if (!IsValidUUID(String(viewEntity?.ID ?? '')))
|
|
1579
|
+
throw new Error(`ExcludeDataFromAllPriorViewRuns requires a saved view with a GUID ID`);
|
|
1523
1580
|
sExcludeSQL += ` UserViewID=${viewEntity?.ID})`;
|
|
1581
|
+
}
|
|
1524
1582
|
else {
|
|
1525
1583
|
// SECURITY: excludeUserViewRunID is user-supplied (GraphQL input) and is
|
|
1526
1584
|
// interpolated directly into SQL here. Unlike ExtraFilter/OrderBy/
|
|
@@ -1536,6 +1594,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1536
1594
|
if (overrideExcludeFilter.length > 0) {
|
|
1537
1595
|
if (!this.ValidateUserProvidedSQLClause(overrideExcludeFilter))
|
|
1538
1596
|
throw new Error(`Invalid OverrideExcludeFilter: ${overrideExcludeFilter}, contains one more for forbidden keywords`);
|
|
1597
|
+
this.AssertClauseBalanced(overrideExcludeFilter, 'OverrideExcludeFilter');
|
|
1539
1598
|
sExcludeSQL += ' OR (' + overrideExcludeFilter + ')';
|
|
1540
1599
|
}
|
|
1541
1600
|
whereSQL = bHasWhere ? `${whereSQL} AND (${sExcludeSQL})` : `(${sExcludeSQL})`;
|
|
@@ -1598,6 +1657,12 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1598
1657
|
const orderBy = rawOrderBy.length > 0
|
|
1599
1658
|
? (usingKeyset || orderByIsPkFallback ? rawOrderBy : this.TransformExternalSQLClause(rawOrderBy, entityInfo))
|
|
1600
1659
|
: '';
|
|
1660
|
+
if (orderBy.length > 0 && !usingKeyset && !orderByIsPkFallback) {
|
|
1661
|
+
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
1662
|
+
// No caller OrderBy means the sort came from the saved view's stored sort state.
|
|
1663
|
+
if (!params.OrderBy && viewEntity)
|
|
1664
|
+
this.ScreenStoredViewOrderBy(orderBy, user);
|
|
1665
|
+
}
|
|
1601
1666
|
// View run logging (SQL Server-specific, others return null)
|
|
1602
1667
|
let userViewRunID = '';
|
|
1603
1668
|
if (viewEntity?.ID && String(viewEntity.ID).length > 0 && saveViewResults && user) {
|
|
@@ -1762,6 +1827,40 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1762
1827
|
/**************************************************************************/
|
|
1763
1828
|
// InternalRunView Helpers
|
|
1764
1829
|
/**************************************************************************/
|
|
1830
|
+
/**
|
|
1831
|
+
* Builds the aggregate query without running the caller's text. Each expression must be a single
|
|
1832
|
+
* aggregate function call over this entity's columns: the query runs the SQL that
|
|
1833
|
+
* {@link CheckAggregateExpression} rebuilds from the checked parse tree (with this provider's
|
|
1834
|
+
* dialect), once the keyword validator has also accepted that SQL. A refused expression becomes a
|
|
1835
|
+
* per-aggregate error in request order. The accepted ones are aliased `Agg_0`, `Agg_1`, … in
|
|
1836
|
+
* request order, which is how `RunViewCore` reads their values back.
|
|
1837
|
+
*/
|
|
1838
|
+
BuildAggregateSQL(aggregates, entityInfo, schemaName, baseView, whereSQL) {
|
|
1839
|
+
const columns = entityInfo.Fields.map((f) => f.Name);
|
|
1840
|
+
const items = [];
|
|
1841
|
+
const validationErrors = [];
|
|
1842
|
+
for (const agg of aggregates ?? []) {
|
|
1843
|
+
const screened = this.screenAggregateExpression(agg.expression, columns);
|
|
1844
|
+
if ('SQL' in screened) {
|
|
1845
|
+
items.push(`${screened.SQL} AS ${this.QuoteIdentifier(`Agg_${items.length}`)}`);
|
|
1846
|
+
}
|
|
1847
|
+
else {
|
|
1848
|
+
validationErrors.push({ expression: agg.expression, alias: agg.alias || agg.expression, value: null, error: screened.Error });
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
if (items.length === 0)
|
|
1852
|
+
return { aggregateSQL: null, validationErrors };
|
|
1853
|
+
const where = whereSQL ? ` WHERE ${whereSQL}` : '';
|
|
1854
|
+
return { aggregateSQL: `SELECT ${items.join(', ')} FROM ${this.QuoteSchemaAndView(schemaName, baseView)}${where}`, validationErrors };
|
|
1855
|
+
}
|
|
1856
|
+
/** The SQL to run for one caller aggregate expression, or why it is refused. */
|
|
1857
|
+
screenAggregateExpression(expression, columns) {
|
|
1858
|
+
const check = CheckAggregateExpression(expression, this.Dialect, columns);
|
|
1859
|
+
if (!check.IsAllowed || check.SQL === null)
|
|
1860
|
+
return { Error: `Invalid aggregate expression: ${check.Reason}` };
|
|
1861
|
+
const keywordCheck = SQLExpressionValidator.Instance.validate(check.SQL, { context: 'aggregate', entityFields: columns });
|
|
1862
|
+
return keywordCheck.valid ? { SQL: check.SQL } : { Error: keywordCheck.error || 'Validation failed' };
|
|
1863
|
+
}
|
|
1765
1864
|
/**
|
|
1766
1865
|
* Returns the SELECT list for a single-record load: `*` normally, or an explicit list of
|
|
1767
1866
|
* the columns this user is allowed to read when field security denies them any.
|
|
@@ -1951,9 +2050,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1951
2050
|
// Note this restores the pre-#4392 screen for this path; it does not close the
|
|
1952
2051
|
// unquoted-format hole, which the denylist never covered (`1) OR 1=1` carries no
|
|
1953
2052
|
// forbidden keyword). Quoting `{0}` in the format is what actually closes that.
|
|
1954
|
-
|
|
2053
|
+
//
|
|
2054
|
+
// The screen reads the quote-doubled term, because that is the text `{0}` becomes.
|
|
2055
|
+
if (this.userSearchFieldsUseCustomFormat(entityInfo, deniedSearchFields) && !this.ValidateUserProvidedSQLClause(safeUserSearchString)) {
|
|
1955
2056
|
throw new Error(`Invalid User Search string: this entity has a field using UserSearchParamFormatAPI, ` +
|
|
1956
|
-
`which splices the term directly into SQL, and the term contains
|
|
2057
|
+
`which splices the term directly into SQL, and the term is not allowed there: it contains ` +
|
|
2058
|
+
`a forbidden keyword, a comment or a semicolon, or text that cannot be read as complete SQL ` +
|
|
2059
|
+
`tokens, such as an unbalanced quote or bracket.`);
|
|
1957
2060
|
}
|
|
1958
2061
|
const escapedTerm = this.escapeLikeTerm(safeUserSearchString);
|
|
1959
2062
|
for (const field of entityInfo.Fields) {
|
|
@@ -1971,6 +2074,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
1971
2074
|
if (sUserSearchSQL.length > 0)
|
|
1972
2075
|
sUserSearchSQL = '(' + sUserSearchSQL + ')';
|
|
1973
2076
|
}
|
|
2077
|
+
// A UserSearchParamFormatAPI format may splice the term outside quotes; the term must not end the statement there.
|
|
2078
|
+
this.AssertClauseFragmentIsSingleStatement(sUserSearchSQL, 'UserSearchString');
|
|
1974
2079
|
return sUserSearchSQL;
|
|
1975
2080
|
}
|
|
1976
2081
|
/**
|
|
@@ -2070,6 +2175,50 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2070
2175
|
return true;
|
|
2071
2176
|
}
|
|
2072
2177
|
/**************************************************************************/
|
|
2178
|
+
// Client clause screening
|
|
2179
|
+
/**************************************************************************/
|
|
2180
|
+
/**
|
|
2181
|
+
* SECURITY — refuses a statement separator or comment in a filter, sort or search fragment.
|
|
2182
|
+
* Runs for every RunView caller, server-internal ones included, and cannot refuse a legitimate
|
|
2183
|
+
* fragment. The full base-view screen runs at the client entry points; see {@link ClientClauseScreen}.
|
|
2184
|
+
*/
|
|
2185
|
+
AssertClauseFragmentIsSingleStatement(clause, label) {
|
|
2186
|
+
ClientClauseScreen.AssertSingleStatementFragment(clause, label, this.Dialect);
|
|
2187
|
+
}
|
|
2188
|
+
/**
|
|
2189
|
+
* SECURITY — the full client-clause screen ({@link ClientClauseScreen.AssertClauseUsesEntityBaseViews})
|
|
2190
|
+
* against this provider's entities and dialect, with `contextUser` as the acting user. With
|
|
2191
|
+
* `entityInfo`, the clause is screened in the form this provider runs a client clause for that
|
|
2192
|
+
* entity ({@link TransformExternalSQLClause}). Server code that hands client SQL text to RunView
|
|
2193
|
+
* outside the API entry points calls this: ad-hoc list sources (`ListOperations`) and the
|
|
2194
|
+
* saved-view save gate (`MJUserViewEntityServer`).
|
|
2195
|
+
*/
|
|
2196
|
+
ScreenClientClause(clause, label, contextUser, entityInfo) {
|
|
2197
|
+
const text = clause && entityInfo ? this.TransformExternalSQLClause(clause, entityInfo) : clause;
|
|
2198
|
+
ClientClauseScreen.AssertClauseUsesEntityBaseViews(text, label, this.Entities, this.Dialect, contextUser);
|
|
2199
|
+
}
|
|
2200
|
+
/**
|
|
2201
|
+
* SECURITY — screens a saved view's rendered WhereClause with the full client-clause screen.
|
|
2202
|
+
* Any user who can save a view can write its WhereClause, directly or through FilterState or a
|
|
2203
|
+
* Smart Filter. Exempt: a CustomWhereClause view loaded as an entity, whose clause only an Owner
|
|
2204
|
+
* can set (MJUserViewEntityServer). The flag on any other object, such as one built from a
|
|
2205
|
+
* request body, is not trusted. The exemption tests `instanceof BaseEntity`, so a second copy of
|
|
2206
|
+
* `@memberjunction/core` in the process makes loaded custom views fail closed, not open.
|
|
2207
|
+
*/
|
|
2208
|
+
ScreenStoredViewWhereClause(viewEntity, renderedWhere, user) {
|
|
2209
|
+
if (viewEntity instanceof BaseEntity && !!viewEntity.CustomWhereClause)
|
|
2210
|
+
return; // truthy — the DB may hand back true or 1
|
|
2211
|
+
this.AssertClauseFragmentIsSingleStatement(renderedWhere, 'view WhereClause');
|
|
2212
|
+
this.ScreenClientClause(renderedWhere, 'view WhereClause', user);
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* SECURITY — screens the ORDER BY a saved view builds from its stored SortState / GridState with
|
|
2216
|
+
* the full client-clause screen. Any user who can save a view can write those.
|
|
2217
|
+
*/
|
|
2218
|
+
ScreenStoredViewOrderBy(orderBy, user) {
|
|
2219
|
+
this.ScreenClientClause(orderBy, 'OrderBy', user);
|
|
2220
|
+
}
|
|
2221
|
+
/**************************************************************************/
|
|
2073
2222
|
// RenderViewWhereClause — View Template Rendering
|
|
2074
2223
|
/**************************************************************************/
|
|
2075
2224
|
/**
|
|
@@ -2482,7 +2631,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2482
2631
|
async buildWhereClauseForCacheCheck(params, entityInfo, user) {
|
|
2483
2632
|
let whereSQL = '';
|
|
2484
2633
|
let bHasWhere = false;
|
|
2485
|
-
|
|
2634
|
+
// PrepareExtraFilterSQL transforms and balance-checks the filter; the single-statement
|
|
2635
|
+
// check then runs on the result, as on the main view path.
|
|
2636
|
+
const extraFilter = this.PrepareExtraFilterSQL(params.ExtraFilter || '', entityInfo);
|
|
2637
|
+
this.AssertClauseFragmentIsSingleStatement(extraFilter, 'ExtraFilter');
|
|
2486
2638
|
if (extraFilter.length > 0) {
|
|
2487
2639
|
if (!this.ValidateUserProvidedSQLClause(extraFilter))
|
|
2488
2640
|
throw new Error(`Invalid Extra Filter: ${extraFilter}`);
|
|
@@ -2879,6 +3031,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
2879
3031
|
if (orderBy.length > 0) {
|
|
2880
3032
|
if (!this.ValidateUserProvidedSQLClause(orderBy))
|
|
2881
3033
|
throw new Error(`Invalid OrderBy clause: ${orderBy}`);
|
|
3034
|
+
this.AssertClauseFragmentIsSingleStatement(orderBy, 'OrderBy');
|
|
2882
3035
|
sql += ` ORDER BY ${orderBy}`;
|
|
2883
3036
|
}
|
|
2884
3037
|
return await this.ExecuteSQL(sql, undefined, undefined, contextUser);
|
|
@@ -3101,22 +3254,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3101
3254
|
const promises = items.map(async ({ index, query }) => {
|
|
3102
3255
|
try {
|
|
3103
3256
|
const rows = await this.ExecuteSQL(query.CacheValidationSQL, undefined, undefined, contextUser);
|
|
3104
|
-
|
|
3105
|
-
const row = rows[0];
|
|
3106
|
-
results.set(index, {
|
|
3107
|
-
success: true,
|
|
3108
|
-
// Both spellings accepted. The shipped `CacheValidationSQL` field description tells authors
|
|
3109
|
-
// to return `TotalRows`, while this has only ever read `RowCount` — so a query written
|
|
3110
|
-
// from the documentation yields `Number(undefined)` = NaN, `NaN !== NaN` makes the slot
|
|
3111
|
-
// never validate, and NaN is then written back into the client's cache entry where `??`
|
|
3112
|
-
// cannot clear it. Silent, permanent degradation to always-refetch, with no error.
|
|
3113
|
-
rowCount: Number(row['RowCount'] ?? row['TotalRows']),
|
|
3114
|
-
maxUpdatedAt: row['MaxUpdatedAt'] ? new Date(String(row['MaxUpdatedAt'])).toISOString() : undefined,
|
|
3115
|
-
});
|
|
3116
|
-
}
|
|
3117
|
-
else {
|
|
3118
|
-
results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
|
|
3119
|
-
}
|
|
3257
|
+
results.set(index, this.QueryCacheStatusFromRow(rows?.[0]));
|
|
3120
3258
|
}
|
|
3121
3259
|
catch (e) {
|
|
3122
3260
|
results.set(index, { success: false, errorMessage: e instanceof Error ? e.message : String(e) });
|
|
@@ -3125,6 +3263,30 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3125
3263
|
await Promise.all(promises);
|
|
3126
3264
|
return results;
|
|
3127
3265
|
}
|
|
3266
|
+
/**
|
|
3267
|
+
* Reads the first row a query's CacheValidationSQL returned into a cache status. No row means
|
|
3268
|
+
* an empty result: zero rows, no timestamp.
|
|
3269
|
+
*
|
|
3270
|
+
* Both spellings of the count are accepted. The shipped `CacheValidationSQL` field description
|
|
3271
|
+
* tells authors to return `TotalRows`, while older queries return `RowCount`. Reading only one
|
|
3272
|
+
* of them yields `Number(undefined)` = NaN for the other, `NaN !== NaN` makes the slot never
|
|
3273
|
+
* validate, and NaN is then written back into the client's cache entry where `??` cannot clear
|
|
3274
|
+
* it: a silent, permanent degradation to always-refetch, with no error. Platform providers that
|
|
3275
|
+
* batch the validation SQL read their rows through this too.
|
|
3276
|
+
*/
|
|
3277
|
+
QueryCacheStatusFromRow(row) {
|
|
3278
|
+
if (!row) {
|
|
3279
|
+
return { success: true, rowCount: 0, maxUpdatedAt: undefined };
|
|
3280
|
+
}
|
|
3281
|
+
const maxUpdatedAt = row['MaxUpdatedAt'];
|
|
3282
|
+
return {
|
|
3283
|
+
success: true,
|
|
3284
|
+
rowCount: Number(row['RowCount'] ?? row['TotalRows']),
|
|
3285
|
+
maxUpdatedAt: maxUpdatedAt
|
|
3286
|
+
? (maxUpdatedAt instanceof Date ? maxUpdatedAt : new Date(String(maxUpdatedAt))).toISOString()
|
|
3287
|
+
: undefined,
|
|
3288
|
+
};
|
|
3289
|
+
}
|
|
3128
3290
|
/**
|
|
3129
3291
|
* Runs a full query and returns results with cache metadata.
|
|
3130
3292
|
*/
|
|
@@ -3483,7 +3645,8 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3483
3645
|
let matTotalRowCount;
|
|
3484
3646
|
let matExecutionTime;
|
|
3485
3647
|
if (matUseSQLPaging) {
|
|
3486
|
-
const
|
|
3648
|
+
const matStartRow = QueryPagingEngine.ResolveStartRow(params.StartRow);
|
|
3649
|
+
const paging = QueryPagingEngine.WrapWithPaging(materializedSQL, matStartRow, params.MaxRows, this.PlatformKey);
|
|
3487
3650
|
const start = Date.now();
|
|
3488
3651
|
const [dataResult, countResult] = await Promise.all([
|
|
3489
3652
|
this.ExecuteSQL(paging.DataSQL, matPlan.parameters, undefined, contextUser),
|
|
@@ -3511,7 +3674,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3511
3674
|
Results: rows,
|
|
3512
3675
|
RowCount: rows.length,
|
|
3513
3676
|
TotalRowCount: matTotalRowCount,
|
|
3514
|
-
PageNumber: matUseSQLPaging
|
|
3677
|
+
PageNumber: matUseSQLPaging
|
|
3678
|
+
? Math.floor(QueryPagingEngine.ResolveStartRow(params.StartRow) / params.MaxRows) + 1
|
|
3679
|
+
: undefined,
|
|
3515
3680
|
PageSize: matUseSQLPaging ? params.MaxRows : undefined,
|
|
3516
3681
|
ExecutionTime: matExecutionTime,
|
|
3517
3682
|
ErrorMessage: '',
|
|
@@ -3558,7 +3723,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3558
3723
|
if (pagedCacheHit) {
|
|
3559
3724
|
return pagedCacheHit;
|
|
3560
3725
|
}
|
|
3561
|
-
const paging = QueryPagingEngine.WrapWithPaging(finalSQL, params.StartRow, params.MaxRows, this.PlatformKey);
|
|
3726
|
+
const paging = QueryPagingEngine.WrapWithPaging(finalSQL, QueryPagingEngine.ResolveStartRow(params.StartRow), params.MaxRows, this.PlatformKey);
|
|
3562
3727
|
// Execute data + count queries in parallel
|
|
3563
3728
|
const start = Date.now();
|
|
3564
3729
|
const [dataResult, countResult] = await Promise.all([
|
|
@@ -3607,7 +3772,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3607
3772
|
Results: paginatedResult,
|
|
3608
3773
|
RowCount: paginatedResult.length,
|
|
3609
3774
|
TotalRowCount: totalRowCount,
|
|
3610
|
-
PageNumber: useSQLPaging
|
|
3775
|
+
PageNumber: useSQLPaging
|
|
3776
|
+
? Math.floor(QueryPagingEngine.ResolveStartRow(params.StartRow) / params.MaxRows) + 1
|
|
3777
|
+
: undefined,
|
|
3611
3778
|
PageSize: useSQLPaging ? params.MaxRows : undefined,
|
|
3612
3779
|
ExecutionTime: executionTime,
|
|
3613
3780
|
ErrorMessage: '',
|
|
@@ -3648,8 +3815,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3648
3815
|
async ExecuteAdhocQuery(params, contextUser) {
|
|
3649
3816
|
try {
|
|
3650
3817
|
const validator = SQLExpressionValidator.Instance;
|
|
3651
|
-
const validation = validator.validateFullQuery(params.SQL);
|
|
3652
|
-
|
|
3818
|
+
const validation = validator.validateFullQuery(params.SQL, this.PlatformKey);
|
|
3819
|
+
const statementCheck = IsReadOnlyQuery(params.SQL, this.Dialect);
|
|
3820
|
+
if (!validation.valid || !statementCheck.IsReadOnly) {
|
|
3653
3821
|
return {
|
|
3654
3822
|
Success: false,
|
|
3655
3823
|
QueryID: '',
|
|
@@ -3658,17 +3826,18 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3658
3826
|
RowCount: 0,
|
|
3659
3827
|
TotalRowCount: 0,
|
|
3660
3828
|
ExecutionTime: 0,
|
|
3661
|
-
ErrorMessage: validation.
|
|
3829
|
+
ErrorMessage: !validation.valid
|
|
3830
|
+
? validation.error || 'SQL validation failed'
|
|
3831
|
+
: `Ad-hoc SQL must be a single read query: ${statementCheck.Reason}.`,
|
|
3662
3832
|
};
|
|
3663
3833
|
}
|
|
3664
|
-
const {
|
|
3665
|
-
const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
|
|
3834
|
+
const { rows, totalRowCount, executionTime } = await this.runAdhocSQL(params, contextUser);
|
|
3666
3835
|
return {
|
|
3667
3836
|
Success: true,
|
|
3668
3837
|
QueryID: '',
|
|
3669
3838
|
QueryName: 'Ad-Hoc Query',
|
|
3670
|
-
Results:
|
|
3671
|
-
RowCount:
|
|
3839
|
+
Results: rows,
|
|
3840
|
+
RowCount: rows.length,
|
|
3672
3841
|
TotalRowCount: totalRowCount,
|
|
3673
3842
|
ExecutionTime: executionTime,
|
|
3674
3843
|
ErrorMessage: '',
|
|
@@ -3689,6 +3858,60 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3689
3858
|
};
|
|
3690
3859
|
}
|
|
3691
3860
|
}
|
|
3861
|
+
/**
|
|
3862
|
+
* Runs validated ad-hoc SQL. It is rendered the way caller-supplied SQL always is: composition
|
|
3863
|
+
* tokens resolved, comments removed, and a single read query required. With `MaxRows` the
|
|
3864
|
+
* database returns that page and a count runs beside it, as for saved queries, so the server
|
|
3865
|
+
* sends one page rather than every row; without it every row is returned, offset by `StartRow`
|
|
3866
|
+
* when one is given. `TimeoutSeconds` limits every statement the run sends.
|
|
3867
|
+
*/
|
|
3868
|
+
async runAdhocSQL(params, contextUser) {
|
|
3869
|
+
const usePaging = QueryPagingEngine.ShouldPage(params.StartRow, params.MaxRows);
|
|
3870
|
+
const startRow = QueryPagingEngine.ResolveStartRow(params.StartRow);
|
|
3871
|
+
const rendered = RenderPipeline.Run(params.SQL, {
|
|
3872
|
+
Platform: this.PlatformKey,
|
|
3873
|
+
ContextUser: contextUser,
|
|
3874
|
+
RequireReadStatement: true,
|
|
3875
|
+
...(usePaging ? { Paging: { StartRow: startRow, MaxRows: params.MaxRows } } : {}),
|
|
3876
|
+
});
|
|
3877
|
+
const options = this.adhocSQLOptions(params);
|
|
3878
|
+
if (!usePaging) {
|
|
3879
|
+
const { result, executionTime } = await this.executeQueryWithTiming(rendered.FinalSQL, contextUser, undefined, options);
|
|
3880
|
+
const { paginatedResult, totalRowCount } = this.applyQueryPagination(result, params);
|
|
3881
|
+
return { rows: paginatedResult, totalRowCount, executionTime };
|
|
3882
|
+
}
|
|
3883
|
+
const start = Date.now();
|
|
3884
|
+
const [dataResult, total] = await Promise.all([
|
|
3885
|
+
this.ExecuteSQL(rendered.FinalSQL, undefined, options, contextUser),
|
|
3886
|
+
this.countAdhocRows(rendered.PagingResult?.CountSQL ?? null, options, contextUser),
|
|
3887
|
+
]);
|
|
3888
|
+
const rows = dataResult ?? [];
|
|
3889
|
+
return { rows, totalRowCount: total ?? startRow + rows.length, executionTime: Date.now() - start };
|
|
3890
|
+
}
|
|
3891
|
+
/**
|
|
3892
|
+
* The total row count for a page of ad-hoc SQL, or `null` when it cannot be had. A count that
|
|
3893
|
+
* fails does not fail the run: some queries page fine but cannot be counted (duplicate column
|
|
3894
|
+
* names are legal in a result but not inside the count's wrap), so the caller reports a lower
|
|
3895
|
+
* bound instead.
|
|
3896
|
+
*/
|
|
3897
|
+
async countAdhocRows(countSQL, options, contextUser) {
|
|
3898
|
+
if (!countSQL)
|
|
3899
|
+
return null;
|
|
3900
|
+
try {
|
|
3901
|
+
const countResult = await this.ExecuteSQL(countSQL, undefined, options, contextUser);
|
|
3902
|
+
const total = Number(countResult?.[0]?.TotalRowCount);
|
|
3903
|
+
return Number.isFinite(total) && total >= 0 ? Math.floor(total) : null;
|
|
3904
|
+
}
|
|
3905
|
+
catch (e) {
|
|
3906
|
+
LogError(`Ad-hoc query row count failed; reporting a lower-bound total. ${e instanceof Error ? e.message : String(e)}`);
|
|
3907
|
+
return null;
|
|
3908
|
+
}
|
|
3909
|
+
}
|
|
3910
|
+
/** The options every statement of an ad-hoc run uses: caller-SQL protections, plus its timeout. */
|
|
3911
|
+
adhocSQLOptions(params) {
|
|
3912
|
+
const seconds = params.TimeoutSeconds;
|
|
3913
|
+
return seconds && seconds > 0 ? { ...CALLER_SQL_OPTIONS, timeoutMs: seconds * 1000 } : CALLER_SQL_OPTIONS;
|
|
3914
|
+
}
|
|
3692
3915
|
/**
|
|
3693
3916
|
* Finds a query from RunQueryParams and validates user permissions.
|
|
3694
3917
|
* Uses `resolveQuery()` for lookup and `ValidateQueryForExecution()` for permissions.
|
|
@@ -3855,7 +4078,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3855
4078
|
const resolved = this.resolveSpecParameters(spec, contextUser);
|
|
3856
4079
|
finalSQL = resolved.finalSQL;
|
|
3857
4080
|
// Execute
|
|
3858
|
-
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser);
|
|
4081
|
+
const { result, executionTime } = await this.executeQueryWithTiming(finalSQL, contextUser, undefined, CALLER_SQL_OPTIONS);
|
|
3859
4082
|
return {
|
|
3860
4083
|
Success: true,
|
|
3861
4084
|
QueryID: '',
|
|
@@ -3905,6 +4128,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3905
4128
|
Dependencies: spec.Dependencies,
|
|
3906
4129
|
OriginalSQL: spec.SQL,
|
|
3907
4130
|
MaxRows: spec.MaxRows,
|
|
4131
|
+
RequireReadStatement: true,
|
|
3908
4132
|
});
|
|
3909
4133
|
if (!result.HasCompositions && !spec.UsesTemplate && spec.Parameters && Object.keys(spec.Parameters).length > 0) {
|
|
3910
4134
|
LogStatus('Warning: Parameters provided but query does not use templates. Parameters will be ignored.');
|
|
@@ -3930,9 +4154,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
3930
4154
|
/**
|
|
3931
4155
|
* Executes the query SQL and tracks execution time.
|
|
3932
4156
|
*/
|
|
3933
|
-
async executeQueryWithTiming(sql, contextUser, parameters) {
|
|
4157
|
+
async executeQueryWithTiming(sql, contextUser, parameters, options) {
|
|
3934
4158
|
const start = Date.now();
|
|
3935
|
-
const result = await this.ExecuteSQL(sql, parameters,
|
|
4159
|
+
const result = await this.ExecuteSQL(sql, parameters, options, contextUser);
|
|
3936
4160
|
const executionTime = Date.now() - start;
|
|
3937
4161
|
if (!result) {
|
|
3938
4162
|
throw new Error('Error executing query SQL');
|
|
@@ -4187,6 +4411,10 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4187
4411
|
/**
|
|
4188
4412
|
* Checks whether a new record's field values pass the Create RLS filter.
|
|
4189
4413
|
* Builds a synthetic single-row subquery from entity field values, then tests the RLS filter against it.
|
|
4414
|
+
* Null fields are projected as typed NULLs (see {@link BuildRLSSyntheticRowProjections}), so a
|
|
4415
|
+
* filter that references a column the new row leaves NULL evaluates instead of failing to bind.
|
|
4416
|
+
* The row is what the caller sends: a column the database fills on insert (a non-literal default
|
|
4417
|
+
* or a trigger) is seen as NULL here.
|
|
4190
4418
|
*/
|
|
4191
4419
|
async CheckCreateRLS(entity, user) {
|
|
4192
4420
|
const entityInfo = entity.EntityInfo;
|
|
@@ -4194,7 +4422,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4194
4422
|
if (!rlsWhereClause || rlsWhereClause.length === 0) {
|
|
4195
4423
|
return true;
|
|
4196
4424
|
}
|
|
4197
|
-
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo
|
|
4425
|
+
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
|
|
4198
4426
|
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
|
|
4199
4427
|
const result = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4200
4428
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
@@ -4227,7 +4455,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4227
4455
|
return true; // pre-image check already passed and no filter-referenced column changed
|
|
4228
4456
|
}
|
|
4229
4457
|
}
|
|
4230
|
-
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo
|
|
4458
|
+
const projections = this.BuildRLSSyntheticRowProjections(entity, entityInfo);
|
|
4231
4459
|
const sql = `SELECT CASE WHEN (${rlsWhereClause}) THEN 1 ELSE 0 END AS pass FROM (SELECT ${projections}) AS newrow`;
|
|
4232
4460
|
const result = await this.ExecuteSQL(sql, undefined, undefined, user);
|
|
4233
4461
|
return result && result.length > 0 && Number(result[0]['pass']) === 1;
|
|
@@ -4263,22 +4491,19 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4263
4491
|
* Builds field projections for an RLS synthetic-row subquery (Create post-image and
|
|
4264
4492
|
* Update post-image checks).
|
|
4265
4493
|
*
|
|
4266
|
-
*
|
|
4267
|
-
*
|
|
4268
|
-
*
|
|
4269
|
-
* differently from a real row, so nulls are emitted as
|
|
4270
|
-
* the field's metadata-resolved type. An unresolvable
|
|
4271
|
-
* rather than emitting an untyped NULL.
|
|
4272
|
-
|
|
4273
|
-
|
|
4274
|
-
BuildRLSSyntheticRowProjections(entity, entityInfo, includeNulls) {
|
|
4494
|
+
* Every non-virtual field is projected, null fields included: a filter referencing a
|
|
4495
|
+
* column the row leaves NULL must see SQL NULL, not a missing column (which fails to
|
|
4496
|
+
* bind with `Invalid column name` instead of evaluating). A bare `SELECT NULL AS Col` is
|
|
4497
|
+
* untyped and can evaluate differently from a real row, so nulls are emitted as
|
|
4498
|
+
* `CAST(NULL AS <sqltype>)` using the field's metadata-resolved type. An unresolvable
|
|
4499
|
+
* type fails the save (throw) rather than emitting an untyped NULL.
|
|
4500
|
+
*/
|
|
4501
|
+
BuildRLSSyntheticRowProjections(entity, entityInfo) {
|
|
4275
4502
|
const parts = [];
|
|
4276
4503
|
for (const field of entityInfo.Fields) {
|
|
4277
4504
|
if (field.IsVirtual)
|
|
4278
4505
|
continue;
|
|
4279
4506
|
const val = entity.Get(field.Name);
|
|
4280
|
-
if (val == null && !includeNulls)
|
|
4281
|
-
continue;
|
|
4282
4507
|
parts.push(`${this.renderRLSProjectionValue(field, val)} AS ${this.QuoteIdentifier(field.Name)}`);
|
|
4283
4508
|
}
|
|
4284
4509
|
return parts.join(', ');
|
|
@@ -4307,7 +4532,7 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4307
4532
|
// spot check and still emits `CAST(NULL AS nvarchar(50))` on the very next field.
|
|
4308
4533
|
const baseType = field.Type;
|
|
4309
4534
|
if (!baseType || baseType.trim().length === 0) {
|
|
4310
|
-
throw new Error(`Cannot build RLS
|
|
4535
|
+
throw new Error(`Cannot build RLS row projection: field ${field.Name} has no resolvable SQL type for a typed NULL`);
|
|
4311
4536
|
}
|
|
4312
4537
|
// `field.Length` is the SYSTEM (byte) length from `sys.columns`, but
|
|
4313
4538
|
// `MapDataTypeToString` takes a CHARACTER count — `RuntimeSchemaManager` calls it as
|
|
@@ -4352,12 +4577,56 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4352
4577
|
BuildParameterPlaceholder(index) {
|
|
4353
4578
|
return `$${index + 1}`;
|
|
4354
4579
|
}
|
|
4580
|
+
/**
|
|
4581
|
+
* Resolves how one dataset item reads for the caller. A caller's ItemFilter must pass the same
|
|
4582
|
+
* denylist as a RunView ExtraFilter. With a context user, the item's entity must be readable by
|
|
4583
|
+
* that user and the user's effective read row filter applies. MJ_Metadata is exempt from the
|
|
4584
|
+
* user checks: every authenticated client loads it to learn the schema, including principals
|
|
4585
|
+
* (widget guests, magic-link sessions) whose roles hold no read grant on the metadata entities.
|
|
4586
|
+
*/
|
|
4587
|
+
resolveDatasetItemScope(datasetName, item, itemFilters, contextUser) {
|
|
4588
|
+
const code = String(item['Code']);
|
|
4589
|
+
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
4590
|
+
const clientFilter = itemFilters?.find(f => f?.ItemCode === code)?.Filter ?? '';
|
|
4591
|
+
if (clientFilter && !this.ValidateUserProvidedSQLClause(clientFilter)) {
|
|
4592
|
+
return { Filter: '', RowFilter: '', Refusal: `Invalid ItemFilter for dataset item '${code}': contains one or more forbidden keywords` };
|
|
4593
|
+
}
|
|
4594
|
+
const filter = whereClause && clientFilter ? `${whereClause} AND (${clientFilter})` : (whereClause || clientFilter);
|
|
4595
|
+
if (!contextUser || datasetName === GenericDatabaseProvider._mjMetadataDatasetName) {
|
|
4596
|
+
return { Filter: filter, RowFilter: '', Refusal: null };
|
|
4597
|
+
}
|
|
4598
|
+
const entityName = String(item['Entity']);
|
|
4599
|
+
const entity = this.EntityByName(entityName);
|
|
4600
|
+
if (!entity) {
|
|
4601
|
+
return { Filter: filter, RowFilter: '', Refusal: `Entity '${entityName}' of dataset item '${code}' not found in metadata` };
|
|
4602
|
+
}
|
|
4603
|
+
if (!entity.GetUserPermisions(contextUser)?.CanRead) {
|
|
4604
|
+
return { Filter: filter, RowFilter: '', Refusal: `User ${contextUser.Email} does not have read permissions on ${entity.Name}` };
|
|
4605
|
+
}
|
|
4606
|
+
return { Filter: filter, RowFilter: entity.GetEffectiveRowFilterWhereClause(contextUser, EntityPermissionType.Read, ''), Refusal: null };
|
|
4607
|
+
}
|
|
4608
|
+
/**
|
|
4609
|
+
* The WHERE text for a dataset item: the caller's row filter AND'd with the item's filter. The
|
|
4610
|
+
* item's filter sits two parentheses deep because a client ItemFilter is screened inside one
|
|
4611
|
+
* level, so an OR it reaches by closing a parenthesis still cannot widen the row filter.
|
|
4612
|
+
*/
|
|
4613
|
+
datasetItemWhereClause(scope) {
|
|
4614
|
+
if (!scope.RowFilter)
|
|
4615
|
+
return scope.Filter;
|
|
4616
|
+
if (!scope.Filter)
|
|
4617
|
+
return scope.RowFilter;
|
|
4618
|
+
return `(${scope.RowFilter}) AND ((${scope.Filter}))`;
|
|
4619
|
+
}
|
|
4355
4620
|
/**
|
|
4356
4621
|
* Retrieves a dataset by name, executing all item queries via ExecuteSQLBatch
|
|
4357
4622
|
* and aggregating results. Uses dialect-neutral quoting for all SQL construction.
|
|
4358
4623
|
*
|
|
4359
4624
|
* ExecuteSQLBatch gives SQL Server true multi-result-set batching automatically,
|
|
4360
4625
|
* while PG (and the default) use parallel individual queries.
|
|
4626
|
+
*
|
|
4627
|
+
* An ItemFilter that fails the denylist refuses its item. With a context user, each item needs
|
|
4628
|
+
* CanRead on its entity and gets the user's read row filter (MJ_Metadata excepted). A refused
|
|
4629
|
+
* item runs no SQL and fails the dataset.
|
|
4361
4630
|
*/
|
|
4362
4631
|
async GetDatasetByName(datasetName, itemFilters, contextUser, providerToUse, forceRefresh) {
|
|
4363
4632
|
const provider = (providerToUse ?? this);
|
|
@@ -4403,7 +4672,6 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4403
4672
|
const code = String(item['Code']);
|
|
4404
4673
|
const entityName = String(item['Entity']);
|
|
4405
4674
|
const entityID = String(item['EntityID']);
|
|
4406
|
-
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
4407
4675
|
// External-data-source entities have no MJ base view — their data is proxied live and
|
|
4408
4676
|
// can't be served through the dataset's batched MJ-DB SQL path. Fail loud for that item
|
|
4409
4677
|
// rather than silently querying a non-existent (or wrongly same-named) local view.
|
|
@@ -4420,19 +4688,26 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4420
4688
|
});
|
|
4421
4689
|
continue;
|
|
4422
4690
|
}
|
|
4423
|
-
//
|
|
4424
|
-
|
|
4425
|
-
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
4430
|
-
|
|
4431
|
-
|
|
4691
|
+
// The item's filter and the caller's row filter, or why it is refused. A refused item
|
|
4692
|
+
// never reaches the cache or the database.
|
|
4693
|
+
const scope = provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser);
|
|
4694
|
+
if (scope.Refusal) {
|
|
4695
|
+
errorResults.push({
|
|
4696
|
+
EntityID: entityID,
|
|
4697
|
+
EntityName: entityName,
|
|
4698
|
+
Code: code,
|
|
4699
|
+
Results: [],
|
|
4700
|
+
LatestUpdateDate: undefined,
|
|
4701
|
+
Status: scope.Refusal,
|
|
4702
|
+
Success: false,
|
|
4703
|
+
});
|
|
4704
|
+
continue;
|
|
4432
4705
|
}
|
|
4706
|
+
// The row filter keys the slot, so one user's filtered rows are never served to another.
|
|
4707
|
+
const rowFilterKey = scope.RowFilter || undefined;
|
|
4433
4708
|
// Try cache first
|
|
4434
4709
|
if (cacheAvailable) {
|
|
4435
|
-
const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter:
|
|
4710
|
+
const fingerprint = cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code));
|
|
4436
4711
|
const cached = await cache.GetRunViewResult(fingerprint);
|
|
4437
4712
|
if (cached) {
|
|
4438
4713
|
cacheHitCount++;
|
|
@@ -4464,12 +4739,13 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4464
4739
|
});
|
|
4465
4740
|
continue;
|
|
4466
4741
|
}
|
|
4467
|
-
const
|
|
4742
|
+
const whereSQL = this.datasetItemWhereClause(scope);
|
|
4743
|
+
const filterSQL = whereSQL ? 'WHERE ' + whereSQL : '';
|
|
4468
4744
|
uncachedQueries.push(`SELECT ${columns} FROM ${provider.QuoteSchemaAndView(entitySchemaName, entityBaseView)} ${filterSQL}`);
|
|
4469
4745
|
uncachedItems.push(item);
|
|
4470
4746
|
// Store fingerprint for write-through caching after SQL
|
|
4471
4747
|
const fp = cacheAvailable
|
|
4472
|
-
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter:
|
|
4748
|
+
? cache.GenerateRunViewFingerprint({ EntityName: entityName, ExtraFilter: scope.Filter }, this.InstanceConnectionString, rowFilterKey, this.datasetCacheSegment(datasetName, code))
|
|
4473
4749
|
: '';
|
|
4474
4750
|
uncachedFingerprints.push(fp);
|
|
4475
4751
|
}
|
|
@@ -4569,6 +4845,9 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4569
4845
|
/**
|
|
4570
4846
|
* Retrieves status information for a dataset by name: per-entity row count and
|
|
4571
4847
|
* latest update date. Uses ExecuteSQLBatch for per-item status queries.
|
|
4848
|
+
*
|
|
4849
|
+
* Items read with the same scope as {@link GetDatasetByName}. When any item is refused, the
|
|
4850
|
+
* status fails with the refusal and no status SQL runs.
|
|
4572
4851
|
*/
|
|
4573
4852
|
async GetDatasetStatusByName(datasetName, itemFilters, contextUser, providerToUse) {
|
|
4574
4853
|
const overallStart = performance.now();
|
|
@@ -4606,33 +4885,35 @@ export class GenericDatabaseProvider extends DatabaseProviderBase {
|
|
|
4606
4885
|
// in GetDatasetByName.
|
|
4607
4886
|
const updateDates = [];
|
|
4608
4887
|
let overallLatestDate = new Date(1900, 1, 1);
|
|
4888
|
+
// Same scope as GetDatasetByName's data read — the stored item WhereClause, the caller's
|
|
4889
|
+
// ItemFilter and the caller's row filter — so status and data describe the same row set.
|
|
4890
|
+
// (Every shipped MJ_Metadata item has a NULL WhereClause and no row filter, so for
|
|
4891
|
+
// metadata this is an unfiltered aggregate.)
|
|
4892
|
+
const scopes = items.map(item => provider.resolveDatasetItemScope(datasetName, item, itemFilters, contextUser));
|
|
4893
|
+
const refusal = scopes.find(scope => scope.Refusal)?.Refusal;
|
|
4894
|
+
if (refusal) {
|
|
4895
|
+
return {
|
|
4896
|
+
DatasetID: String(items[0]['DatasetID']),
|
|
4897
|
+
DatasetName: datasetName,
|
|
4898
|
+
Success: false,
|
|
4899
|
+
Status: refusal,
|
|
4900
|
+
LatestUpdateDate: new Date(0),
|
|
4901
|
+
EntityUpdateDates: [],
|
|
4902
|
+
};
|
|
4903
|
+
}
|
|
4609
4904
|
const itemMeta = [];
|
|
4610
|
-
const queries = items.map((item) => {
|
|
4905
|
+
const queries = items.map((item, index) => {
|
|
4611
4906
|
const entitySchemaName = String(item['EntitySchemaName'] ?? schema);
|
|
4612
4907
|
const entityBaseView = String(item['EntityBaseView']);
|
|
4613
|
-
const code = String(item['Code']);
|
|
4614
4908
|
const dateFieldToCheck = String(item['DateFieldToCheck'] ?? '__mj_UpdatedAt');
|
|
4615
|
-
const whereClause = item['WhereClause'] ? String(item['WhereClause']) : '';
|
|
4616
4909
|
itemMeta.push({ entityID: String(item['EntityID']), entityName: String(item['Entity']) });
|
|
4617
4910
|
// The floor for the reported timestamp: an edit to the dataset DEFINITION itself
|
|
4618
4911
|
// (item added, filter changed) must read as a change even when no entity row moved.
|
|
4619
4912
|
const itemUpdatedAt = new Date(String(item['DatasetItemUpdatedAt']));
|
|
4620
4913
|
const datasetUpdatedAt = new Date(String(item['DatasetUpdatedAt']));
|
|
4621
4914
|
const datasetMaxUpdatedAt = new Date(Math.max(itemUpdatedAt.getTime(), datasetUpdatedAt.getTime())).toISOString();
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
// row set. (Every shipped MJ_Metadata item has a NULL WhereClause, so for metadata
|
|
4625
|
-
// this is identical to an unfiltered aggregate.)
|
|
4626
|
-
let effectiveFilter = whereClause;
|
|
4627
|
-
if (itemFilters && itemFilters.length > 0) {
|
|
4628
|
-
const filter = itemFilters.find(f => f.ItemCode === code);
|
|
4629
|
-
if (filter) {
|
|
4630
|
-
effectiveFilter = whereClause
|
|
4631
|
-
? `${whereClause} AND (${filter.Filter})`
|
|
4632
|
-
: filter.Filter;
|
|
4633
|
-
}
|
|
4634
|
-
}
|
|
4635
|
-
const filterSQL = effectiveFilter ? ' WHERE ' + effectiveFilter : '';
|
|
4915
|
+
const whereSQL = this.datasetItemWhereClause(scopes[index]);
|
|
4916
|
+
const filterSQL = whereSQL ? ' WHERE ' + whereSQL : '';
|
|
4636
4917
|
return `SELECT ` +
|
|
4637
4918
|
`CASE ` +
|
|
4638
4919
|
`WHEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) > '${datasetMaxUpdatedAt}' THEN MAX(${provider.QuoteIdentifier(dateFieldToCheck)}) ` +
|