@warlock.js/cascade 4.6.0 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/cjs/index.cjs +372 -56
- package/cjs/index.cjs.map +1 -1
- package/esm/contracts/database-driver.contract.d.mts +8 -0
- package/esm/contracts/database-driver.contract.d.mts.map +1 -1
- package/esm/contracts/index.d.mts +1 -1
- package/esm/contracts/query-builder.contract.d.mts +36 -1
- package/esm/contracts/query-builder.contract.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.d.mts +5 -0
- package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-driver.mjs +10 -4
- package/esm/drivers/mongodb/mongodb-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +4 -0
- package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs +5 -2
- package/esm/drivers/mongodb/mongodb-migration-driver.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts +15 -0
- package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-builder.mjs +24 -0
- package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts +16 -0
- package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs +33 -1
- package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-driver.d.mts +69 -13
- package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-driver.mjs +155 -27
- package/esm/drivers/postgres/postgres-driver.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.d.mts +14 -3
- package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-builder.mjs +44 -8
- package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts +6 -1
- package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
- package/esm/drivers/postgres/postgres-query-parser.mjs +13 -0
- package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
- package/esm/drivers/postgres/postgres-sql-serializer.mjs +15 -4
- package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/migration/migration-runner.d.mts.map +1 -1
- package/esm/migration/migration-runner.mjs +25 -3
- package/esm/migration/migration-runner.mjs.map +1 -1
- package/esm/migration/migration.d.mts +6 -3
- package/esm/migration/migration.d.mts.map +1 -1
- package/esm/migration/migration.mjs +6 -3
- package/esm/migration/migration.mjs.map +1 -1
- package/esm/model/methods/scope-methods.mjs +18 -4
- package/esm/model/methods/scope-methods.mjs.map +1 -1
- package/esm/model/model.d.mts +6 -0
- package/esm/model/model.d.mts.map +1 -1
- package/esm/model/model.mjs +6 -0
- package/esm/model/model.mjs.map +1 -1
- package/esm/query-builder/query-builder.d.mts +12 -1
- package/esm/query-builder/query-builder.d.mts.map +1 -1
- package/esm/query-builder/query-builder.mjs +19 -0
- package/esm/query-builder/query-builder.mjs.map +1 -1
- package/llms-full.txt +41 -7
- package/llms.txt +1 -1
- package/package.json +4 -4
- package/skills/README.md +1 -1
- package/skills/manage-transactions/SKILL.md +41 -7
|
@@ -125,13 +125,22 @@ var PostgresDriver = class {
|
|
|
125
125
|
*/
|
|
126
126
|
_syncAdapter;
|
|
127
127
|
/**
|
|
128
|
-
*
|
|
129
|
-
* (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text
|
|
128
|
+
* Explicit, table-agnostic override list of column names that hold native
|
|
129
|
+
* PostgreSQL arrays (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text
|
|
130
|
+
* encoded. Merged with (and superseded per-table by) the schema
|
|
131
|
+
* introspection below; kept as a manual escape hatch.
|
|
130
132
|
*
|
|
131
133
|
* @see PostgresPoolConfig.nativeArrayColumns
|
|
132
134
|
*/
|
|
133
135
|
_nativeArrayColumns;
|
|
134
136
|
/**
|
|
137
|
+
* Native-array columns discovered by introspecting the live schema on
|
|
138
|
+
* connect, keyed `table → { column, … }`. Authoritative and table-scoped, so
|
|
139
|
+
* a column that is `TEXT[]` in one table and `jsonb` in another is encoded
|
|
140
|
+
* correctly for each — no app configuration required.
|
|
141
|
+
*/
|
|
142
|
+
_introspectedArrayColumns = /* @__PURE__ */ new Map();
|
|
143
|
+
/**
|
|
135
144
|
* Create a new PostgreSQL driver instance.
|
|
136
145
|
*
|
|
137
146
|
* @param config - PostgreSQL connection configuration
|
|
@@ -197,6 +206,7 @@ var PostgresDriver = class {
|
|
|
197
206
|
(await this._pool.connect()).release();
|
|
198
207
|
log.success("database.postgres", "connection", `Connected to database ${colors.bold(colors.yellowBright(this.config.database))}`);
|
|
199
208
|
this._isConnected = true;
|
|
209
|
+
await this.loadNativeArrayColumns();
|
|
200
210
|
this.emit("connected");
|
|
201
211
|
} catch (error) {
|
|
202
212
|
log.fatal("database.postgres", "connection", "Failed to connect to database");
|
|
@@ -233,13 +243,15 @@ var PostgresDriver = class {
|
|
|
233
243
|
* that need special handling for PostgreSQL storage.
|
|
234
244
|
*
|
|
235
245
|
* @param data - The data object to serialize
|
|
246
|
+
* @param table - Optional table name; when given, columns introspected as
|
|
247
|
+
* native arrays on that table are bound raw (see {@link serializeValue}).
|
|
236
248
|
* @returns Serialized data ready for PostgreSQL
|
|
237
249
|
*/
|
|
238
|
-
serialize(data) {
|
|
250
|
+
serialize(data, table) {
|
|
239
251
|
const serialized = {};
|
|
240
252
|
for (const [key, value] of Object.entries(data)) {
|
|
241
253
|
if (value === void 0) continue;
|
|
242
|
-
serialized[key] = this.serializeValue(key, value);
|
|
254
|
+
serialized[key] = this.serializeValue(key, value, table);
|
|
243
255
|
}
|
|
244
256
|
return serialized;
|
|
245
257
|
}
|
|
@@ -259,36 +271,87 @@ var PostgresDriver = class {
|
|
|
259
271
|
* `JSON.stringify`. node-pg renders a raw JS array as a PostgreSQL array
|
|
260
272
|
* literal `{...}` (and `[]` as `{}`), which a `json` / `jsonb` column
|
|
261
273
|
* rejects — so we bind the value as JSON text instead, the form those
|
|
262
|
-
* columns accept. Columns
|
|
263
|
-
*
|
|
264
|
-
*
|
|
274
|
+
* columns accept. Columns known to be native arrays — via schema
|
|
275
|
+
* introspection or the `nativeArrayColumns` config — are exempt: their raw
|
|
276
|
+
* array is passed through so node-pg emits the `{...}` literal a genuine
|
|
277
|
+
* `JSONB[]` / `TEXT[]` column needs.
|
|
265
278
|
* - plain object → `JSON.stringify`. Equivalent to node-pg's own object
|
|
266
279
|
* handling, made explicit so both write paths agree.
|
|
267
280
|
* - everything else (scalars: string, number, boolean, null) → untouched.
|
|
268
281
|
*
|
|
269
|
-
*
|
|
270
|
-
*
|
|
271
|
-
*
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
282
|
+
* Distinguishing native-array from `json` / `jsonb` columns: a value alone
|
|
283
|
+
* can't tell them apart, so the driver introspects the live schema on connect
|
|
284
|
+
* (see {@link loadNativeArrayColumns}) and consults that per-table map here
|
|
285
|
+
* via {@link isNativeArrayColumn}. The explicit `nativeArrayColumns` config
|
|
286
|
+
* still works as a table-agnostic override. No `::jsonb` placeholder cast is
|
|
287
|
+
* added: a JSON-text string binds correctly to `json` / `jsonb` without one,
|
|
288
|
+
* and a blind cast would misfire on columns we cannot positively identify as
|
|
289
|
+
* jsonb.
|
|
275
290
|
*
|
|
276
|
-
* @param key - Column name (used to
|
|
291
|
+
* @param key - Column name (used to resolve native-array columns)
|
|
277
292
|
* @param value - The raw value to serialize (never `undefined`)
|
|
293
|
+
* @param table - Optional table name; enables the per-table native-array lookup
|
|
278
294
|
* @returns The value ready to bind as a query parameter
|
|
279
295
|
*/
|
|
280
|
-
serializeValue(key, value) {
|
|
296
|
+
serializeValue(key, value, table) {
|
|
281
297
|
if (value instanceof Date) return value.toISOString();
|
|
282
298
|
if (typeof value === "bigint") return value.toString();
|
|
283
299
|
if (Array.isArray(value)) {
|
|
284
300
|
if (value.length > 0 && value.every((v) => typeof v === "number")) return `[${value.join(",")}]`;
|
|
285
|
-
if (this.
|
|
301
|
+
if (this.isNativeArrayColumn(table, key)) return value;
|
|
286
302
|
return JSON.stringify(value);
|
|
287
303
|
}
|
|
288
304
|
if (typeof value === "object" && value !== null) return JSON.stringify(value);
|
|
289
305
|
return value;
|
|
290
306
|
}
|
|
291
307
|
/**
|
|
308
|
+
* Whether `column` on `table` is a native PostgreSQL array. True when the
|
|
309
|
+
* connect-time schema introspection saw it as `data_type = 'ARRAY'` for that
|
|
310
|
+
* table (authoritative, per-table), or when it's listed in the table-agnostic
|
|
311
|
+
* `nativeArrayColumns` config override.
|
|
312
|
+
*/
|
|
313
|
+
isNativeArrayColumn(table, column) {
|
|
314
|
+
if (table && this._introspectedArrayColumns.get(table)?.has(column)) return true;
|
|
315
|
+
return this._nativeArrayColumns.has(column);
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Introspect the live schema for native-array columns so array values bind
|
|
319
|
+
* correctly with zero app configuration.
|
|
320
|
+
*
|
|
321
|
+
* A JS array must be bound two opposite ways depending on the column: as JSON
|
|
322
|
+
* text for a `json` / `jsonb` column, but as a raw array (which node-pg
|
|
323
|
+
* renders `{...}`) for a native `TEXT[]` / `JSONB[]` / `INTEGER[]` column. The
|
|
324
|
+
* serializer sees values, not types, so without this it JSON-stringifies
|
|
325
|
+
* every array — which a native-array column rejects with "malformed array
|
|
326
|
+
* literal". One `information_schema` query at connect, cached for the
|
|
327
|
+
* connection lifetime, removes the need to hand-list `nativeArrayColumns`.
|
|
328
|
+
*
|
|
329
|
+
* Best-effort: any failure (e.g. restricted catalog access) is logged and
|
|
330
|
+
* leaves the map empty so the config override still applies — it never blocks
|
|
331
|
+
* connect. A schema change made within a live connection isn't reflected
|
|
332
|
+
* until the next connect.
|
|
333
|
+
*/
|
|
334
|
+
async loadNativeArrayColumns() {
|
|
335
|
+
try {
|
|
336
|
+
const result = await this.query(`SELECT table_name, column_name
|
|
337
|
+
FROM information_schema.columns
|
|
338
|
+
WHERE table_schema = ANY (current_schemas(false))
|
|
339
|
+
AND data_type = 'ARRAY'`);
|
|
340
|
+
const map = /* @__PURE__ */ new Map();
|
|
341
|
+
for (const { table_name, column_name } of result.rows) {
|
|
342
|
+
let columns = map.get(table_name);
|
|
343
|
+
if (!columns) {
|
|
344
|
+
columns = /* @__PURE__ */ new Set();
|
|
345
|
+
map.set(table_name, columns);
|
|
346
|
+
}
|
|
347
|
+
columns.add(column_name);
|
|
348
|
+
}
|
|
349
|
+
this._introspectedArrayColumns = map;
|
|
350
|
+
} catch {
|
|
351
|
+
log.warn("database.postgres", "introspection", "Could not introspect native-array columns; using the nativeArrayColumns config only");
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
292
355
|
* Get the dirty tracker for this driver.
|
|
293
356
|
*/
|
|
294
357
|
getDirtyTracker(data) {
|
|
@@ -337,7 +400,7 @@ var PostgresDriver = class {
|
|
|
337
400
|
* @returns The inserted document
|
|
338
401
|
*/
|
|
339
402
|
async insert(table, document, _options) {
|
|
340
|
-
const serialized = this.serialize(document);
|
|
403
|
+
const serialized = this.serialize(document, table);
|
|
341
404
|
const filteredData = Object.fromEntries(Object.entries(serialized).filter(([key, value]) => {
|
|
342
405
|
if (key === "id" && (value === null || value === void 0)) return false;
|
|
343
406
|
return true;
|
|
@@ -364,7 +427,7 @@ var PostgresDriver = class {
|
|
|
364
427
|
if (documents.length === 0) return [];
|
|
365
428
|
const allColumns = /* @__PURE__ */ new Set();
|
|
366
429
|
for (const doc of documents) {
|
|
367
|
-
const serialized = this.serialize(doc);
|
|
430
|
+
const serialized = this.serialize(doc, table);
|
|
368
431
|
Object.keys(serialized).forEach((key) => allColumns.add(key));
|
|
369
432
|
}
|
|
370
433
|
const columns = Array.from(allColumns);
|
|
@@ -374,7 +437,7 @@ var PostgresDriver = class {
|
|
|
374
437
|
const params = [];
|
|
375
438
|
let paramIndex = 1;
|
|
376
439
|
for (const doc of documents) {
|
|
377
|
-
const serialized = this.serialize(doc);
|
|
440
|
+
const serialized = this.serialize(doc, table);
|
|
378
441
|
const rowPlaceholders = [];
|
|
379
442
|
for (const col of columns) if (col in serialized) {
|
|
380
443
|
rowPlaceholders.push(this.dialect.placeholder(paramIndex++));
|
|
@@ -441,7 +504,7 @@ var PostgresDriver = class {
|
|
|
441
504
|
* @returns The replaced document or null
|
|
442
505
|
*/
|
|
443
506
|
async replace(table, filter, document, _options) {
|
|
444
|
-
const serialized = this.serialize(document);
|
|
507
|
+
const serialized = this.serialize(document, table);
|
|
445
508
|
const columns = Object.keys(serialized);
|
|
446
509
|
const values = Object.values(serialized);
|
|
447
510
|
const quotedTable = this.dialect.quoteIdentifier(table);
|
|
@@ -463,7 +526,7 @@ var PostgresDriver = class {
|
|
|
463
526
|
* @returns The upserted row
|
|
464
527
|
*/
|
|
465
528
|
async upsert(table, filter, document, options) {
|
|
466
|
-
const serialized = this.serialize(document);
|
|
529
|
+
const serialized = this.serialize(document, table);
|
|
467
530
|
const columns = Object.keys(serialized);
|
|
468
531
|
const values = Object.values(serialized);
|
|
469
532
|
if (columns.length === 0) throw new Error("Cannot upsert empty document");
|
|
@@ -589,13 +652,14 @@ var PostgresDriver = class {
|
|
|
589
652
|
* @throws {Error} If transaction fails or is explicitly rolled back
|
|
590
653
|
*/
|
|
591
654
|
async transaction(fn, options) {
|
|
592
|
-
|
|
655
|
+
const ctx = { rollback(reason) {
|
|
656
|
+
throw new TransactionRollbackError(reason);
|
|
657
|
+
} };
|
|
658
|
+
if (databaseTransactionContext.hasActiveTransaction()) return fn(ctx);
|
|
593
659
|
const tx = await this.beginTransaction(options);
|
|
594
660
|
databaseTransactionContext.enter({ session: tx.context });
|
|
595
661
|
try {
|
|
596
|
-
const result = await fn(
|
|
597
|
-
throw new TransactionRollbackError(reason);
|
|
598
|
-
} });
|
|
662
|
+
const result = await fn(ctx);
|
|
599
663
|
await tx.commit();
|
|
600
664
|
return result;
|
|
601
665
|
} catch (error) {
|
|
@@ -610,6 +674,9 @@ var PostgresDriver = class {
|
|
|
610
674
|
* Perform an atomic update operation.
|
|
611
675
|
*
|
|
612
676
|
* Builds and executes an UPDATE query for the given filter and operations.
|
|
677
|
+
* Updates EVERY matching row — the MongoDB driver's atomic() delegates to
|
|
678
|
+
* updateMany, and Model.findAndUpdate documents multi-row semantics, so the
|
|
679
|
+
* two drivers must agree.
|
|
613
680
|
*
|
|
614
681
|
* @param table - Target table name
|
|
615
682
|
* @param filter - Filter conditions
|
|
@@ -618,7 +685,7 @@ var PostgresDriver = class {
|
|
|
618
685
|
* @returns Update result
|
|
619
686
|
*/
|
|
620
687
|
async atomic(table, filter, operations, _options) {
|
|
621
|
-
const { sql, params } = this.buildUpdateQuery(table, filter, operations
|
|
688
|
+
const { sql, params } = this.buildUpdateQuery(table, filter, operations);
|
|
622
689
|
return { modifiedCount: (await this.query(sql, params)).rowCount ?? 0 };
|
|
623
690
|
}
|
|
624
691
|
/**
|
|
@@ -721,6 +788,13 @@ var PostgresDriver = class {
|
|
|
721
788
|
/**
|
|
722
789
|
* Build a simple WHERE clause from a filter object.
|
|
723
790
|
*
|
|
791
|
+
* Values are bound as plain equality, except Mongo-style operator objects
|
|
792
|
+
* (`{ $in: [...] }`, `{ $gt: 5 }`, ...) which are translated to their SQL
|
|
793
|
+
* equivalents — driver-level callers (e.g. pivot detach) build filters in
|
|
794
|
+
* that portable form. An unrecognized `$` operator throws instead of being
|
|
795
|
+
* bound literally, which would only surface as a cryptic type error from
|
|
796
|
+
* Postgres.
|
|
797
|
+
*
|
|
724
798
|
* @param filter - Filter conditions
|
|
725
799
|
* @param startParamIndex - Starting parameter index
|
|
726
800
|
* @returns Object with WHERE clause string and parameters
|
|
@@ -732,6 +806,49 @@ var PostgresDriver = class {
|
|
|
732
806
|
for (const [key, value] of Object.entries(filter)) {
|
|
733
807
|
const quotedKey = this.dialect.quoteIdentifier(key);
|
|
734
808
|
if (value === null) conditions.push(`${quotedKey} IS NULL`);
|
|
809
|
+
else if (this.isOperatorFilter(value)) for (const [operator, operand] of Object.entries(value)) switch (operator) {
|
|
810
|
+
case "$in":
|
|
811
|
+
case "$nin": {
|
|
812
|
+
const list = operand;
|
|
813
|
+
if (list.length === 0) {
|
|
814
|
+
conditions.push(operator === "$in" ? "FALSE" : "TRUE");
|
|
815
|
+
break;
|
|
816
|
+
}
|
|
817
|
+
const placeholders = list.map(() => this.dialect.placeholder(paramIndex++));
|
|
818
|
+
params.push(...list);
|
|
819
|
+
conditions.push(`${quotedKey} ${operator === "$in" ? "IN" : "NOT IN"} (${placeholders.join(", ")})`);
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
case "$eq":
|
|
823
|
+
if (operand === null) conditions.push(`${quotedKey} IS NULL`);
|
|
824
|
+
else {
|
|
825
|
+
conditions.push(`${quotedKey} = ${this.dialect.placeholder(paramIndex++)}`);
|
|
826
|
+
params.push(operand);
|
|
827
|
+
}
|
|
828
|
+
break;
|
|
829
|
+
case "$ne":
|
|
830
|
+
if (operand === null) conditions.push(`${quotedKey} IS NOT NULL`);
|
|
831
|
+
else {
|
|
832
|
+
conditions.push(`${quotedKey} != ${this.dialect.placeholder(paramIndex++)}`);
|
|
833
|
+
params.push(operand);
|
|
834
|
+
}
|
|
835
|
+
break;
|
|
836
|
+
case "$gt":
|
|
837
|
+
case "$gte":
|
|
838
|
+
case "$lt":
|
|
839
|
+
case "$lte": {
|
|
840
|
+
const sqlOperator = {
|
|
841
|
+
$gt: ">",
|
|
842
|
+
$gte: ">=",
|
|
843
|
+
$lt: "<",
|
|
844
|
+
$lte: "<="
|
|
845
|
+
}[operator];
|
|
846
|
+
conditions.push(`${quotedKey} ${sqlOperator} ${this.dialect.placeholder(paramIndex++)}`);
|
|
847
|
+
params.push(operand);
|
|
848
|
+
break;
|
|
849
|
+
}
|
|
850
|
+
default: throw new Error(`Unsupported filter operator "${operator}" for column "${key}" on the Postgres driver.`);
|
|
851
|
+
}
|
|
735
852
|
else {
|
|
736
853
|
conditions.push(`${quotedKey} = ${this.dialect.placeholder(paramIndex++)}`);
|
|
737
854
|
params.push(value);
|
|
@@ -743,6 +860,17 @@ var PostgresDriver = class {
|
|
|
743
860
|
};
|
|
744
861
|
}
|
|
745
862
|
/**
|
|
863
|
+
* A filter value is an operator object when it is a plain object whose keys
|
|
864
|
+
* ALL start with `$`. Arrays, Dates, and value objects (e.g. jsonb equality
|
|
865
|
+
* payloads) keep their existing bind-as-value behavior.
|
|
866
|
+
*/
|
|
867
|
+
isOperatorFilter(value) {
|
|
868
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
869
|
+
if (value instanceof Date || Buffer.isBuffer(value)) return false;
|
|
870
|
+
const keys = Object.keys(value);
|
|
871
|
+
return keys.length > 0 && keys.every((key) => key.startsWith("$"));
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
746
874
|
* Build an UPDATE query from update operations.
|
|
747
875
|
*
|
|
748
876
|
* @param table - Target table name
|
|
@@ -757,7 +885,7 @@ var PostgresDriver = class {
|
|
|
757
885
|
let paramIndex = 1;
|
|
758
886
|
if (update.$set) for (const [key, value] of Object.entries(update.$set)) {
|
|
759
887
|
setClauses.push(`${this.dialect.quoteIdentifier(key)} = ${this.dialect.placeholder(paramIndex++)}`);
|
|
760
|
-
params.push(value === void 0 ? value : this.serializeValue(key, value));
|
|
888
|
+
params.push(value === void 0 ? value : this.serializeValue(key, value, table));
|
|
761
889
|
}
|
|
762
890
|
if (update.$unset) for (const key of Object.keys(update.$unset)) setClauses.push(`${this.dialect.quoteIdentifier(key)} = NULL`);
|
|
763
891
|
if (update.$inc) for (const [key, amount] of Object.entries(update.$inc)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-driver.mjs","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/postgres/postgres-driver.ts"],"sourcesContent":["/**\n * PostgreSQL Driver\n *\n * Main driver implementation for PostgreSQL database operations.\n * Implements the DriverContract interface to provide a unified API\n * for CRUD operations, transactions, and query building.\n *\n * Uses the `pg` package for database connectivity with connection pooling.\n *\n * @module cascade/drivers/postgres\n */\n\nimport { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport { databaseTransactionContext } from \"../../context/database-transaction-context\";\nimport type {\n CreateDatabaseOptions,\n DriverContract,\n DriverEventListener,\n DriverTransactionContract,\n DropDatabaseOptions,\n InsertResult,\n TransactionContext,\n UpdateOperations,\n UpdateResult,\n} from \"../../contracts/database-driver.contract\";\nimport type { DriverBlueprintContract } from \"../../contracts/driver-blueprint.contract\";\nimport type { MigrationDriverContract } from \"../../contracts/migration-driver.contract\";\nimport type { QueryBuilderContract } from \"../../contracts/query-builder.contract\";\nimport type { SyncAdapterContract } from \"../../contracts/sync-adapter.contract\";\nimport { TransactionRollbackError } from \"../../errors/transaction-rollback.error\";\nimport { SQLSerializer } from \"../../migration/sql-serializer\";\nimport { SqlDatabaseDirtyTracker } from \"../../sql-database-dirty-tracker\";\nimport type { ModelDefaults } from \"../../types\";\nimport { DatabaseDriver } from \"../../utils/connect-to-database\";\nimport { isValidDateValue } from \"../../utils/is-valid-date-value\";\nimport { PostgresBlueprint } from \"./postgres-blueprint\";\nimport { PostgresDialect } from \"./postgres-dialect\";\nimport { PostgresMigrationDriver } from \"./postgres-migration-driver\";\nimport { PostgresQueryBuilder } from \"./postgres-query-builder\";\nimport { PostgresSQLSerializer } from \"./postgres-sql-serializer\";\nimport { PostgresSyncAdapter } from \"./postgres-sync-adapter\";\nimport type { PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions } from \"./types\";\n\n/**\n * Lazily loaded pg module types.\n */\ntype PgPool = import(\"pg\").Pool;\ntype PgPoolClient = import(\"pg\").PoolClient;\ntype PgPoolConfig = import(\"pg\").PoolConfig;\n\n/**\n * Cached pg module reference.\n */\nlet pgModule: typeof import(\"pg\") | undefined;\n\n/**\n * Lazily load the pg package.\n *\n * @returns The pg module\n * @throws Error if pg is not installed\n */\nasync function loadPg(): Promise<typeof import(\"pg\")> {\n if (pgModule) {\n return pgModule;\n }\n\n try {\n pgModule = await import(\"pg\");\n return pgModule;\n } catch {\n throw new Error(\n 'The \"pg\" package is required for PostgreSQL support. ' + \"Please install it: npm install pg\",\n );\n }\n}\n\n/**\n * PostgreSQL database driver implementing the Cascade DriverContract.\n *\n * Provides connection pooling, CRUD operations, transactions, and\n * integration with Cascade's query builder and migration systems.\n *\n * @example\n * ```typescript\n * const driver = new PostgresDriver({\n * host: 'localhost',\n * port: 5432,\n * database: 'myapp',\n * user: 'postgres',\n * password: 'secret'\n * });\n *\n * await driver.connect();\n *\n * // Insert a document\n * const result = await driver.insert('users', { name: 'Alice', email: 'alice@example.com' });\n *\n * // Query using the query builder\n * const users = await driver.queryBuilder('users')\n * .where('name', 'Alice')\n * .get();\n *\n * await driver.disconnect();\n * ```\n */\nexport class PostgresDriver implements DriverContract {\n /**\n * Driver name identifier.\n */\n public readonly name = \"postgres\" as DatabaseDriver;\n\n /**\n * SQL dialect for PostgreSQL-specific syntax.\n */\n public readonly dialect = new PostgresDialect();\n\n /**\n * PostgreSQL driver model defaults.\n *\n * PostgreSQL follows SQL conventions:\n * - snake_case naming for columns (created_at, updated_at, deleted_at)\n * - Native AUTO_INCREMENT for IDs (no manual generation)\n * - Timestamps enabled by default\n * - Permanent delete strategy (hard deletes)\n */\n public readonly modelDefaults: Partial<ModelDefaults> = {\n namingConvention: \"snake_case\",\n createdAtColumn: \"created_at\",\n updatedAtColumn: \"updated_at\",\n deletedAtColumn: \"deleted_at\",\n timestamps: true,\n autoGenerateId: false, // PostgreSQL uses SERIAL/BIGSERIAL\n strictMode: \"fail\",\n deleteStrategy: \"permanent\",\n };\n\n /**\n * Connection pool instance.\n */\n private _pool: PgPool | undefined;\n\n /**\n * Event listeners for driver lifecycle events.\n */\n private readonly _eventListeners = new Map<string, Set<DriverEventListener>>();\n\n /**\n * Whether the driver is currently connected.\n */\n private _isConnected = false;\n\n /**\n * Blueprint instance (lazy-loaded).\n */\n private _blueprint: DriverBlueprintContract | undefined;\n\n /**\n * Migration driver instance (lazy-loaded).\n */\n private _migrationDriver: MigrationDriverContract | undefined;\n\n /**\n * Sync adapter instance (lazy-loaded).\n */\n private _syncAdapter: SyncAdapterContract | undefined;\n\n /**\n * Lookup set of column names that hold native PostgreSQL arrays\n * (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text encoded.\n *\n * @see PostgresPoolConfig.nativeArrayColumns\n */\n private readonly _nativeArrayColumns: ReadonlySet<string>;\n\n /**\n * Create a new PostgreSQL driver instance.\n *\n * @param config - PostgreSQL connection configuration\n */\n public constructor(private readonly config: PostgresPoolConfig) {\n this._nativeArrayColumns = new Set(config.nativeArrayColumns ?? []);\n }\n\n /**\n * Get the connection pool instance.\n *\n * @throws Error if not connected\n */\n public get pool(): PgPool {\n if (!this._pool) {\n throw new Error(\"PostgreSQL driver is not connected. Call connect() first.\");\n }\n return this._pool;\n }\n\n /**\n * Get database native client\n */\n public getClient<Client = PgPool>(): Client {\n return this.pool as Client;\n }\n\n /**\n * Check if the driver is currently connected.\n */\n public get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Get the driver blueprint (information schema).\n */\n public get blueprint(): DriverBlueprintContract {\n if (!this._blueprint) {\n this._blueprint = new PostgresBlueprint(this);\n }\n return this._blueprint;\n }\n\n /**\n * Establish connection to the PostgreSQL database.\n *\n * Creates a connection pool with the configured options.\n * Emits 'connected' event on successful connection.\n */\n public async connect(): Promise<void> {\n if (this._isConnected) {\n return;\n }\n\n const pg = await loadPg();\n\n try {\n const poolConfig: PgPoolConfig = {\n host: this.config.host ?? \"localhost\",\n port: this.config.port ?? 5432,\n database: this.config.database,\n user: this.config.user,\n password: this.config.password,\n connectionString: this.config.connectionString,\n max: this.config.max ?? 10,\n min: this.config.min ?? 0,\n idleTimeoutMillis: this.config.idleTimeoutMillis ?? 30000,\n connectionTimeoutMillis: this.config.connectionTimeoutMillis ?? 2000,\n application_name: this.config.application_name ?? \"cascade\",\n ssl: this.config.ssl,\n };\n\n log.info(\n \"database.postgres\",\n \"connection\",\n `Connecting to database ${colors.bold(colors.yellowBright(this.config.database))}`,\n );\n\n this._pool = new pg.Pool(poolConfig);\n\n // Test the connection\n const client = await this._pool.connect();\n client.release();\n\n log.success(\n \"database.postgres\",\n \"connection\",\n `Connected to database ${colors.bold(colors.yellowBright(this.config.database))}`,\n );\n\n this._isConnected = true;\n this.emit(\"connected\");\n } catch (error) {\n // Boot-time database connection failure is unrecoverable in every\n // realistic caller (app boot, CLI migrations, workers) — `fatal` makes\n // \"page on fatal only\" alerting clean. Per-query failures stay at error.\n log.fatal(\"database.postgres\", \"connection\", \"Failed to connect to database\");\n throw error;\n }\n }\n\n /**\n * Close the database connection pool.\n *\n * Waits for all active queries to complete before closing.\n * Emits 'disconnected' event on successful disconnection.\n */\n public async disconnect(): Promise<void> {\n if (!this._isConnected || !this._pool) {\n return;\n }\n\n await this._pool.end();\n this._pool = undefined;\n this._isConnected = false;\n this.emit(\"disconnected\");\n }\n\n /**\n * Register an event listener for driver lifecycle events.\n *\n * @param event - Event name ('connected', 'disconnected', etc.)\n * @param listener - Callback function to invoke\n */\n public on(event: string, listener: DriverEventListener): void {\n if (!this._eventListeners.has(event)) {\n this._eventListeners.set(event, new Set());\n }\n\n this._eventListeners.get(event)!.add(listener);\n }\n\n /**\n * Serialize data for storage in PostgreSQL.\n *\n * Handles Date objects, BigInt, and other JavaScript types\n * that need special handling for PostgreSQL storage.\n *\n * @param data - The data object to serialize\n * @returns Serialized data ready for PostgreSQL\n */\n public serialize(data: Record<string, unknown>): Record<string, unknown> {\n const serialized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(data)) {\n if (value === undefined) {\n continue; // Skip undefined values\n }\n\n serialized[key] = this.serializeValue(key, value);\n }\n\n return serialized;\n }\n\n /**\n * Serialize a single column value into a node-pg bindable parameter.\n *\n * Shared by {@link serialize} (INSERT path) and {@link buildUpdateQuery}\n * `$set` (UPDATE path) so both encode `json` / `jsonb` columns identically.\n *\n * Encoding rules (in order):\n * - `Date` → ISO string.\n * - `bigint` → decimal string (node-pg has no native bigint binding).\n * - all-number array → pgvector literal `'[n1,n2,...]'`. node-pg would\n * otherwise emit a `{n1,n2,...}` array literal, which the `vector` type\n * rejects. This branch is preserved exactly.\n * - any other array (object-array, string-array, mixed, empty `[]`) →\n * `JSON.stringify`. node-pg renders a raw JS array as a PostgreSQL array\n * literal `{...}` (and `[]` as `{}`), which a `json` / `jsonb` column\n * rejects — so we bind the value as JSON text instead, the form those\n * columns accept. Columns listed in `nativeArrayColumns` are exempt:\n * their raw array is passed through so node-pg emits the `{...}` literal\n * a genuine `JSONB[]` / `TEXT[]` column needs.\n * - plain object → `JSON.stringify`. Equivalent to node-pg's own object\n * handling, made explicit so both write paths agree.\n * - everything else (scalars: string, number, boolean, null) → untouched.\n *\n * Boundary note: the serializer has no access to the table schema, so it\n * cannot tell a `json` / `jsonb` column from a native-array column purely\n * from the value. `nativeArrayColumns` is the explicit, opt-in escape hatch\n * for the latter. No `::jsonb` placeholder cast is added: a JSON-text string\n * binds correctly to `json` / `jsonb` without one, and a blind cast would\n * misfire on columns we cannot positively identify as jsonb.\n *\n * @param key - Column name (used to honour `nativeArrayColumns`)\n * @param value - The raw value to serialize (never `undefined`)\n * @returns The value ready to bind as a query parameter\n */\n private serializeValue(key: string, value: unknown): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n if (value.length > 0 && value.every((v) => typeof v === \"number\")) {\n // pgvector columns expect the literal '[n1,n2,...]' format.\n return `[${value.join(\",\")}]`;\n }\n\n // Genuine native PostgreSQL array columns (JSONB[], TEXT[], …) must\n // keep their raw array so node-pg emits a '{...}' array literal.\n if (this._nativeArrayColumns.has(key)) {\n return value;\n }\n\n // json / jsonb columns: bind as JSON text. Covers object-arrays,\n // string-arrays, mixed arrays, and empty [] (which would otherwise\n // store as '{}' instead of '[]').\n return JSON.stringify(value);\n }\n\n if (typeof value === \"object\" && value !== null) {\n // Plain object → JSONB. Explicit JSON.stringify matches node-pg's own\n // object encoding while keeping both write paths consistent.\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n /**\n * Get the dirty tracker for this driver.\n */\n public getDirtyTracker(data: Record<string, unknown>): SqlDatabaseDirtyTracker {\n return new SqlDatabaseDirtyTracker(data);\n }\n\n /**\n * Deserialize data retrieved from PostgreSQL.\n *\n * Converts PostgreSQL types back to JavaScript equivalents.\n *\n * @param data - The data object from PostgreSQL\n * @returns Deserialized JavaScript object\n */\n public deserialize(data: Record<string, unknown>): Record<string, unknown> {\n // PostgreSQL pg driver handles most type conversions automatically\n // Special handling can be added here if needed\n for (const [key, value] of Object.entries(data)) {\n // Only re-inflate strings — pg already returns Date objects from DB reads\n if (typeof value !== \"string\") continue;\n\n if (isValidDateValue(value)) {\n data[key] = new Date(value);\n continue;\n }\n\n // pgvector columns are returned as '[n1,n2,...]' strings.\n // charCodeAt is faster than startsWith/endsWith — no string allocation.\n // '[' = 91, ']' = 93\n if (value.charCodeAt(0) === 91 && value.charCodeAt(value.length - 1) === 93) {\n const parts = value.slice(1, -1).split(\",\");\n const nums = new Array<number>(parts.length);\n let isNumericVector = parts.length > 0;\n\n for (let i = 0; i < parts.length; i++) {\n const n = +parts[i]; // unary + is the fastest string-to-number coercion\n if (!Number.isFinite(n)) {\n isNumericVector = false;\n break; // early-exit — not a numeric vector, leave value untouched\n }\n nums[i] = n;\n }\n\n if (isNumericVector) {\n data[key] = nums;\n }\n }\n }\n\n return data;\n }\n\n /**\n * Insert a single row into a table.\n *\n * Uses INSERT ... RETURNING to get the inserted row with generated values.\n *\n * @param table - Target table name\n * @param document - Data to insert\n * @param options - Optional insertion options\n * @returns The inserted document\n */\n public async insert(\n table: string,\n document: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<InsertResult> {\n const serialized = this.serialize(document);\n\n // Filter out id if null/undefined to let PostgreSQL SERIAL auto-generate\n const filteredData = Object.fromEntries(\n Object.entries(serialized).filter(([key, value]) => {\n // Exclude id if null/undefined (let SERIAL handle it)\n if (key === \"id\" && (value === null || value === undefined)) {\n return false;\n }\n return true;\n }),\n );\n\n const columns = Object.keys(filteredData);\n const values = Object.values(filteredData);\n\n if (columns.length === 0) {\n throw new Error(\"Cannot insert empty document\");\n }\n\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const placeholders = columns.map((_, i) => this.dialect.placeholder(i + 1)).join(\", \");\n const quotedTable = this.dialect.quoteIdentifier(table);\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES (${placeholders}) RETURNING *`;\n\n const result = await this.query<Record<string, unknown>>(sql, values);\n\n return {\n document: result.rows[0],\n };\n }\n\n /**\n * Insert multiple rows into a table.\n *\n * Uses a single INSERT statement with multiple value sets for efficiency.\n *\n * @param table - Target table name\n * @param documents - Array of documents to insert\n * @param options - Optional insertion options\n * @returns Array of inserted documents\n */\n public async insertMany(\n table: string,\n documents: Record<string, unknown>[],\n _options?: Record<string, unknown>,\n ): Promise<InsertResult[]> {\n if (documents.length === 0) {\n return [];\n }\n\n // Get all unique columns across all documents\n const allColumns = new Set<string>();\n for (const doc of documents) {\n const serialized = this.serialize(doc);\n Object.keys(serialized).forEach((key) => allColumns.add(key));\n }\n const columns = Array.from(allColumns);\n\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const quotedTable = this.dialect.quoteIdentifier(table);\n\n // Build value sets and params\n const valueSets: string[] = [];\n const params: unknown[] = [];\n let paramIndex = 1;\n\n for (const doc of documents) {\n const serialized = this.serialize(doc);\n const rowPlaceholders: string[] = [];\n\n for (const col of columns) {\n if (col in serialized) {\n rowPlaceholders.push(this.dialect.placeholder(paramIndex++));\n params.push(serialized[col]);\n } else {\n rowPlaceholders.push(\"DEFAULT\");\n }\n }\n\n valueSets.push(`(${rowPlaceholders.join(\", \")})`);\n }\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES ${valueSets.join(\", \")} RETURNING *`;\n\n const result = await this.query<Record<string, unknown>>(sql, params);\n\n return result.rows as unknown as InsertResult[];\n }\n\n /**\n * Update a single row matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations ($set, $unset, $inc)\n * @param options - Optional update options\n * @returns Update result with modified count\n */\n public async update(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update, 1);\n try {\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n } catch (error) {\n console.log(\"PG Query Error in:\", sql, params);\n\n throw error;\n }\n }\n\n /**\n * Find one and update a single row matching the filter and return the updated row\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations ($set, $unset, $inc)\n * @param options - Optional update options\n * @returns The updated row or null\n */\n public async findOneAndUpdate<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update, 1);\n // Add RETURNING * to get the updated row back\n const sqlWithReturning = `${sql} RETURNING *`;\n const result = await this.query<T>(sqlWithReturning, params);\n return result.rows[0] ?? null;\n }\n\n /**\n * Update multiple rows matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations\n * @param options - Optional update options\n * @returns Update result with modified count\n */\n public async updateMany(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update);\n\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n }\n\n /**\n * Replace a document matching the filter.\n *\n * Completely replaces the document (not a partial update).\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param document - New document data\n * @param options - Optional options\n * @returns The replaced document or null\n */\n public async replace<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const serialized = this.serialize(document);\n const columns = Object.keys(serialized);\n const values = Object.values(serialized);\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const setClauses = columns\n .map((col, i) => `${this.dialect.quoteIdentifier(col)} = ${this.dialect.placeholder(i + 1)}`)\n .join(\", \");\n\n const { whereClause, whereParams } = this.buildWhereClause(filter, columns.length + 1);\n\n const sql = `UPDATE ${quotedTable} SET ${setClauses} ${whereClause} RETURNING *`;\n const params = [...values, ...whereParams];\n\n const result = await this.query<T>(sql, params);\n\n return result.rows[0] ?? null;\n }\n\n /**\n * Upsert (insert or update) a single row.\n *\n * Uses PostgreSQL's INSERT ... ON CONFLICT ... DO UPDATE syntax.\n *\n * @param table - Target table name\n * @param filter - Filter conditions to find existing row (used for conflict detection)\n * @param document - Document data to insert or update\n * @param options - Upsert options (conflictColumns for conflict target)\n * @returns The upserted row\n */\n public async upsert<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n options?: Record<string, unknown>,\n ): Promise<T> {\n const serialized = this.serialize(document);\n const columns = Object.keys(serialized);\n const values = Object.values(serialized);\n\n if (columns.length === 0) {\n throw new Error(\"Cannot upsert empty document\");\n }\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const placeholders = columns.map((_, i) => this.dialect.placeholder(i + 1)).join(\", \");\n\n // Determine conflict columns from options or filter\n const conflictColumns = (options?.conflictColumns as string[]) ?? Object.keys(filter);\n if (conflictColumns.length === 0) {\n throw new Error(\"Upsert requires conflictColumns option or filter with columns\");\n }\n\n const quotedConflictColumns = conflictColumns\n .map((c) => this.dialect.quoteIdentifier(c))\n .join(\", \");\n\n // Build UPDATE clause for ON CONFLICT\n // Update all columns except the conflict columns (they stay the same)\n const updateColumns = columns.filter((col) => !conflictColumns.includes(col));\n const setClauses = updateColumns\n .map((col, i) => {\n const valueIndex = columns.indexOf(col) + 1;\n return `${this.dialect.quoteIdentifier(col)} = ${this.dialect.placeholder(valueIndex)}`;\n })\n .join(\", \");\n\n // If there are no columns to update (all columns are conflict columns), use EXCLUDED\n const updateClause =\n setClauses.length > 0\n ? setClauses\n : columns\n .map(\n (col) =>\n `${this.dialect.quoteIdentifier(col)} = EXCLUDED.${this.dialect.quoteIdentifier(col)}`,\n )\n .join(\", \");\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES (${placeholders}) ON CONFLICT (${quotedConflictColumns}) DO UPDATE SET ${updateClause} RETURNING *`;\n\n const result = await this.query<T>(sql, values);\n\n return result.rows[0]! as T;\n }\n\n /**\n * Find one and delete a single row matching the filter and return the deleted row.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional delete options\n * @returns The deleted row or null\n */\n public async findOneAndDelete<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter, 1);\n\n // Use ctid for single row deletion with RETURNING\n const sql = `DELETE FROM ${quotedTable} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1) RETURNING *`;\n\n const result = await this.query<T>(sql, whereParams);\n\n return result.rows[0] ? (result.rows[0] as T) : null;\n }\n\n /**\n * Delete a single row matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional options\n * @returns Number of deleted rows (0 or 1)\n */\n public async delete(\n table: string,\n filter?: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter ?? {}, 1);\n\n // Use ctid for single row deletion\n const sql = `DELETE FROM ${quotedTable} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1)`;\n\n const result = await this.query(sql, whereParams);\n\n return result.rowCount ?? 0;\n }\n\n /**\n * Delete multiple rows matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional options\n * @returns Number of deleted rows\n */\n public async deleteMany(\n table: string,\n filter?: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter ?? {}, 1);\n\n const sql = `DELETE FROM ${quotedTable} ${whereClause}`;\n\n const result = await this.query(sql, whereParams);\n\n return result.rowCount ?? 0;\n }\n\n /**\n * Truncate a table (remove all rows).\n *\n * Uses TRUNCATE TABLE for fast deletion with RESTART IDENTITY.\n *\n * @param table - Target table name\n * @param options - Optional options\n * @param options.cascade - If true, automatically truncate all tables with foreign key references (use with caution)\n * @returns Number of deleted rows (always 0 for TRUNCATE)\n */\n public async truncateTable(table: string, options?: { cascade?: boolean }): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const cascadeClause = options?.cascade ? \" CASCADE\" : \"\";\n await this.query(`TRUNCATE TABLE ${quotedTable} RESTART IDENTITY${cascadeClause}`);\n return 0; // TRUNCATE doesn't return row count\n }\n\n /**\n * Get a query builder for the specified table.\n *\n * @param table - Target table name\n * @returns Query builder instance\n */\n public queryBuilder<T = unknown>(table: string): QueryBuilderContract<T> {\n return new PostgresQueryBuilder<T>(table) as unknown as QueryBuilderContract<T>;\n }\n\n /**\n * Begin a new database transaction.\n *\n * Acquires a client from the pool and starts a transaction.\n * The client is stored in AsyncLocalStorage for automatic\n * participation by subsequent queries.\n *\n * @param options - Optional transaction options\n * @returns Transaction contract with commit/rollback methods\n */\n public async beginTransaction(\n options?: PostgresTransactionOptions,\n ): Promise<DriverTransactionContract<PgPoolClient>> {\n const client = await this.pool.connect();\n\n let beginSql = \"BEGIN\";\n if (options?.isolationLevel) {\n beginSql += ` ISOLATION LEVEL ${options.isolationLevel.toUpperCase()}`;\n }\n if (options?.readOnly) {\n beginSql += \" READ ONLY\";\n }\n if (options?.deferrable) {\n beginSql += \" DEFERRABLE\";\n }\n\n await client.query(beginSql);\n\n return {\n context: client,\n commit: async () => {\n await client.query(\"COMMIT\");\n client.release();\n },\n rollback: async () => {\n await client.query(\"ROLLBACK\");\n client.release();\n },\n };\n }\n\n /**\n * Execute a function within a transaction scope (recommended pattern).\n *\n * Automatically commits on success, rolls back on any error, and guarantees\n * resource cleanup. This is the recommended way to use transactions.\n *\n * @param fn - Async function to execute within transaction\n * @param options - Transaction options (isolation level, read-only, etc.)\n * @returns The return value of the callback function\n * @throws {Error} If transaction fails or is explicitly rolled back\n */\n public async transaction<T>(\n fn: (ctx: TransactionContext) => Promise<T>,\n options?: Record<string, unknown>,\n ): Promise<T> {\n // Prevent nested transaction() calls\n if (databaseTransactionContext.hasActiveTransaction()) {\n // throw new Error(\n // \"Nested transaction() calls are not supported. \" +\n // \"Use beginTransaction() with savepoints for advanced transaction patterns.\",\n // );\n }\n\n const tx = await this.beginTransaction(options);\n\n // Set transaction context for queries within callback\n databaseTransactionContext.enter({ session: tx.context });\n\n try {\n // Create transaction context with rollback method\n const ctx: TransactionContext = {\n rollback(reason?: string): never {\n throw new TransactionRollbackError(reason);\n },\n };\n\n // Execute callback\n const result = await fn(ctx);\n\n // Auto-commit on success\n await tx.commit();\n\n return result;\n } catch (error) {\n // Auto-rollback on any error (including explicit rollback)\n await tx.rollback();\n log.error(\n `database.postgress`,\n \"transaction\",\n \"Transaction operation failed, rolled back everything\",\n );\n throw error;\n } finally {\n // Guaranteed cleanup\n databaseTransactionContext.exit();\n }\n }\n\n /**\n * Perform an atomic update operation.\n *\n * Builds and executes an UPDATE query for the given filter and operations.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param operations - Update operations\n * @param options - Optional options\n * @returns Update result\n */\n public async atomic(\n table: string,\n filter: Record<string, unknown>,\n operations: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, operations, 1);\n\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n }\n\n /**\n * Get the sync adapter for bulk denormalized updates.\n *\n * @returns Sync adapter instance\n */\n public syncAdapter(): SyncAdapterContract {\n if (!this._syncAdapter) {\n this._syncAdapter = new PostgresSyncAdapter(this);\n }\n return this._syncAdapter;\n }\n\n /**\n * Get the migration driver for schema operations.\n *\n * @returns Migration driver instance\n */\n public migrationDriver(): MigrationDriverContract {\n if (!this._migrationDriver) {\n this._migrationDriver = new PostgresMigrationDriver(this);\n }\n\n return this._migrationDriver;\n }\n\n /**\n * Return a SQL serializer for this driver's dialect.\n * Used by Migration.toSQL() to convert pending operations to SQL strings.\n */\n public getSQLSerializer(): SQLSerializer {\n return new PostgresSQLSerializer(this.dialect);\n }\n\n /**\n * Execute a raw SQL query.\n *\n * Automatically uses the transaction client if one is active.\n *\n * @param sql - SQL query string\n * @param params - Query parameters\n * @returns Query result\n */\n public async query<T = Record<string, unknown>>(\n sql: string,\n params: unknown[] = [],\n ): Promise<PostgresQueryResult<T>> {\n // Check for active transaction client\n const txClient = databaseTransactionContext.getSession() as PgPoolClient | undefined;\n\n const startTime = this.config.logging ? performance.now() : 0;\n\n let paramsString = \"\";\n if (this.config.logging && params.length > 0) {\n paramsString = JSON.stringify(params);\n if (paramsString.length > 300) {\n paramsString = paramsString.substring(0, 300) + \"...\";\n }\n paramsString = ` | Params: ${paramsString}`;\n }\n\n try {\n let result;\n if (this.config.logging) {\n log.info({\n module: \"database.postgres\",\n action: \"query.executing\",\n message: `${sql}${paramsString}`,\n context: { params, sql },\n });\n }\n if (txClient) {\n result = await txClient.query(sql, params);\n } else {\n result = await this.pool.query(sql, params);\n }\n\n if (this.config.logging) {\n const duration = (performance.now() - startTime).toFixed(2);\n log.success({\n module: \"database.postgres\",\n action: \"query.executed\",\n message: `[${duration}ms] ${sql}${paramsString}`,\n context: { params, sql, duration },\n });\n }\n\n return result as PostgresQueryResult<T>;\n } catch (error) {\n if (this.config.logging) {\n const duration = (performance.now() - startTime).toFixed(2);\n log.error({\n module: \"database.postgres\",\n action: \"query.error\",\n message: `[${duration}ms] ${sql}${paramsString}`,\n context: {\n sql,\n params,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n }\n throw error;\n }\n }\n\n /**\n * Emit an event to all registered listeners.\n *\n * @param event - Event name\n * @param args - Event arguments\n */\n private emit(event: string, ...args: unknown[]): void {\n const listeners = this._eventListeners.get(event);\n if (listeners) {\n for (const listener of listeners) {\n listener(...args);\n }\n }\n }\n\n /**\n * Build a simple WHERE clause from a filter object.\n *\n * @param filter - Filter conditions\n * @param startParamIndex - Starting parameter index\n * @returns Object with WHERE clause string and parameters\n */\n private buildWhereClause(\n filter: Record<string, unknown>,\n startParamIndex: number,\n ): { whereClause: string; whereParams: unknown[] } {\n const conditions: string[] = [];\n const params: unknown[] = [];\n let paramIndex = startParamIndex;\n\n for (const [key, value] of Object.entries(filter)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n\n if (value === null) {\n conditions.push(`${quotedKey} IS NULL`);\n } else {\n conditions.push(`${quotedKey} = ${this.dialect.placeholder(paramIndex++)}`);\n params.push(value);\n }\n }\n\n const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(\" AND \")}` : \"\";\n\n return { whereClause, whereParams: params };\n }\n\n /**\n * Build an UPDATE query from update operations.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations\n * @param limit - Optional limit (for single row update)\n * @returns Object with SQL and parameters\n */\n private buildUpdateQuery(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n limit?: number,\n ): { sql: string; params: unknown[] } {\n const setClauses: string[] = [];\n const params: unknown[] = [];\n let paramIndex = 1;\n\n // Handle $set\n if (update.$set) {\n for (const [key, value] of Object.entries(update.$set)) {\n setClauses.push(\n `${this.dialect.quoteIdentifier(key)} = ${this.dialect.placeholder(paramIndex++)}`,\n );\n // Apply the same json/jsonb-aware serialization used on the INSERT\n // path so object/array $set values aren't corrupted into Postgres\n // array literals. undefined is skipped — never bind it.\n params.push(value === undefined ? value : this.serializeValue(key, value));\n }\n }\n\n // Handle $unset (set to NULL)\n if (update.$unset) {\n for (const key of Object.keys(update.$unset)) {\n setClauses.push(`${this.dialect.quoteIdentifier(key)} = NULL`);\n }\n }\n\n // Handle $inc\n if (update.$inc) {\n for (const [key, amount] of Object.entries(update.$inc)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n setClauses.push(\n `${quotedKey} = COALESCE(${quotedKey}, 0) + ${this.dialect.placeholder(paramIndex++)}`,\n );\n params.push(amount);\n }\n }\n\n // Handle $dec\n if (update.$dec) {\n for (const [key, amount] of Object.entries(update.$dec)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n setClauses.push(\n `${quotedKey} = COALESCE(${quotedKey}, 0) - ${this.dialect.placeholder(paramIndex++)}`,\n );\n params.push(amount);\n }\n }\n\n if (setClauses.length === 0) {\n throw new Error(\"No update operations specified\");\n }\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter, paramIndex);\n params.push(...whereParams);\n\n let sql = `UPDATE ${quotedTable} SET ${setClauses.join(\", \")} ${whereClause}`;\n\n // For single row update, use ctid subquery\n if (limit === 1 && whereClause) {\n sql = `UPDATE ${quotedTable} SET ${setClauses.join(\", \")} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1)`;\n }\n\n return { sql, params };\n }\n\n // ============================================================\n // Database Lifecycle Operations\n // ============================================================\n\n /**\n * Create a new database.\n *\n * Note: This requires connecting to a system database (like 'postgres')\n * since you cannot create a database while connected to it.\n *\n * @param name - Database name to create\n * @param options - Creation options (encoding, template, etc.)\n * @returns true if created, false if already exists\n */\n public async createDatabase(name: string, options?: CreateDatabaseOptions): Promise<boolean> {\n // Check if database already exists\n if (await this.databaseExists(name)) {\n return false;\n }\n\n // Build CREATE DATABASE statement\n const quotedName = this.dialect.quoteIdentifier(name);\n let sql = `CREATE DATABASE ${quotedName}`;\n\n const withClauses: string[] = [];\n\n if (options?.encoding) {\n withClauses.push(`ENCODING = '${options.encoding}'`);\n }\n if (options?.template) {\n withClauses.push(`TEMPLATE = ${this.dialect.quoteIdentifier(options.template)}`);\n }\n if (options?.locale) {\n withClauses.push(`LC_COLLATE = '${options.locale}'`);\n withClauses.push(`LC_CTYPE = '${options.locale}'`);\n }\n if (options?.owner) {\n withClauses.push(`OWNER = ${this.dialect.quoteIdentifier(options.owner)}`);\n }\n\n if (withClauses.length > 0) {\n sql += ` WITH ${withClauses.join(\" \")}`;\n }\n\n try {\n await this.query(sql);\n log.success(\"database\", \"lifecycle\", `Created database ${name}`);\n return true;\n } catch (error) {\n log.error(\"database\", \"lifecycle\", `Failed to create database ${name}: ${error}`);\n throw error;\n }\n }\n\n /**\n * Drop a database.\n *\n * @param name - Database name to drop\n * @param options - Drop options\n * @returns true if dropped, false if didn't exist\n */\n public async dropDatabase(name: string, options?: DropDatabaseOptions): Promise<boolean> {\n // Check if database exists first (if ifExists option not set)\n if (!options?.ifExists && !(await this.databaseExists(name))) {\n return false;\n }\n\n const quotedName = this.dialect.quoteIdentifier(name);\n let sql = \"DROP DATABASE\";\n\n if (options?.ifExists) {\n sql += \" IF EXISTS\";\n }\n\n sql += ` ${quotedName}`;\n\n // PostgreSQL 13+ supports WITH (FORCE) to terminate active connections\n if (options?.force) {\n sql += \" WITH (FORCE)\";\n }\n\n try {\n await this.query(sql);\n log.success(\"database\", \"lifecycle\", `Dropped database ${name}`);\n return true;\n } catch (error) {\n log.error(\"database\", \"lifecycle\", `Failed to drop database ${name}: ${error}`);\n throw error;\n }\n }\n\n /**\n * Check if a database exists.\n *\n * @param name - Database name to check\n * @returns true if database exists\n */\n public async databaseExists(name: string): Promise<boolean> {\n const result = await this.query<{ exists: boolean }>(\n `SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1) as exists`,\n [name],\n );\n\n return result.rows[0]?.exists ?? false;\n }\n\n /**\n * List all databases.\n *\n * @returns Array of database names\n */\n public async listDatabases(): Promise<string[]> {\n const result = await this.query<{ datname: string }>(\n `SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname`,\n );\n\n return result.rows.map((row) => row.datname);\n }\n\n // ============================================================\n // Table Management Operations\n // ============================================================\n\n /**\n * Drop a table.\n *\n * @param name - Table name to drop\n * @throws Error if table doesn't exist\n */\n public async dropTable(name: string): Promise<void> {\n const quotedName = this.dialect.quoteIdentifier(name);\n await this.query(`DROP TABLE ${quotedName}`);\n log.success(\"database\", \"table\", `Dropped table ${name}`);\n }\n\n /**\n * Drop a table if it exists.\n *\n * @param name - Table name to drop\n */\n public async dropTableIfExists(name: string): Promise<void> {\n const quotedName = this.dialect.quoteIdentifier(name);\n await this.query(`DROP TABLE IF EXISTS ${quotedName}`);\n }\n\n /**\n * Drop all tables in the current database.\n *\n * Uses CASCADE to handle foreign key dependencies.\n * Useful for `migrate:fresh` command.\n */\n public async dropAllTables(): Promise<void> {\n // Get all tables from blueprint\n const tables = await this.blueprint.listTables();\n\n if (tables.length === 0) {\n return;\n }\n\n // Drop all tables with CASCADE to handle foreign keys\n for (const table of tables) {\n const quotedName = this.dialect.quoteIdentifier(table);\n await this.query(`DROP TABLE IF EXISTS ${quotedName} CASCADE`);\n }\n\n log.success(\"database\", \"table\", `Dropped ${tables.length} tables`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAI;;;;;;;AAQJ,eAAe,SAAuC;CACpD,IAAI,UACF,OAAO;CAGT,IAAI;EACF,WAAW,MAAM,OAAO;E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AI,OAAO;GAC9E,MAAM;EACR;CACF;;;;;;;CAQA,MAAa,eAAe,MAAgC;EAM1D,QAAO,MALc,KAAK,MACxB,yEACA,CAAC,IAAI,CACP,EAEa,CAAC,KAAK,EAAE,EAAE,UAAU;CACnC;;;;;;CAOA,MAAa,gBAAmC;EAK9C,QAAO,MAJc,KAAK,MACxB,8EACF,EAEa,CAAC,KAAK,KAAK,QAAQ,IAAI,OAAO;CAC7C;;;;;;;CAYA,MAAa,UAAU,MAA6B;EAClD,MAAM,aAAa,KAAK,QAAQ,gBAAgB,IAAI;EACpD,MAAM,KAAK,MAAM,cAAc,YAAY;EAC3C,IAAI,QAAQ,YAAY,SAAS,iBAAiB,MAAM;CAC1D;;;;;;CAOA,MAAa,kBAAkB,MAA6B;EAC1D,MAAM,aAAa,KAAK,QAAQ,gBAAgB,IAAI;EACpD,MAAM,KAAK,MAAM,wBAAwB,YAAY;CACvD;;;;;;;CAQA,MAAa,gBAA+B;EAE1C,MAAM,SAAS,MAAM,KAAK,UAAU,WAAW;EAE/C,IAAI,OAAO,WAAW,GACpB;EAIF,KAAK,MAAM,SAAS,QAAQ;GAC1B,MAAM,aAAa,KAAK,QAAQ,gBAAgB,KAAK;GACrD,MAAM,KAAK,MAAM,wBAAwB,WAAW,SAAS;EAC/D;EAEA,IAAI,QAAQ,YAAY,SAAS,WAAW,OAAO,OAAO,QAAQ;CACpE;AACF"}
|
|
1
|
+
{"version":3,"file":"postgres-driver.mjs","names":[],"sources":["../../../../../../../../@warlock.js/cascade/src/drivers/postgres/postgres-driver.ts"],"sourcesContent":["/**\n * PostgreSQL Driver\n *\n * Main driver implementation for PostgreSQL database operations.\n * Implements the DriverContract interface to provide a unified API\n * for CRUD operations, transactions, and query building.\n *\n * Uses the `pg` package for database connectivity with connection pooling.\n *\n * @module cascade/drivers/postgres\n */\n\nimport { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport { databaseTransactionContext } from \"../../context/database-transaction-context\";\nimport type {\n CreateDatabaseOptions,\n DriverContract,\n DriverEventListener,\n DriverTransactionContract,\n DropDatabaseOptions,\n InsertResult,\n TransactionContext,\n UpdateOperations,\n UpdateResult,\n} from \"../../contracts/database-driver.contract\";\nimport type { DriverBlueprintContract } from \"../../contracts/driver-blueprint.contract\";\nimport type { MigrationDriverContract } from \"../../contracts/migration-driver.contract\";\nimport type { QueryBuilderContract } from \"../../contracts/query-builder.contract\";\nimport type { SyncAdapterContract } from \"../../contracts/sync-adapter.contract\";\nimport { TransactionRollbackError } from \"../../errors/transaction-rollback.error\";\nimport { SQLSerializer } from \"../../migration/sql-serializer\";\nimport { SqlDatabaseDirtyTracker } from \"../../sql-database-dirty-tracker\";\nimport type { ModelDefaults } from \"../../types\";\nimport { DatabaseDriver } from \"../../utils/connect-to-database\";\nimport { isValidDateValue } from \"../../utils/is-valid-date-value\";\nimport { PostgresBlueprint } from \"./postgres-blueprint\";\nimport { PostgresDialect } from \"./postgres-dialect\";\nimport { PostgresMigrationDriver } from \"./postgres-migration-driver\";\nimport { PostgresQueryBuilder } from \"./postgres-query-builder\";\nimport { PostgresSQLSerializer } from \"./postgres-sql-serializer\";\nimport { PostgresSyncAdapter } from \"./postgres-sync-adapter\";\nimport type { PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions } from \"./types\";\n\n/**\n * Lazily loaded pg module types.\n */\ntype PgPool = import(\"pg\").Pool;\ntype PgPoolClient = import(\"pg\").PoolClient;\ntype PgPoolConfig = import(\"pg\").PoolConfig;\n\n/**\n * Cached pg module reference.\n */\nlet pgModule: typeof import(\"pg\") | undefined;\n\n/**\n * Lazily load the pg package.\n *\n * @returns The pg module\n * @throws Error if pg is not installed\n */\nasync function loadPg(): Promise<typeof import(\"pg\")> {\n if (pgModule) {\n return pgModule;\n }\n\n try {\n pgModule = await import(\"pg\");\n return pgModule;\n } catch {\n throw new Error(\n 'The \"pg\" package is required for PostgreSQL support. ' + \"Please install it: npm install pg\",\n );\n }\n}\n\n/**\n * PostgreSQL database driver implementing the Cascade DriverContract.\n *\n * Provides connection pooling, CRUD operations, transactions, and\n * integration with Cascade's query builder and migration systems.\n *\n * @example\n * ```typescript\n * const driver = new PostgresDriver({\n * host: 'localhost',\n * port: 5432,\n * database: 'myapp',\n * user: 'postgres',\n * password: 'secret'\n * });\n *\n * await driver.connect();\n *\n * // Insert a document\n * const result = await driver.insert('users', { name: 'Alice', email: 'alice@example.com' });\n *\n * // Query using the query builder\n * const users = await driver.queryBuilder('users')\n * .where('name', 'Alice')\n * .get();\n *\n * await driver.disconnect();\n * ```\n */\nexport class PostgresDriver implements DriverContract {\n /**\n * Driver name identifier.\n */\n public readonly name = \"postgres\" as DatabaseDriver;\n\n /**\n * SQL dialect for PostgreSQL-specific syntax.\n */\n public readonly dialect = new PostgresDialect();\n\n /**\n * PostgreSQL driver model defaults.\n *\n * PostgreSQL follows SQL conventions:\n * - snake_case naming for columns (created_at, updated_at, deleted_at)\n * - Native AUTO_INCREMENT for IDs (no manual generation)\n * - Timestamps enabled by default\n * - Permanent delete strategy (hard deletes)\n */\n public readonly modelDefaults: Partial<ModelDefaults> = {\n namingConvention: \"snake_case\",\n createdAtColumn: \"created_at\",\n updatedAtColumn: \"updated_at\",\n deletedAtColumn: \"deleted_at\",\n timestamps: true,\n autoGenerateId: false, // PostgreSQL uses SERIAL/BIGSERIAL\n strictMode: \"fail\",\n deleteStrategy: \"permanent\",\n };\n\n /**\n * Connection pool instance.\n */\n private _pool: PgPool | undefined;\n\n /**\n * Event listeners for driver lifecycle events.\n */\n private readonly _eventListeners = new Map<string, Set<DriverEventListener>>();\n\n /**\n * Whether the driver is currently connected.\n */\n private _isConnected = false;\n\n /**\n * Blueprint instance (lazy-loaded).\n */\n private _blueprint: DriverBlueprintContract | undefined;\n\n /**\n * Migration driver instance (lazy-loaded).\n */\n private _migrationDriver: MigrationDriverContract | undefined;\n\n /**\n * Sync adapter instance (lazy-loaded).\n */\n private _syncAdapter: SyncAdapterContract | undefined;\n\n /**\n * Explicit, table-agnostic override list of column names that hold native\n * PostgreSQL arrays (`JSONB[]`, `TEXT[]`, …) and must NOT be JSON-text\n * encoded. Merged with (and superseded per-table by) the schema\n * introspection below; kept as a manual escape hatch.\n *\n * @see PostgresPoolConfig.nativeArrayColumns\n */\n private readonly _nativeArrayColumns: ReadonlySet<string>;\n\n /**\n * Native-array columns discovered by introspecting the live schema on\n * connect, keyed `table → { column, … }`. Authoritative and table-scoped, so\n * a column that is `TEXT[]` in one table and `jsonb` in another is encoded\n * correctly for each — no app configuration required.\n */\n private _introspectedArrayColumns: ReadonlyMap<string, ReadonlySet<string>> = new Map();\n\n /**\n * Create a new PostgreSQL driver instance.\n *\n * @param config - PostgreSQL connection configuration\n */\n public constructor(private readonly config: PostgresPoolConfig) {\n this._nativeArrayColumns = new Set(config.nativeArrayColumns ?? []);\n }\n\n /**\n * Get the connection pool instance.\n *\n * @throws Error if not connected\n */\n public get pool(): PgPool {\n if (!this._pool) {\n throw new Error(\"PostgreSQL driver is not connected. Call connect() first.\");\n }\n return this._pool;\n }\n\n /**\n * Get database native client\n */\n public getClient<Client = PgPool>(): Client {\n return this.pool as Client;\n }\n\n /**\n * Check if the driver is currently connected.\n */\n public get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Get the driver blueprint (information schema).\n */\n public get blueprint(): DriverBlueprintContract {\n if (!this._blueprint) {\n this._blueprint = new PostgresBlueprint(this);\n }\n return this._blueprint;\n }\n\n /**\n * Establish connection to the PostgreSQL database.\n *\n * Creates a connection pool with the configured options.\n * Emits 'connected' event on successful connection.\n */\n public async connect(): Promise<void> {\n if (this._isConnected) {\n return;\n }\n\n const pg = await loadPg();\n\n try {\n const poolConfig: PgPoolConfig = {\n host: this.config.host ?? \"localhost\",\n port: this.config.port ?? 5432,\n database: this.config.database,\n user: this.config.user,\n password: this.config.password,\n connectionString: this.config.connectionString,\n max: this.config.max ?? 10,\n min: this.config.min ?? 0,\n idleTimeoutMillis: this.config.idleTimeoutMillis ?? 30000,\n connectionTimeoutMillis: this.config.connectionTimeoutMillis ?? 2000,\n application_name: this.config.application_name ?? \"cascade\",\n ssl: this.config.ssl,\n };\n\n log.info(\n \"database.postgres\",\n \"connection\",\n `Connecting to database ${colors.bold(colors.yellowBright(this.config.database))}`,\n );\n\n this._pool = new pg.Pool(poolConfig);\n\n // Test the connection\n const client = await this._pool.connect();\n client.release();\n\n log.success(\n \"database.postgres\",\n \"connection\",\n `Connected to database ${colors.bold(colors.yellowBright(this.config.database))}`,\n );\n\n this._isConnected = true;\n\n // Learn which columns are native arrays straight from the live schema so\n // the value serializer encodes them correctly with zero app config.\n await this.loadNativeArrayColumns();\n\n this.emit(\"connected\");\n } catch (error) {\n // Boot-time database connection failure is unrecoverable in every\n // realistic caller (app boot, CLI migrations, workers) — `fatal` makes\n // \"page on fatal only\" alerting clean. Per-query failures stay at error.\n log.fatal(\"database.postgres\", \"connection\", \"Failed to connect to database\");\n throw error;\n }\n }\n\n /**\n * Close the database connection pool.\n *\n * Waits for all active queries to complete before closing.\n * Emits 'disconnected' event on successful disconnection.\n */\n public async disconnect(): Promise<void> {\n if (!this._isConnected || !this._pool) {\n return;\n }\n\n await this._pool.end();\n this._pool = undefined;\n this._isConnected = false;\n this.emit(\"disconnected\");\n }\n\n /**\n * Register an event listener for driver lifecycle events.\n *\n * @param event - Event name ('connected', 'disconnected', etc.)\n * @param listener - Callback function to invoke\n */\n public on(event: string, listener: DriverEventListener): void {\n if (!this._eventListeners.has(event)) {\n this._eventListeners.set(event, new Set());\n }\n\n this._eventListeners.get(event)!.add(listener);\n }\n\n /**\n * Serialize data for storage in PostgreSQL.\n *\n * Handles Date objects, BigInt, and other JavaScript types\n * that need special handling for PostgreSQL storage.\n *\n * @param data - The data object to serialize\n * @param table - Optional table name; when given, columns introspected as\n * native arrays on that table are bound raw (see {@link serializeValue}).\n * @returns Serialized data ready for PostgreSQL\n */\n public serialize(\n data: Record<string, unknown>,\n table?: string,\n ): Record<string, unknown> {\n const serialized: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(data)) {\n if (value === undefined) {\n continue; // Skip undefined values\n }\n\n serialized[key] = this.serializeValue(key, value, table);\n }\n\n return serialized;\n }\n\n /**\n * Serialize a single column value into a node-pg bindable parameter.\n *\n * Shared by {@link serialize} (INSERT path) and {@link buildUpdateQuery}\n * `$set` (UPDATE path) so both encode `json` / `jsonb` columns identically.\n *\n * Encoding rules (in order):\n * - `Date` → ISO string.\n * - `bigint` → decimal string (node-pg has no native bigint binding).\n * - all-number array → pgvector literal `'[n1,n2,...]'`. node-pg would\n * otherwise emit a `{n1,n2,...}` array literal, which the `vector` type\n * rejects. This branch is preserved exactly.\n * - any other array (object-array, string-array, mixed, empty `[]`) →\n * `JSON.stringify`. node-pg renders a raw JS array as a PostgreSQL array\n * literal `{...}` (and `[]` as `{}`), which a `json` / `jsonb` column\n * rejects — so we bind the value as JSON text instead, the form those\n * columns accept. Columns known to be native arrays — via schema\n * introspection or the `nativeArrayColumns` config — are exempt: their raw\n * array is passed through so node-pg emits the `{...}` literal a genuine\n * `JSONB[]` / `TEXT[]` column needs.\n * - plain object → `JSON.stringify`. Equivalent to node-pg's own object\n * handling, made explicit so both write paths agree.\n * - everything else (scalars: string, number, boolean, null) → untouched.\n *\n * Distinguishing native-array from `json` / `jsonb` columns: a value alone\n * can't tell them apart, so the driver introspects the live schema on connect\n * (see {@link loadNativeArrayColumns}) and consults that per-table map here\n * via {@link isNativeArrayColumn}. The explicit `nativeArrayColumns` config\n * still works as a table-agnostic override. No `::jsonb` placeholder cast is\n * added: a JSON-text string binds correctly to `json` / `jsonb` without one,\n * and a blind cast would misfire on columns we cannot positively identify as\n * jsonb.\n *\n * @param key - Column name (used to resolve native-array columns)\n * @param value - The raw value to serialize (never `undefined`)\n * @param table - Optional table name; enables the per-table native-array lookup\n * @returns The value ready to bind as a query parameter\n */\n private serializeValue(key: string, value: unknown, table?: string): unknown {\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n if (value.length > 0 && value.every((v) => typeof v === \"number\")) {\n // pgvector columns expect the literal '[n1,n2,...]' format.\n return `[${value.join(\",\")}]`;\n }\n\n // Genuine native PostgreSQL array columns (JSONB[], TEXT[], …) must\n // keep their raw array so node-pg emits a '{...}' array literal.\n if (this.isNativeArrayColumn(table, key)) {\n return value;\n }\n\n // json / jsonb columns: bind as JSON text. Covers object-arrays,\n // string-arrays, mixed arrays, and empty [] (which would otherwise\n // store as '{}' instead of '[]').\n return JSON.stringify(value);\n }\n\n if (typeof value === \"object\" && value !== null) {\n // Plain object → JSONB. Explicit JSON.stringify matches node-pg's own\n // object encoding while keeping both write paths consistent.\n return JSON.stringify(value);\n }\n\n return value;\n }\n\n /**\n * Whether `column` on `table` is a native PostgreSQL array. True when the\n * connect-time schema introspection saw it as `data_type = 'ARRAY'` for that\n * table (authoritative, per-table), or when it's listed in the table-agnostic\n * `nativeArrayColumns` config override.\n */\n private isNativeArrayColumn(table: string | undefined, column: string): boolean {\n if (table && this._introspectedArrayColumns.get(table)?.has(column)) {\n return true;\n }\n\n return this._nativeArrayColumns.has(column);\n }\n\n /**\n * Introspect the live schema for native-array columns so array values bind\n * correctly with zero app configuration.\n *\n * A JS array must be bound two opposite ways depending on the column: as JSON\n * text for a `json` / `jsonb` column, but as a raw array (which node-pg\n * renders `{...}`) for a native `TEXT[]` / `JSONB[]` / `INTEGER[]` column. The\n * serializer sees values, not types, so without this it JSON-stringifies\n * every array — which a native-array column rejects with \"malformed array\n * literal\". One `information_schema` query at connect, cached for the\n * connection lifetime, removes the need to hand-list `nativeArrayColumns`.\n *\n * Best-effort: any failure (e.g. restricted catalog access) is logged and\n * leaves the map empty so the config override still applies — it never blocks\n * connect. A schema change made within a live connection isn't reflected\n * until the next connect.\n */\n private async loadNativeArrayColumns(): Promise<void> {\n try {\n const result = await this.query<{ table_name: string; column_name: string }>(\n `SELECT table_name, column_name\n FROM information_schema.columns\n WHERE table_schema = ANY (current_schemas(false))\n AND data_type = 'ARRAY'`,\n );\n\n const map = new Map<string, Set<string>>();\n\n for (const { table_name, column_name } of result.rows) {\n let columns = map.get(table_name);\n\n if (!columns) {\n columns = new Set<string>();\n map.set(table_name, columns);\n }\n\n columns.add(column_name);\n }\n\n this._introspectedArrayColumns = map;\n } catch {\n // Introspection is an optimization, never a hard dependency — fall back\n // to the `nativeArrayColumns` config so a locked-down catalog or an\n // unusual search_path can't break connect.\n log.warn(\n \"database.postgres\",\n \"introspection\",\n \"Could not introspect native-array columns; using the nativeArrayColumns config only\",\n );\n }\n }\n\n /**\n * Get the dirty tracker for this driver.\n */\n public getDirtyTracker(data: Record<string, unknown>): SqlDatabaseDirtyTracker {\n return new SqlDatabaseDirtyTracker(data);\n }\n\n /**\n * Deserialize data retrieved from PostgreSQL.\n *\n * Converts PostgreSQL types back to JavaScript equivalents.\n *\n * @param data - The data object from PostgreSQL\n * @returns Deserialized JavaScript object\n */\n public deserialize(data: Record<string, unknown>): Record<string, unknown> {\n // PostgreSQL pg driver handles most type conversions automatically\n // Special handling can be added here if needed\n for (const [key, value] of Object.entries(data)) {\n // Only re-inflate strings — pg already returns Date objects from DB reads\n if (typeof value !== \"string\") continue;\n\n if (isValidDateValue(value)) {\n data[key] = new Date(value);\n continue;\n }\n\n // pgvector columns are returned as '[n1,n2,...]' strings.\n // charCodeAt is faster than startsWith/endsWith — no string allocation.\n // '[' = 91, ']' = 93\n if (value.charCodeAt(0) === 91 && value.charCodeAt(value.length - 1) === 93) {\n const parts = value.slice(1, -1).split(\",\");\n const nums = new Array<number>(parts.length);\n let isNumericVector = parts.length > 0;\n\n for (let i = 0; i < parts.length; i++) {\n const n = +parts[i]; // unary + is the fastest string-to-number coercion\n if (!Number.isFinite(n)) {\n isNumericVector = false;\n break; // early-exit — not a numeric vector, leave value untouched\n }\n nums[i] = n;\n }\n\n if (isNumericVector) {\n data[key] = nums;\n }\n }\n }\n\n return data;\n }\n\n /**\n * Insert a single row into a table.\n *\n * Uses INSERT ... RETURNING to get the inserted row with generated values.\n *\n * @param table - Target table name\n * @param document - Data to insert\n * @param options - Optional insertion options\n * @returns The inserted document\n */\n public async insert(\n table: string,\n document: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<InsertResult> {\n const serialized = this.serialize(document, table);\n\n // Filter out id if null/undefined to let PostgreSQL SERIAL auto-generate\n const filteredData = Object.fromEntries(\n Object.entries(serialized).filter(([key, value]) => {\n // Exclude id if null/undefined (let SERIAL handle it)\n if (key === \"id\" && (value === null || value === undefined)) {\n return false;\n }\n return true;\n }),\n );\n\n const columns = Object.keys(filteredData);\n const values = Object.values(filteredData);\n\n if (columns.length === 0) {\n throw new Error(\"Cannot insert empty document\");\n }\n\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const placeholders = columns.map((_, i) => this.dialect.placeholder(i + 1)).join(\", \");\n const quotedTable = this.dialect.quoteIdentifier(table);\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES (${placeholders}) RETURNING *`;\n\n const result = await this.query<Record<string, unknown>>(sql, values);\n\n return {\n document: result.rows[0],\n };\n }\n\n /**\n * Insert multiple rows into a table.\n *\n * Uses a single INSERT statement with multiple value sets for efficiency.\n *\n * @param table - Target table name\n * @param documents - Array of documents to insert\n * @param options - Optional insertion options\n * @returns Array of inserted documents\n */\n public async insertMany(\n table: string,\n documents: Record<string, unknown>[],\n _options?: Record<string, unknown>,\n ): Promise<InsertResult[]> {\n if (documents.length === 0) {\n return [];\n }\n\n // Get all unique columns across all documents\n const allColumns = new Set<string>();\n for (const doc of documents) {\n const serialized = this.serialize(doc, table);\n Object.keys(serialized).forEach((key) => allColumns.add(key));\n }\n const columns = Array.from(allColumns);\n\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const quotedTable = this.dialect.quoteIdentifier(table);\n\n // Build value sets and params\n const valueSets: string[] = [];\n const params: unknown[] = [];\n let paramIndex = 1;\n\n for (const doc of documents) {\n const serialized = this.serialize(doc, table);\n const rowPlaceholders: string[] = [];\n\n for (const col of columns) {\n if (col in serialized) {\n rowPlaceholders.push(this.dialect.placeholder(paramIndex++));\n params.push(serialized[col]);\n } else {\n rowPlaceholders.push(\"DEFAULT\");\n }\n }\n\n valueSets.push(`(${rowPlaceholders.join(\", \")})`);\n }\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES ${valueSets.join(\", \")} RETURNING *`;\n\n const result = await this.query<Record<string, unknown>>(sql, params);\n\n return result.rows as unknown as InsertResult[];\n }\n\n /**\n * Update a single row matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations ($set, $unset, $inc)\n * @param options - Optional update options\n * @returns Update result with modified count\n */\n public async update(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update, 1);\n try {\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n } catch (error) {\n console.log(\"PG Query Error in:\", sql, params);\n\n throw error;\n }\n }\n\n /**\n * Find one and update a single row matching the filter and return the updated row\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations ($set, $unset, $inc)\n * @param options - Optional update options\n * @returns The updated row or null\n */\n public async findOneAndUpdate<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update, 1);\n // Add RETURNING * to get the updated row back\n const sqlWithReturning = `${sql} RETURNING *`;\n const result = await this.query<T>(sqlWithReturning, params);\n return result.rows[0] ?? null;\n }\n\n /**\n * Update multiple rows matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations\n * @param options - Optional update options\n * @returns Update result with modified count\n */\n public async updateMany(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, update);\n\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n }\n\n /**\n * Replace a document matching the filter.\n *\n * Completely replaces the document (not a partial update).\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param document - New document data\n * @param options - Optional options\n * @returns The replaced document or null\n */\n public async replace<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const serialized = this.serialize(document, table);\n const columns = Object.keys(serialized);\n const values = Object.values(serialized);\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const setClauses = columns\n .map((col, i) => `${this.dialect.quoteIdentifier(col)} = ${this.dialect.placeholder(i + 1)}`)\n .join(\", \");\n\n const { whereClause, whereParams } = this.buildWhereClause(filter, columns.length + 1);\n\n const sql = `UPDATE ${quotedTable} SET ${setClauses} ${whereClause} RETURNING *`;\n const params = [...values, ...whereParams];\n\n const result = await this.query<T>(sql, params);\n\n return result.rows[0] ?? null;\n }\n\n /**\n * Upsert (insert or update) a single row.\n *\n * Uses PostgreSQL's INSERT ... ON CONFLICT ... DO UPDATE syntax.\n *\n * @param table - Target table name\n * @param filter - Filter conditions to find existing row (used for conflict detection)\n * @param document - Document data to insert or update\n * @param options - Upsert options (conflictColumns for conflict target)\n * @returns The upserted row\n */\n public async upsert<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n document: Record<string, unknown>,\n options?: Record<string, unknown>,\n ): Promise<T> {\n const serialized = this.serialize(document, table);\n const columns = Object.keys(serialized);\n const values = Object.values(serialized);\n\n if (columns.length === 0) {\n throw new Error(\"Cannot upsert empty document\");\n }\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const quotedColumns = columns.map((c) => this.dialect.quoteIdentifier(c)).join(\", \");\n const placeholders = columns.map((_, i) => this.dialect.placeholder(i + 1)).join(\", \");\n\n // Determine conflict columns from options or filter\n const conflictColumns = (options?.conflictColumns as string[]) ?? Object.keys(filter);\n if (conflictColumns.length === 0) {\n throw new Error(\"Upsert requires conflictColumns option or filter with columns\");\n }\n\n const quotedConflictColumns = conflictColumns\n .map((c) => this.dialect.quoteIdentifier(c))\n .join(\", \");\n\n // Build UPDATE clause for ON CONFLICT\n // Update all columns except the conflict columns (they stay the same)\n const updateColumns = columns.filter((col) => !conflictColumns.includes(col));\n const setClauses = updateColumns\n .map((col, i) => {\n const valueIndex = columns.indexOf(col) + 1;\n return `${this.dialect.quoteIdentifier(col)} = ${this.dialect.placeholder(valueIndex)}`;\n })\n .join(\", \");\n\n // If there are no columns to update (all columns are conflict columns), use EXCLUDED\n const updateClause =\n setClauses.length > 0\n ? setClauses\n : columns\n .map(\n (col) =>\n `${this.dialect.quoteIdentifier(col)} = EXCLUDED.${this.dialect.quoteIdentifier(col)}`,\n )\n .join(\", \");\n\n const sql = `INSERT INTO ${quotedTable} (${quotedColumns}) VALUES (${placeholders}) ON CONFLICT (${quotedConflictColumns}) DO UPDATE SET ${updateClause} RETURNING *`;\n\n const result = await this.query<T>(sql, values);\n\n return result.rows[0]! as T;\n }\n\n /**\n * Find one and delete a single row matching the filter and return the deleted row.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional delete options\n * @returns The deleted row or null\n */\n public async findOneAndDelete<T = unknown>(\n table: string,\n filter: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<T | null> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter, 1);\n\n // Use ctid for single row deletion with RETURNING\n const sql = `DELETE FROM ${quotedTable} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1) RETURNING *`;\n\n const result = await this.query<T>(sql, whereParams);\n\n return result.rows[0] ? (result.rows[0] as T) : null;\n }\n\n /**\n * Delete a single row matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional options\n * @returns Number of deleted rows (0 or 1)\n */\n public async delete(\n table: string,\n filter?: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter ?? {}, 1);\n\n // Use ctid for single row deletion\n const sql = `DELETE FROM ${quotedTable} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1)`;\n\n const result = await this.query(sql, whereParams);\n\n return result.rowCount ?? 0;\n }\n\n /**\n * Delete multiple rows matching the filter.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param options - Optional options\n * @returns Number of deleted rows\n */\n public async deleteMany(\n table: string,\n filter?: Record<string, unknown>,\n _options?: Record<string, unknown>,\n ): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter ?? {}, 1);\n\n const sql = `DELETE FROM ${quotedTable} ${whereClause}`;\n\n const result = await this.query(sql, whereParams);\n\n return result.rowCount ?? 0;\n }\n\n /**\n * Truncate a table (remove all rows).\n *\n * Uses TRUNCATE TABLE for fast deletion with RESTART IDENTITY.\n *\n * @param table - Target table name\n * @param options - Optional options\n * @param options.cascade - If true, automatically truncate all tables with foreign key references (use with caution)\n * @returns Number of deleted rows (always 0 for TRUNCATE)\n */\n public async truncateTable(table: string, options?: { cascade?: boolean }): Promise<number> {\n const quotedTable = this.dialect.quoteIdentifier(table);\n const cascadeClause = options?.cascade ? \" CASCADE\" : \"\";\n await this.query(`TRUNCATE TABLE ${quotedTable} RESTART IDENTITY${cascadeClause}`);\n return 0; // TRUNCATE doesn't return row count\n }\n\n /**\n * Get a query builder for the specified table.\n *\n * @param table - Target table name\n * @returns Query builder instance\n */\n public queryBuilder<T = unknown>(table: string): QueryBuilderContract<T> {\n return new PostgresQueryBuilder<T>(table) as unknown as QueryBuilderContract<T>;\n }\n\n /**\n * Begin a new database transaction.\n *\n * Acquires a client from the pool and starts a transaction.\n * The client is stored in AsyncLocalStorage for automatic\n * participation by subsequent queries.\n *\n * @param options - Optional transaction options\n * @returns Transaction contract with commit/rollback methods\n */\n public async beginTransaction(\n options?: PostgresTransactionOptions,\n ): Promise<DriverTransactionContract<PgPoolClient>> {\n const client = await this.pool.connect();\n\n let beginSql = \"BEGIN\";\n if (options?.isolationLevel) {\n beginSql += ` ISOLATION LEVEL ${options.isolationLevel.toUpperCase()}`;\n }\n if (options?.readOnly) {\n beginSql += \" READ ONLY\";\n }\n if (options?.deferrable) {\n beginSql += \" DEFERRABLE\";\n }\n\n await client.query(beginSql);\n\n return {\n context: client,\n commit: async () => {\n await client.query(\"COMMIT\");\n client.release();\n },\n rollback: async () => {\n await client.query(\"ROLLBACK\");\n client.release();\n },\n };\n }\n\n /**\n * Execute a function within a transaction scope (recommended pattern).\n *\n * Automatically commits on success, rolls back on any error, and guarantees\n * resource cleanup. This is the recommended way to use transactions.\n *\n * @param fn - Async function to execute within transaction\n * @param options - Transaction options (isolation level, read-only, etc.)\n * @returns The return value of the callback function\n * @throws {Error} If transaction fails or is explicitly rolled back\n */\n public async transaction<T>(\n fn: (ctx: TransactionContext) => Promise<T>,\n options?: Record<string, unknown>,\n ): Promise<T> {\n const ctx: TransactionContext = {\n rollback(reason?: string): never {\n throw new TransactionRollbackError(reason);\n },\n };\n\n // Flat nesting: a transaction() called while one is already active JOINS it\n // instead of opening a second, independent transaction on another pool\n // connection. An independent inner transaction can't see the outer's\n // uncommitted writes (a row inserted moments earlier), so a service that\n // opens its own transaction — correct when called standalone — would hit\n // phantom FK violations when called inside an outer transaction (e.g. a\n // seeder that creates a row, then calls a service that references it). The\n // outermost transaction owns BEGIN / COMMIT / ROLLBACK; the inner block\n // runs on the same session, and a throw still unwinds the whole outer\n // transaction. (Savepoint-based partial rollback is a separate, explicit\n // concern — use `beginTransaction()` directly for that.)\n if (databaseTransactionContext.hasActiveTransaction()) {\n return fn(ctx);\n }\n\n const tx = await this.beginTransaction(options);\n\n // Set transaction context for queries within callback\n databaseTransactionContext.enter({ session: tx.context });\n\n try {\n // Execute callback\n const result = await fn(ctx);\n\n // Auto-commit on success\n await tx.commit();\n\n return result;\n } catch (error) {\n // Auto-rollback on any error (including explicit rollback)\n await tx.rollback();\n log.error(\n `database.postgress`,\n \"transaction\",\n \"Transaction operation failed, rolled back everything\",\n );\n throw error;\n } finally {\n // Guaranteed cleanup\n databaseTransactionContext.exit();\n }\n }\n\n /**\n * Perform an atomic update operation.\n *\n * Builds and executes an UPDATE query for the given filter and operations.\n * Updates EVERY matching row — the MongoDB driver's atomic() delegates to\n * updateMany, and Model.findAndUpdate documents multi-row semantics, so the\n * two drivers must agree.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param operations - Update operations\n * @param options - Optional options\n * @returns Update result\n */\n public async atomic(\n table: string,\n filter: Record<string, unknown>,\n operations: UpdateOperations,\n _options?: Record<string, unknown>,\n ): Promise<UpdateResult> {\n const { sql, params } = this.buildUpdateQuery(table, filter, operations);\n\n const result = await this.query(sql, params);\n\n return {\n modifiedCount: result.rowCount ?? 0,\n };\n }\n\n /**\n * Get the sync adapter for bulk denormalized updates.\n *\n * @returns Sync adapter instance\n */\n public syncAdapter(): SyncAdapterContract {\n if (!this._syncAdapter) {\n this._syncAdapter = new PostgresSyncAdapter(this);\n }\n return this._syncAdapter;\n }\n\n /**\n * Get the migration driver for schema operations.\n *\n * @returns Migration driver instance\n */\n public migrationDriver(): MigrationDriverContract {\n if (!this._migrationDriver) {\n this._migrationDriver = new PostgresMigrationDriver(this);\n }\n\n return this._migrationDriver;\n }\n\n /**\n * Return a SQL serializer for this driver's dialect.\n * Used by Migration.toSQL() to convert pending operations to SQL strings.\n */\n public getSQLSerializer(): SQLSerializer {\n return new PostgresSQLSerializer(this.dialect);\n }\n\n /**\n * Execute a raw SQL query.\n *\n * Automatically uses the transaction client if one is active.\n *\n * @param sql - SQL query string\n * @param params - Query parameters\n * @returns Query result\n */\n public async query<T = Record<string, unknown>>(\n sql: string,\n params: unknown[] = [],\n ): Promise<PostgresQueryResult<T>> {\n // Check for active transaction client\n const txClient = databaseTransactionContext.getSession() as PgPoolClient | undefined;\n\n const startTime = this.config.logging ? performance.now() : 0;\n\n let paramsString = \"\";\n if (this.config.logging && params.length > 0) {\n paramsString = JSON.stringify(params);\n if (paramsString.length > 300) {\n paramsString = paramsString.substring(0, 300) + \"...\";\n }\n paramsString = ` | Params: ${paramsString}`;\n }\n\n try {\n let result;\n if (this.config.logging) {\n log.info({\n module: \"database.postgres\",\n action: \"query.executing\",\n message: `${sql}${paramsString}`,\n context: { params, sql },\n });\n }\n if (txClient) {\n result = await txClient.query(sql, params);\n } else {\n result = await this.pool.query(sql, params);\n }\n\n if (this.config.logging) {\n const duration = (performance.now() - startTime).toFixed(2);\n log.success({\n module: \"database.postgres\",\n action: \"query.executed\",\n message: `[${duration}ms] ${sql}${paramsString}`,\n context: { params, sql, duration },\n });\n }\n\n return result as PostgresQueryResult<T>;\n } catch (error) {\n if (this.config.logging) {\n const duration = (performance.now() - startTime).toFixed(2);\n log.error({\n module: \"database.postgres\",\n action: \"query.error\",\n message: `[${duration}ms] ${sql}${paramsString}`,\n context: {\n sql,\n params,\n error: error instanceof Error ? error.message : String(error),\n },\n });\n }\n throw error;\n }\n }\n\n /**\n * Emit an event to all registered listeners.\n *\n * @param event - Event name\n * @param args - Event arguments\n */\n private emit(event: string, ...args: unknown[]): void {\n const listeners = this._eventListeners.get(event);\n if (listeners) {\n for (const listener of listeners) {\n listener(...args);\n }\n }\n }\n\n /**\n * Build a simple WHERE clause from a filter object.\n *\n * Values are bound as plain equality, except Mongo-style operator objects\n * (`{ $in: [...] }`, `{ $gt: 5 }`, ...) which are translated to their SQL\n * equivalents — driver-level callers (e.g. pivot detach) build filters in\n * that portable form. An unrecognized `$` operator throws instead of being\n * bound literally, which would only surface as a cryptic type error from\n * Postgres.\n *\n * @param filter - Filter conditions\n * @param startParamIndex - Starting parameter index\n * @returns Object with WHERE clause string and parameters\n */\n private buildWhereClause(\n filter: Record<string, unknown>,\n startParamIndex: number,\n ): { whereClause: string; whereParams: unknown[] } {\n const conditions: string[] = [];\n const params: unknown[] = [];\n let paramIndex = startParamIndex;\n\n for (const [key, value] of Object.entries(filter)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n\n if (value === null) {\n conditions.push(`${quotedKey} IS NULL`);\n } else if (this.isOperatorFilter(value)) {\n for (const [operator, operand] of Object.entries(value as Record<string, unknown>)) {\n switch (operator) {\n case \"$in\":\n case \"$nin\": {\n const list = operand as unknown[];\n if (list.length === 0) {\n // $in [] matches nothing; $nin [] matches everything.\n conditions.push(operator === \"$in\" ? \"FALSE\" : \"TRUE\");\n break;\n }\n const placeholders = list.map(() => this.dialect.placeholder(paramIndex++));\n params.push(...list);\n conditions.push(\n `${quotedKey} ${operator === \"$in\" ? \"IN\" : \"NOT IN\"} (${placeholders.join(\", \")})`,\n );\n break;\n }\n case \"$eq\":\n if (operand === null) {\n conditions.push(`${quotedKey} IS NULL`);\n } else {\n conditions.push(`${quotedKey} = ${this.dialect.placeholder(paramIndex++)}`);\n params.push(operand);\n }\n break;\n case \"$ne\":\n if (operand === null) {\n conditions.push(`${quotedKey} IS NOT NULL`);\n } else {\n conditions.push(`${quotedKey} != ${this.dialect.placeholder(paramIndex++)}`);\n params.push(operand);\n }\n break;\n case \"$gt\":\n case \"$gte\":\n case \"$lt\":\n case \"$lte\": {\n const sqlOperator = { $gt: \">\", $gte: \">=\", $lt: \"<\", $lte: \"<=\" }[operator];\n conditions.push(`${quotedKey} ${sqlOperator} ${this.dialect.placeholder(paramIndex++)}`);\n params.push(operand);\n break;\n }\n default:\n throw new Error(\n `Unsupported filter operator \"${operator}\" for column \"${key}\" on the Postgres driver.`,\n );\n }\n }\n } else {\n conditions.push(`${quotedKey} = ${this.dialect.placeholder(paramIndex++)}`);\n params.push(value);\n }\n }\n\n const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(\" AND \")}` : \"\";\n\n return { whereClause, whereParams: params };\n }\n\n /**\n * A filter value is an operator object when it is a plain object whose keys\n * ALL start with `$`. Arrays, Dates, and value objects (e.g. jsonb equality\n * payloads) keep their existing bind-as-value behavior.\n */\n private isOperatorFilter(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n if (value instanceof Date || Buffer.isBuffer(value)) {\n return false;\n }\n\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key) => key.startsWith(\"$\"));\n }\n\n /**\n * Build an UPDATE query from update operations.\n *\n * @param table - Target table name\n * @param filter - Filter conditions\n * @param update - Update operations\n * @param limit - Optional limit (for single row update)\n * @returns Object with SQL and parameters\n */\n private buildUpdateQuery(\n table: string,\n filter: Record<string, unknown>,\n update: UpdateOperations,\n limit?: number,\n ): { sql: string; params: unknown[] } {\n const setClauses: string[] = [];\n const params: unknown[] = [];\n let paramIndex = 1;\n\n // Handle $set\n if (update.$set) {\n for (const [key, value] of Object.entries(update.$set)) {\n setClauses.push(\n `${this.dialect.quoteIdentifier(key)} = ${this.dialect.placeholder(paramIndex++)}`,\n );\n // Apply the same json/jsonb-aware serialization used on the INSERT\n // path so object/array $set values aren't corrupted into Postgres\n // array literals. undefined is skipped — never bind it.\n params.push(value === undefined ? value : this.serializeValue(key, value, table));\n }\n }\n\n // Handle $unset (set to NULL)\n if (update.$unset) {\n for (const key of Object.keys(update.$unset)) {\n setClauses.push(`${this.dialect.quoteIdentifier(key)} = NULL`);\n }\n }\n\n // Handle $inc\n if (update.$inc) {\n for (const [key, amount] of Object.entries(update.$inc)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n setClauses.push(\n `${quotedKey} = COALESCE(${quotedKey}, 0) + ${this.dialect.placeholder(paramIndex++)}`,\n );\n params.push(amount);\n }\n }\n\n // Handle $dec\n if (update.$dec) {\n for (const [key, amount] of Object.entries(update.$dec)) {\n const quotedKey = this.dialect.quoteIdentifier(key);\n setClauses.push(\n `${quotedKey} = COALESCE(${quotedKey}, 0) - ${this.dialect.placeholder(paramIndex++)}`,\n );\n params.push(amount);\n }\n }\n\n if (setClauses.length === 0) {\n throw new Error(\"No update operations specified\");\n }\n\n const quotedTable = this.dialect.quoteIdentifier(table);\n const { whereClause, whereParams } = this.buildWhereClause(filter, paramIndex);\n params.push(...whereParams);\n\n let sql = `UPDATE ${quotedTable} SET ${setClauses.join(\", \")} ${whereClause}`;\n\n // For single row update, use ctid subquery\n if (limit === 1 && whereClause) {\n sql = `UPDATE ${quotedTable} SET ${setClauses.join(\", \")} WHERE ctid IN (SELECT ctid FROM ${quotedTable} ${whereClause} LIMIT 1)`;\n }\n\n return { sql, params };\n }\n\n // ============================================================\n // Database Lifecycle Operations\n // ============================================================\n\n /**\n * Create a new database.\n *\n * Note: This requires connecting to a system database (like 'postgres')\n * since you cannot create a database while connected to it.\n *\n * @param name - Database name to create\n * @param options - Creation options (encoding, template, etc.)\n * @returns true if created, false if already exists\n */\n public async createDatabase(name: string, options?: CreateDatabaseOptions): Promise<boolean> {\n // Check if database already exists\n if (await this.databaseExists(name)) {\n return false;\n }\n\n // Build CREATE DATABASE statement\n const quotedName = this.dialect.quoteIdentifier(name);\n let sql = `CREATE DATABASE ${quotedName}`;\n\n const withClauses: string[] = [];\n\n if (options?.encoding) {\n withClauses.push(`ENCODING = '${options.encoding}'`);\n }\n if (options?.template) {\n withClauses.push(`TEMPLATE = ${this.dialect.quoteIdentifier(options.template)}`);\n }\n if (options?.locale) {\n withClauses.push(`LC_COLLATE = '${options.locale}'`);\n withClauses.push(`LC_CTYPE = '${options.locale}'`);\n }\n if (options?.owner) {\n withClauses.push(`OWNER = ${this.dialect.quoteIdentifier(options.owner)}`);\n }\n\n if (withClauses.length > 0) {\n sql += ` WITH ${withClauses.join(\" \")}`;\n }\n\n try {\n await this.query(sql);\n log.success(\"database\", \"lifecycle\", `Created database ${name}`);\n return true;\n } catch (error) {\n log.error(\"database\", \"lifecycle\", `Failed to create database ${name}: ${error}`);\n throw error;\n }\n }\n\n /**\n * Drop a database.\n *\n * @param name - Database name to drop\n * @param options - Drop options\n * @returns true if dropped, false if didn't exist\n */\n public async dropDatabase(name: string, options?: DropDatabaseOptions): Promise<boolean> {\n // Check if database exists first (if ifExists option not set)\n if (!options?.ifExists && !(await this.databaseExists(name))) {\n return false;\n }\n\n const quotedName = this.dialect.quoteIdentifier(name);\n let sql = \"DROP DATABASE\";\n\n if (options?.ifExists) {\n sql += \" IF EXISTS\";\n }\n\n sql += ` ${quotedName}`;\n\n // PostgreSQL 13+ supports WITH (FORCE) to terminate active connections\n if (options?.force) {\n sql += \" WITH (FORCE)\";\n }\n\n try {\n await this.query(sql);\n log.success(\"database\", \"lifecycle\", `Dropped database ${name}`);\n return true;\n } catch (error) {\n log.error(\"database\", \"lifecycle\", `Failed to drop database ${name}: ${error}`);\n throw error;\n }\n }\n\n /**\n * Check if a database exists.\n *\n * @param name - Database name to check\n * @returns true if database exists\n */\n public async databaseExists(name: string): Promise<boolean> {\n const result = await this.query<{ exists: boolean }>(\n `SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1) as exists`,\n [name],\n );\n\n return result.rows[0]?.exists ?? false;\n }\n\n /**\n * List all databases.\n *\n * @returns Array of database names\n */\n public async listDatabases(): Promise<string[]> {\n const result = await this.query<{ datname: string }>(\n `SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname`,\n );\n\n return result.rows.map((row) => row.datname);\n }\n\n // ============================================================\n // Table Management Operations\n // ============================================================\n\n /**\n * Drop a table.\n *\n * @param name - Table name to drop\n * @throws Error if table doesn't exist\n */\n public async dropTable(name: string): Promise<void> {\n const quotedName = this.dialect.quoteIdentifier(name);\n await this.query(`DROP TABLE ${quotedName}`);\n log.success(\"database\", \"table\", `Dropped table ${name}`);\n }\n\n /**\n * Drop a table if it exists.\n *\n * @param name - Table name to drop\n */\n public async dropTableIfExists(name: string): Promise<void> {\n const quotedName = this.dialect.quoteIdentifier(name);\n await this.query(`DROP TABLE IF EXISTS ${quotedName}`);\n }\n\n /**\n * Drop all tables in the current database.\n *\n * Uses CASCADE to handle foreign key dependencies.\n * Useful for `migrate:fresh` command.\n */\n public async dropAllTables(): Promise<void> {\n // Get all tables from blueprint\n const tables = await this.blueprint.listTables();\n\n if (tables.length === 0) {\n return;\n }\n\n // Drop all tables with CASCADE to handle foreign keys\n for (const table of tables) {\n const quotedName = this.dialect.quoteIdentifier(table);\n await this.query(`DROP TABLE IF EXISTS ${quotedName} CASCADE`);\n }\n\n log.success(\"database\", \"table\", `Dropped ${tables.length} tables`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,IAAI;;;;;;;AAQJ,eAAe,SAAuC;CACpD,IAAI,UACF,OAAO;CAGT,IAAI;EACF,WAAW,MAAM,OAAO;EACxB,OAAO;CACT,QAAQ;EACN,MAAM,IAAI,MACR,0FACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,iBAAb,MAAsD;CAoFhB;;;;CAhFpC,AAAgB,OAAO;;;;CAKvB,AAAgB,UAAU,IAAI,gBAAgB;;;;;;;;;;CAW9C,AAAgB,gBAAwC;EACtD,kBAAkB;EAClB,iBAAiB;EACjB,iBAAiB;EACjB,iBAAiB;EACjB,YAAY;EACZ,gBAAgB;EAChB,YAAY;EACZ,gBAAgB;CAClB;;;;CAKA,AAAQ;;;;CAKR,AAAiB,kCAAkB,IAAI,IAAsC;;;;CAK7E,AAAQ,eAAe;;;;CAKvB,AAAQ;;;;CAKR,AAAQ;;;;CAKR,AAAQ;;;;;;;;;CAUR,AAAiB;;;;;;;CAQjB,AAAQ,4CAAsE,IAAI,IAAI;;;;;;CAOtF,AAAO,YAAY,AAAiB,QAA4B;EAA5B;EAClC,KAAK,sBAAsB,IAAI,IAAI,OAAO,sBAAsB,CAAC,CAAC;CACpE;;;;;;CAOA,IAAW,OAAe;EACxB,IAAI,CAAC,KAAK,OACR,MAAM,IAAI,MAAM,2DAA2D;EAE7E,OAAO,KAAK;CACd;;;;C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