@warlock.js/cascade 5.7.0 → 5.8.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.
@@ -1,6 +1,6 @@
1
1
  import { PostgresDialect } from "./postgres-dialect.mjs";
2
2
  import { PostgresConnectionConfig, PostgresCopyOptions, PostgresIsolationLevel, PostgresNotification, PostgresOperation, PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions, PostgresWhereClause } from "./types.mjs";
3
- import { PostgresDriver } from "./postgres-driver.mjs";
3
+ import { PostgresDriver, buildPostgresPoolConfig } from "./postgres-driver.mjs";
4
4
  import { PostgresBlueprint } from "./postgres-blueprint.mjs";
5
5
  import { PostgresMigrationDriver } from "./postgres-migration-driver.mjs";
6
6
  import { PostgresQueryBuilder } from "./postgres-query-builder.mjs";
@@ -4,6 +4,6 @@ import { PostgresMigrationDriver } from "./postgres-migration-driver.mjs";
4
4
  import { PostgresQueryParser } from "./postgres-query-parser.mjs";
5
5
  import { PostgresQueryBuilder } from "./postgres-query-builder.mjs";
6
6
  import { PostgresSyncAdapter } from "./postgres-sync-adapter.mjs";
7
- import { PostgresDriver } from "./postgres-driver.mjs";
7
+ import { PostgresDriver, buildPostgresPoolConfig } from "./postgres-driver.mjs";
8
8
 
9
9
  export { };
@@ -16,6 +16,23 @@ import { PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions } f
16
16
  */
17
17
  type PgPool = import("pg").Pool;
18
18
  type PgPoolClient = import("pg").PoolClient;
19
+ type PgPoolConfig = import("pg").PoolConfig;
20
+ /**
21
+ * Build pg's `PoolConfig` from cascade's `PostgresPoolConfig`, coercing the
22
+ * string-typed connection fields.
23
+ *
24
+ * `env()` (@mongez/dotenv) coerces a numeric-looking value to a number, so a
25
+ * `DB_NAME` / `DB_USERNAME` / `DB_PASSWORD` like "12345" arrives here as a
26
+ * number. pg's connection fields must be strings — a number reaches deep into
27
+ * the driver and crashes with an inscrutable Buffer error rather than a
28
+ * legible "database does not exist" (finding 51639bf8). So `host`, `database`,
29
+ * `user` and `password` are coerced to strings; `port` is a real number and
30
+ * `undefined` is left untouched so pg's own defaults still apply.
31
+ *
32
+ * Exported (not inlined into `connect()`) so the coercion is unit-testable
33
+ * without a live database.
34
+ */
35
+ declare function buildPostgresPoolConfig(config: PostgresPoolConfig): PgPoolConfig;
19
36
  /**
20
37
  * PostgreSQL database driver implementing the Cascade DriverContract.
21
38
  *
@@ -518,5 +535,5 @@ declare class PostgresDriver implements DriverContract {
518
535
  dropAllTables(): Promise<void>;
519
536
  }
520
537
  //#endregion
521
- export { PostgresDriver };
538
+ export { PostgresDriver, buildPostgresPoolConfig };
522
539
  //# sourceMappingURL=postgres-driver.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-driver.d.mts","names":[],"sources":["../../../../../../../../cascade/src/drivers/postgres/postgres-driver.ts"],"mappings":";;;;;;;;;;;;;AAgD2C;AA0D3C;;AA1D2C,KADtC,MAAA,gBAAsB,IAAI;AAAA,KAC1B,YAAA,gBAA4B,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0D9B,cAAA,YAA0B,cAAA;EAAA,iBAoFD,MAAA;EA0f1B;;;EAAA,SA1kBM,IAAA,EAAqB,cAAA;EA+lB3B;;;EAAA,SA1lBM,OAAA,EAAO,eAAA;EA6lBpB;;;;;;;;;EAAA,SAllBa,aAAA,EAAe,OAAA,CAAQ,aAAA;EAgpBpC;;;EAAA,QAloBK,KAAA;EAisBL;;;EAAA,iBA5rBc,eAAA;EA0uBN;;;EAAA,QAruBH,YAAA;EAywB8D;;;EAAA,QApwB9D,UAAA;EAoxBG;;;EAAA,QA/wBH,gBAAA;EAwzB2B;;;EAAA,QAnzB3B,YAAA;EAu3BE;;;;;;;;EAAA,iBA72BO,mBAAA;EAu6Bc;;;;;;EAAA,QA/5BvB,yBAAA;EAmwCmC;;;;;cA5vCP,MAAA,EAAQ,kBAAA;EApFO;;;;;EAAA,IA6FxC,IAAA,IA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,CAAA,GACzC,OAAA,GAAU,MAAA,oBACT,OAAA,CAAQ,CAAA;;;;;;;;;;;;;;;EAgEE,MAAA,CACX,KAAA,UACA,MAAA,EAAQ,MAAA,mBACR,UAAA,EAAY,gBAAA,EACZ,QAAA,GAAW,MAAA,oBACV,OAAA,CAAQ,YAAA;;;;;;EAeJ,WAAA,IAAe,mBAAA;;;;;;EAYf,eAAA,IAAmB,uBAAA;;;;;EAYnB,gBAAA,IAAoB,aAAA;;;;;;;;;;EAad,KAAA,KAAU,MAAA,mBACrB,GAAA,UACA,MAAA,eACC,OAAA,CAAQ,mBAAA,CAAoB,CAAA;;;;;;;UAkEvB,IAAA;;;;;;;;;;;;;;;UAuBA,gBAAA;;;;;;UA8EA,gBAAA;;;;;;;;;;UAsBA,gBAAA;;;;;;;;;;;EAoFK,cAAA,CAAe,IAAA,UAAc,OAAA,GAAU,qBAAA,GAAwB,OAAA;;;;;;;;EA+C/D,YAAA,CAAa,IAAA,UAAc,OAAA,GAAU,mBAAA,GAAsB,OAAA;;;;;;;EAoC3D,cAAA,CAAe,IAAA,WAAe,OAAA;;;;;;EAc9B,aAAA,IAAiB,OAAA;;;;;;;EAkBjB,SAAA,CAAU,IAAA,WAAe,OAAA;;;;;;EAWzB,iBAAA,CAAkB,IAAA,WAAe,OAAA;;;;;;;EAWjC,aAAA,IAAiB,OAAA;AAAA"}
@@ -24,6 +24,38 @@ import { log } from "@warlock.js/logger";
24
24
  * @module cascade/drivers/postgres
25
25
  */
26
26
  /**
27
+ * Build pg's `PoolConfig` from cascade's `PostgresPoolConfig`, coercing the
28
+ * string-typed connection fields.
29
+ *
30
+ * `env()` (@mongez/dotenv) coerces a numeric-looking value to a number, so a
31
+ * `DB_NAME` / `DB_USERNAME` / `DB_PASSWORD` like "12345" arrives here as a
32
+ * number. pg's connection fields must be strings — a number reaches deep into
33
+ * the driver and crashes with an inscrutable Buffer error rather than a
34
+ * legible "database does not exist" (finding 51639bf8). So `host`, `database`,
35
+ * `user` and `password` are coerced to strings; `port` is a real number and
36
+ * `undefined` is left untouched so pg's own defaults still apply.
37
+ *
38
+ * Exported (not inlined into `connect()`) so the coercion is unit-testable
39
+ * without a live database.
40
+ */
41
+ function buildPostgresPoolConfig(config) {
42
+ const asString = (value) => typeof value === "number" ? String(value) : value;
43
+ return {
44
+ host: asString(config.host) ?? "localhost",
45
+ port: config.port ?? 5432,
46
+ database: asString(config.database),
47
+ user: asString(config.user),
48
+ password: asString(config.password),
49
+ connectionString: config.connectionString,
50
+ max: config.max ?? 10,
51
+ min: config.min ?? 0,
52
+ idleTimeoutMillis: config.idleTimeoutMillis ?? 3e4,
53
+ connectionTimeoutMillis: config.connectionTimeoutMillis ?? 2e3,
54
+ application_name: config.application_name ?? "cascade",
55
+ ssl: config.ssl
56
+ };
57
+ }
58
+ /**
27
59
  * Cached pg module reference.
28
60
  */
29
61
  let pgModule;
@@ -187,21 +219,8 @@ var PostgresDriver = class {
187
219
  if (this._isConnected) return;
188
220
  const pg = await loadPg();
189
221
  try {
190
- const poolConfig = {
191
- host: this.config.host ?? "localhost",
192
- port: this.config.port ?? 5432,
193
- database: this.config.database,
194
- user: this.config.user,
195
- password: this.config.password,
196
- connectionString: this.config.connectionString,
197
- max: this.config.max ?? 10,
198
- min: this.config.min ?? 0,
199
- idleTimeoutMillis: this.config.idleTimeoutMillis ?? 3e4,
200
- connectionTimeoutMillis: this.config.connectionTimeoutMillis ?? 2e3,
201
- application_name: this.config.application_name ?? "cascade",
202
- ssl: this.config.ssl
203
- };
204
- log.info("database.postgres", "connection", `Connecting to database ${colors.bold(colors.yellowBright(this.config.database))}`);
222
+ const poolConfig = buildPostgresPoolConfig(this.config);
223
+ log.info("database.postgres", "connection", `Connecting to database ${colors.bold(colors.yellowBright(poolConfig.database ?? ""))}`);
205
224
  this._pool = new pg.Pool(poolConfig);
206
225
  (await this._pool.connect()).release();
207
226
  log.success("database.postgres", "connection", `Connected to database ${colors.bold(colors.yellowBright(this.config.database))}`);
@@ -1018,5 +1037,5 @@ var PostgresDriver = class {
1018
1037
  };
1019
1038
 
1020
1039
  //#endregion
1021
- export { PostgresDriver };
1040
+ export { PostgresDriver, buildPostgresPoolConfig };
1022
1041
  //# sourceMappingURL=postgres-driver.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-driver.mjs","names":[],"sources":["../../../../../../../../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 { type 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 // `parts[i]` is `string | undefined` under noUncheckedIndexedAccess even\n // though `i < parts.length`. `+undefined` is NaN, which the finite check\n // below already rejects — so `?? \"\"` keeps the coercion total without\n // changing which inputs count as a numeric vector (+\"\" is 0, but an\n // empty segment cannot occur for i < length).\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;;;;;;;;;;;;;;;;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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":["../../../../../../../../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 { type 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 * Build pg's `PoolConfig` from cascade's `PostgresPoolConfig`, coercing the\n * string-typed connection fields.\n *\n * `env()` (@mongez/dotenv) coerces a numeric-looking value to a number, so a\n * `DB_NAME` / `DB_USERNAME` / `DB_PASSWORD` like \"12345\" arrives here as a\n * number. pg's connection fields must be strings — a number reaches deep into\n * the driver and crashes with an inscrutable Buffer error rather than a\n * legible \"database does not exist\" (finding 51639bf8). So `host`, `database`,\n * `user` and `password` are coerced to strings; `port` is a real number and\n * `undefined` is left untouched so pg's own defaults still apply.\n *\n * Exported (not inlined into `connect()`) so the coercion is unit-testable\n * without a live database.\n */\nexport function buildPostgresPoolConfig(config: PostgresPoolConfig): PgPoolConfig {\n const asString = (value: unknown): string | undefined =>\n typeof value === \"number\" ? String(value) : (value as string | undefined);\n\n return {\n host: asString(config.host) ?? \"localhost\",\n port: config.port ?? 5432,\n database: asString(config.database),\n user: asString(config.user),\n password: asString(config.password),\n connectionString: config.connectionString,\n max: config.max ?? 10,\n min: config.min ?? 0,\n idleTimeoutMillis: config.idleTimeoutMillis ?? 30000,\n connectionTimeoutMillis: config.connectionTimeoutMillis ?? 2000,\n application_name: config.application_name ?? \"cascade\",\n ssl: config.ssl,\n };\n}\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 = buildPostgresPoolConfig(this.config);\n\n log.info(\n \"database.postgres\",\n \"connection\",\n `Connecting to database ${colors.bold(colors.yellowBright(poolConfig.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 // `parts[i]` is `string | undefined` under noUncheckedIndexedAccess even\n // though `i < parts.length`. `+undefined` is NaN, which the finite check\n // below already rejects — so `?? \"\"` keeps the coercion total without\n // changing which inputs count as a numeric vector (+\"\" is 0, but an\n // empty segment cannot occur for i < length).\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAAgB,wBAAwB,QAA0C;CAChF,MAAM,YAAY,UAChB,OAAO,UAAU,WAAW,OAAO,KAAK,IAAK;CAE/C,OAAO;EACL,MAAM,SAAS,OAAO,IAAI,KAAK;EAC/B,MAAM,OAAO,QAAQ;EACrB,UAAU,SAAS,OAAO,QAAQ;EAClC,MAAM,SAAS,OAAO,IAAI;EAC1B,UAAU,SAAS,OAAO,QAAQ;EAClC,kBAAkB,OAAO;EACzB,KAAK,OAAO,OAAO;EACnB,KAAK,OAAO,OAAO;EACnB,mBAAmB,OAAO,qBAAqB;EAC/C,yBAAyB,OAAO,2BAA2B;EAC3D,kBAAkB,OAAO,oBAAoB;EAC7C,KAAK,OAAO;CACd;AACF;;;;AAKA,IAAI;;;;;;;AAQJ,eAAe,SAAuC;CACpD,IAAI,UACF,OAAO;CAGT,IAAI;EACF,WAAW,MAAM,OAAO;EACxB,OAAO;CACT,QAAQ;EACN,MAAM,IAAI,MACR,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Aa,KAAK,QAAQ,gBAAgB,KAAK;GACrD,MAAM,KAAK,MAAM,wBAAwB,WAAW,SAAS;EAC/D;EAEA,IAAI,QAAQ,YAAY,SAAS,WAAW,OAAO,OAAO,QAAQ;CACpE;AACF"}
package/esm/index.d.mts CHANGED
@@ -62,13 +62,13 @@ import { SqlDialectContract } from "./drivers/sql/sql-dialect.contract.mjs";
62
62
  import { SqlAggregateFunction, SqlDeleteOperation, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType } from "./drivers/sql/sql-types.mjs";
63
63
  import { PostgresDialect } from "./drivers/postgres/postgres-dialect.mjs";
64
64
  import { PostgresConnectionConfig, PostgresCopyOptions, PostgresIsolationLevel, PostgresNotification, PostgresOperation, PostgresPoolConfig, PostgresQueryResult, PostgresTransactionOptions, PostgresWhereClause } from "./drivers/postgres/types.mjs";
65
- import { PostgresDriver } from "./drivers/postgres/postgres-driver.mjs";
65
+ import { PostgresDriver, buildPostgresPoolConfig } from "./drivers/postgres/postgres-driver.mjs";
66
66
  import { PostgresBlueprint } from "./drivers/postgres/postgres-blueprint.mjs";
67
67
  import { PostgresMigrationDriver } from "./drivers/postgres/postgres-migration-driver.mjs";
68
68
  import { PostgresQueryBuilder } from "./drivers/postgres/postgres-query-builder.mjs";
69
69
  import { PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresQueryParser } from "./drivers/postgres/postgres-query-parser.mjs";
70
70
  import { PostgresSyncAdapter } from "./drivers/postgres/postgres-sync-adapter.mjs";
71
71
  import { MongoClientOptions, TransactionOptions } from "mongodb";
72
- export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, PendingMigration, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult, PostgresSyncAdapter, PostgresTransactionOptions, PostgresWhereClause, QueryBuilderContract, RELATION_METADATA_KEY, RawColumnExpression, RawExpression, RawQueryResult, RegisterModel, RegisterModelOptions, type RelationConstraintCallback, type RelationConstraints, RelationDefaults, type RelationDefinition, type RelationDefinitions, RelationHydrator, RelationLoader, type RelationType, RemoverContract, RemoverOptions, RemoverResult, RestorerContract, RestorerOptions, RestorerResult, RollbackMigrationsOptions, type RollbackOptions, type RunMigrationsOptions, type ScopeTiming, type SerializedRelation, SqlAggregateFunction, SqlDeleteOperation, SqlDialectContract, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType, StrictMode, SyncAdapterContract, type SyncConfig, type SyncContext, SyncContextManager, type SyncEventPayload, SyncInstruction, type SyncInstructionOptions, SyncManager, type SyncResult, type TableIndexInformation, TransactionContext, type TransactionOptions, TransactionRollbackError, UniqueEntry, type UniqueRuleOptions, UnsafeFilterError, UnsafeRawExpressionError, UpdateOperations, UpdateResult, UuidStrategy, VectorIndexOptions, WhereCallback, WhereObject, WhereOperator, WriterContract, WriterOptions, WriterResult, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
72
+ export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, PendingMigration, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult, PostgresSyncAdapter, PostgresTransactionOptions, PostgresWhereClause, QueryBuilderContract, RELATION_METADATA_KEY, RawColumnExpression, RawExpression, RawQueryResult, RegisterModel, RegisterModelOptions, type RelationConstraintCallback, type RelationConstraints, RelationDefaults, type RelationDefinition, type RelationDefinitions, RelationHydrator, RelationLoader, type RelationType, RemoverContract, RemoverOptions, RemoverResult, RestorerContract, RestorerOptions, RestorerResult, RollbackMigrationsOptions, type RollbackOptions, type RunMigrationsOptions, type ScopeTiming, type SerializedRelation, SqlAggregateFunction, SqlDeleteOperation, SqlDialectContract, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType, StrictMode, SyncAdapterContract, type SyncConfig, type SyncContext, SyncContextManager, type SyncEventPayload, SyncInstruction, type SyncInstructionOptions, SyncManager, type SyncResult, type TableIndexInformation, TransactionContext, type TransactionOptions, TransactionRollbackError, UniqueEntry, type UniqueRuleOptions, UnsafeFilterError, UnsafeRawExpressionError, UpdateOperations, UpdateResult, UuidStrategy, VectorIndexOptions, WhereCallback, WhereObject, WhereOperator, WriterContract, WriterOptions, WriterResult, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, buildPostgresPoolConfig, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
73
73
  import "./validation/plugins/database-rules-plugin.mjs";
74
74
  import "./validation/plugins/embed-validator-plugin.mjs";
package/esm/index.mjs CHANGED
@@ -39,7 +39,7 @@ import { PostgresMigrationDriver } from "./drivers/postgres/postgres-migration-d
39
39
  import { PostgresQueryParser } from "./drivers/postgres/postgres-query-parser.mjs";
40
40
  import { PostgresQueryBuilder } from "./drivers/postgres/postgres-query-builder.mjs";
41
41
  import { PostgresSyncAdapter } from "./drivers/postgres/postgres-sync-adapter.mjs";
42
- import { PostgresDriver } from "./drivers/postgres/postgres-driver.mjs";
42
+ import { PostgresDriver, buildPostgresPoolConfig } from "./drivers/postgres/postgres-driver.mjs";
43
43
  import "./drivers/postgres/index.mjs";
44
44
  import { connectToDatabase, getDatabaseDriver, transaction } from "./utils/connect-to-database.mjs";
45
45
  import { useModelTransformer } from "./utils/database-writer.utils.mjs";
@@ -55,4 +55,4 @@ import { createDatabase, dropAllTables } from "./operations/database.mjs";
55
55
  import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
56
56
  import "./operations/index.mjs";
57
57
 
58
- export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser, PostgresSyncAdapter, RELATION_METADATA_KEY, RegisterModel, RelationHydrator, RelationLoader, SyncContextManager, SyncManager, TransactionRollbackError, UnsafeFilterError, UnsafeRawExpressionError, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
58
+ export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser, PostgresSyncAdapter, RELATION_METADATA_KEY, RegisterModel, RelationHydrator, RelationLoader, SyncContextManager, SyncManager, TransactionRollbackError, UnsafeFilterError, UnsafeRawExpressionError, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, buildPostgresPoolConfig, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, escapeRegex, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, likePatternToRegexSource, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveLikePattern, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, sanitizeFilter, sanitizeFilterValue, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
@@ -163,6 +163,14 @@ interface MigrationContract {
163
163
  * Alias for bigInteger().
164
164
  */
165
165
  bigInt(column: string): ColumnBuilder;
166
+ /**
167
+ * Add a foreign-key id column whose TYPE matches the DataSource's default
168
+ * primary key (`migrationDefaults.primaryKey`), so a reference to a
169
+ * default-PK model is always type-compatible with that model's `id`. Use it
170
+ * for plain (non-`.references()`) FK id columns — e.g. a polymorphic
171
+ * `user_id` paired with a `user_type` — instead of hardcoding one type.
172
+ */
173
+ foreignId(column: string): ColumnBuilder;
166
174
  /**
167
175
  * Add a float column.
168
176
  */
@@ -1296,6 +1304,25 @@ declare abstract class Migration implements MigrationContract {
1296
1304
  * ```
1297
1305
  */
1298
1306
  primaryUuid(name?: string): ColumnBuilder;
1307
+ /**
1308
+ * Add a foreign-key id column whose TYPE matches the DataSource's default
1309
+ * primary key (`migrationDefaults.primaryKey`), resolved EXACTLY as the auto
1310
+ * primary key resolves it: `migrationDefaults.primaryKey` → `"int"`.
1311
+ *
1312
+ * This is the column to use for a plain FK id — notably a polymorphic
1313
+ * `user_id` paired with a `user_type` — because hardcoding a single type
1314
+ * silently breaks every app whose models use another: an integer id written
1315
+ * into a `uuid` column throws at insert time, and the failure surfaces as an
1316
+ * opaque 500 (finding 5e47bdb3). Deriving the column type from the same
1317
+ * config the model's PK derives from keeps the two in lockstep for every app.
1318
+ *
1319
+ * `false` (no auto PK) is treated as `"int"` here: a referencing column still
1320
+ * needs a concrete type, and integer is the framework default.
1321
+ *
1322
+ * @param name - Column name
1323
+ * @returns Column builder for chaining modifiers (`.index()`, `.nullable()`, …)
1324
+ */
1325
+ foreignId(name: string): ColumnBuilder;
1299
1326
  /**
1300
1327
  * Add createdAt and updatedAt timestamp columns.
1301
1328
  *