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

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 (86) hide show
  1. package/README.md +150 -0
  2. package/dist/GenericDatabaseProvider.d.ts +244 -39
  3. package/dist/GenericDatabaseProvider.d.ts.map +1 -1
  4. package/dist/GenericDatabaseProvider.js +676 -233
  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 +7 -0
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +5 -0
  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/package.json +14 -14
package/README.md CHANGED
@@ -66,6 +66,14 @@ DatabaseProviderBase (@memberjunction/core — no heavy deps, abstract)
66
66
  | `getUpdatedRowsSince()` | Virtual: queries entity view for rows updated since a timestamp |
67
67
  | `resolveQuery()` | Resolves query from RunQueryParams (by ID or Name+CategoryPath) via QueryEngine |
68
68
  | `resolveCategoryPath()` | Resolves hierarchical category path to CategoryID |
69
+ | `InternalRunQuery()` | Runs a saved query (or routes ad hoc `SQL` to `ExecuteAdhocQuery`): render, authorize the rendered statement, optional materialized read, paging, field-level security column filtering. See [Running Queries](#running-queries) |
70
+ | `InternalExecuteQueryFromSpec()` | Runs a transient query spec (SQL, parameter definitions, inline dependencies) through the same render pipeline and safety gate |
71
+ | `ExecuteAdhocQuery()` | Runs caller-supplied SQL; it must be a single read statement |
72
+ | `processQueryParameters()` | Renders a saved query with `RenderPipeline.Run` for this provider's platform (or an external data source's dialect) |
73
+ | `ValidateRenderedQueryForExecution()` | Authorizes the rendered statement for the user, including field-level security; reports whether denied columns must be dropped from a `*` |
74
+ | `DescribeStatement()` | Asks the database to describe a statement's result columns without returning rows. Base implementation reports a failure; SQL Server and PostgreSQL override it |
75
+ | `buildMaterializedReadQuery()` | Static, pure builder for a read from a materialized snapshot, with every filter value bound as a parameter |
76
+ | `QueryUnavailableMessage()` / `RequestedQueryLabel()` | Static: the single refusal message used both for a query that does not exist and for one the caller may not run |
69
77
  | `BuildParameterPlaceholder()` | Virtual: PG-style $1/$2 by default; SQL Server overrides to @p0/@p1 |
70
78
  | `getColumnsForDatasetItem()` | Validates and quotes column names for dataset item queries |
71
79
 
@@ -105,9 +113,148 @@ export class MyDatabaseProvider extends GenericDatabaseProvider {
105
113
  // Implement remaining abstract methods from DatabaseProviderBase
106
114
  // Override EnqueueAfterSaveAIAction if you need transaction-aware deferral
107
115
  // Override PostProcessRows if you need platform-specific row processing (call super first)
116
+ // Override DescribeStatement if your database can describe a statement's result columns
108
117
  }
109
118
  ```
110
119
 
120
+ ## Running Queries
121
+
122
+ Every query path in this package (saved queries, ad hoc SQL, transient specs used by `TestQuerySQL`, data contexts and materialized reads) turns query text into the SQL that runs through one entry point, `RenderPipeline.Run`. The query language itself (template tags, filters, `Context` tokens, composition syntax and save-time rules) is specified in **[MJ Query Language](../../guides/MJ_QUERY_LANGUAGE.md)**. This section covers what the provider does with it.
123
+
124
+ ### The render pipeline
125
+
126
+ `RenderPipeline.Run(sql, ctx)` runs these steps in a fixed order:
127
+
128
+ 1. SQL comments are removed, so a template tag inside a comment does nothing.
129
+ 2. A template must pass the MJ Query language check; a template with errors is refused.
130
+ 3. **Render, then compose.** The outer query is rendered once with the caller's values. Each composition it reaches, `{{query:"Category/Path/Name(Arg=Value)"}}`, becomes one *instance*: the composed query plus its arguments, evaluated in the outer query's scope. Each instance is then rendered on its own, with only its own arguments and its own parameter definitions, recursively (up to 10 levels; cycles are refused). The rendered pieces are assembled into one statement, each instance as a CTE. The assembled SQL is never rendered again, so a value that happens to look like a template tag stays a plain value.
131
+ 4. **Safety gate** (below).
132
+ 5. **Row cap or paging** (below), applied last because a template can decide whether the statement has an `ORDER BY`.
133
+
134
+ What this means for query authors:
135
+
136
+ - **Arguments are explicit, like a function call.** A composed query's parameter that is not passed has no value, even when the outer query has a parameter with the same name. Write `(Region=Region)` to pass it on.
137
+ - **A composed query's required parameters are checked.** Leaving one out is a parameter error, not a silently dropped filter.
138
+ - **A branch not taken emits nothing.** A composition inside an `{% if %}` that renders false produces no CTE.
139
+ - **Two uses of the same query with the same arguments share one CTE**; different arguments give separate CTEs.
140
+ - **Lookup is by category path and name.** There is no name-only fallback. A path that is a whole-segment suffix of exactly one query's full path still runs, with a warning logged once, but saving such a path is refused; write the full path.
141
+ - A saved composed query must be Reusable, Approved and runnable by the user. One the user may not run is refused with the same message as one that does not exist.
142
+ - **Dialect.** Template values render for the dialect of the provider handling the request (`RenderContext.Platform`, or `DialectKey` when it differs, as for a query on an external data source). Two providers on different platforms in one process each render with their own rules.
143
+
144
+ `RenderResult` carries `FinalSQL`, `AppliedParameters`, `ContextValues` (the `Context` members the template read), `HasCompositions`, `CTEs`, `PagingResult`, `RowCap`, and a `Trace`:
145
+
146
+ | `Trace` field | Contents |
147
+ |---|---|
148
+ | `AfterComposition` | The assembled statement: every template rendered, every composition emitted as a CTE. Before row caps and paging |
149
+ | `AfterTemplates` | The same text as `AfterComposition`. Authorization checks read it, so it always includes every composed query |
150
+ | `AfterPaging` | The final SQL when paging was applied, otherwise `null` |
151
+ | `Instances` | Each composed instance, dependencies first: query, path, CTE name, evaluated arguments and its own rendered SQL |
152
+ | `CompositionDiagnostics` | Per instance: CTE name, whether its `ORDER BY` was removed, how many inner CTEs were hoisted |
153
+
154
+ ```typescript
155
+ import { RenderPipeline, IsQuerySafetyError } from '@memberjunction/generic-database-provider';
156
+ import type { UserInfo } from '@memberjunction/core';
157
+
158
+ function renderPage(sql: string, user: UserInfo): string | null {
159
+ try {
160
+ const result = RenderPipeline.Run(sql, {
161
+ Platform: 'sqlserver',
162
+ ContextUser: user,
163
+ Parameters: { Region: 'West' },
164
+ Paging: { StartRow: 0, MaxRows: 50 },
165
+ RequireReadStatement: true, // the caller supplied this SQL
166
+ });
167
+ return result.FinalSQL;
168
+ } catch (e) {
169
+ if (IsQuerySafetyError(e)) return null; // not a single read query
170
+ throw e;
171
+ }
172
+ }
173
+ ```
174
+
175
+ `Paging` and `MaxRows` are mutually exclusive; passing both throws.
176
+
177
+ ### The safety gate
178
+
179
+ Every rendered statement, on every path, passes `SafetyGate` before it can run. The check reads the SQL with the dialect's lexer, not a full parser, so it works on any statement the database itself would accept. The statement must be exactly one read query, starting with `SELECT` or `WITH`, and may not call functions the dialect lists as forbidden (functions that run SQL given as text or read files or other databases). It fails closed: SQL it cannot read is refused, never passed. SQL with no statement at all is refused when `RequireReadStatement` is set, which the ad hoc and test paths do.
180
+
181
+ A refusal is a `QuerySafetyError`; use `IsQuerySafetyError(e)` to recognise one (it also matches an error thrown by a second loaded copy of the module). Saving a new or edited query applies the same check, so a query that writes or calls a forbidden function cannot be saved; a refresh of an existing one reports it, and it is refused whenever it runs.
182
+
183
+ ### Paging and row caps
184
+
185
+ `QueryPagingEngine` pages by editing the statement's text in place: it reads the statement's structure and changes only the clauses it must. It never regenerates SQL from a syntax tree, and it does not wrap the query, so column scopes, `ORDER BY` references and table aliases stay valid.
186
+
187
+ - **Data SQL** (`WrapWithPaging(sql, startRow, maxRows, platform)` returns `PagingWrappedSQL` with `DataSQL`, `CountSQL`, `Offset`, `PageSize`): `OFFSET … FETCH NEXT …` on SQL Server, `LIMIT … OFFSET …` on PostgreSQL, after the statement's `ORDER BY` and before clauses that must stay last, such as `OPTION (…)`. A statement with no `ORDER BY` gets a default one.
188
+ - **Count SQL** puts the query, without its `ORDER BY`, in a CTE and selects `COUNT(*) AS TotalRowCount`.
189
+ - **The query's own row cap counts.** A numeric `TOP n`, `LIMIT n` or `FETCH NEXT n` is folded into the page arithmetic, so the smaller limit wins and the total is the size of the capped result. Any other cap (`TOP … PERCENT`, `WITH TIES`, an expression) is kept, and the query is paged as a derived table.
190
+ - **Row caps without paging** (`ApplyMaxRows`) add `TOP n` on SQL Server or `LIMIT n` on PostgreSQL, keep a tighter cap already present, and fall back to a derived table only for shapes that cannot be capped in place. `RowCapOutcome` reports whether the cap holds and how (`RowCapMethod`); when it could not be applied the pipeline logs why.
191
+ - A statement ending in `FOR JSON` / `FOR XML` returns a document, not rows; asking to page it is an error.
192
+ - `ShouldPage(startRow, maxRows)` is true when `MaxRows` is set, even without a `StartRow`, so a plain cap is applied in SQL rather than by fetching everything.
193
+
194
+ ### Materialized reads and named parameters
195
+
196
+ A saved query with an active materialization can be served from its snapshot table when the caller asks for it and the read would return the same rows as the live query; on any doubt the provider runs the query live. `buildMaterializedReadQuery` builds that read, with every filter value **bound as a parameter**, never written into the SQL text. The read orders by the snapshot's stable row ID, so pages do not skip or repeat rows.
197
+
198
+ Parameters are typed from the snapshot's own columns. The provider describes the snapshot table (see `DescribeStatement` below), keeps the column types until the next refresh, and binds each value as a `TypedQueryParameter` with the type of the column it is compared with. On SQL Server that is a named, declared parameter, so a `varchar` column is compared with a `varchar` value and keeps its index seek; on PostgreSQL it is a positional parameter with a cast. A value the column type cannot hold sends the read back to the live query.
199
+
200
+ Two classes describe bind parameters for `ExecuteSQL`:
201
+
202
+ | Class | Use |
203
+ |---|---|
204
+ | `TypedQueryParameter(Name, SQLType, Value)` | A parameter with an explicit database type. `TypedBindValue(value, sqlType)` converts a value to what that type binds, or returns `undefined` when it cannot |
205
+ | `NamedQueryParameter(Name, Value)` | A parameter passed by name whose type the driver infers. SQL Server binds `@p0` as `p0` and leaves the statement text alone; PostgreSQL binds by position (`$1`) |
206
+
207
+ A plain array of values (`[value1, value2]`) is the **legacy positional form**: SQL Server providers bind it by rewriting every `?` in the text, including one inside a string literal or comment. Prefer named parameters in new code:
208
+
209
+ ```typescript
210
+ import { NamedQueryParameter, type GenericDatabaseProvider } from '@memberjunction/generic-database-provider';
211
+ import type { UserInfo } from '@memberjunction/core';
212
+
213
+ // SQL Server: @p0 is bound by name as p0
214
+ async function customerNames(provider: GenericDatabaseProvider, contextUser: UserInfo): Promise<string[]> {
215
+ const rows = await provider.ExecuteSQL<{ Name: string }>(
216
+ 'SELECT Name FROM [dbo].[Customer] WHERE Region = @p0',
217
+ [new NamedQueryParameter('p0', 'West')],
218
+ undefined,
219
+ contextUser,
220
+ );
221
+ return rows.map(r => r.Name);
222
+ }
223
+ ```
224
+
225
+ ### `DescribeStatement`
226
+
227
+ ```typescript
228
+ public async DescribeStatement(sql: string, contextUser?: UserInfo): Promise<DescribeStatementResult>
229
+ ```
230
+
231
+ Asks the database server to describe the result columns a statement would return, without returning its rows. SQL Server compiles the statement without running it; PostgreSQL runs it with no rows returned inside a transaction that is rolled back. The base class reports a failure, so a provider for a database that cannot describe statements needs no override.
232
+
233
+ The result has `Success`, `Columns` and `Diagnostics` (the server's error text on failure). Each `DescribedColumn` gives `Name`, `Ordinal`, `SQLBaseType`, `SQLFullType` (such as `nvarchar(100)`), `IsNullable` (`null` when the server does not say, as on PostgreSQL), `IsComputed`, and `Source`: the table or view column the value passes through unchanged, or `null`. Build results with `DescribeStatementSuccess` / `DescribeStatementFailure`; `BaseTypeOf('decimal(18,2)')` returns `decimal`.
234
+
235
+ It is used to record a query's output columns and types when the query is saved, to read a snapshot's column types for materialized reads, and by field-level security on `*` (below). Descriptions are cached per statement and dialect for a short time.
236
+
237
+ ### Field-level security on queries
238
+
239
+ When a user is denied read access to some fields, a saved query is checked against those permissions on the **rendered** statement, so composed queries and template branches are covered:
240
+
241
+ - A query that names a field the user may not read, anywhere in the statement, is refused before it runs. The message is the same as for a query that does not exist: `Query '<what you asked for>' does not exist or you do not have permission to run it.` It echoes only the identifier the caller supplied.
242
+ - A denied field that reaches the output only through a plain `*` or `alias.*` does not refuse the query. The query runs, and that column is removed from this user's results, so the result columns can differ between users. The columns to remove come from `DescribeStatement`; if the statement cannot be described, the run is refused rather than risk returning a denied column. A query on an external data source that would need this filtering is refused.
243
+ - A query authorized by its own `MJ: Query Permissions` rows runs with the rights its author granted, and field-level security does not change it.
244
+
245
+ ### Deprecated in this package
246
+
247
+ These still work and remain until 7.0. The last row is a legacy form rather than a marked deprecation:
248
+
249
+ | Deprecated | Use instead |
250
+ |---|---|
251
+ | `buildMaterializedReadQuery({ isPostgres })` | Pass `dialect` (and `columnTypes` for typed binding) |
252
+ | `buildMaterializedReadQuery` without `columnTypes` | Pass the snapshot's `columnTypes`, so values bind as `TypedQueryParameter` |
253
+ | `QueryPagingEngine.StripTopClause` / `stripTopClause` | `SqlDocument.Parse(sql, dialect).RowCaps()` from `@memberjunction/sql-parser` to find a `TOP`, and an `EditSet` to remove it |
254
+ | `QueryPagingEngine.extractOrderBy` | `QueryPagingEngine.ExtractOrderBy` |
255
+ | `ClientClauseScreen.AstContainsWriteNode` | `StrictFragmentValidator.ValidateReadOnlyStatement` from `@memberjunction/sql-parser` (its result reports `ContainsNestedWrite`) |
256
+ | Positional `?` parameter arrays | `NamedQueryParameter` or `TypedQueryParameter` lists |
257
+
111
258
  ## Keyset (Seek) Pagination
112
259
 
113
260
  `InternalRunView` honors `RunViewParams.AfterKey` (a `CompositeKey`) to emit keyset-style SQL — `WHERE pk > @lastSeen ORDER BY pk LIMIT N` — instead of `OFFSET ... FETCH NEXT N`. Keyset stays O(log N) regardless of depth, making it the right tool for background jobs iterating large entities.
@@ -215,5 +362,8 @@ This package implements the `createViewUserSearchSQL()` method which generates p
215
362
  - `@memberjunction/encryption` — Field-level encryption/decryption
216
363
  - `@memberjunction/global` — Global object store, `ensureRegExps` for pattern filtering
217
364
  - `@memberjunction/queue` — Task queue for after-save AI actions
365
+ - `@memberjunction/sql-parser` — Lexer, structural reader and edits used by the safety gate, composition assembly and paging
366
+ - `@memberjunction/sql-dialect` — Per-platform quoting, parameter placeholders and forbidden-function lists
367
+ - `@memberjunction/query-processor` — Template rendering and parameter validation for queries
218
368
  - `sql-formatter` — SQL pretty-printing for log output
219
369
  - `uuid` — Session ID generation
@@ -19,6 +19,7 @@ import { BaseEntity, DatabaseProviderBase, EntityInfo, EntityFieldInfo, EntitySa
19
19
  import { 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';
@@ -257,7 +258,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
257
258
  * `Validate` and `Before*` ignore RunMode entirely — deferring work that decides whether the
258
259
  * save succeeds is not a durability improvement, it is a different feature.
259
260
  */
260
- protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[]): Promise<ActionResult[]>;
261
+ protected HandleEntityActions(entity: BaseEntity, baseType: 'save' | 'delete' | 'validate', before: boolean, user: UserInfo, originatingEntityActionIDs?: string[], runModeFilter?: 'DurableOnly' | 'NonDurableOnly'): Promise<ActionResult[]>;
261
262
  /**
262
263
  * Handles Entity AI Actions for save or delete operations.
263
264
  *
@@ -281,7 +282,9 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
281
282
  /**************************************************************************/
282
283
  protected OnValidateBeforeSave(entity: BaseEntity, user: UserInfo): Promise<string | null>;
283
284
  protected OnBeforeSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
284
- protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, _context: SaveContext): void;
285
+ protected ShouldEnlistSaveInTransaction(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, isNewRecord: boolean): Promise<boolean>;
286
+ protected OnDurableAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<void>;
287
+ protected OnAfterSaveExecute(entity: BaseEntity, user: UserInfo, options: EntitySaveOptions, context: SaveContext): void;
285
288
  protected OnSaveCompleted(entity: BaseEntity, saveSQLResult: SaveSQLResult, user: UserInfo, options: EntitySaveOptions, context: SaveContext): Promise<Record<string, unknown> | null>;
286
289
  protected OnBeforeDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): Promise<void>;
287
290
  protected OnAfterDeleteExecute(entity: BaseEntity, user: UserInfo, options: EntityDeleteOptions): void;
@@ -291,6 +294,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
291
294
  private cleanupGeoCodesForDeletedRecord;
292
295
  /**************************************************************************/
293
296
  /**************************************************************************/
297
+ /**
298
+ * Tracks pre-decryption normalized row arrays (binary -> base64, datetime adjusted, ciphertext
299
+ * preserved) keyed by the post-decryption array returned from {@link PostProcessRows}.
300
+ * Used by {@link PrepareRowsForCacheStorage} so local/Redis caches store ciphertext at rest.
301
+ */
302
+ private static readonly _preDecryptionRowsByResult;
294
303
  /**
295
304
  * Post-processes rows: first applies platform-specific datetime adjustments
296
305
  * via the virtual `AdjustDatetimeFields` hook, then handles field-level
@@ -299,7 +308,18 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
299
308
  * Subclasses should NOT override this method. Instead, override
300
309
  * `AdjustDatetimeFields` for platform-specific datetime corrections.
301
310
  */
302
- protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo): Promise<Record<string, unknown>[]>;
311
+ protected PostProcessRows(rows: Record<string, unknown>[], entityInfo: EntityInfo, user: UserInfo, options?: {
312
+ preserveRestrictedApiCiphertext?: boolean;
313
+ }): Promise<Record<string, unknown>[]>;
314
+ /**
315
+ * Decrypts encrypted fields on shallow row copies for an in-process or API consumer.
316
+ * When `preserveRestrictedApiCiphertext` is `true`, fields with `AllowDecryptInAPI === false`
317
+ * remain in their stored ciphertext form so API layers never decrypt-then-re-encrypt or
318
+ * needlessly decrypt values destined for sentinel redaction.
319
+ */
320
+ private decryptRowsForConsumer;
321
+ protected PrepareRowsForCacheStorage(rows: unknown[], entityInfo?: EntityInfo): unknown[];
322
+ protected MaterializeCachedRowsForCaller(rows: Record<string, unknown>[], entityInfo?: EntityInfo, contextUser?: UserInfo, preserveRestrictedApiCiphertext?: boolean): Promise<Record<string, unknown>[]>;
303
323
  private static _encryptedFieldsCache;
304
324
  private static getEncryptedFields;
305
325
  /**
@@ -1245,6 +1265,12 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1245
1265
  * them: the entity resolved here is named explicitly.
1246
1266
  */
1247
1267
  protected projectExternalRowsForCaller<T>(rows: T[], entityInfo: EntityInfo, params: RunViewParams, user: UserInfo): T[];
1268
+ /**
1269
+ * Keys the ciphertext copy that {@link PostProcessRows} kept for `rows` to their projection,
1270
+ * narrowed the same way, so {@link PrepareRowsForCacheStorage} stores ciphertext at the
1271
+ * caller's width instead of finding no copy and falling back to the decrypted rows.
1272
+ */
1273
+ private carryCiphertextRowsForCache;
1248
1274
  /**
1249
1275
  * Folds a saved view's stored WhereClause and OrderByClause into the RunView params before
1250
1276
  * external dispatch. The external branch returns before the normal SQL path that applies
@@ -1264,7 +1290,7 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1264
1290
  private cacheStatusFieldSecurityDiffers;
1265
1291
  /**
1266
1292
  * 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
1293
+ * Returns the resolution if found ('current', 'stale' when the server slot is newer than the client's copy, or
1268
1294
  * 'needs_verification' when the server slot's freshness window has elapsed),
1269
1295
  * or null if the server cache doesn't have this data (or was evicted due to client monotonicity).
1270
1296
  */
@@ -1276,20 +1302,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1276
1302
  /**
1277
1303
  * Runs a differential query and returns only changes since the client's cached state.
1278
1304
  * Includes updated/created rows and deleted record IDs.
1279
- * Falls back to full query if hidden deletes are detected.
1305
+ * Falls back to full query if the client timestamp is not a date or hidden deletes are detected.
1280
1306
  */
1281
1307
  protected runDifferentialQueryAndReturn<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, clientMaxUpdatedAt: string, clientRowCount: number, serverStatus: {
1282
1308
  maxUpdatedAt?: string;
1283
1309
  rowCount?: number;
1284
1310
  }, whereSQL: string, viewIndex: number, contextUser?: UserInfo, callerFields?: string[] | null): Promise<RunViewWithCacheCheckResult<T>>;
1311
+ /**
1312
+ * Formats a client timestamp as ISO 8601 for a SQL literal.
1313
+ * Throws when the value is not a date.
1314
+ */
1315
+ private toSQLTimestamp;
1285
1316
  /**
1286
1317
  * Gets IDs of records deleted since a given timestamp.
1287
- * Uses dialect-neutral quoting. Subclasses can override for parameterized queries.
1318
+ * Uses dialect-neutral quoting and sends the timestamp in ISO 8601 form.
1319
+ * Subclasses can override for parameterized queries.
1288
1320
  */
1289
1321
  protected getDeletedRecordIDsSince(entityID: string, sinceTimestamp: string, contextUser?: UserInfo): Promise<string[]>;
1290
1322
  /**
1291
1323
  * Gets rows updated/created since a given timestamp.
1292
- * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy.
1324
+ * Uses dialect-neutral quoting and TransformExternalSQLClause for OrderBy, and sends the
1325
+ * timestamp in ISO 8601 form as its own predicate group.
1293
1326
  */
1294
1327
  protected getUpdatedRowsSince<T = unknown>(params: RunViewParams, entityInfo: EntityInfo, sinceTimestamp: string, whereSQL: string, contextUser?: UserInfo): Promise<T[]>;
1295
1328
  /**************************************************************************/
@@ -1355,9 +1388,11 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1355
1388
  *
1356
1389
  * @param query - The resolved MJQueryEntityExtended to validate
1357
1390
  * @param contextUser - The user attempting to execute the query
1391
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1392
+ * refusal echoes it and nothing else. The query's ID when omitted.
1358
1393
  * @throws Error if the user does not have permission to run the query
1359
1394
  */
1360
- protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo): void;
1395
+ protected ValidateQueryForExecution(query: MJQueryEntityExtended, contextUser?: UserInfo, requestedLabel?: string): void;
1361
1396
  /**
1362
1397
  * For a `RequireApproved` run: refuses unless the query, and every query it composes, has a
1363
1398
  * current approval — status Approved and a stored fingerprint equal to the fingerprint of the
@@ -1375,15 +1410,71 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1375
1410
  * and field-level security on every column it references. A template that injects an
1376
1411
  * identifier, a `{% if %}` branch and a `{{query:"..."}}` composition are all checked as they
1377
1412
  * 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
1413
  *
1414
+ * A refusal reads exactly like the message for a query that does not exist
1415
+ * ({@link QueryUnavailableMessage}): it never says which field, clause or entity caused it.
1416
+ *
1417
+ * @param requestedLabel - The identifier the caller supplied ({@link RequestedQueryLabel}); the
1418
+ * refusal echoes it and nothing else. The query's ID when omitted.
1419
+ * @returns Whether the run must drop denied columns from its rows: true when a plain `*` or
1420
+ * `alias.*` that reaches only the output reads an entity the user is denied a field on.
1380
1421
  * @throws Error when the user may not run this rendering of the query
1381
1422
  */
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. */
1423
+ protected ValidateRenderedQueryForExecution(query: MJQueryEntityExtended, renderedSQL: string, contextUser?: UserInfo, requestedLabel?: string): {
1424
+ NeedsColumnFiltering: boolean;
1425
+ };
1426
+ /**
1427
+ * The message for a saved query that does not exist or that the caller may not run. The two
1428
+ * are worded identically, so a refusal does not confirm that the query, or anything it reads,
1429
+ * exists.
1430
+ *
1431
+ * It echoes only the identifier the caller supplied ({@link RequestedQueryLabel}), never one
1432
+ * looked up from the resolved query: a refusal of a request by ID that named the query would
1433
+ * both differ from that request's not-found message and disclose the query's name.
1434
+ *
1435
+ * @param label - What the caller asked for, as {@link RequestedQueryLabel} gives it
1436
+ */
1437
+ static QueryUnavailableMessage(label: string): string;
1438
+ /**
1439
+ * The identifier a request supplied, for {@link QueryUnavailableMessage}: its category path and
1440
+ * name (`Sales/Reports/Top Customers`) when it names a query, its ID otherwise.
1441
+ */
1442
+ static RequestedQueryLabel(params: Pick<RunQueryParams, 'QueryID' | 'QueryName' | 'CategoryPath'>): string;
1443
+ /** The refusal for a request the caller may not run, echoing `requestedLabel` ({@link QueryUnavailableMessage}). */
1384
1444
  private queryRunRefusalMessage;
1385
- /** The run-time checks of `query` for `user` on this provider's entities and dialect; logs a field-security refusal. */
1445
+ /**
1446
+ * The OPERATOR's record of why a run was refused. The refusal returned to the caller is
1447
+ * {@link QueryUnavailableMessage}, worded like not-found and naming no field, clause or entity:
1448
+ * that is the information-disclosure guard, and it is unchanged. This is the server-side copy.
1449
+ *
1450
+ * Without it a refusal is unattributable: the query's own role list, SQL the field-security
1451
+ * gate could not read, and a field-security violation all end in the same caller message.
1452
+ *
1453
+ * Previously only the field-security case logged anything, and only at `verboseOnly`, which
1454
+ * CI does not enable — so a recurring ~3% integration-tier failure (ten checks across four
1455
+ * bundles refusing together) could not be diagnosed from the logs at all. Called from every
1456
+ * refusal gate, so no path is silent.
1457
+ *
1458
+ * The loaded-role count is here because an empty or undefined `UserRoles` denies every
1459
+ * permission-bearing query at once — exactly the all-or-nothing signature those runs show.
1460
+ * Telling "no roles loaded" apart from "roles loaded but not granted" is the first question
1461
+ * to ask and it costs one integer.
1462
+ */
1463
+ private logQueryRunRefusal;
1464
+ /**
1465
+ * The run-time checks of `query` for `user` on this provider's entities and dialect; logs a
1466
+ * refusal unless `logRefusal` is false. For a user denied a field anywhere, the statement's
1467
+ * projection stars are read first ({@link projectionStarOffsets}), so a plain `*` can run with
1468
+ * its denied columns dropped instead of being refused.
1469
+ */
1386
1470
  private checkRenderedQuery;
1471
+ /** Projection-star offsets per rendered statement and dialect ({@link FindProjectionStars}). */
1472
+ private static readonly projectionStarMemo;
1473
+ /**
1474
+ * The projection stars of `renderedSQL` ({@link FindProjectionStars}), read only for a user
1475
+ * denied a field on some entity and only when the text holds a `*`; undefined otherwise.
1476
+ */
1477
+ private projectionStarOffsets;
1387
1478
  /**
1388
1479
  * The full authorization of a saved query for one request: {@link MJQueryEntityExtended.UserCanRun}
1389
1480
  * and the run-time checks on the query rendered with `parameters`. A rendering that fails
@@ -1454,32 +1545,27 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1454
1545
  * {@link buildMaterializedReadQuery}).
1455
1546
  */
1456
1547
  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
1548
  /**
1460
1549
  * PURE, dialect-aware builder for the Phase-2 materialized read query (plan §5). Given the query's
1461
1550
  * 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).
1551
+ * parameter values, and the dialect, returns `{ sql, parameters }` whose WHERE injects each spec
1552
+ * predicate as `column <op> <placeholder>` with the value **bound** — never interpolating a caller
1553
+ * value (SQL-injection-safe by construction).
1554
+ *
1555
+ * With `columnTypes` (the snapshot's column types, as the server describes them) every value binds as
1556
+ * a {@link TypedQueryParameter} of the filtered column's own type, referenced by the dialect's typed
1557
+ * placeholder (`DialectBinding.TypedParameter`): a named, declared parameter on SQL Server, so a
1558
+ * varchar column is compared with a varchar value and keeps its index seek; `$n::type` on PostgreSQL.
1559
+ * Without `columnTypes` (deprecated) values bind untyped: with a `dialect`, as named parameters
1560
+ * ({@link NamedQueryParameter}, referenced `@pN` on SQL Server, `$n` on PostgreSQL); with neither a
1561
+ * dialect nor column types, as the legacy positional array (SQL Server `?`, PostgreSQL `$n`).
1465
1562
  *
1466
1563
  * Returns null on ANY condition that would make the materialized read UNFAITHFUL to the live query, so
1467
1564
  * the caller falls back to running live (always correct): an operator outside the safe set, a spec
1468
1565
  * 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`.
1566
+ * an empty/non-array value for a list (`IN`/`NOT IN`) predicate, or (typed) a filtered column with no
1567
+ * known type or a value its type cannot hold. No IO — fully unit-testable.
1481
1568
  */
1482
- static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1483
1569
  static buildMaterializedReadQuery(opts: {
1484
1570
  outputColumns: string[];
1485
1571
  schemaName: string;
@@ -1494,11 +1580,32 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1494
1580
  /** Declared parameter type per paramName (from MJ: Query Parameters). Drives type-faithful binding so a
1495
1581
  * scalar value matches the live path's typed literal instead of a raw string the DB implicitly coerces. */
1496
1582
  paramTypes?: Record<string, string>;
1497
- isPostgres: boolean;
1583
+ /** The dialect the read runs in: identifier quoting and parameter references. */
1584
+ dialect?: SQLDialect;
1585
+ /** @deprecated Pass {@link dialect}. True for PostgreSQL when no dialect is given. */
1586
+ isPostgres?: boolean;
1587
+ /** The snapshot's column types, column name → SQL type (`varchar(50)`, `datetime2(7)`). Names match ignoring case. */
1588
+ columnTypes?: Record<string, string>;
1498
1589
  }): {
1499
1590
  sql: string;
1500
1591
  parameters: unknown[];
1501
1592
  } | null;
1593
+ /**
1594
+ * The parameter list one materialized read builds, and how a value joins it: typed by the filtered
1595
+ * column when the snapshot's column types are known, otherwise untyped (the deprecated form).
1596
+ */
1597
+ private static materializedBinder;
1598
+ /**
1599
+ * Adds `value` to `parameters` as a {@link NamedQueryParameter} and returns the dialect's placeholder for
1600
+ * it (`@p0` bound as `p0` on SQL Server, `$1` on PostgreSQL). Passing the value by name keeps a SQL Server
1601
+ * provider from rewriting `?` in the statement text, which the legacy positional array form does
1602
+ * everywhere, inside a quoted identifier included. Null (→ live) for a value no parameter can carry.
1603
+ */
1604
+ private static bindNamedParameter;
1605
+ /** `value` as a bind parameter value, or undefined when it is not a scalar a parameter can carry. */
1606
+ private static namedParameterValue;
1607
+ /** One spec element as a bound predicate, or null when it cannot be served faithfully (→ live). */
1608
+ private static materializedPredicate;
1502
1609
  /**
1503
1610
  * Coerces a scalar row-filter value to its declared `MJ: Query Parameters`.Type for type-faithful binding
1504
1611
  * (see {@link buildMaterializedReadQuery}). This mirrors the TYPE-CONVERSION SWITCH of the live path's
@@ -1513,25 +1620,88 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1513
1620
  * the live TYPE conversion would ALSO reject the value (→ caller falls back to live).
1514
1621
  * - `number` → `Number(value)` (JS trims); non-finite → refuse (live pushes a validation error → live).
1515
1622
  * - `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.
1623
+ * else is false (live never refuses a boolean). Native forms keep the boolean; otherwise BIT 1/0.
1517
1624
  * - `date` → `new Date(value).toISOString()` — the UTC ISO string, exactly what live stores/renders. NOT
1518
1625
  * 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.
1626
+ * diverge for any timed value. Invalid date → refuse. Without native forms the ISO 'Z' zone
1627
+ * suffix is dropped, because SQL Server rejects it for an untyped datetime2/datetime value
1628
+ * (error 241); the zone-less string is the same UTC wall-clock.
1520
1629
  * - `string` → `String(value)` (matches live); `array`-element / unspecified → bound as-is.
1630
+ *
1631
+ * @param nativeForms - Keep booleans as booleans and the ISO zone suffix (typed bindings, PostgreSQL).
1521
1632
  */
1522
1633
  private static coerceMaterializedScalarValue;
1634
+ /**
1635
+ * The snapshot's column types (lower-cased column name → SQL type) for a materialization, read by
1636
+ * describing `SELECT * FROM <schema>.<view>` and kept until the snapshot is refreshed: the key carries
1637
+ * the materialization's ID and `LastRefreshedAt`, which every refresh moves. Null when the view cannot
1638
+ * be described (→ live).
1639
+ */
1640
+ private materializedColumnTypes;
1641
+ /** Snapshot column types per materialization and refresh ({@link materializedColumnTypes}). */
1642
+ private static readonly materializedColumnTypeMemo;
1643
+ /** Top-level ORDER BY answers per (SQL, dialect) ({@link queryHasTopLevelOrderBy}). */
1644
+ private static readonly topLevelOrderByMemo;
1645
+ /**
1646
+ * True if `sql`'s top-level query carries an ORDER BY. Used to refuse a materialized RowFilterBroad read:
1647
+ * {@link buildMaterializedReadQuery} orders by the snapshot's row id and the snapshot is built with the
1648
+ * source's top-level ORDER BY stripped, so an ordered query must be served LIVE (where its ordering — and
1649
+ * therefore its pagination under StartRow/MaxRows — is preserved) rather than from the snapshot. Read with
1650
+ * `SqlDocument.TopLevelOrderBy()`; SQL that is not read completely, or that is not one query, returns `true`
1651
+ * (refuse-to-live: treat unknown as ordered rather than risk serving mis-ordered pages). Memoized per
1652
+ * (SQL, dialect) in a bounded memo.
1653
+ *
1654
+ * @internal Materialized-read ordering-fidelity gate — NOT part of this package's supported public API;
1655
+ * `static` only so it can be unit-tested. Do not call from outside `@memberjunction/generic-database-provider`.
1656
+ */
1657
+ static queryHasTopLevelOrderBy(sql: string, platformKey: string | undefined): boolean;
1523
1658
  /**
1524
1659
  * Phase 2 (plan §5): resolve a materialized read plan for a query IF the caller opted into
1525
1660
  * `DataSource:'Materialized'` AND the query has a fresh, Active `RowFilterBroad` materialization whose
1526
1661
  * persisted spec fully covers the query's parameters. Returns null on ANY uncertainty → the caller runs
1527
1662
  * the live query (serving live is always correct — this is a transparent optimization, never a
1528
1663
  * correctness dependency).
1664
+ *
1665
+ * @param renderedSQL - The SQL the live path runs for this call (rendered, not paged). The ordering
1666
+ * check reads it; without it the check reads the platform SQL, where template syntax makes any
1667
+ * template query read as ordered (→ live).
1529
1668
  */
1530
- protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>): Promise<{
1669
+ protected tryBuildMaterializedQueryPlan(query: MJQueryEntityExtended, params: RunQueryParams, contextUser?: UserInfo, contextValues?: Record<string, string>, renderedSQL?: string): Promise<{
1531
1670
  sql: string;
1532
1671
  parameters: unknown[];
1533
1672
  } | null>;
1534
1673
  protected InternalRunQuery(params: RunQueryParams, contextUser?: UserInfo): Promise<RunQueryResult>;
1674
+ /** Descriptions of rendered statements, shared by every caller; schema-dependent, so they expire. */
1675
+ private static readonly describedStatementMemo;
1676
+ /**
1677
+ * Describes the result set of `sql` without returning its rows: each output column's name,
1678
+ * position, exact type, nullability and, for a pass-through column, the table or view column it
1679
+ * comes from. The statement is never run for its rows (SQL Server compiles it only; PostgreSQL
1680
+ * runs it under `LIMIT 0` in a transaction that is rolled back).
1681
+ *
1682
+ * This base implementation describes nothing: it reports a failure. Providers for a database
1683
+ * that can describe a statement override it.
1684
+ *
1685
+ * @param sql - The rendered statement, in this provider's dialect.
1686
+ * @param _contextUser - The user the description is for.
1687
+ */
1688
+ DescribeStatement(sql: string, _contextUser?: UserInfo): Promise<DescribeStatementResult>;
1689
+ /**
1690
+ * SECURITY — the output columns of `renderedSQL` that `user` must not receive
1691
+ * ({@link WithheldColumnNames}), from the statement's description, kept per statement and dialect.
1692
+ *
1693
+ * @throws Error with the refusal message when the statement cannot be described: without the
1694
+ * description no column can be shown to be safe, so the run is refused.
1695
+ */
1696
+ private queryColumnFilter;
1697
+ /** The catalog entities `query`'s `QueryEntities` rows name. */
1698
+ private declaredQueryEntities;
1699
+ /**
1700
+ * `rows` with the filter's withheld columns dropped, as new row objects. A column the
1701
+ * description does not list is dropped too, and the description is forgotten: the statement's
1702
+ * shape changed since it was described (a view redefined), so the next run describes it again.
1703
+ */
1704
+ private filterQueryRows;
1535
1705
  /**
1536
1706
  * Batch query execution — runs all queries in parallel.
1537
1707
  */
@@ -1588,12 +1758,22 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1588
1758
  *
1589
1759
  * Delegates to {@link RenderPipeline.Run} for the composition → template
1590
1760
  * pipeline. Paging is handled separately by the caller (InternalRunQuery).
1761
+ *
1762
+ * @param dialectKey - The dialect the template's values render for (`sqlString` literals,
1763
+ * booleans); this provider's platform when omitted. An external data source's query passes
1764
+ * the source's dialect.
1591
1765
  */
1592
- protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>): {
1766
+ protected processQueryParameters(query: MJQueryEntityExtended, parameters?: Record<string, string>, contextUser?: UserInfo, serverSet?: Pick<RunQueryParams, 'ServerParameters' | 'TimeZone'>, dialectKey?: string): {
1593
1767
  finalSQL: string;
1594
1768
  appliedParameters: Record<string, string>;
1595
1769
  renderResult: RenderResult;
1596
1770
  };
1771
+ /**
1772
+ * The dialect key of the external data source `query` reads, so its template values render as
1773
+ * that database reads literals; undefined when the source has no SQL dialect (a document
1774
+ * store), in which case the query renders with this provider's platform as before.
1775
+ */
1776
+ private externalQueryDialectKey;
1597
1777
  /**
1598
1778
  * Checks the columns an external-data-source query returned against the fields the Query
1599
1779
  * *declares* (its QueryField metadata) and logs a warning naming any declared field that
@@ -1644,17 +1824,36 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1644
1824
  * pipeline. Supports inline dependencies for transient query testing.
1645
1825
  */
1646
1826
  private resolveSpecParameters;
1827
+ /**
1828
+ * Where a server-side result cache keeps this run's rows: one slot per rendered statement and
1829
+ * dialect, and, when the caller is denied a field the statement's projection star reads, per
1830
+ * field-security profile ({@link FieldSecuritySQLGate.CatalogDenialProfileKey}). Callers whose
1831
+ * runs drop the same columns share a slot; a restricted caller and an unrestricted one never do.
1832
+ * The rendered statement carries every parameter value, server-set ones included, so they need
1833
+ * no separate part of the key.
1834
+ */
1835
+ private queryResultCacheSlot;
1647
1836
  /**
1648
1837
  * Checks the query cache for existing results and returns them if valid.
1649
1838
  * Currently always returns null (query caching is not active).
1839
+ *
1840
+ * An override must look results up by `slotKey` alone, the same key {@link cacheQueryResults}
1841
+ * stores under: it separates rendered statements and field-security profiles, so a slot never
1842
+ * serves one caller rows shaped for another. The returned rows must be the statement's full
1843
+ * output; the caller's withheld columns are dropped from them after the hit.
1650
1844
  */
1651
- protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1845
+ protected checkQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1652
1846
  /**
1653
1847
  * Checks the paged cache for a specific page of query results.
1654
1848
  * Returns a full RunQueryResult on hit, null on miss.
1655
1849
  * Currently always returns null (query caching is not active).
1850
+ *
1851
+ * An override must look the page up by `slotKey` alone: it names the rendered statement, the
1852
+ * caller's field-security profile and the page, so a page cached for a restricted caller is
1853
+ * never served to an unrestricted one or the reverse. The caller's withheld columns are dropped
1854
+ * from the returned rows after the hit.
1656
1855
  */
1657
- protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>): Promise<RunQueryResult | null>;
1856
+ protected checkPagedQueryCache(_query: MJQueryEntityExtended, _params: RunQueryParams, _appliedParameters: Record<string, string>, _slotKey: string): Promise<RunQueryResult | null>;
1658
1857
  /**
1659
1858
  * Executes the query SQL and tracks execution time.
1660
1859
  */
@@ -1702,8 +1901,11 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1702
1901
  /**
1703
1902
  * Caches query results if caching is enabled for the query.
1704
1903
  * Currently a no-op (query caching is not active).
1904
+ *
1905
+ * `results` is the statement's full output, before the caller's withheld columns are dropped.
1906
+ * An override must store it under `slotKey`, the key {@link checkQueryCache} reads.
1705
1907
  */
1706
- protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[]): Promise<void>;
1908
+ protected cacheQueryResults(_query: MJQueryEntityExtended, _parameters: Record<string, string>, _results: Record<string, unknown>[], _slotKey: string): Promise<void>;
1707
1909
  /**************************************************************************/
1708
1910
  /**************************************************************************/
1709
1911
  /**
@@ -1934,7 +2136,10 @@ export declare abstract class GenericDatabaseProvider extends DatabaseProviderBa
1934
2136
  * `AIEngine.Models` to recover the driver class / APIName and call
1935
2137
  * `EmbedText(model, text)` directly. If the EntityDocument does not specify
1936
2138
  * a model (or the model isn't loaded) we fall back to
1937
- * `EmbedTextLocal` (highest-power local model) only as a last resort.
2139
+ * `EmbedTextLocal` (the default local model) only as a last resort. The search
2140
+ * text is embedded as a query (`inputType: 'query'`). The index's
2141
+ * `VectorIndex.Dimensions` is not passed, so this pass assumes an index stored at
2142
+ * the model's native size.
1938
2143
  *
1939
2144
  * Vector ranking runs against the in-process `SimpleVectorServiceProvider`,
1940
2145
  * which rehydrates the vector pool for `entityDocumentId` from