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

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.
Files changed (88) hide show
  1. package/README.md +150 -0
  2. package/dist/GenericDatabaseProvider.d.ts +329 -41
  3. package/dist/GenericDatabaseProvider.d.ts.map +1 -1
  4. package/dist/GenericDatabaseProvider.js +864 -238
  5. package/dist/GenericDatabaseProvider.js.map +1 -1
  6. package/dist/clientClauseScreen.d.ts +16 -72
  7. package/dist/clientClauseScreen.d.ts.map +1 -1
  8. package/dist/clientClauseScreen.js +34 -278
  9. package/dist/clientClauseScreen.js.map +1 -1
  10. package/dist/composition/compositionAssembler.d.ts +33 -0
  11. package/dist/composition/compositionAssembler.d.ts.map +1 -0
  12. package/dist/composition/compositionAssembler.js +270 -0
  13. package/dist/composition/compositionAssembler.js.map +1 -0
  14. package/dist/composition/compositionInfo.d.ts +7 -0
  15. package/dist/composition/compositionInfo.d.ts.map +1 -0
  16. package/dist/composition/compositionInfo.js +31 -0
  17. package/dist/composition/compositionInfo.js.map +1 -0
  18. package/dist/composition/compositionLookup.d.ts +44 -0
  19. package/dist/composition/compositionLookup.d.ts.map +1 -0
  20. package/dist/composition/compositionLookup.js +122 -0
  21. package/dist/composition/compositionLookup.js.map +1 -0
  22. package/dist/composition/compositionRender.d.ts +136 -0
  23. package/dist/composition/compositionRender.d.ts.map +1 -0
  24. package/dist/composition/compositionRender.js +264 -0
  25. package/dist/composition/compositionRender.js.map +1 -0
  26. package/dist/composition/compositionTypes.d.ts +40 -0
  27. package/dist/composition/compositionTypes.d.ts.map +1 -0
  28. package/dist/composition/compositionTypes.js +2 -0
  29. package/dist/composition/compositionTypes.js.map +1 -0
  30. package/dist/composition/quotedTagRefusal.d.ts +44 -0
  31. package/dist/composition/quotedTagRefusal.d.ts.map +1 -0
  32. package/dist/composition/quotedTagRefusal.js +132 -0
  33. package/dist/composition/quotedTagRefusal.js.map +1 -0
  34. package/dist/composition/renderSteps.d.ts +16 -0
  35. package/dist/composition/renderSteps.d.ts.map +1 -0
  36. package/dist/composition/renderSteps.js +42 -0
  37. package/dist/composition/renderSteps.js.map +1 -0
  38. package/dist/composition/safetyGate.d.ts +46 -0
  39. package/dist/composition/safetyGate.d.ts.map +1 -0
  40. package/dist/composition/safetyGate.js +61 -0
  41. package/dist/composition/safetyGate.js.map +1 -0
  42. package/dist/composition/templateUnit.d.ts +95 -0
  43. package/dist/composition/templateUnit.d.ts.map +1 -0
  44. package/dist/composition/templateUnit.js +189 -0
  45. package/dist/composition/templateUnit.js.map +1 -0
  46. package/dist/describeStatement.d.ts +51 -0
  47. package/dist/describeStatement.d.ts.map +1 -0
  48. package/dist/describeStatement.js +19 -0
  49. package/dist/describeStatement.js.map +1 -0
  50. package/dist/fieldSecurity/projectionStars.d.ts +15 -0
  51. package/dist/fieldSecurity/projectionStars.d.ts.map +1 -0
  52. package/dist/fieldSecurity/projectionStars.js +116 -0
  53. package/dist/fieldSecurity/projectionStars.js.map +1 -0
  54. package/dist/fieldSecurity/queryColumnSecurity.d.ts +35 -0
  55. package/dist/fieldSecurity/queryColumnSecurity.d.ts.map +1 -0
  56. package/dist/fieldSecurity/queryColumnSecurity.js +84 -0
  57. package/dist/fieldSecurity/queryColumnSecurity.js.map +1 -0
  58. package/dist/index.d.ts +10 -2
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +6 -1
  61. package/dist/index.js.map +1 -1
  62. package/dist/pagingLayout.d.ts +68 -0
  63. package/dist/pagingLayout.d.ts.map +1 -0
  64. package/dist/pagingLayout.js +190 -0
  65. package/dist/pagingLayout.js.map +1 -0
  66. package/dist/queryCompositionEngine.d.ts +22 -222
  67. package/dist/queryCompositionEngine.d.ts.map +1 -1
  68. package/dist/queryCompositionEngine.js +35 -729
  69. package/dist/queryCompositionEngine.js.map +1 -1
  70. package/dist/queryPagingEngine.d.ts +26 -5
  71. package/dist/queryPagingEngine.d.ts.map +1 -1
  72. package/dist/queryPagingEngine.js +51 -15
  73. package/dist/queryPagingEngine.js.map +1 -1
  74. package/dist/renderPipeline.d.ts +77 -85
  75. package/dist/renderPipeline.d.ts.map +1 -1
  76. package/dist/renderPipeline.js +70 -220
  77. package/dist/renderPipeline.js.map +1 -1
  78. package/dist/statementMemo.d.ts +29 -0
  79. package/dist/statementMemo.d.ts.map +1 -0
  80. package/dist/statementMemo.js +61 -0
  81. package/dist/statementMemo.js.map +1 -0
  82. package/dist/typedQueryParameter.d.ts +55 -0
  83. package/dist/typedQueryParameter.d.ts.map +1 -0
  84. package/dist/typedQueryParameter.js +122 -0
  85. package/dist/typedQueryParameter.js.map +1 -0
  86. package/dist/types.d.ts +11 -0
  87. package/dist/types.d.ts.map +1 -1
  88. package/package.json +14 -14
@@ -15,10 +15,11 @@
15
15
  *
16
16
  * @module @memberjunction/generic-database-provider
17
17
  */
18
- import { BaseEntity, DatabaseProviderBase, EntityInfo, EntityFieldInfo, EntitySaveOptions, EntityDeleteOptions, EntityPermissionType, ExecuteSQLOptions, ILocalStorageProvider, RunViewParams, RunViewResult, RunViewWithCacheCheckParams, RunViewDatabaseStatus, RunViewsWithCacheCheckResponse, RunViewWithCacheCheckResult, RunQueryParams, RunQueryResult, RunQueryWithCacheCheckParams, RunQueriesWithCacheCheckResponse, RunQueryWithCacheCheckResult, QueryCacheAuthorization, QueryDefinitionSignature, AggregateResult, CompositeKey, DatasetItemFilterType, DatasetResultType, DatasetStatusResultType, IMetadataProvider, ProviderConfigDataBase, UserInfo, PostCommitTask, PostCommitToken, QueryExecutionSpec, SaveContext, SaveSQLResult, ExternalDataSourceReadRouter, UserViewProperty, ViewPropertyValues } from '@memberjunction/core';
19
- import { SqlLoggingOptions, SqlLoggingSession } from './types.js';
18
+ import { BaseEntity, DatabaseProviderBase, EntityInfo, EntityFieldInfo, EntitySaveOptions, EntityDeleteOptions, EntityPermissionType, ExecuteSQLOptions, ILocalStorageProvider, RunViewParams, RunViewResult, RunViewWithCacheCheckParams, RunViewDatabaseStatus, RunViewsWithCacheCheckResponse, RunViewWithCacheCheckResult, RunQueryParams, RunQueryResult, RunQueryWithCacheCheckParams, RunQueriesWithCacheCheckResponse, RunQueryWithCacheCheckResult, QueryCacheAuthorization, QueryDefinitionSignature, AggregateResult, CompositeKey, DatasetItemFilterType, DatasetResultType, DatasetStatusResultType, IMetadataProvider, ProviderConfigDataBase, UserInfo, DiagnosticContext, PostCommitTask, PostCommitToken, QueryExecutionSpec, SaveContext, SaveSQLResult, ExternalDataSourceReadRouter, UserViewProperty, ViewPropertyValues } from '@memberjunction/core';
19
+ import { DatabasePoolStats, SqlLoggingOptions, SqlLoggingSession } from './types.js';
20
20
  import { SQLDialect } from '@memberjunction/sql-dialect';
21
21
  import { type BalancedFragmentOptions } from '@memberjunction/sql-parser';
22
+ import { type DescribeStatementResult } from './describeStatement.js';
22
23
  import { type RenderResult } from './renderPipeline.js';
23
24
  import { CRUDSprocType } from './crudSprocFieldRules.js';
24
25
  import { SaveCoercedValue, SaveCallBinding, SaveSQLFragment, SaveReturnContext } from './saveTypes.js';
@@ -63,7 +64,88 @@ export declare class DoomedTransactionError extends Error {
63
64
  cause?: unknown;
64
65
  });
65
66
  }
67
+ /**
68
+ * Summary of a bound SQL parameter (name, runtime type, byte length, and value only when safe).
69
+ * Mutation parameters omit values by default so customer field writes are not captured.
70
+ */
71
+ export interface SqlParameterSummary {
72
+ name: string;
73
+ type: string;
74
+ byteLength?: number;
75
+ value?: string | number | boolean | null;
76
+ }
77
+ /**
78
+ * Structured observation emitted for each executed SQL statement or batch.
79
+ */
80
+ export interface SqlObservation {
81
+ ts: number;
82
+ durationMs: number;
83
+ sql: string;
84
+ description?: string;
85
+ isMutation: boolean;
86
+ rowCount?: number;
87
+ parameterSummaries?: SqlParameterSummary[];
88
+ parameterTypes?: Array<{
89
+ name: string;
90
+ sqlType: string;
91
+ byteLength: number;
92
+ }>;
93
+ error?: {
94
+ name: string;
95
+ message: string;
96
+ code?: string;
97
+ };
98
+ errorMessage?: string;
99
+ diagnosticContext?: DiagnosticContext;
100
+ sessionId?: string;
101
+ traceId?: string;
102
+ spanId?: string;
103
+ ignoreLogging?: boolean;
104
+ }
105
+ /**
106
+ * Observer callback for SQL statement executions across SQL Server and PostgreSQL providers.
107
+ */
108
+ export interface ISqlObserver {
109
+ onSqlExecuted(observation: SqlObservation): void;
110
+ }
111
+ /**
112
+ * Builds a safe parameter summary list for SQL error messages and diagnostic observations.
113
+ * When `includeReadValues` is false (e.g., mutations or error strings), only parameter names,
114
+ * types, and byte lengths are included — never raw parameter values.
115
+ */
116
+ export declare function SummarizeSqlParameters(parameters: unknown, includeReadValues?: boolean): SqlParameterSummary[];
117
+ /**
118
+ * Formats parameter summaries into a compact `name:type(bytes)` string for safe error messages.
119
+ */
120
+ export declare function FormatSqlParameterTypesForError(parameters: unknown): string;
66
121
  export declare abstract class GenericDatabaseProvider extends DatabaseProviderBase implements ClientClauseScreeningProvider {
122
+ private static readonly _sqlObserversGlobalKey;
123
+ private static readonly _fallbackSqlObservers;
124
+ private static get _sqlObservers();
125
+ /**
126
+ * Registers a global SQL observer that receives timing and metadata for all SQL executions
127
+ * across provider instances (including per-request providers and pool shims).
128
+ * Returns an unsubscribe function.
129
+ */
130
+ static RegisterSqlObserver(observer: ISqlObserver | ((observation: SqlObservation) => void)): () => void;
131
+ /**
132
+ * Returns the live connection pool counts, or `null` when this provider has no pool to measure.
133
+ * Providers that own a pool override this.
134
+ */
135
+ GetPoolStats(): DatabasePoolStats | null;
136
+ /**
137
+ * Instance convenience alias for {@link GenericDatabaseProvider.RegisterSqlObserver}.
138
+ */
139
+ RegisterSqlObserver(observer: ISqlObserver | ((observation: SqlObservation) => void)): () => void;
140
+ /**
141
+ * Returns true when at least one SQL observer is registered and capture is not suppressed.
142
+ */
143
+ static HasSqlObservers(): boolean;
144
+ /**
145
+ * Dispatches a SQL execution observation to all registered observers unless `ignoreLogging`
146
+ * or `WithoutDiagnosticCapture` is active. Automatically enriches with ambient `DiagnosticContext`.
147
+ */
148
+ static NotifySqlObservers(observation: SqlObservation): void;
67
149
  /**************************************************************************/
68
150
  /**************************************************************************/
69
151
  /**
@@ -144,6 +226,8 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
144
226
  * cached dataset item slots against live SQL row counts and timestamps.
145
227
  */
146
228
  private _lastDatasetStatusByName;
229
+ protected invalidateInflightViewsForEntity(lowerEntityName: string): void;
230
+ ClearDatasetCache(datasetName: string, itemFilters?: DatasetItemFilterType[]): Promise<void>;
147
231
  /**************************************************************************/
148
232
  /**************************************************************************/
149
233
  private static _sqlLoggingSessionsKey;
@@ -257,7 +341,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
257
341
  * `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
258
342
  * save succeeds is not a durability improvement, it is a different feature.
259
343
  */
260
- protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[]): Promise<ActionResult[]>;
344
+ protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[], runModeFilter?: 'DurableOnly' | 'NonDurableOnly'): Promise<ActionResult[]>;
261
345
  /**
262
346
  * Handles Entity AI Actions for save or delete operations.
263
347
  *
@@ -281,7 +365,9 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
281
365
  /**************************************************************************/
282
366
  protected OnValidateBeforeSave(entity: BaseEntity, user: UserInfo): Promise<string | null>;
283
367
  protected OnBeforeSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
284
- protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, _context: SaveContext): void;
368
+ protected ShouldEnlistSaveInTransaction(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, isNewRecord: boolean): Promise<boolean>;
369
+ protected OnDurableAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
370
+ protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): void;
285
371
  protected OnSaveCompleted(entity: BaseEntity, saveSQLResult: SaveSQLResult, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<Record<string, unknown> | null>;
286
372
  protected OnBeforeDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): Promise<void>;
287
373
  protected OnAfterDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): void;
@@ -291,6 +377,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
291
377
  private cleanupGeoCodesForDeletedRecord;
292
378
  /**************************************************************************/
293
379
  /**************************************************************************/
380
+ /**
381
+ * Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
382
+ * preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
383
+ * Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
384
+ */
385
+ private static readonly _preDecryptionRowsByResult;
294
386
  /**
295
387
  * Post-processes rows: first applies platform-specific datetime adjustments
296
388
  * via the virtual `AdjustDatetimeFields` hook, then handles field-level
@@ -299,7 +391,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
299
391
  * Subclasses should NOT override this method. Instead, override
300
392
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
301
393
  */
302
- protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo): Promise<Record<string, unknown>[]>;
394
+ protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo, options?: {
395
+ preserveRestrictedApiCiphertext?: boolean;
396
+ }): Promise<Record<string, unknown>[]>;
397
+ /**
398
+ * Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
399
+ * When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
400
+ * remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
401
+ * needlessly decrypt values destined for sentinel redaction.
402
+ */
403
+ private decryptRowsForConsumer;
404
+ protected PrepareRowsForCacheStorage(rows: unknown[], entityInfo?: EntityInfo): unknown[];
405
+ protected MaterializeCachedRowsForCaller(rows: Record<string, unknown>[], entityInfo?: EntityInfo, contextUser?: UserInfo, preserveRestrictedApiCiphertext?: boolean): Promise<Record<string, unknown>[]>;
303
406
  private static _encryptedFieldsCache;
304
407
  private static getEncryptedFields;
305
408
  /**
@@ -1245,6 +1348,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1245
1348
  * them: the entity resolved here is named explicitly.
1246
1349
  */
1247
1350
  protected projectExternalRowsForCaller<T>(rows: T[], entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): T[];
1351
+ /**
1352
+ * Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
1353
+ * narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
1354
+ * caller's width instead of finding no copy and falling back to the decrypted rows.
1355
+ */
1356
+ private carryCiphertextRowsForCache;
1248
1357
  /**
1249
1358
  * Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
1250
1359
  * external dispatch. The external branch returns before the normal SQL path that applies
@@ -1264,7 +1373,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1264
1373
  private cacheStatusFieldSecurityDiffers;
1265
1374
  /**
1266
1375
  * Checks the server's LocalCacheManager for cached data matching the client's request.
1267
- * Returns the resolution if found ('current', 'stale' server-cached data to serve, or
1376
+ * Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
1268
1377
  * 'needs_verification' when the server slot's freshness window has elapsed),
1269
1378
  * or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
1270
1379
  */
@@ -1276,20 +1385,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1276
1385
  /**
1277
1386
  * Runs a differential query and returns only changes since the client's cached state.
1278
1387
  * Includes updated/created rows and deleted record IDs.
1279
- * Falls back to full query if hidden deletes are detected.
1388
+ * Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
1280
1389
  */
1281
1390
  protected runDifferentialQueryAndReturn<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, clientMaxUpdatedAt: string, clientRowCount: number, serverStatus: {
1282
1391
  maxUpdatedAt?: string;
1283
1392
  rowCount?: number;
1284
1393
  }, whereSQL: string, viewIndex: number, contextUser?: UserInfo, callerFields?: string[] | null): Promise<RunViewWithCacheCheckResult<T>>;
1394
+ /**
1395
+ * Formats a client timestamp as ISO 8601 for a SQL literal.
1396
+ * Throws when the value is not a date.
1397
+ */
1398
+ private toSQLTimestamp;
1285
1399
  /**
1286
1400
  * Gets IDs of records deleted since a given timestamp.
1287
- * Uses dialect-neutral quoting. Subclasses can override for parameterized queries.
1401
+ * Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
1402
+ * Subclasses can override for parameterized queries.
1288
1403
  */
1289
1404
  protected getDeletedRecordIDsSince(entityID: string, sinceTimestamp: string, contextUser?: UserInfo): Promise<string[]>;
1290
1405
  /**
1291
1406
  * Gets rows updated/created since a given timestamp.
1292
- * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy.
1407
+ * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
1408
+ * timestamp in ISO 8601 form as its own predicate group.
1293
1409
  */
1294
1410
  protected getUpdatedRowsSince<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, sinceTimestamp: string, whereSQL: string, contextUser?: UserInfo): Promise<T[]>;
1295
1411
  /**************************************************************************/
@@ -1355,9 +1471,11 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1355
1471
  *
1356
1472
  * @param query - The resolved MJQueryEntityExtended to validate
1357
1473
  * @param contextUser - The user attempting to execute the query
1474
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1475
+ * refusal echoes it and nothing else. The query's ID when omitted.
1358
1476
  * @throws Error if the user does not have permission to run the query
1359
1477
  */
1360
- protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo): void;
1478
+ protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo, requestedLabel?: string): void;
1361
1479
  /**
1362
1480
  * For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
1363
1481
  * current approval — status Approved and a stored fingerprint equal to the fingerprint of the
@@ -1375,15 +1493,71 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1375
1493
  * and field-level security on every column it references. A template that injects an
1376
1494
  * identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
1377
1495
  * render. A query carrying `MJ: Query Permissions` rows is authorized by its role list alone.
1378
- * The refusal does not say which field or clause caused it.
1379
1496
  *
1497
+ * A refusal reads exactly like the message for a query that does not exist
1498
+ * ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
1499
+ *
1500
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1501
+ * refusal echoes it and nothing else. The query's ID when omitted.
1502
+ * @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
1503
+ * `alias.*` that reaches only the output reads an entity the user is denied a field on.
1380
1504
  * @throws Error when the user may not run this rendering of the query
1381
1505
  */
1382
- protected ValidateRenderedQueryForExecution(query: MJQueryEntityExtended, renderedSQL: string, contextUser?: UserInfo): void;
1383
- /** The refusal for a user who may not run `query`; names entities the user cannot read, never a field. */
1506
+ protected ValidateRenderedQueryForExecution(query: MJQueryEntityExtended, renderedSQL: string, contextUser?: UserInfo, requestedLabel?: string): {
1507
+ NeedsColumnFiltering: boolean;
1508
+ };
1509
+ /**
1510
+ * The message for a saved query that does not exist or that the caller may not run. The two
1511
+ * are worded identically, so a refusal does not confirm that the query, or anything it reads,
1512
+ * exists.
1513
+ *
1514
+ * It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
1515
+ * looked up from the resolved query: a refusal of a request by ID that named the query would
1516
+ * both differ from that request's not-found message and disclose the query's name.
1517
+ *
1518
+ * @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
1519
+ */
1520
+ static QueryUnavailableMessage(label: string): string;
1521
+ /**
1522
+ * The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
1523
+ * name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
1524
+ */
1525
+ static RequestedQueryLabel(params: Pick<RunQueryParams, 'QueryID' | 'QueryName' | 'CategoryPath'>): string;
1526
+ /** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
1384
1527
  private queryRunRefusalMessage;
1385
- /** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
1528
+ /**
1529
+ * The OPERATOR's record of why a run was refused. The refusal returned to the caller is
1530
+ * {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
1531
+ * that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
1532
+ *
1533
+ * Without it a refusal is unattributable: the query's own role list, SQL the field-security
1534
+ * gate could not read, and a field-security violation all end in the same caller message.
1535
+ *
1536
+ * Previously only the field-security case logged anything, and only at `verboseOnly`, which
1537
+ * CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
1538
+ * bundles refusing together) could not be diagnosed from the logs at all. Called from every
1539
+ * refusal gate, so no path is silent.
1540
+ *
1541
+ * The loaded-role count is here because an empty or undefined `UserRoles` denies every
1542
+ * permission-bearing query at once — exactly the all-or-nothing signature those runs show.
1543
+ * Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
1544
+ * to ask and it costs one integer.
1545
+ */
1546
+ private logQueryRunRefusal;
1547
+ /**
1548
+ * The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
1549
+ * refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
1550
+ * projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
1551
+ * its denied columns dropped instead of being refused.
1552
+ */
1386
1553
  private checkRenderedQuery;
1554
+ /** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
1555
+ private static readonly projectionStarMemo;
1556
+ /**
1557
+ * The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
1558
+ * denied a field on some entity and only when the text holds a `*`; undefined otherwise.
1559
+ */
1560
+ private projectionStarOffsets;
1387
1561
  /**
1388
1562
  * The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
1389
1563
  * and the run-time checks on the query rendered with `parameters`. A rendering that fails
@@ -1454,32 +1628,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1454
1628
  * {@link buildMaterializedReadQuery}).
1455
1629
  */
1456
1630
  private static readonly MATERIALIZED_SURROGATE_ORDER_COLUMN;
1457
- /** Quotes a SQL identifier for the target engine (SQL Server `[x]`, PostgreSQL `"x"`), escaping the closer. */
1458
- private static quoteMaterializedIdentifier;
1459
1631
  /**
1460
1632
  * PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
1461
1633
  * output columns, the materialized view (schema + name), the persisted read-filter spec, the caller's
1462
- * parameter values, and the platform, returns `{ sql, parameters }` whose WHERE injects each spec
1463
- * predicate as `column <op> <placeholder>` with the value **bound** (SQL Server `?`, PostgreSQL `$n`) —
1464
- * never interpolating a caller value (SQL-injection-safe by construction).
1634
+ * parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
1635
+ * predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
1636
+ * value (SQL-injection-safe by construction).
1637
+ *
1638
+ * With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
1639
+ * a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
1640
+ * placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
1641
+ * varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
1642
+ * Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
1643
+ * ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
1644
+ * dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
1465
1645
  *
1466
1646
  * Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
1467
1647
  * the caller falls back to running live (always correct): an operator outside the safe set, a spec
1468
1648
  * parameter the caller did not supply (the live query would apply the param's default), a null value,
1469
- * or an empty/non-array value for a list (`IN`/`NOT IN`) predicate. No IO — fully unit-testable.
1470
- */
1471
- /**
1472
- * True if `sql`'s top-level SELECT carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
1473
- * {@link buildMaterializedReadQuery} emits no ORDER BY and the snapshot is built with the source's top-level
1474
- * ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and therefore its
1475
- * pagination under StartRow/MaxRows — is preserved) rather than from the unordered snapshot. Parse failure or
1476
- * an un-reasoned statement shape returns `true` (refuse-to-live: treat unknown as ordered rather than risk
1477
- * serving mis-ordered pages). Mirrors MaterializationRefresher.stripTopLevelOrderBy's AST detection.
1478
- *
1479
- * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
1480
- * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
1649
+ * an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
1650
+ * known type or a value its type cannot hold. No IO — fully unit-testable.
1481
1651
  */
1482
- static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1483
1652
  static buildMaterializedReadQuery(opts: {
1484
1653
  outputColumns: string[];
1485
1654
  schemaName: string;
@@ -1494,11 +1663,32 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1494
1663
  /** Declared parameter type per paramName (from MJ: Query Parameters). Drives type-faithful binding so a
1495
1664
  * scalar value matches the live path's typed literal instead of a raw string the DB implicitly coerces. */
1496
1665
  paramTypes?: Record<string, string>;
1497
- isPostgres: boolean;
1666
+ /** The dialect the read runs in: identifier quoting and parameter references. */
1667
+ dialect?: SQLDialect;
1668
+ /** @deprecated Pass {@link dialect}. True for PostgreSQL when no dialect is given. */
1669
+ isPostgres?: boolean;
1670
+ /** The snapshot's column types, column name → SQL type (`varchar(50)`, `datetime2(7)`). Names match ignoring case. */
1671
+ columnTypes?: Record<string, string>;
1498
1672
  }): {
1499
1673
  sql: string;
1500
1674
  parameters: unknown[];
1501
1675
  } | null;
1676
+ /**
1677
+ * The parameter list one materialized read builds, and how a value joins it: typed by the filtered
1678
+ * column when the snapshot's column types are known, otherwise untyped (the deprecated form).
1679
+ */
1680
+ private static materializedBinder;
1681
+ /**
1682
+ * Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
1683
+ * it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
1684
+ * provider from rewriting `?` in the statement text, which the legacy positional array form does
1685
+ * everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
1686
+ */
1687
+ private static bindNamedParameter;
1688
+ /** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
1689
+ private static namedParameterValue;
1690
+ /** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
1691
+ private static materializedPredicate;
1502
1692
  /**
1503
1693
  * Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
1504
1694
  * (see {@link buildMaterializedReadQuery}). This mirrors the TYPE-CONVERSION SWITCH of the live path's
@@ -1513,25 +1703,88 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1513
1703
  * the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
1514
1704
  * - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
1515
1705
  * - `boolean` → live truthiness: ONLY 'true' (case-insensitive) or a real boolean `true` is true; everything
1516
- * else is false (live never refuses a boolean). SQL Server binds BIT 1/0; PostgreSQL binds bool.
1706
+ * else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
1517
1707
  * - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
1518
1708
  * the naive input string: live applies the local→UTC shift, so binding the raw string would
1519
- * diverge for any timed value. Invalid date → refuse.
1709
+ * diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
1710
+ * suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
1711
+ * (error 241); the zone-less string is the same UTC wall-clock.
1520
1712
  * - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
1713
+ *
1714
+ * @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
1521
1715
  */
1522
1716
  private static coerceMaterializedScalarValue;
1717
+ /**
1718
+ * The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
1719
+ * describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
1720
+ * the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
1721
+ * be described (→ live).
1722
+ */
1723
+ private materializedColumnTypes;
1724
+ /** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
1725
+ private static readonly materializedColumnTypeMemo;
1726
+ /** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
1727
+ private static readonly topLevelOrderByMemo;
1728
+ /**
1729
+ * True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
1730
+ * {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
1731
+ * source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
1732
+ * therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
1733
+ * `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
1734
+ * (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
1735
+ * (SQL, dialect) in a bounded memo.
1736
+ *
1737
+ * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
1738
+ * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
1739
+ */
1740
+ static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1523
1741
  /**
1524
1742
  * Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
1525
1743
  * `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
1526
1744
  * persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
1527
1745
  * the live query (serving live is always correct — this is a transparent optimization, never a
1528
1746
  * correctness dependency).
1747
+ *
1748
+ * @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
1749
+ * check reads it; without it the check reads the platform SQL, where template syntax makes any
1750
+ * template query read as ordered (→ live).
1529
1751
  */
1530
- protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>): Promise<{
1752
+ protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>, renderedSQL?: string): Promise<{
1531
1753
  sql: string;
1532
1754
  parameters: unknown[];
1533
1755
  } | null>;
1534
1756
  protected InternalRunQuery(params: RunQueryParams, contextUser?: UserInfo): Promise<RunQueryResult>;
1757
+ /** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
1758
+ private static readonly describedStatementMemo;
1759
+ /**
1760
+ * Describes the result set of `sql` without returning its rows: each output column's name,
1761
+ * position, exact type, nullability and, for a pass-through column, the table or view column it
1762
+ * comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
1763
+ * runs it under `LIMIT 0` in a transaction that is rolled back).
1764
+ *
1765
+ * This base implementation describes nothing: it reports a failure. Providers for a database
1766
+ * that can describe a statement override it.
1767
+ *
1768
+ * @param sql - The rendered statement, in this provider's dialect.
1769
+ * @param _contextUser - The user the description is for.
1770
+ */
1771
+ DescribeStatement(sql: string, _contextUser?: UserInfo): Promise<DescribeStatementResult>;
1772
+ /**
1773
+ * SECURITY — the output columns of `renderedSQL` that `user` must not receive
1774
+ * ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
1775
+ *
1776
+ * @throws Error with the refusal message when the statement cannot be described: without the
1777
+ * description no column can be shown to be safe, so the run is refused.
1778
+ */
1779
+ private queryColumnFilter;
1780
+ /** The catalog entities `query`'s `QueryEntities` rows name. */
1781
+ private declaredQueryEntities;
1782
+ /**
1783
+ * `rows` with the filter's withheld columns dropped, as new row objects. A column the
1784
+ * description does not list is dropped too, and the description is forgotten: the statement's
1785
+ * shape changed since it was described (a view redefined), so the next run describes it again.
1786
+ */
1787
+ private filterQueryRows;
1535
1788
  /**
1536
1789
  * Batch query execution — runs all queries in parallel.
1537
1790
  */
@@ -1588,12 +1841,22 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1588
1841
  *
1589
1842
  * Delegates to {@link RenderPipeline.Run} for the composition → template
1590
1843
  * pipeline. Paging is handled separately by the caller (InternalRunQuery).
1844
+ *
1845
+ * @param dialectKey - The dialect the template's values render for (`sqlString` literals,
1846
+ * booleans); this provider's platform when omitted. An external data source's query passes
1847
+ * the source's dialect.
1591
1848
  */
1592
- protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>): {
1849
+ protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>, dialectKey?: string): {
1593
1850
  finalSQL: string;
1594
1851
  appliedParameters: Record<string, string>;
1595
1852
  renderResult: RenderResult;
1596
1853
  };
1854
+ /**
1855
+ * The dialect key of the external data source `query` reads, so its template values render as
1856
+ * that database reads literals; undefined when the source has no SQL dialect (a document
1857
+ * store), in which case the query renders with this provider's platform as before.
1858
+ */
1859
+ private externalQueryDialectKey;
1597
1860
  /**
1598
1861
  * Checks the columns an external-data-source query returned against the fields the Query
1599
1862
  * *declares* (its QueryField metadata) and logs a warning naming any declared field that
@@ -1644,17 +1907,36 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1644
1907
  * pipeline. Supports inline dependencies for transient query testing.
1645
1908
  */
1646
1909
  private resolveSpecParameters;
1910
+ /**
1911
+ * Where a server-side result cache keeps this run's rows: one slot per rendered statement and
1912
+ * dialect, and, when the caller is denied a field the statement's projection star reads, per
1913
+ * field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
1914
+ * runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
1915
+ * The rendered statement carries every parameter value, server-set ones included, so they need
1916
+ * no separate part of the key.
1917
+ */
1918
+ private queryResultCacheSlot;
1647
1919
  /**
1648
1920
  * Checks the query cache for existing results and returns them if valid.
1649
1921
  * Currently always returns null (query caching is not active).
1922
+ *
1923
+ * An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
1924
+ * stores under: it separates rendered statements and field-security profiles, so a slot never
1925
+ * serves one caller rows shaped for another. The returned rows must be the statement's full
1926
+ * output; the caller's withheld columns are dropped from them after the hit.
1650
1927
  */
1651
- protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1928
+ protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1652
1929
  /**
1653
1930
  * Checks the paged cache for a specific page of query results.
1654
1931
  * Returns a full RunQueryResult on hit, null on miss.
1655
1932
  * Currently always returns null (query caching is not active).
1933
+ *
1934
+ * An override must look the page up by `slotKey` alone: it names the rendered statement, the
1935
+ * caller's field-security profile and the page, so a page cached for a restricted caller is
1936
+ * never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
1937
+ * from the returned rows after the hit.
1656
1938
  */
1657
- protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1939
+ protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1658
1940
  /**
1659
1941
  * Executes the query SQL and tracks execution time.
1660
1942
  */
@@ -1702,8 +1984,11 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1702
1984
  /**
1703
1985
  * Caches query results if caching is enabled for the query.
1704
1986
  * Currently a no-op (query caching is not active).
1987
+ *
1988
+ * `results` is the statement's full output, before the caller's withheld columns are dropped.
1989
+ * An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
1705
1990
  */
1706
- protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[]): Promise<void>;
1991
+ protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[], _slotKey: string): Promise<void>;
1707
1992
  /**************************************************************************/
1708
1993
  /**************************************************************************/
1709
1994
  /**
@@ -1934,7 +2219,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1934
2219
  * `AIEngine.Models` to recover the driver class / APIName and call
1935
2220
  * `EmbedText(model, text)` directly. If the EntityDocument does not specify
1936
2221
  * a model (or the model isn't loaded) we fall back to
1937
- * `EmbedTextLocal` (highest-power local model) only as a last resort.
2222
+ * `EmbedTextLocal` (the default local model) only as a last resort. The search
2223
+ * text is embedded as a query (`inputType: 'query'`). The index's
2224
+ * `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
2225
+ * the model's native size.
1938
2226
  *
1939
2227
  * Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
1940
2228
  * which rehydrates the vector pool for `entityDocumentId` from