@memberjunction/postgresql-dataprovider 6.2.2 → 6.3.0-edge.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import pg from 'pg';
|
|
2
|
-
import { DatabasePlatform, ExecuteSQLOptions, UserInfo, EntityInfo, EntityFieldInfo, ProviderType, CompositeKey, EntityDependency, GetRecordDependenciesOptions, BaseEntity, BaseEntityResult, SaveSQLResult, DeleteSQLResult, TransactionGroupBase, IMetadataProvider, RestoreContext, CloneContext, RecordChangeSource, RecordChangePayload, EntityDeleteOptions, EntitySaveOptions } from '@memberjunction/core';
|
|
3
|
-
import { GenericDatabaseProvider, SaveCoercedValue, SaveCallBinding, SaveSQLFragment, SaveReturnContext } from '@memberjunction/generic-database-provider';
|
|
2
|
+
import { DatabasePlatform, ExecuteSQLOptions, UserInfo, EntityInfo, EntityFieldInfo, ProviderType, CompositeKey, EntityDependency, GetRecordDependenciesOptions, BaseEntity, BaseEntityResult, SaveSQLResult, DeleteSQLResult, TransactionGroupBase, IMetadataProvider, RestoreContext, CloneContext, RecordChangeSource, RecordChangePayload, EntityDeleteOptions, EntitySaveOptions, RunViewWithCacheCheckParams } from '@memberjunction/core';
|
|
3
|
+
import { GenericDatabaseProvider, SaveCoercedValue, SaveCallBinding, SaveSQLFragment, SaveReturnContext, ExecuteSQLBatchOptions, NamedQueryParameter } from '@memberjunction/generic-database-provider';
|
|
4
4
|
import type { DatabasePoolStats, DescribeStatementResult } from '@memberjunction/generic-database-provider';
|
|
5
5
|
import type { IColocatedVectorHost } from '@memberjunction/ai-vectordb';
|
|
6
6
|
import { PostgreSQLDialect } from '@memberjunction/sql-dialect';
|
|
@@ -75,6 +75,17 @@ export declare class PostgreSQLDataProvider extends GenericDatabaseProvider impl
|
|
|
75
75
|
protected get Metadata(): IMetadataProvider;
|
|
76
76
|
Config(configData: PostgreSQLProviderConfigData): Promise<boolean>;
|
|
77
77
|
private connectionConfigsEqual;
|
|
78
|
+
/**
|
|
79
|
+
* Returns `true` when global metadata and `LocalCacheManager` are warm in memory and `pool`
|
|
80
|
+
* is non-null so {@link ConfigureFromGlobalSync} can configure a per-request provider without I/O.
|
|
81
|
+
*/
|
|
82
|
+
static CanConfigureFromGlobalSync(pool: pg.Pool | null | undefined): boolean;
|
|
83
|
+
/**
|
|
84
|
+
* Synchronously configures a per-request `PostgreSQLDataProvider` sharing `existingPool` when
|
|
85
|
+
* global metadata and `LocalCacheManager` are already warm in memory. Returns `false` if any
|
|
86
|
+
* dependency is not yet warm, allowing callers to fall back to async {@link ConfigWithSharedPool}.
|
|
87
|
+
*/
|
|
88
|
+
ConfigureFromGlobalSync(configData: PostgreSQLProviderConfigData, existingPool: pg.Pool): boolean;
|
|
78
89
|
/**
|
|
79
90
|
* Configures this provider to share an existing pool from another PostgreSQLDataProvider.
|
|
80
91
|
* Used for per-request providers that should reuse the primary provider's connection pool.
|
|
@@ -117,6 +128,40 @@ export declare class PostgreSQLDataProvider extends GenericDatabaseProvider impl
|
|
|
117
128
|
* Advisory locks the statement took are released before the connection goes back to the pool.
|
|
118
129
|
*/
|
|
119
130
|
private executeOnOwnConnection;
|
|
131
|
+
/**
|
|
132
|
+
* Executes multiple SQL queries on a single connection and returns an array of result arrays,
|
|
133
|
+
* one per query. Overrides GenericDatabaseProvider.ExecuteSQLBatch to avoid checking out multiple
|
|
134
|
+
* connections from the pool in parallel.
|
|
135
|
+
*
|
|
136
|
+
* - Empty `queries`: returns `[]` immediately without checking out any connection.
|
|
137
|
+
* - Single query: delegates to `ExecuteSQL` and wraps in a single-element array.
|
|
138
|
+
* - Multiple queries without parameters: joins statements with `\n;\n` to prevent trailing `--`
|
|
139
|
+
* comments from swallowing subsequent tokens, executing in a single network round-trip on one
|
|
140
|
+
* connection.
|
|
141
|
+
* - Multiple queries with parameters: executes sequentially on the same checked-out connection.
|
|
142
|
+
* - Always releases checked-out connections in a `finally` block to prevent pool starvation.
|
|
143
|
+
*/
|
|
144
|
+
ExecuteSQLBatch(queries: string[], parameters?: unknown[][] | ExecuteSQLBatchOptions, options?: ExecuteSQLBatchOptions | UserInfo, contextUser?: UserInfo): Promise<Record<string, unknown>[][]>;
|
|
145
|
+
private executeSequentialBatchOnClient;
|
|
146
|
+
private executeMultiStatementBatchOnClient;
|
|
147
|
+
/**
|
|
148
|
+
* Executes server cache status checks for multiple views in a single UNION ALL query
|
|
149
|
+
* over 1 network round-trip instead of K separate pool connections.
|
|
150
|
+
* If any query has bound parameters or the UNION ALL query fails, falls back to the
|
|
151
|
+
* base class per-item execution.
|
|
152
|
+
*/
|
|
153
|
+
protected getBatchedServerCacheStatus(items: Array<{
|
|
154
|
+
index: number;
|
|
155
|
+
item: RunViewWithCacheCheckParams;
|
|
156
|
+
entityInfo: EntityInfo;
|
|
157
|
+
whereSQL: string;
|
|
158
|
+
queryParameters?: NamedQueryParameter[];
|
|
159
|
+
}>, contextUser?: UserInfo): Promise<Map<number, {
|
|
160
|
+
success: boolean;
|
|
161
|
+
maxUpdatedAt?: string;
|
|
162
|
+
rowCount?: number;
|
|
163
|
+
errorMessage?: string;
|
|
164
|
+
}>>;
|
|
120
165
|
/**
|
|
121
166
|
* Describes the result set of `sqlText`: it runs as `SELECT * FROM (<sql>) _q LIMIT 0` on a
|
|
122
167
|
* connection of its own, inside a read-only transaction that is always rolled back, with JIT
|
|
@@ -263,6 +308,13 @@ export declare class PostgreSQLDataProvider extends GenericDatabaseProvider impl
|
|
|
263
308
|
* set explicitly to NULL.
|
|
264
309
|
*/
|
|
265
310
|
protected RenderSaveCallBinding(entity: BaseEntity, fieldValues: Map<EntityFieldInfo, unknown>, isUpdate: boolean, _spName: string): SaveCallBinding;
|
|
311
|
+
/**
|
|
312
|
+
* Reads the target record's physical columns from `"schema"."BaseTable" WHERE ... FOR UPDATE`
|
|
313
|
+
* inside the save transaction so concurrent writers serialize on the row lock before `spUpdate*`
|
|
314
|
+
* executes. Queries `BaseTable` directly because PostgreSQL does not allow `FOR UPDATE` on views
|
|
315
|
+
* containing `LEFT JOIN`s.
|
|
316
|
+
*/
|
|
317
|
+
protected RenderLockedRowReadSQL(entityInfo: EntityInfo, pkWhereClause: string, columns: string[]): string | null;
|
|
266
318
|
/**
|
|
267
319
|
* Wraps a PG binding with the bare `SELECT * FROM schema.fn(...)`
|
|
268
320
|
* result-capture pattern. PG returns the row directly; no
|
|
@@ -288,6 +340,28 @@ export declare class PostgreSQLDataProvider extends GenericDatabaseProvider impl
|
|
|
288
340
|
* returns `returnContext.finalSelectColumnsSQL` from `save_result`.
|
|
289
341
|
*/
|
|
290
342
|
protected WrapSaveCallWithRecordChange(saveSQL: SaveSQLFragment, binding: SaveCallBinding, payload: RecordChangePayload, entity: BaseEntity, options?: EntitySaveOptions, returnContext?: SaveReturnContext): SaveSQLFragment;
|
|
343
|
+
/**
|
|
344
|
+
* True when a save's Record Change snapshot can be built from the row its function returned:
|
|
345
|
+
* `save_result` holds the whole row, because neither the compiled function nor this call
|
|
346
|
+
* returns datestamps only.
|
|
347
|
+
*
|
|
348
|
+
* Built from the returned row, the snapshot holds what the database stored: values another writer
|
|
349
|
+
* committed to columns this save did not change, server-set timestamps and defaults, current
|
|
350
|
+
* joined display values, and encrypted columns as their ciphertext.
|
|
351
|
+
*/
|
|
352
|
+
protected BuildsFullRecordJSONFromResultRow(_entity: BaseEntity, returnContext: SaveReturnContext): boolean;
|
|
353
|
+
/**
|
|
354
|
+
* A scalar subquery rendering the current `rowAlias` row as the snapshot's JSON text, one key per
|
|
355
|
+
* entity field, each column rendered as {@link renderResultRowSnapshotColumn} describes.
|
|
356
|
+
*/
|
|
357
|
+
private renderResultRowSnapshotSQL;
|
|
358
|
+
/**
|
|
359
|
+
* One returned column as the snapshot writes it, matching how a loaded entity serializes the same
|
|
360
|
+
* value: date-times as UTC ISO-8601 with milliseconds and `Z` (MJ's date-time columns are
|
|
361
|
+
* `timestamptz`), `bigint` as a string, `bytea` as base64 rather than `row_to_json`'s `\x` hex,
|
|
362
|
+
* and `json`/`jsonb` and unrecognized types as text rather than nested JSON.
|
|
363
|
+
*/
|
|
364
|
+
private renderResultRowSnapshotColumn;
|
|
291
365
|
/**
|
|
292
366
|
* Generates PostgreSQL function-call SQL for Delete.
|
|
293
367
|
* Returns parameterized SQL with $1, $2, ... placeholders.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PostgreSQLDataProvider.d.ts","sourceRoot":"","sources":["../src/PostgreSQLDataProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACH,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,UAAU,EACV,eAAe,EAEf,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,4BAA4B,EAC5B,UAAU,EACV,gBAAgB,EAChB,aAAa,EACb,eAAe,EAEf,oBAAoB,EACpB,iBAAiB,EAEjB,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,
|
|
1
|
+
{"version":3,"file":"PostgreSQLDataProvider.d.ts","sourceRoot":"","sources":["../src/PostgreSQLDataProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EACH,gBAAgB,EAChB,iBAAiB,EACjB,QAAQ,EACR,UAAU,EACV,eAAe,EAEf,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,4BAA4B,EAC5B,UAAU,EACV,gBAAgB,EAChB,aAAa,EACb,eAAe,EAEf,oBAAoB,EACpB,iBAAiB,EAEjB,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EAGjB,2BAA2B,EAG9B,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACH,uBAAuB,EACvB,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,iBAAiB,EAIjB,sBAAsB,EACtB,mBAAmB,EAEtB,M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,5 @@
|
|
|
1
|
-
import { EntityFieldTSType, ProviderType, CompositeKey, LogError, RunQuerySQLFilterManager, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, } from '@memberjunction/core';
|
|
2
|
-
import { GenericDatabaseProvider, DescribeStatementFailure, SummarizeSqlParameters, FormatSqlParameterTypesForError, } from '@memberjunction/generic-database-provider';
|
|
1
|
+
import { EntityFieldTSType, ProviderType, CompositeKey, LogError, RunQuerySQLFilterManager, GetDiagnosticContext, IsDiagnosticCaptureSuppressed, Metadata, LocalCacheManager, } from '@memberjunction/core';
|
|
2
|
+
import { GenericDatabaseProvider, DescribeStatementFailure, SummarizeSqlParameters, FormatSqlParameterTypesForError, RecordChangeSnapshotColumnKindOf, } from '@memberjunction/generic-database-provider';
|
|
3
3
|
import { DescribeCatalogParameters, DescribeWrapperSQL, FieldDescriptionOf, MapPostgreSQLDescribeFields, POSTGRESQL_DESCRIBE_CATALOG_SQL, POSTGRESQL_DESCRIBE_TIMEOUT_MS, } from './statementDescription.js';
|
|
4
4
|
import { BytesToBase64, EscapeSQLString, IsByteArray, TryBase64ToBytes } from '@memberjunction/global';
|
|
5
5
|
import { PostgreSQLDialect, AutoQuotePostgreSQLIdentifiers } from '@memberjunction/sql-dialect';
|
|
@@ -152,7 +152,6 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
152
152
|
const fkField = relatedEntityInfo.Fields.find(f => f.Name.trim().toLowerCase() === dep.FieldName?.trim().toLowerCase());
|
|
153
153
|
if (fkField?.EntityIDFieldName && fkField.EntityIDFieldName.trim().length > 0)
|
|
154
154
|
continue;
|
|
155
|
-
const quotes = entityInfo.FirstPrimaryKey.NeedsQuotes ? "'" : ''; // first-pk-ok: a foreign key targets a single column; quoting follows that FK target's type
|
|
156
155
|
const pksToProject = relatedEntityInfo.PrimaryKeys?.length ? relatedEntityInfo.PrimaryKeys : entityInfo.PrimaryKeys;
|
|
157
156
|
const pkParts = [];
|
|
158
157
|
for (const pk of pksToProject) {
|
|
@@ -160,8 +159,7 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
160
159
|
}
|
|
161
160
|
const primaryKeySelectString = pkParts.join(" || '" + CompositeKey.DefaultFieldDelimiter + "' || ");
|
|
162
161
|
const sourceObject = this.resolveDependencySourceObject(relatedEntityInfo, [dep.FieldName]);
|
|
163
|
-
const
|
|
164
|
-
const escapedVal = quotes.length > 0 ? rawVal.replace(/'/g, "''") : rawVal;
|
|
162
|
+
const pkLiteral = this.RenderPrimaryKeyLiteral(entityInfo.FirstPrimaryKey, compositeKey.GetValueByIndex(0), entityInfo.Name); // first-pk-ok: a foreign key targets a single column; quoting follows that FK target's type
|
|
165
163
|
if (sSQL.length > 0)
|
|
166
164
|
sSQL += ' UNION ALL ';
|
|
167
165
|
sSQL += 'SELECT '
|
|
@@ -172,7 +170,7 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
172
170
|
+ 'false AS "IsSoftLink", '
|
|
173
171
|
+ 'NULL AS "EntityIDFieldName" '
|
|
174
172
|
+ 'FROM ' + pgDialect.QuoteSchema(relatedEntityInfo.SchemaName, sourceObject) + ' '
|
|
175
|
-
+ 'WHERE ' + pgDialect.QuoteIdentifier(dep.FieldName) + ' = ' +
|
|
173
|
+
+ 'WHERE ' + pgDialect.QuoteIdentifier(dep.FieldName) + ' = ' + pkLiteral;
|
|
176
174
|
}
|
|
177
175
|
return sSQL;
|
|
178
176
|
}
|
|
@@ -279,6 +277,9 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
279
277
|
throw new Error('PostgreSQLDataProvider.CreateIndependentInstance: provider is not configured');
|
|
280
278
|
}
|
|
281
279
|
const cfg = new PostgreSQLProviderConfigData(parent.ConnectionConfig, this.MJCoreSchemaName, 0, parent.IncludeSchemas, parent.ExcludeSchemas, false);
|
|
280
|
+
cfg.ConcurrencyCheck = this.ConcurrencyCheck;
|
|
281
|
+
cfg.DeltaUpdates = this.DeltaUpdates;
|
|
282
|
+
cfg.LoadQueryMetadata = this.LoadsQueryMetadata;
|
|
282
283
|
await child.ConfigWithSharedPool(cfg, this.DatabaseConnection);
|
|
283
284
|
return child;
|
|
284
285
|
}
|
|
@@ -324,6 +325,34 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
324
325
|
&& ka.User === kb.User
|
|
325
326
|
&& ka.Password === kb.Password;
|
|
326
327
|
}
|
|
328
|
+
/**
|
|
329
|
+
* Returns `true` when global metadata and `LocalCacheManager` are warm in memory and `pool`
|
|
330
|
+
* is non-null so {@link ConfigureFromGlobalSync} can configure a per-request provider without I/O.
|
|
331
|
+
*/
|
|
332
|
+
static CanConfigureFromGlobalSync(pool) {
|
|
333
|
+
if (!pool || !Metadata.Provider || !LocalCacheManager.Instance.IsInitialized) { // global-provider-ok: fast-path readiness check for global metadata
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
return (Metadata.Provider.AllMetadata?.AllEntities?.length ?? 0) > 0; // global-provider-ok: verifies global metadata entities are warm
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Synchronously configures a per-request `PostgreSQLDataProvider` sharing `existingPool` when
|
|
340
|
+
* global metadata and `LocalCacheManager` are already warm in memory. Returns `false` if any
|
|
341
|
+
* dependency is not yet warm, allowing callers to fall back to async {@link ConfigWithSharedPool}.
|
|
342
|
+
*/
|
|
343
|
+
ConfigureFromGlobalSync(configData, existingPool) {
|
|
344
|
+
if (!existingPool) {
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
if (!this.ConfigureFromGlobalMetadataSync(configData)) {
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
this._configData = configData;
|
|
351
|
+
this._schemaName = configData.MJCoreSchemaName || '__mj';
|
|
352
|
+
this._connectionManager.InitializeWithExistingPool(existingPool, configData.ConnectionConfig);
|
|
353
|
+
RunQuerySQLFilterManager.Instance.SetPlatform('postgresql');
|
|
354
|
+
return true;
|
|
355
|
+
}
|
|
327
356
|
/**
|
|
328
357
|
* Configures this provider to share an existing pool from another PostgreSQLDataProvider.
|
|
329
358
|
* Used for per-request providers that should reuse the primary provider's connection pool.
|
|
@@ -501,6 +530,237 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
501
530
|
await this.releaseOwnConnection(client);
|
|
502
531
|
}
|
|
503
532
|
}
|
|
533
|
+
/**
|
|
534
|
+
* Executes multiple SQL queries on a single connection and returns an array of result arrays,
|
|
535
|
+
* one per query. Overrides GenericDatabaseProvider.ExecuteSQLBatch to avoid checking out multiple
|
|
536
|
+
* connections from the pool in parallel.
|
|
537
|
+
*
|
|
538
|
+
* - Empty `queries`: returns `[]` immediately without checking out any connection.
|
|
539
|
+
* - Single query: delegates to `ExecuteSQL` and wraps in a single-element array.
|
|
540
|
+
* - Multiple queries without parameters: joins statements with `\n;\n` to prevent trailing `--`
|
|
541
|
+
* comments from swallowing subsequent tokens, executing in a single network round-trip on one
|
|
542
|
+
* connection.
|
|
543
|
+
* - Multiple queries with parameters: executes sequentially on the same checked-out connection.
|
|
544
|
+
* - Always releases checked-out connections in a `finally` block to prevent pool starvation.
|
|
545
|
+
*/
|
|
546
|
+
async ExecuteSQLBatch(queries, parameters, options, contextUser) {
|
|
547
|
+
if (!queries || queries.length === 0) {
|
|
548
|
+
return [];
|
|
549
|
+
}
|
|
550
|
+
let actualParams;
|
|
551
|
+
let actualOptions;
|
|
552
|
+
let actualUser;
|
|
553
|
+
if (Array.isArray(parameters)) {
|
|
554
|
+
actualParams = parameters;
|
|
555
|
+
actualOptions = options;
|
|
556
|
+
actualUser = contextUser;
|
|
557
|
+
}
|
|
558
|
+
else if (parameters && typeof parameters === 'object' && !('length' in parameters)) {
|
|
559
|
+
actualParams = undefined;
|
|
560
|
+
actualOptions = parameters;
|
|
561
|
+
actualUser = options;
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
actualParams = undefined;
|
|
565
|
+
actualOptions = options;
|
|
566
|
+
actualUser = contextUser;
|
|
567
|
+
}
|
|
568
|
+
if (queries.length === 1) {
|
|
569
|
+
const execOptions = actualOptions ? {
|
|
570
|
+
description: actualOptions.description,
|
|
571
|
+
ignoreLogging: actualOptions.ignoreLogging,
|
|
572
|
+
isMutation: actualOptions.isMutation,
|
|
573
|
+
ignoreAmbientTransaction: actualOptions.ignoreAmbientTransaction,
|
|
574
|
+
} : undefined;
|
|
575
|
+
const singleParam = actualParams?.[0];
|
|
576
|
+
const singleResult = await this.ExecuteSQL(queries[0], singleParam, execOptions, actualUser);
|
|
577
|
+
return [singleResult];
|
|
578
|
+
}
|
|
579
|
+
const optionsConnectionSource = actualOptions?.connectionSource;
|
|
580
|
+
const joinsAmbient = !actualOptions?.ignoreAmbientTransaction && this.IsCallerInAmbientTransaction();
|
|
581
|
+
if (joinsAmbient) {
|
|
582
|
+
this.AssertAmbientTransactionUsable();
|
|
583
|
+
}
|
|
584
|
+
let client = null;
|
|
585
|
+
const shouldRelease = !joinsAmbient && !optionsConnectionSource;
|
|
586
|
+
try {
|
|
587
|
+
if (optionsConnectionSource) {
|
|
588
|
+
client = optionsConnectionSource;
|
|
589
|
+
}
|
|
590
|
+
else if (joinsAmbient) {
|
|
591
|
+
client = this._transaction;
|
|
592
|
+
}
|
|
593
|
+
else {
|
|
594
|
+
client = await this._connectionManager.AcquireClient();
|
|
595
|
+
}
|
|
596
|
+
const hasParams = actualParams !== undefined && actualParams.some((p) => p && p.length > 0);
|
|
597
|
+
if (hasParams) {
|
|
598
|
+
return await this.executeSequentialBatchOnClient(client, queries, actualParams, actualOptions, actualUser);
|
|
599
|
+
}
|
|
600
|
+
return await this.executeMultiStatementBatchOnClient(client, queries, actualOptions, actualUser);
|
|
601
|
+
}
|
|
602
|
+
finally {
|
|
603
|
+
if (shouldRelease && client) {
|
|
604
|
+
await this.releaseOwnConnection(client);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
async executeSequentialBatchOnClient(client, queries, parameters, options, contextUser) {
|
|
609
|
+
const results = [];
|
|
610
|
+
for (let i = 0; i < queries.length; i++) {
|
|
611
|
+
const q = queries[i];
|
|
612
|
+
const p = parameters?.[i];
|
|
613
|
+
const quotedQuery = this.AutoQuoteIdentifiers(q);
|
|
614
|
+
const processedParams = PGQueryParameterProcessor.ProcessParameters(p);
|
|
615
|
+
const execOptions = options ? {
|
|
616
|
+
description: options.description ? `${options.description} [${i + 1}/${queries.length}]` : undefined,
|
|
617
|
+
ignoreLogging: options.ignoreLogging,
|
|
618
|
+
isMutation: options.isMutation,
|
|
619
|
+
ignoreAmbientTransaction: options.ignoreAmbientTransaction,
|
|
620
|
+
} : undefined;
|
|
621
|
+
const rows = await this.ExecuteObservedQuery(client, quotedQuery, processedParams, execOptions, contextUser);
|
|
622
|
+
results.push(rows);
|
|
623
|
+
}
|
|
624
|
+
return results;
|
|
625
|
+
}
|
|
626
|
+
async executeMultiStatementBatchOnClient(client, queries, options, contextUser) {
|
|
627
|
+
const quotedQueries = queries.map((q) => this.AutoQuoteIdentifiers(q));
|
|
628
|
+
const formattedQueries = quotedQueries.map((q) => {
|
|
629
|
+
const trimmed = q.trim();
|
|
630
|
+
return trimmed.endsWith(';') ? `${trimmed}\n` : `${trimmed}\n;\n`;
|
|
631
|
+
});
|
|
632
|
+
const combinedSql = formattedQueries.join('');
|
|
633
|
+
const startTime = performance.now();
|
|
634
|
+
try {
|
|
635
|
+
const rawResult = await client.query(combinedSql);
|
|
636
|
+
const durationMs = performance.now() - startTime;
|
|
637
|
+
const resultSets = Array.isArray(rawResult)
|
|
638
|
+
? rawResult
|
|
639
|
+
: [rawResult];
|
|
640
|
+
const totalRowCount = resultSets.reduce((sum, r) => sum + (Array.isArray(r?.rows) ? r.rows.length : (typeof r?.rowCount === 'number' ? r.rowCount : 0)), 0);
|
|
641
|
+
if (!options?.ignoreLogging && !IsDiagnosticCaptureSuppressed() && GenericDatabaseProvider.HasSqlObservers()) {
|
|
642
|
+
GenericDatabaseProvider.NotifySqlObservers({
|
|
643
|
+
ts: Date.now(),
|
|
644
|
+
sql: combinedSql,
|
|
645
|
+
parameterSummaries: [],
|
|
646
|
+
durationMs,
|
|
647
|
+
rowCount: totalRowCount,
|
|
648
|
+
isMutation: options?.isMutation ?? false,
|
|
649
|
+
description: options?.description ?? 'ExecuteSQLBatch',
|
|
650
|
+
diagnosticContext: GetDiagnosticContext(),
|
|
651
|
+
ignoreLogging: options?.ignoreLogging,
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
if (!options?.ignoreLogging && this.HasActiveSqlLoggingSessions) {
|
|
655
|
+
await this._logSqlStatement(combinedSql, undefined, options?.description ?? 'ExecuteSQLBatch', options?.ignoreLogging ?? false, options?.isMutation ?? false, undefined, contextUser);
|
|
656
|
+
}
|
|
657
|
+
if (Array.isArray(rawResult)) {
|
|
658
|
+
return resultSets.map((r) => (r?.rows ?? []));
|
|
659
|
+
}
|
|
660
|
+
return queries.map(() => (resultSets[0]?.rows ?? []));
|
|
661
|
+
}
|
|
662
|
+
catch (err) {
|
|
663
|
+
const durationMs = performance.now() - startTime;
|
|
664
|
+
if (!options?.ignoreLogging && !IsDiagnosticCaptureSuppressed() && GenericDatabaseProvider.HasSqlObservers()) {
|
|
665
|
+
GenericDatabaseProvider.NotifySqlObservers({
|
|
666
|
+
ts: Date.now(),
|
|
667
|
+
sql: combinedSql,
|
|
668
|
+
parameterSummaries: [],
|
|
669
|
+
durationMs,
|
|
670
|
+
rowCount: 0,
|
|
671
|
+
isMutation: options?.isMutation ?? false,
|
|
672
|
+
errorMessage: err instanceof Error ? err.message : String(err),
|
|
673
|
+
description: options?.description ?? 'ExecuteSQLBatch',
|
|
674
|
+
diagnosticContext: GetDiagnosticContext(),
|
|
675
|
+
ignoreLogging: options?.ignoreLogging,
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
const desc = options?.description ? ` [${options.description}]` : '';
|
|
679
|
+
LogError(`PostgreSQLDataProvider.ExecuteSQLBatch failed${desc}: ${err instanceof Error ? err.message : String(err)}`);
|
|
680
|
+
throw err;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Executes server cache status checks for multiple views in a single UNION ALL query
|
|
685
|
+
* over 1 network round-trip instead of K separate pool connections.
|
|
686
|
+
* If any query has bound parameters or the UNION ALL query fails, falls back to the
|
|
687
|
+
* base class per-item execution.
|
|
688
|
+
*/
|
|
689
|
+
async getBatchedServerCacheStatus(items, contextUser) {
|
|
690
|
+
const results = new Map();
|
|
691
|
+
if (!items || items.length === 0) {
|
|
692
|
+
return results;
|
|
693
|
+
}
|
|
694
|
+
// Parameterized cache status queries fall back to individual execution
|
|
695
|
+
if (items.some((it) => it.queryParameters && it.queryParameters.length > 0)) {
|
|
696
|
+
return await super.getBatchedServerCacheStatus(items, contextUser);
|
|
697
|
+
}
|
|
698
|
+
const validItems = [];
|
|
699
|
+
for (const entry of items) {
|
|
700
|
+
const { index, item, entityInfo, whereSQL } = entry;
|
|
701
|
+
try {
|
|
702
|
+
const effectiveTarget = await this.resolveEffectiveBaseViewTarget(entityInfo, item.params, contextUser);
|
|
703
|
+
validItems.push({
|
|
704
|
+
index,
|
|
705
|
+
entityInfo,
|
|
706
|
+
effectiveTarget,
|
|
707
|
+
whereSQL,
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
catch (err) {
|
|
711
|
+
results.set(index, {
|
|
712
|
+
success: false,
|
|
713
|
+
errorMessage: err instanceof Error ? err.message : String(err),
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
if (validItems.length === 0) {
|
|
718
|
+
return results;
|
|
719
|
+
}
|
|
720
|
+
const branches = validItems.map(({ index, entityInfo, effectiveTarget, whereSQL }) => {
|
|
721
|
+
const schema = effectiveTarget.schemaName || entityInfo.SchemaName || this._schemaName;
|
|
722
|
+
const view = effectiveTarget.viewName;
|
|
723
|
+
const from = `FROM ${this.QuoteSchemaAndView(schema, view)}${whereSQL ? ' WHERE ' + whereSQL : ''}`;
|
|
724
|
+
const hasUpdatedAt = entityInfo.Fields?.some((f) => f.IsUpdatedAtField);
|
|
725
|
+
const maxUpdatedCol = hasUpdatedAt
|
|
726
|
+
? `MAX(${this.QuoteIdentifier('__mj_UpdatedAt')})::timestamptz`
|
|
727
|
+
: 'CAST(NULL AS timestamptz)';
|
|
728
|
+
return `SELECT ${index} AS "ItemIndex", COUNT(*) AS "TotalRows", ${maxUpdatedCol} AS "MaxUpdatedAt" ${from}`;
|
|
729
|
+
});
|
|
730
|
+
const unionSql = branches.map((b) => `(${b})`).join('\nUNION ALL\n');
|
|
731
|
+
try {
|
|
732
|
+
const rows = await this.ExecuteSQL(unionSql, undefined, { description: 'Batched server cache status check', ignoreLogging: true }, contextUser);
|
|
733
|
+
const rowMap = new Map();
|
|
734
|
+
for (const row of rows) {
|
|
735
|
+
const idx = Number(row['ItemIndex']);
|
|
736
|
+
rowMap.set(idx, row);
|
|
737
|
+
}
|
|
738
|
+
for (const { index } of validItems) {
|
|
739
|
+
const row = rowMap.get(index);
|
|
740
|
+
if (row) {
|
|
741
|
+
const totalRows = Number(row['TotalRows'] ?? 0);
|
|
742
|
+
const rawUpdatedAt = row['MaxUpdatedAt'];
|
|
743
|
+
const maxUpdatedAt = rawUpdatedAt
|
|
744
|
+
? new Date(rawUpdatedAt).toISOString()
|
|
745
|
+
: undefined;
|
|
746
|
+
results.set(index, {
|
|
747
|
+
success: true,
|
|
748
|
+
rowCount: totalRows,
|
|
749
|
+
maxUpdatedAt,
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
results.set(index, { success: true, rowCount: 0, maxUpdatedAt: undefined });
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
catch {
|
|
758
|
+
// One bad view or error fails the UNION ALL batch.
|
|
759
|
+
// Fall back to super (individual queries) so a single bad entity doesn't break the entire sweep.
|
|
760
|
+
return await super.getBatchedServerCacheStatus(items, contextUser);
|
|
761
|
+
}
|
|
762
|
+
return results;
|
|
763
|
+
}
|
|
504
764
|
/**
|
|
505
765
|
* Describes the result set of `sqlText`: it runs as `SELECT * FROM (<sql>) _q LIMIT 0` on a
|
|
506
766
|
* connection of its own, inside a read-only transaction that is always rolled back, with JIT
|
|
@@ -1029,6 +1289,20 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
1029
1289
|
values,
|
|
1030
1290
|
};
|
|
1031
1291
|
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Reads the target record's physical columns from `"schema"."BaseTable" WHERE ... FOR UPDATE`
|
|
1294
|
+
* inside the save transaction so concurrent writers serialize on the row lock before `spUpdate*`
|
|
1295
|
+
* executes. Queries `BaseTable` directly because PostgreSQL does not allow `FOR UPDATE` on views
|
|
1296
|
+
* containing `LEFT JOIN`s.
|
|
1297
|
+
*/
|
|
1298
|
+
RenderLockedRowReadSQL(entityInfo, pkWhereClause, columns) {
|
|
1299
|
+
if (columns.length === 0 || !pkWhereClause || !entityInfo.BaseTable) {
|
|
1300
|
+
return null;
|
|
1301
|
+
}
|
|
1302
|
+
const selectCols = columns.map((c) => this.QuoteIdentifier(c)).join(', ');
|
|
1303
|
+
const tableRef = this.QuoteSchemaAndView(entityInfo.SchemaName, entityInfo.BaseTable);
|
|
1304
|
+
return `SELECT ${selectCols} FROM ${tableRef} WHERE ${pkWhereClause} FOR UPDATE`;
|
|
1305
|
+
}
|
|
1032
1306
|
/**
|
|
1033
1307
|
* Wraps a PG binding with the bare `SELECT * FROM schema.fn(...)`
|
|
1034
1308
|
* result-capture pattern. PG returns the row directly; no
|
|
@@ -1077,36 +1351,86 @@ export class PostgreSQLDataProvider extends GenericDatabaseProvider {
|
|
|
1077
1351
|
throw new Error(`PostgreSQLDataProvider.WrapSaveCallWithRecordChange: unexpected binding kind '${binding.kind}'`);
|
|
1078
1352
|
}
|
|
1079
1353
|
const resolvedReturn = returnContext ?? this.ResolveSaveReturnContext(entity, options);
|
|
1080
|
-
const
|
|
1354
|
+
const parameters = [...(saveSQL.parameters ?? [])];
|
|
1355
|
+
const bind = (value, cast) => {
|
|
1356
|
+
parameters.push(value);
|
|
1357
|
+
return `$${parameters.length}::${cast}`;
|
|
1358
|
+
};
|
|
1081
1359
|
const recordIDExpr = this.buildRecordIDFromCTE(entity.EntityInfo, 'save_result');
|
|
1082
|
-
const
|
|
1083
|
-
const
|
|
1360
|
+
const entityIDSQL = bind(payload.entityID, 'uuid');
|
|
1361
|
+
const userIDSQL = bind(payload.userID, 'uuid');
|
|
1362
|
+
const typeSQL = bind(payload.type, 'varchar');
|
|
1363
|
+
const sourceSQL = bind(payload.source, 'varchar');
|
|
1364
|
+
const changesJSONSQL = bind(payload.changesJSON, 'text');
|
|
1365
|
+
const changesDescriptionSQL = bind(payload.changesDescription, 'text');
|
|
1366
|
+
// The snapshot is the row the function returned, when save_result holds the whole row;
|
|
1367
|
+
// otherwise the payload's in-memory snapshot.
|
|
1368
|
+
const fullRecordJSONSQL = this.BuildsFullRecordJSONFromResultRow(entity, resolvedReturn)
|
|
1369
|
+
? this.renderResultRowSnapshotSQL(entity.EntityInfo, 'save_result')
|
|
1370
|
+
: bind(payload.fullRecordJSON, 'text');
|
|
1371
|
+
const restoredFromIDSQL = bind(payload.restoredFromID, 'uuid');
|
|
1372
|
+
const restoreReasonSQL = bind(payload.restoreReason, 'text');
|
|
1373
|
+
const cc = changeContextSQL(payload.changeContext, parameters.length + 1);
|
|
1374
|
+
parameters.push(...cc.parameters);
|
|
1084
1375
|
const fullSQL = `WITH save_result AS (
|
|
1085
1376
|
${saveSQL.sql}
|
|
1086
1377
|
),
|
|
1087
1378
|
record_change AS (
|
|
1088
1379
|
INSERT INTO ${this._schemaName}."RecordChange"
|
|
1089
1380
|
("EntityID", "RecordID", "UserID", "Type", "Source", "ChangesJSON", "ChangesDescription", "FullRecordJSON", "Status", "RestoredFromID", "RestoreReason"${cc.column})
|
|
1090
|
-
SELECT
|
|
1381
|
+
SELECT ${entityIDSQL}, ${recordIDExpr}, ${userIDSQL}, ${typeSQL}, ${sourceSQL}, ${changesJSONSQL}, ${changesDescriptionSQL}, ${fullRecordJSONSQL}, 'Complete', ${restoredFromIDSQL}, ${restoreReasonSQL}${cc.value}
|
|
1091
1382
|
FROM save_result
|
|
1092
1383
|
RETURNING "ID"
|
|
1093
1384
|
)
|
|
1094
1385
|
SELECT ${resolvedReturn.finalSelectColumnsSQL} FROM save_result`;
|
|
1095
|
-
const parameters = [
|
|
1096
|
-
...baseValues,
|
|
1097
|
-
payload.entityID,
|
|
1098
|
-
payload.userID,
|
|
1099
|
-
payload.type,
|
|
1100
|
-
payload.source,
|
|
1101
|
-
payload.changesJSON,
|
|
1102
|
-
payload.changesDescription,
|
|
1103
|
-
payload.fullRecordJSON,
|
|
1104
|
-
payload.restoredFromID,
|
|
1105
|
-
payload.restoreReason,
|
|
1106
|
-
...cc.parameters,
|
|
1107
|
-
];
|
|
1108
1386
|
return { sql: fullSQL, parameters };
|
|
1109
1387
|
}
|
|
1388
|
+
/**
|
|
1389
|
+
* True when a save's Record Change snapshot can be built from the row its function returned:
|
|
1390
|
+
* `save_result` holds the whole row, because neither the compiled function nor this call
|
|
1391
|
+
* returns datestamps only.
|
|
1392
|
+
*
|
|
1393
|
+
* Built from the returned row, the snapshot holds what the database stored: values another writer
|
|
1394
|
+
* committed to columns this save did not change, server-set timestamps and defaults, current
|
|
1395
|
+
* joined display values, and encrypted columns as their ciphertext.
|
|
1396
|
+
*/
|
|
1397
|
+
BuildsFullRecordJSONFromResultRow(_entity, returnContext) {
|
|
1398
|
+
return !returnContext.spReturnsDatestampsOnly && !returnContext.needsDatestampProjection;
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* A scalar subquery rendering the current `rowAlias` row as the snapshot's JSON text, one key per
|
|
1402
|
+
* entity field, each column rendered as {@link renderResultRowSnapshotColumn} describes.
|
|
1403
|
+
*/
|
|
1404
|
+
renderResultRowSnapshotSQL(entityInfo, rowAlias) {
|
|
1405
|
+
const columns = entityInfo.Fields.map((f) => `${this.renderResultRowSnapshotColumn(f, `${rowAlias}.${this.QuoteIdentifier(f.Name)}`)} AS ${this.QuoteIdentifier(f.Name)}`);
|
|
1406
|
+
return `(SELECT row_to_json(snapshot_row)::text FROM (SELECT ${columns.join(', ')}) snapshot_row)`;
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* One returned column as the snapshot writes it, matching how a loaded entity serializes the same
|
|
1410
|
+
* value: date-times as UTC ISO-8601 with milliseconds and `Z` (MJ's date-time columns are
|
|
1411
|
+
* `timestamptz`), `bigint` as a string, `bytea` as base64 rather than `row_to_json`'s `\x` hex,
|
|
1412
|
+
* and `json`/`jsonb` and unrecognized types as text rather than nested JSON.
|
|
1413
|
+
*/
|
|
1414
|
+
renderResultRowSnapshotColumn(field, col) {
|
|
1415
|
+
switch (RecordChangeSnapshotColumnKindOf(field.Type, 'postgresql')) {
|
|
1416
|
+
case 'utc-datetime':
|
|
1417
|
+
case 'offset-datetime':
|
|
1418
|
+
return `to_char(${col} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
|
|
1419
|
+
case 'date':
|
|
1420
|
+
return `to_char(${col}, 'YYYY-MM-DD') || 'T00:00:00.000Z'`;
|
|
1421
|
+
case 'time':
|
|
1422
|
+
return `'1970-01-01T' || to_char(${col}, 'HH24:MI:SS.MS') || 'Z'`;
|
|
1423
|
+
case 'binary':
|
|
1424
|
+
return `translate(encode(${col}, 'base64'), E'\\n', '')`;
|
|
1425
|
+
case 'bigint':
|
|
1426
|
+
case 'json':
|
|
1427
|
+
case 'clr':
|
|
1428
|
+
case 'text':
|
|
1429
|
+
return `(${col})::text`;
|
|
1430
|
+
default:
|
|
1431
|
+
return col;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1110
1434
|
/**
|
|
1111
1435
|
* Generates PostgreSQL function-call SQL for Delete.
|
|
1112
1436
|
* Returns parameterized SQL with $1, $2, ... placeholders.
|
|
@@ -1301,12 +1625,16 @@ SELECT * FROM delete_result`;
|
|
|
1301
1625
|
// Negative lookahead: don't quote words followed by ( — those are function calls
|
|
1302
1626
|
// (e.g., LENGTH(...), LEFT(...)), not column references. Without this, a field
|
|
1303
1627
|
// named "Length" causes LENGTH() to be quoted as "Length"() which PG can't resolve.
|
|
1628
|
+
// Negative lookbehind (?<!\$): don't quote $1 parameter tokens whose identifier
|
|
1629
|
+
// part might match a numeric/field pattern (BindExtraFilterParameters rewrites
|
|
1630
|
+
// @paramName to $1 before TransformExternalSQLClause runs; on PostgreSQL, @ is the
|
|
1631
|
+
// unary absolute-value operator, so @FieldName must still quote "FieldName").
|
|
1304
1632
|
// `fieldName` is escaped before interpolation: PostgreSQL identifiers may
|
|
1305
1633
|
// legally contain regex metacharacters (`$`, `(`, `.`), and injecting one
|
|
1306
1634
|
// raw built a pattern that either matched nothing — a `$` became an
|
|
1307
1635
|
// end-anchor, so `a$$b` was never quoted at all — or matched the wrong
|
|
1308
1636
|
// text. Discovered alongside issue #3171.
|
|
1309
|
-
const re = new RegExp(
|
|
1637
|
+
const re = new RegExp(`(?<!\\$)\\b${escapeRegExp(fieldName)}\\b(?!\\s*\\()`, 'gi');
|
|
1310
1638
|
// Function replacement, for the same reason on the other side: a quoted
|
|
1311
1639
|
// identifier containing `$` would be expanded by a string replacement.
|
|
1312
1640
|
const quoted = pgDialect.QuoteIdentifier(fieldName);
|