@nextlyhq/adapter-postgres 0.0.2-alpha.8 → 0.0.2-alpha.81

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 +1 @@
1
- {"version":3,"sources":["../src/provider.ts","../src/index.ts"],"names":["net","DrizzleAdapter","Pool","checkDialectVersion","createDatabaseError","drizzle","isDatabaseError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBO,SAAS,sBAAA,CACd,KACA,gBAAA,EACkB;AAElB,EAAA,IAAI,gBAAA,EAAkB;AACpB,IAAA,MAAM,UAAA,GAAa,iBAAiB,WAAA,EAAY;AAChD,IAAA,IACE,UAAA,KAAe,MAAA,IACf,UAAA,KAAe,UAAA,IACf,eAAe,UAAA,EACf;AACA,MAAA,OAAO,UAAA;AAAA,IACT;AAAA,EACF;AAGA,EAAA,IAAI,IAAI,QAAA,CAAS,YAAY,KAAK,GAAA,CAAI,QAAA,CAAS,OAAO,CAAA,EAAG;AACvD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,IAAI,IAAI,QAAA,CAAS,YAAY,KAAK,GAAA,CAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AAC3D,IAAA,OAAO,UAAA;AAAA,EACT;AAEA,EAAA,OAAO,UAAA;AACT;AAGO,SAAS,oBACd,QAAA,EACkB;AAClB,EAAA,QAAQ,QAAA;AAAU,IAChB,KAAK,MAAA;AAEH,MAAA,OAAO;AAAA,QACL,GAAA,EAAK,IAAA;AAAA,QACL,OAAA,EAAS,CAAA;AAAA,QACT,OAAA,EAAS,CAAA;AAAA,QACT,aAAA,EAAe,GAAA;AAAA,QACf,mBAAA,EAAqB,GAAA;AAAA,QACrB,kBAAA,EAAoB,GAAA;AAAA,QACpB,aAAA,EAAe;AAAA,OACjB;AAAA,IACF,KAAK,UAAA;AAEH,MAAA,OAAO;AAAA,QACL,GAAA,EAAK,IAAA;AAAA,QACL,OAAA,EAAS,CAAA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ern\n// and returns appropriate connection defaults.\n// Standard pg driver works with all providers - only config changes.\n\nexport type PostgresProvider = \"standard\" | \"neon\" | \"supabase\";\n\nexport interface ProviderDefaults {\n ssl: boolean;\n poolMax: number;\n poolMin: number;\n idleTimeoutMs: number;\n connectionTimeoutMs: number;\n statementTimeoutMs: number;\n retryAttempts: number;\n}\n\n// Detect provider from URL pattern or explicit override\nexport function detectPostgresProvider(\n url: string,\n explicitProvider?: string\n): PostgresProvider {\n // Explicit override takes priority (if valid)\n if (explicitProvider) {\n const normalized = explicitProvider.toLowerCase();\n if (\n normalized === \"neon\" ||\n normalized === \"supabase\" ||\n normalized === \"standard\"\n ) {\n return normalized;\n }\n }\n\n // Auto-detect from URL hostname\n if (url.includes(\".neon.tech\") || url.includes(\"neon.\")) {\n return \"neon\";\n }\n if (url.includes(\".supabase.\") || url.includes(\"supabase.\")) {\n return \"supabase\";\n }\n\n return \"standard\";\n}\n\n// Get connection defaults for a provider\nexport function getProviderDefaults(\n provider: PostgresProvider\n): ProviderDefaults {\n switch (provider) {\n case \"neon\":\n // Neon: serverless PG with auto-suspend, cold starts need more retries\n return {\n ssl: true,\n poolMax: 5,\n poolMin: 0,\n idleTimeoutMs: 10000,\n connectionTimeoutMs: 20000,\n statementTimeoutMs: 30000,\n retryAttempts: 5,\n };\n case \"supabase\":\n // Supabase: managed PG with Supavisor pooler, SSL required\n return {\n ssl: true,\n poolMax: 5,\n poolMin: 0,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n statementTimeoutMs: 15000,\n retryAttempts: 3,\n };\n case \"standard\":\n default:\n // Standard: Docker, self-hosted, direct PG connections\n return {\n ssl: false,\n poolMax: 10,\n poolMin: 0,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n statementTimeoutMs: 15000,\n retryAttempts: 3,\n };\n }\n}\n","/**\n * @nextlyhq/adapter-postgres\n *\n * PostgreSQL database adapter for Nextly.\n * Extends the base DrizzleAdapter from @nextlyhq/adapter-drizzle to provide\n * PostgreSQL-specific functionality.\n *\n * @remarks\n * This adapter uses the `pg` (node-postgres) driver for database connections\n * and integrates with Drizzle ORM for type-safe queries.\n *\n * Features:\n * - Connection pooling via pg.Pool\n * - Full transaction support with savepoints\n * - RETURNING clause support for all CRUD operations\n * - PostgreSQL-specific error classification\n * - JSONB support\n * - Full-text search capabilities\n * - Automatic retry for serialization failures and deadlocks\n *\n * @example\n * Simple usage with connection string:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n * ```\n *\n * @example\n * Full configuration:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 2,\n * max: 20,\n * idleTimeoutMs: 30000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * },\n * applicationName: 'my-nextly-app',\n * });\n * ```\n *\n * @example\n * Using the adapter class directly:\n * ```typescript\n * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';\n * import type { PostgresAdapterConfig } from '@nextlyhq/adapter-postgres';\n *\n * const config: PostgresAdapterConfig = {\n * url: process.env.DATABASE_URL!,\n * };\n *\n * const adapter = new PostgresAdapter(config);\n * await adapter.connect();\n * ```\n *\n * @packageDocumentation\n */\n\nimport * as net from \"node:net\";\n\nimport { DrizzleAdapter } from \"@nextlyhq/adapter-drizzle\";\n// F17: connect-time DB version check shared across all adapters.\nimport type {\n PostgresAdapterConfig,\n DatabaseCapabilities,\n PoolStats,\n TransactionContext,\n TransactionOptions,\n SqlParam,\n SelectOptions,\n InsertOptions,\n UpdateOptions,\n DeleteOptions,\n UpsertOptions,\n WhereClause,\n DatabaseError,\n DatabaseErrorKind,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport {\n createDatabaseError,\n isDatabaseError,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport { checkDialectVersion } from \"@nextlyhq/adapter-drizzle/version-check\";\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { PoolClient, PoolConfig } from \"pg\";\nimport { Pool } from \"pg\";\n\nimport {\n detectPostgresProvider,\n getProviderDefaults,\n type PostgresProvider,\n type ProviderDefaults,\n} from \"./provider\";\n\n// Re-export types from @nextlyhq/adapter-drizzle for convenience\nexport type {\n PostgresAdapterConfig,\n DatabaseCapabilities,\n PoolStats,\n TransactionContext,\n TransactionOptions,\n SqlParam,\n // Additional types users might need\n BaseAdapterConfig,\n AdapterLogger,\n PoolConfig as AdapterPoolConfig,\n SslConfig,\n WhereClause,\n WhereCondition,\n WhereOperator,\n SelectOptions,\n InsertOptions,\n UpdateOptions,\n DeleteOptions,\n UpsertOptions,\n OrderBySpec,\n JoinSpec,\n DatabaseError,\n DatabaseErrorKind,\n} from \"@nextlyhq/adapter-drizzle/types\";\n\n/**\n * Package version.\n */\nexport const VERSION = \"0.1.0\";\n\n/**\n * Default pool configuration values.\n *\n * min: 0 – Never eagerly create background connections. This is critical\n * for cold-start recovery (e.g. Neon auto-suspend): after the\n * initial smoke-test connection, the pool won't immediately try\n * to create additional connections that might still fail while\n * the DB is waking up.\n *\n * max: 5 – Conservative default to avoid overwhelming cloud databases\n * (Neon free-tier limit is ~25-30 simultaneous connections).\n * With Next.js spawning up to 7 build workers this keeps the\n * total connection count safely under typical limits.\n */\nconst DEFAULT_POOL_CONFIG = {\n min: 0,\n max: 5,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n};\n\n/**\n * PostgreSQL error codes mapping to DatabaseErrorKind.\n *\n * @see https://www.postgresql.org/docs/current/errcodes-appendix.html\n */\nconst PG_ERROR_CODES: Record<string, DatabaseErrorKind> = {\n // Class 08 - Connection Exception\n \"08000\": \"connection\",\n \"08003\": \"connection\",\n \"08006\": \"connection\",\n \"08001\": \"connection\",\n \"08004\": \"connection\",\n \"08007\": \"connection\",\n \"08P01\": \"connection\",\n\n // Class 23 - Integrity Constraint Violation\n \"23000\": \"constraint\",\n \"23001\": \"constraint\",\n \"23502\": \"not_null_violation\",\n \"23503\": \"foreign_key_violation\",\n \"23505\": \"unique_violation\",\n \"23514\": \"check_violation\",\n \"23P01\": \"constraint\",\n\n // Class 40 - Transaction Rollback\n \"40000\": \"query\",\n \"40001\": \"serialization_failure\",\n \"40002\": \"constraint\",\n \"40003\": \"query\",\n \"40P01\": \"deadlock\",\n\n // Class 57 - Operator Intervention\n \"57014\": \"timeout\",\n \"57P01\": \"connection\",\n \"57P02\": \"connection\",\n \"57P03\": \"connection\",\n};\n\n/**\n * Delay helper for retry logic.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n// Node 20+ defaults the Happy Eyeballs per-address connection-attempt timeout\n// to 250ms. For consumers connecting from a region with RTT > 250ms to their\n// database (typical transcontinental: Pakistan→Singapore is ~310ms),\n// every TCP attempt is killed mid-handshake and the pg driver reports\n// ETIMEDOUT after exhausting all DNS-resolved addresses — even though the\n// network is fine.\n//\n// We bump the timeout to 5000ms on first adapter connect. This is process-\n// global state but the change is purely permissive (only increases the\n// per-address budget; cannot break anything that worked at 250ms). If the\n// process has already set a higher value, we leave it alone.\n//\n// References:\n// https://nodejs.org/api/net.html#netsetdefaultautoselectfamilyattempttimeoutvalue\n// https://www.rfc-editor.org/rfc/rfc8305\nconst HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5000;\nlet happyEyeballsTimeoutApplied = false;\nfunction applyHappyEyeballsTimeoutOnce(): void {\n if (happyEyeballsTimeoutApplied) return;\n happyEyeballsTimeoutApplied = true;\n try {\n const current =\n typeof net.getDefaultAutoSelectFamilyAttemptTimeout === \"function\"\n ? net.getDefaultAutoSelectFamilyAttemptTimeout()\n : 0;\n if (current < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) {\n net.setDefaultAutoSelectFamilyAttemptTimeout(\n HAPPY_EYEBALLS_MIN_TIMEOUT_MS\n );\n }\n } catch {\n // Older Node versions (< 20) don't have these APIs. Swallow — the\n // 250ms default they have predates Happy Eyeballs anyway, so they\n // don't suffer this bug.\n }\n}\n\n/**\n * PostgreSQL database adapter for Nextly.\n *\n * @remarks\n * This class extends the base DrizzleAdapter to provide PostgreSQL-specific\n * functionality including:\n *\n * - Connection pooling with pg.Pool\n * - Transaction support with savepoints\n * - PostgreSQL-specific error codes\n * - JSONB and array type support\n * - Full-text search\n * - Automatic retry for serialization failures and deadlocks\n *\n * For most use cases, use the `createPostgresAdapter` factory function\n * instead of instantiating this class directly.\n *\n * @example\n * ```typescript\n * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = new PostgresAdapter({\n * url: 'postgres://user:pass@localhost:5432/mydb',\n * });\n *\n * await adapter.connect();\n *\n * // Use the adapter\n * const users = await adapter.select('users', {\n * where: { and: [{ column: 'status', op: '=', value: 'active' }] },\n * });\n *\n * await adapter.disconnect();\n * ```\n *\n * @public\n */\nexport class PostgresAdapter extends DrizzleAdapter {\n /**\n * The database dialect - always 'postgresql' for this adapter.\n */\n public readonly dialect = \"postgresql\" as const;\n\n /**\n * Adapter configuration.\n */\n protected readonly config: PostgresAdapterConfig;\n\n /**\n * Connection pool instance.\n */\n private pool: Pool | null = null;\n\n /**\n * Connection state flag.\n */\n private connected = false;\n\n /**\n * Auto-detected provider (Neon, Supabase, or standard).\n * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.\n */\n private detectedProvider: PostgresProvider = \"standard\";\n\n /**\n * Provider-specific connection defaults. Applied as fallbacks when\n * user config doesn't specify a value.\n */\n private providerDefaults: ProviderDefaults = getProviderDefaults(\"standard\");\n\n /**\n * Creates a new PostgreSQL adapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: PostgresAdapterConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Establishes a connection to the PostgreSQL database.\n *\n * @remarks\n * This method initializes the connection pool and verifies connectivity\n * by executing a simple query. It is idempotent - calling it multiple\n * times will not create multiple pools.\n *\n * @throws {DatabaseError} If connection fails\n */\n async connect(): Promise<void> {\n // Fix Node 20+ Happy Eyeballs default before constructing the pool —\n // see applyHappyEyeballsTimeoutOnce above.\n applyHappyEyeballsTimeoutOnce();\n\n if (this.connected && this.pool) {\n return;\n }\n\n // Auto-detect provider from URL and apply defaults\n const url = this.config.url || \"\";\n this.detectedProvider = detectPostgresProvider(\n url,\n process.env.DB_PROVIDER\n );\n this.providerDefaults = getProviderDefaults(this.detectedProvider);\n\n // Log detected provider for developer awareness\n if (this.config.logger?.info) {\n const source = process.env.DB_PROVIDER ? \"(explicit)\" : \"(auto-detected)\";\n this.config.logger.info(\n `PostgreSQL provider: ${this.detectedProvider} ${source}`,\n {}\n );\n }\n\n // Node.js network error codes that are safe to retry (transient failures).\n // These cover cloud databases (e.g. Neon) waking from auto-suspend, brief\n // network hiccups, and DNS resolution races during build parallelism.\n const retryableNodeCodes = new Set([\n \"ETIMEDOUT\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n ]);\n\n // Use provider-specific retry count (Neon needs more for cold starts)\n const maxAttempts = this.providerDefaults.retryAttempts;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const poolConfig = this.buildPoolConfig();\n this.pool = new Pool(poolConfig);\n\n // Handle pool errors (background errors on idle clients)\n this.pool.on(\"error\", (err: Error) => {\n // Log through adapter logger if configured\n if (this.config.logger?.error) {\n this.config.logger.error(err, {\n context: \"pool_error\",\n message: \"Unexpected error on idle client\",\n });\n }\n // Client is automatically removed from pool, no action needed\n });\n\n // Verify connection with smoke test, then check dialect version.\n // Why: F17 hard-fails at connect on unsupported PG versions (<15.0)\n // so users see a clear upgrade pointer instead of cryptic errors\n // mid-apply later. The version query runs inside the existing retry\n // loop's try block, so transient network failures (Neon cold start,\n // EAI_AGAIN) continue to retry; only confirmed version mismatch\n // surfaces as UnsupportedDialectVersionError and exits the loop.\n const client = await this.pool.connect();\n try {\n await client.query(\"SELECT 1\");\n await checkDialectVersion(client, \"postgresql\", {\n // Why: route any future variant warnings through the adapter's\n // logger. PG has no recognized variants today, but this keeps\n // the integration symmetric with MySQL.\n onWarning: msg => this.config.logger?.warn?.(msg),\n });\n this.connected = true;\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"PostgreSQL connection established\", {\n host: this.config.host ?? \"from URL\",\n database: this.config.database ?? \"from URL\",\n });\n }\n\n return; // Success — exit retry loop\n } finally {\n client.release();\n }\n } catch (error) {\n // Clean up the failed pool before deciding whether to retry\n if (this.pool) {\n await this.pool.end().catch(() => {});\n this.pool = null;\n }\n\n const nodeError = error as { code?: string };\n const isRetryable =\n nodeError.code != null && retryableNodeCodes.has(nodeError.code);\n\n if (isRetryable && attempt < maxAttempts) {\n // Exponential back-off with jitter: ~1 s, ~2 s, ~3 s, ~4 s\n const waitMs = 1000 * attempt;\n const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;\n if (this.config.logger?.warn) {\n this.config.logger.warn(msg);\n } else {\n console.warn(`[PostgresAdapter] ${msg}`);\n }\n await delay(waitMs);\n continue;\n }\n\n // Non-retryable error or exhausted retries — surface to caller\n throw this.classifyError(error);\n }\n }\n }\n\n /**\n * Closes the database connection and releases all pool resources.\n *\n * @remarks\n * This method is idempotent - calling it multiple times is safe.\n * It waits for all checked-out clients to be returned before shutting down.\n */\n async disconnect(): Promise<void> {\n if (!this.pool) {\n return;\n }\n\n try {\n await this.pool.end();\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"PostgreSQL connection closed\");\n }\n } finally {\n this.pool = null;\n this.connected = false;\n }\n }\n\n /**\n * Checks if the adapter is currently connected.\n *\n * @returns True if connected and pool is available\n */\n override isConnected(): boolean {\n return this.connected && this.pool !== null;\n }\n\n /**\n * Executes a raw SQL query.\n *\n * @param sql - SQL statement with $1, $2, ... placeholders\n * @param params - Query parameters\n * @returns Array of result rows\n *\n * @throws {DatabaseError} If query execution fails\n */\n async executeQuery<T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> {\n const pool = this.ensurePool();\n const startTime = Date.now();\n\n // Transient network errors that are safe to retry at the query level.\n // These occur when Neon auto-suspends between the pool smoke-test and the\n // actual query, or when multiple build workers compete for cold-start.\n const retryableNodeCodes = new Set([\n \"ETIMEDOUT\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n ]);\n const maxQueryAttempts = 3;\n\n for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) {\n try {\n const result = await pool.query(sql, params as unknown[]);\n\n // Log query if logger configured\n if (this.config.logger?.query) {\n const durationMs = Date.now() - startTime;\n this.config.logger.query(sql, params, durationMs);\n }\n\n return result.rows as T[];\n } catch (error) {\n const nodeError = error as { code?: string };\n const isRetryable =\n nodeError.code != null && retryableNodeCodes.has(nodeError.code);\n\n if (isRetryable && attempt < maxQueryAttempts) {\n const waitMs = 500 * attempt;\n console.warn(\n `[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`\n );\n await delay(waitMs);\n continue;\n }\n\n throw this.classifyError(error, sql);\n }\n }\n\n // Unreachable — loop always returns or throws\n throw this.classifyError(new Error(\"executeQuery: exhausted retries\"));\n }\n\n /**\n * Executes a callback within a database transaction.\n *\n * @remarks\n * PostgreSQL supports full ACID transactions with savepoints.\n * If the callback throws, the transaction is rolled back.\n *\n * Supports automatic retry for serialization failures (40001) and\n * deadlocks (40P01) when `retryCount` is specified in options.\n *\n * @param callback - Function to execute within the transaction\n * @param options - Transaction options (isolation level, timeout, retry)\n * @returns The result of the callback\n *\n * @throws {DatabaseError} If transaction fails after all retries\n */\n async transaction<T>(\n callback: (ctx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n const pool = this.ensurePool();\n const maxAttempts = (options?.retryCount ?? 0) + 1;\n const retryDelayMs = options?.retryDelayMs ?? 100;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const client = await pool.connect();\n const startTime = Date.now();\n\n try {\n // Begin transaction with options\n await this.beginTransaction(client, options);\n\n // Create transaction context\n const ctx = this.createTransactionContext(client);\n\n // Execute callback\n const result = await callback(ctx);\n\n // Commit transaction\n await client.query(\"COMMIT\");\n\n // Log success\n if (this.config.logger?.debug) {\n const durationMs = Date.now() - startTime;\n this.config.logger.debug(\"Transaction committed\", {\n attempt,\n durationMs,\n });\n }\n\n return result;\n } catch (error) {\n // Rollback transaction\n await client.query(\"ROLLBACK\").catch(() => {});\n\n lastError = error;\n\n // Check if error is retryable\n const pgError = error as { code?: string };\n const isRetryable =\n pgError.code === \"40001\" || // serialization_failure\n pgError.code === \"40P01\"; // deadlock\n\n if (isRetryable && attempt < maxAttempts) {\n if (this.config.logger?.warn) {\n this.config.logger.warn(\n `Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`,\n { code: pgError.code, attempt }\n );\n }\n await delay(retryDelayMs * attempt); // Exponential backoff\n continue;\n }\n\n throw this.classifyError(error);\n } finally {\n client.release();\n }\n }\n\n // Should not reach here, but handle just in case\n throw this.classifyError(lastError);\n }\n\n /**\n * Returns the database capabilities for PostgreSQL.\n *\n * @remarks\n * PostgreSQL has the most comprehensive feature set of all supported\n * databases, including JSONB, arrays, full-text search, and more.\n */\n getCapabilities(): DatabaseCapabilities {\n return {\n dialect: \"postgresql\",\n supportsJsonb: true,\n supportsJson: true,\n supportsArrays: true,\n supportsGeneratedColumns: true,\n supportsFts: true,\n supportsIlike: true,\n supportsReturning: true,\n supportsSavepoints: true,\n supportsOnConflict: true,\n maxParamsPerQuery: 65535, // PostgreSQL limit\n maxIdentifierLength: 63, // PostgreSQL default\n };\n }\n\n /**\n * Returns connection pool statistics.\n *\n * @returns Pool stats or null if not connected\n */\n override getPoolStats(): PoolStats | null {\n if (!this.pool) {\n return null;\n }\n\n return {\n total: this.pool.totalCount,\n idle: this.pool.idleCount,\n waiting: this.pool.waitingCount,\n active: this.pool.totalCount - this.pool.idleCount,\n };\n }\n\n /**\n * Override insertMany for bulk insert optimization.\n *\n * @remarks\n * Uses a single multi-row INSERT statement for better performance\n * when inserting multiple records.\n */\n override async insertMany<T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> {\n if (data.length === 0) {\n return [];\n }\n\n // For single record, use parent implementation\n if (data.length === 1) {\n const result = await this.insert<T>(table, data[0], options);\n return [result];\n }\n\n // Build multi-row INSERT\n const columns = Object.keys(data[0]);\n const params: SqlParam[] = [];\n const valuesClauses: string[] = [];\n\n for (let i = 0; i < data.length; i++) {\n const record = data[i];\n const placeholders: string[] = [];\n\n for (const col of columns) {\n params.push(record[col] as SqlParam);\n placeholders.push(`$${params.length}`);\n }\n\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n const columnList = columns\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(\", \")}`;\n\n // Add RETURNING clause\n if (options?.returning) {\n const returning =\n options.returning === \"*\"\n ? \"*\"\n : options.returning.map(col => this.escapeIdentifier(col)).join(\", \");\n sql += ` RETURNING ${returning}`;\n }\n\n try {\n return await this.executeQuery<T>(sql, params);\n } catch (error) {\n throw this.handleQueryError(error, \"insertMany\", table);\n }\n }\n\n // ============================================================\n // Protected Helper Methods\n // ============================================================\n\n /**\n * Ensures pool is connected and returns it.\n *\n * @throws {DatabaseError} If not connected\n */\n private ensurePool(): Pool {\n if (!this.pool) {\n throw createDatabaseError({\n kind: \"connection\",\n message: \"PostgresAdapter is not connected. Call connect() first.\",\n });\n }\n return this.pool;\n }\n\n /**\n * Return the typed Drizzle instance for PostgreSQL.\n * Guarded for server-only usage and requires an active connection.\n *\n * @param schema - Optional schema for relational queries (db.query.*)\n * @returns Drizzle ORM instance wrapping the pg pool connection\n * @throws {Error} If called in browser or not connected\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n getDrizzle<T = NodePgDatabase<any>>(schema?: Record<string, unknown>): T {\n if (typeof window !== \"undefined\") {\n throw new Error(\"getDrizzle() is server-only\");\n }\n const pool = this.ensurePool();\n return (schema ? drizzle(pool, { schema }) : drizzle(pool)) as T;\n }\n\n /**\n * Builds pg Pool configuration from adapter config.\n */\n private buildPoolConfig(): PoolConfig {\n const config: PoolConfig = {};\n\n // Connection string or explicit options\n if (this.config.url) {\n config.connectionString = this.config.url;\n } else {\n if (this.config.host) config.host = this.config.host;\n if (this.config.port) config.port = this.config.port;\n if (this.config.database) config.database = this.config.database;\n if (this.config.user) config.user = this.config.user;\n if (this.config.password) config.password = this.config.password;\n }\n\n // Pool settings (user config > provider defaults > hardcoded defaults)\n config.min =\n this.config.pool?.min ??\n this.providerDefaults.poolMin ??\n DEFAULT_POOL_CONFIG.min;\n config.max =\n this.config.pool?.max ??\n this.providerDefaults.poolMax ??\n DEFAULT_POOL_CONFIG.max;\n config.idleTimeoutMillis =\n this.config.pool?.idleTimeoutMs ??\n this.providerDefaults.idleTimeoutMs ??\n DEFAULT_POOL_CONFIG.idleTimeoutMs;\n config.connectionTimeoutMillis =\n this.config.pool?.connectionTimeoutMs ??\n this.providerDefaults.connectionTimeoutMs ??\n DEFAULT_POOL_CONFIG.connectionTimeoutMs;\n\n // TCP keepalive - prevents cloud databases (e.g. Neon) from silently\n // dropping idle connections between the pool smoke-test and the first\n // real query, which manifests as ETIMEDOUT on the query itself.\n config.keepAlive = true;\n config.keepAliveInitialDelayMillis = 10000;\n\n // SSL configuration (user config > provider default)\n if (this.config.ssl) {\n if (typeof this.config.ssl === \"boolean\") {\n config.ssl = this.config.ssl;\n } else {\n if (this.config.ssl.rejectUnauthorized === false) {\n console.warn(\n \"[nextly/adapter-postgres] ssl.rejectUnauthorized is set to false — \" +\n \"TLS certificates will not be validated. This is unsafe on untrusted networks. \" +\n \"Provide a trusted `ca` cert instead, or remove the rejectUnauthorized override.\"\n );\n }\n config.ssl = {\n rejectUnauthorized: this.config.ssl.rejectUnauthorized,\n ca: this.config.ssl.ca,\n cert: this.config.ssl.cert,\n key: this.config.ssl.key,\n };\n }\n } else if (this.providerDefaults.ssl) {\n // Provider requires SSL but user didn't explicitly configure it.\n // Default to validating certs; the user can opt out by setting\n // `ssl: { rejectUnauthorized: false }` explicitly (which logs a warning above).\n config.ssl = { rejectUnauthorized: true };\n }\n\n // PostgreSQL-specific options\n if (this.config.applicationName) {\n config.application_name = this.config.applicationName;\n }\n\n // User config beats provider default; both beat \"unset\".\n // Why: provider.ts:58 declared a Neon statementTimeoutMs default but the\n // adapter previously ignored it, leaving stuck queries to pin pool slots\n // indefinitely. Wire the fallback chain here so the declared defaults\n // actually fire.\n const effectiveStatementTimeout =\n this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;\n if (effectiveStatementTimeout !== undefined) {\n config.statement_timeout = effectiveStatementTimeout;\n }\n\n if (this.config.queryTimeout) {\n config.query_timeout = this.config.queryTimeout;\n }\n\n return config;\n }\n\n /**\n * Begins a transaction with the specified options.\n */\n private async beginTransaction(\n client: PoolClient,\n options?: TransactionOptions\n ): Promise<void> {\n let beginSql = \"BEGIN\";\n\n // Add isolation level if specified\n if (options?.isolationLevel) {\n const isolationMap: Record<string, string> = {\n \"read uncommitted\": \"READ UNCOMMITTED\",\n \"read committed\": \"READ COMMITTED\",\n \"repeatable read\": \"REPEATABLE READ\",\n serializable: \"SERIALIZABLE\",\n };\n const level = isolationMap[options.isolationLevel];\n if (level) {\n beginSql += ` ISOLATION LEVEL ${level}`;\n }\n }\n\n // Add read-only mode if specified\n if (options?.readOnly) {\n beginSql += \" READ ONLY\";\n }\n\n await client.query(beginSql);\n\n // Set statement timeout if specified\n if (options?.timeoutMs) {\n await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);\n }\n }\n\n /**\n * Creates a TransactionContext for the given client.\n */\n private createTransactionContext(client: PoolClient): TransactionContext {\n return {\n execute: async <T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> => {\n const result = await client.query(sql, params as unknown[]);\n return result.rows as T[];\n },\n\n insert: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options?: InsertOptions\n ): Promise<T> => {\n const columns = Object.keys(data);\n const values = Object.values(data);\n const placeholders = values.map((_, i) => `$${i + 1}`).join(\", \");\n\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES (${placeholders})`;\n\n if (options?.returning) {\n const returning =\n options.returning === \"*\"\n ? \"*\"\n : options.returning\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n sql += ` RETURNING ${returning}`;\n } else {\n sql += \" RETURNING *\";\n }\n\n const result = await client.query(sql, values);\n return result.rows[0] as T;\n },\n\n insertMany: async <T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> => {\n if (data.length === 0) return [];\n\n const columns = Object.keys(data[0]);\n const params: unknown[] = [];\n const valuesClauses: string[] = [];\n\n for (const record of data) {\n const placeholders: string[] = [];\n for (const col of columns) {\n params.push(record[col]);\n placeholders.push(`$${params.length}`);\n }\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES ${valuesClauses.join(\", \")}`;\n\n if (options?.returning) {\n const returning =\n options.returning === \"*\"\n ? \"*\"\n : options.returning\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n sql += ` RETURNING ${returning}`;\n } else {\n sql += \" RETURNING *\";\n }\n\n const result = await client.query(sql, params);\n return result.rows as T[];\n },\n\n // TransactionContext CRUD methods delegate to the adapter's CRUD\n // which uses Drizzle query API via the TableResolver.\n // The Drizzle transaction is handled at a higher level.\n select: async <T = unknown>(\n table: string,\n options?: SelectOptions\n ): Promise<T[]> => {\n return this.select<T>(table, options);\n },\n\n selectOne: async <T = unknown>(\n table: string,\n options?: SelectOptions\n ): Promise<T | null> => {\n return this.selectOne<T>(table, options);\n },\n\n update: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n where: WhereClause,\n options?: UpdateOptions\n ): Promise<T[]> => {\n return this.update<T>(table, data, where, options);\n },\n\n delete: async (\n table: string,\n where: WhereClause,\n _options?: DeleteOptions\n ): Promise<number> => {\n return this.delete(table, where);\n },\n\n upsert: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options: UpsertOptions\n ): Promise<T> => {\n return this.upsert<T>(table, data, options);\n },\n\n savepoint: async (name: string): Promise<void> => {\n await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);\n },\n\n rollbackToSavepoint: async (name: string): Promise<void> => {\n await client.query(\n `ROLLBACK TO SAVEPOINT ${this.escapeIdentifier(name)}`\n );\n },\n\n releaseSavepoint: async (name: string): Promise<void> => {\n await client.query(`RELEASE SAVEPOINT ${this.escapeIdentifier(name)}`);\n },\n };\n }\n\n /**\n * Classifies a PostgreSQL error into a DatabaseError.\n *\n * @param error - Original error from pg\n * @param sql - SQL statement that caused the error (optional)\n * @returns DatabaseError with proper classification\n */\n private classifyError(error: unknown, sql?: string): DatabaseError {\n // Why short-circuit on existing DatabaseError: F17's\n // UnsupportedDialectVersionError is already a typed DatabaseError with\n // kind: \"unsupported_version\" plus detectedVersion/requiredVersion\n // fields. Re-wrapping it here would erase those fields and re-tag it\n // as kind: \"unknown\".\n if (isDatabaseError(error)) return error;\n\n const pgError = error as {\n code?: string;\n message?: string;\n constraint?: string;\n table?: string;\n column?: string;\n detail?: string;\n hint?: string;\n severity?: string;\n };\n\n // Determine error kind from PostgreSQL error code\n const kind: DatabaseErrorKind =\n (pgError.code && PG_ERROR_CODES[pgError.code]) || \"unknown\";\n\n // Build error message\n let message = pgError.message ?? String(error);\n if (sql && kind === \"query\") {\n message = `Query failed: ${message}`;\n }\n\n return createDatabaseError({\n kind,\n message,\n code: pgError.code,\n constraint: pgError.constraint,\n table: pgError.table,\n column: pgError.column,\n detail: pgError.detail,\n hint: pgError.hint,\n cause: error instanceof Error ? error : undefined,\n });\n }\n\n /**\n * Override handleQueryError to use PostgreSQL-specific classification.\n */\n protected override handleQueryError(\n error: unknown,\n operation: string,\n table: string\n ): DatabaseError {\n const dbError = this.classifyError(error);\n\n // Add operation context if not already present\n if (!dbError.message.includes(operation)) {\n dbError.message = `${operation} operation failed on table '${table}': ${dbError.message}`;\n }\n\n if (!dbError.table) {\n dbError.table = table;\n }\n\n return dbError;\n }\n}\n\n/**\n * Creates a PostgreSQL database adapter instance.\n *\n * @remarks\n * This is the recommended way to create a PostgreSQL adapter.\n * The adapter is not connected after creation - call `connect()` to\n * establish the database connection.\n *\n * @param config - Adapter configuration\n * @returns A new PostgresAdapter instance\n *\n * @example\n * Simple usage:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n * ```\n *\n * @example\n * With full configuration:\n * ```typescript\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 5,\n * max: 20,\n * idleTimeoutMs: 30000,\n * connectionTimeoutMs: 10000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * ca: process.env.CA_CERT,\n * },\n * applicationName: 'my-app',\n * statementTimeout: 30000,\n * });\n * ```\n *\n * @public\n */\nexport function createPostgresAdapter(\n config: PostgresAdapterConfig\n): PostgresAdapter {\n return new PostgresAdapter(config);\n}\n\n/**\n * Type guard to check if a value is a PostgresAdapter instance.\n *\n * @param value - Value to check\n * @returns True if value is a PostgresAdapter\n *\n * @example\n * ```typescript\n * import { isPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * if (isPostgresAdapter(adapter)) {\n * // TypeScript knows adapter is PostgresAdapter\n * console.log(adapter.dialect); // 'postgresql'\n * }\n * ```\n *\n * @public\n */\nexport function isPostgresAdapter(value: unknown): value is PostgresAdapter {\n return value instanceof PostgresAdapter;\n}\n"]}
1
+ {"version":3,"file":"index.cjs","names":["poolWaitTimeoutError","SERVERLESS_POOL_DEFAULTS","pgTable","timestamp","assertSchemaName","createDatabaseError","net","DrizzleAdapter","isVercelFunction","loadVercelPoolAttacher","Pool","isNextBuildPhase","checkDialectVersion","drizzle","getTableConfig","isDatabaseError"],"sources":["../src/pool-wait.ts","../src/provider.ts","../src/index.ts"],"sourcesContent":["/**\n * The bounded wait for a pooled connection, reported as the adapters' own\n * \"pool wait timeout\" error.\n *\n * pg-pool already bounds the wait: a request that finds every connection in\n * use waits at most `connectionTimeoutMillis`, then is removed from the queue\n * and fails. It fails with a plain `Error` that has no code, though, so\n * nothing downstream could tell it from any other driver failure, and a\n * caller got an internal error for a database that was only busy. This gives\n * that one failure the code core answers with \"database busy\".\n *\n * Only the wait for a connection already in the pool: a new connection that\n * cannot be opened in time is pg-pool's other timeout (\"Connection terminated\n * due to connection timeout\"), a database that cannot be reached rather than\n * one that is busy, and stays as it was.\n */\nimport { poolWaitTimeoutError } from \"@nextlyhq/adapter-drizzle/types\";\nimport type { Pool, PoolClient } from \"pg\";\n\n/**\n * pg-pool's message for a request that waited its bound in the queue. The\n * error carries nothing else to recognise it by; the pool-wait integration\n * test runs against the installed pg-pool, so a reworded message fails there.\n */\nconst QUEUE_WAIT_TIMEOUT_MESSAGE = \"timeout exceeded when trying to connect\";\n\ntype ConnectCallback = (\n err: Error | undefined,\n client: PoolClient | undefined,\n done: (release?: unknown) => void\n) => void;\n\n/** The error a caller should see for one pg-pool raised. */\nfunction translated(error: Error, boundMs: number): Error {\n if (error.message === QUEUE_WAIT_TIMEOUT_MESSAGE) {\n return poolWaitTimeoutError(boundMs, error);\n }\n return error;\n}\n\n/**\n * Makes `pool` report a request that waited past `boundMs` for a connection\n * with the pool-wait timeout error, and returns it. `boundMs` is the pool's\n * own `connectionTimeoutMillis`, unset when the pool has none.\n *\n * Replaces the pool's own `connect`, which its `query` also goes through, so\n * every path to a connection reports the same way: the adapter's statements,\n * its transactions, and the Drizzle handle core services query through.\n */\nexport function reportPoolWaitTimeout(\n pool: Pool,\n boundMs: number | undefined\n): Pool {\n const bound = boundMs ?? 0;\n const connect = pool.connect.bind(pool) as (\n callback?: ConnectCallback\n ) => Promise<PoolClient> | void;\n const bounded = (callback?: ConnectCallback) => {\n if (callback) {\n return connect((err, client, done) =>\n callback(err && translated(err, bound), client, done)\n );\n }\n return (connect() as Promise<PoolClient>).catch((error: Error) => {\n throw translated(error, bound);\n });\n };\n pool.connect = bounded as Pool[\"connect\"];\n return pool;\n}\n","// Auto-detects PostgreSQL provider from DATABASE_URL pattern\n// and returns appropriate connection defaults.\n// Standard pg driver works with all providers - only config changes.\nimport { SERVERLESS_POOL_DEFAULTS } from \"@nextlyhq/adapter-drizzle/serverless\";\n\nexport type PostgresProvider = \"standard\" | \"neon\" | \"supabase\";\n\nexport interface ProviderDefaults {\n ssl: boolean;\n poolMax: number;\n poolMin: number;\n idleTimeoutMs: number;\n connectionTimeoutMs: number;\n statementTimeoutMs: number;\n retryAttempts: number;\n}\n\n// Detect provider from URL pattern or explicit override\nexport function detectPostgresProvider(\n url: string,\n explicitProvider?: string\n): PostgresProvider {\n // Explicit override takes priority (if valid)\n if (explicitProvider) {\n const normalized = explicitProvider.toLowerCase();\n if (\n normalized === \"neon\" ||\n normalized === \"supabase\" ||\n normalized === \"standard\"\n ) {\n return normalized;\n }\n }\n\n // Auto-detect from URL hostname\n if (url.includes(\".neon.tech\") || url.includes(\"neon.\")) {\n return \"neon\";\n }\n if (url.includes(\".supabase.\") || url.includes(\"supabase.\")) {\n return \"supabase\";\n }\n\n return \"standard\";\n}\n\n/** Where the pool runs, as far as its defaults depend on it. */\nexport interface ProviderDefaultsOptions {\n /**\n * The pool runs inside serverless functions (Vercel's), whose suspended\n * instances keep their open connections: the pool size and idle timeout\n * come from `SERVERLESS_POOL_DEFAULTS` instead of the provider's, whatever\n * the provider, since a suspended instance holds a Neon or Supabase\n * connection as surely as any other. The provider keeps every other\n * setting: SSL, the connection and statement timeouts, the connect retries.\n */\n serverless?: boolean;\n}\n\n// Get connection defaults for a provider, for a pool that runs where\n// `options` says.\nexport function getProviderDefaults(\n provider: PostgresProvider,\n options: ProviderDefaultsOptions = {}\n): ProviderDefaults {\n const defaults = providerOwnDefaults(provider);\n if (!options.serverless) return defaults;\n return {\n ...defaults,\n poolMax: SERVERLESS_POOL_DEFAULTS.max,\n poolMin: SERVERLESS_POOL_DEFAULTS.min,\n idleTimeoutMs: SERVERLESS_POOL_DEFAULTS.idleTimeoutMs,\n };\n}\n\n// The provider's own defaults, for a long-running server.\nfunction providerOwnDefaults(provider: PostgresProvider): ProviderDefaults {\n switch (provider) {\n case \"neon\":\n // Neon: serverless PG with auto-suspend, cold starts need more retries\n return {\n ssl: true,\n poolMax: 5,\n poolMin: 0,\n idleTimeoutMs: 10000,\n connectionTimeoutMs: 20000,\n statementTimeoutMs: 30000,\n retryAttempts: 5,\n };\n case \"supabase\":\n // Supabase: managed PG with Supavisor pooler, SSL required\n return {\n ssl: true,\n poolMax: 5,\n poolMin: 0,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n statementTimeoutMs: 15000,\n retryAttempts: 3,\n };\n case \"standard\":\n default:\n // Standard: Docker, self-hosted, direct PG connections\n return {\n ssl: false,\n poolMax: 10,\n poolMin: 0,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n statementTimeoutMs: 15000,\n retryAttempts: 3,\n };\n }\n}\n","/**\n * @nextlyhq/adapter-postgres\n *\n * PostgreSQL database adapter for Nextly.\n * Extends the base DrizzleAdapter from @nextlyhq/adapter-drizzle to provide\n * PostgreSQL-specific functionality.\n *\n * @remarks\n * This adapter uses the `pg` (node-postgres) driver for database connections\n * and integrates with Drizzle ORM for type-safe queries.\n *\n * Features:\n * - Connection pooling via pg.Pool\n * - Full transaction support with savepoints\n * - RETURNING clause support for all CRUD operations\n * - PostgreSQL-specific error classification\n * - JSONB support\n * - Full-text search capabilities\n * - Automatic retry for serialization failures and deadlocks\n *\n * @example\n * Simple usage with connection string:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n * ```\n *\n * @example\n * Full configuration:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 2,\n * max: 20,\n * idleTimeoutMs: 30000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * },\n * applicationName: 'my-nextly-app',\n * });\n * ```\n *\n * @example\n * Using the adapter class directly:\n * ```typescript\n * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';\n * import type { PostgresAdapterConfig } from '@nextlyhq/adapter-postgres';\n *\n * const config: PostgresAdapterConfig = {\n * url: process.env.DATABASE_URL!,\n * };\n *\n * const adapter = new PostgresAdapter(config);\n * await adapter.connect();\n * ```\n *\n * @packageDocumentation\n */\n\nimport * as net from \"node:net\";\n\nimport { DrizzleAdapter } from \"@nextlyhq/adapter-drizzle\";\n// F17: connect-time DB version check shared across all adapters.\nimport { isNextBuildPhase } from \"@nextlyhq/adapter-drizzle/build-phase\";\nimport { assertSchemaName } from \"@nextlyhq/adapter-drizzle/schema-name\";\nimport {\n isVercelFunction,\n loadVercelPoolAttacher,\n} from \"@nextlyhq/adapter-drizzle/serverless\";\nimport type {\n PostgresAdapterConfig,\n ConnectionInspection,\n DatabaseCapabilities,\n PoolStats,\n TransactionBounds,\n TransactionContext,\n TransactionOptions,\n SessionOptions,\n StatementSession,\n SqlParam,\n InsertOptions,\n DatabaseError,\n DatabaseErrorKind,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport {\n createDatabaseError,\n isDatabaseError,\n} from \"@nextlyhq/adapter-drizzle/types\";\nimport { checkDialectVersion } from \"@nextlyhq/adapter-drizzle/version-check\";\nimport type { AnyRelations, SQL } from \"drizzle-orm\";\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport {\n getTableConfig,\n pgTable,\n timestamp,\n type PgTable,\n} from \"drizzle-orm/pg-core\";\nimport type { PoolClient, PoolConfig } from \"pg\";\nimport { Pool } from \"pg\";\n\nimport { reportPoolWaitTimeout } from \"./pool-wait\";\nimport {\n detectPostgresProvider,\n getProviderDefaults,\n type PostgresProvider,\n type ProviderDefaults,\n} from \"./provider\";\n\n// Re-export types from @nextlyhq/adapter-drizzle for convenience\nexport type {\n PostgresAdapterConfig,\n DatabaseCapabilities,\n PoolStats,\n TransactionContext,\n TransactionOptions,\n SqlParam,\n // Additional types users might need\n BaseAdapterConfig,\n AdapterLogger,\n PoolConfig as AdapterPoolConfig,\n SslConfig,\n WhereClause,\n WhereCondition,\n WhereOperator,\n SelectOptions,\n InsertOptions,\n UpdateOptions,\n DeleteOptions,\n UpsertOptions,\n OrderBySpec,\n JoinSpec,\n DatabaseError,\n DatabaseErrorKind,\n} from \"@nextlyhq/adapter-drizzle/types\";\n\n/**\n * A date field's column as the schema generator declares it on PostgreSQL:\n * `timestamp`, without a time zone. Its encoder writes the UTC wall clock,\n * which is what a `Date` bound to an undeclared key is spelled as.\n */\nconst DATE_FIELD_COLUMN = pgTable(\"nextly_date_field\", {\n at: timestamp(\"at\"),\n}).at;\n\n/**\n * Package version.\n */\nexport const VERSION = \"0.1.0\";\n\n/**\n * Default pool configuration values.\n *\n * min: 0 – Never eagerly create background connections. This is critical\n * for cold-start recovery (e.g. Neon auto-suspend): after the\n * initial smoke-test connection, the pool won't immediately try\n * to create additional connections that might still fail while\n * the DB is waking up.\n *\n * max: 5 – Conservative default to avoid overwhelming cloud databases\n * (Neon free-tier limit is ~25-30 simultaneous connections).\n * With Next.js spawning up to 7 build workers this keeps the\n * total connection count safely under typical limits.\n */\nconst DEFAULT_POOL_CONFIG = {\n min: 0,\n max: 5,\n idleTimeoutMs: 30000,\n connectionTimeoutMs: 15000,\n};\n\n/**\n * PostgreSQL error codes mapping to DatabaseErrorKind.\n *\n * @see https://www.postgresql.org/docs/current/errcodes-appendix.html\n */\nconst PG_ERROR_CODES: Record<string, DatabaseErrorKind> = {\n // Class 08 - Connection Exception\n \"08000\": \"connection\",\n \"08003\": \"connection\",\n \"08006\": \"connection\",\n \"08001\": \"connection\",\n \"08004\": \"connection\",\n \"08007\": \"connection\",\n \"08P01\": \"connection\",\n\n // Class 23 - Integrity Constraint Violation\n \"23000\": \"constraint\",\n \"23001\": \"constraint\",\n \"23502\": \"not_null_violation\",\n \"23503\": \"foreign_key_violation\",\n \"23505\": \"unique_violation\",\n \"23514\": \"check_violation\",\n \"23P01\": \"constraint\",\n\n // Class 40 - Transaction Rollback\n \"40000\": \"query\",\n \"40001\": \"serialization_failure\",\n \"40002\": \"constraint\",\n \"40003\": \"query\",\n \"40P01\": \"deadlock\",\n\n // Class 53 - Insufficient Resources: too_many_connections. The server has\n // no connection to give, so the connect fails; retrying it at once would\n // only ask again for what is not there, and the connect does not retry it.\n \"53300\": \"connection\",\n\n // Class 57 - Operator Intervention\n \"57014\": \"timeout\",\n \"57P01\": \"connection\",\n \"57P02\": \"connection\",\n \"57P03\": \"connection\",\n // idle_session_timeout (PostgreSQL 14+): the server closed a connection the\n // pool held idle past the server's limit.\n \"57P05\": \"connection\",\n};\n\n/**\n * Create the configured schema when the database does not have it yet.\n *\n * Looked up before it is created, because `CREATE SCHEMA IF NOT EXISTS` is not\n * a no-op for a schema that exists: PostgreSQL checks the database-level\n * `CREATE` privilege before it checks for the schema, so a role that may use\n * and create objects in `public` but may not create schemas would fail to\n * connect over a schema that is already there. Reading `pg_namespace` needs no\n * privilege, so only a schema that is genuinely missing asks for one.\n *\n * Created inside a transaction holding an advisory lock on the schema's name,\n * and looked up again once the lock is held. `IF NOT EXISTS` alone is not safe\n * against itself: two processes connecting at the same moment can both pass its\n * check, and the second to commit fails with a unique violation on\n * `pg_namespace_nspname_index`, which fails its connect. The transaction-scoped\n * lock makes the second wait for the first to commit, and its lookup, a new\n * statement with a new snapshot, then finds the schema. The transaction is\n * read committed whatever the database's or role's default: at repeatable\n * read or serializable the snapshot is fixed by the first statement, the lock\n * wait, so the lookup would miss the schema and the CREATE that followed would\n * ask for the database privilege the first paragraph avoids. Released by the commit\n * or rollback, so it never outlives this one connection's transaction, and a\n * transaction-mode pooler keeps all of it on one server connection.\n */\nasync function ensureSchemaExists(\n client: PoolClient,\n schema: string\n): Promise<void> {\n const name = assertSchemaName(schema);\n if (await schemaExists(client, name)) return;\n await client.query(\"BEGIN ISOLATION LEVEL READ COMMITTED\");\n try {\n await client.query(\n \"SELECT pg_advisory_xact_lock(hashtext('nextly:create-schema'), hashtext($1))\",\n [name]\n );\n if (!(await schemaExists(client, name))) {\n // Still `IF NOT EXISTS`: a process of an earlier version takes no lock.\n await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);\n }\n await client.query(\"COMMIT\");\n } catch (error) {\n await client.query(\"ROLLBACK\").catch(() => {});\n throw error;\n }\n}\n\n/** PostgreSQL's code for a schema that does not exist. */\nconst INVALID_SCHEMA_NAME = \"3F000\";\n\n/**\n * Fails, without creating it, when the database has no schema of this name:\n * a read-only connect must not change the database, and a `search_path` that\n * names a missing schema would quietly fall through to `public`.\n */\nasync function assertSchemaExists(\n client: PoolClient,\n schema: string,\n /** What to do about it, where the caller knows: said after the fact. */\n remedy?: string\n): Promise<void> {\n const name = assertSchemaName(schema);\n if (await schemaExists(client, name)) return;\n throw createDatabaseError({\n kind: \"connection\",\n message:\n remedy === undefined\n ? `schema \"${name}\" does not exist`\n : `schema \"${name}\" does not exist. ${remedy}`,\n code: INVALID_SCHEMA_NAME,\n });\n}\n\n/** Whether the database has a schema of this name. Needs no privilege. */\nasync function schemaExists(\n client: PoolClient,\n name: string\n): Promise<boolean> {\n const existing = await client.query(\n \"SELECT 1 FROM pg_namespace WHERE nspname = $1\",\n [name]\n );\n return existing.rows.length > 0;\n}\n\n/**\n * The SQLSTATE an error carries: its own, or that of the driver error it\n * wraps, as a Drizzle query error does.\n */\nfunction sqlStateOf(error: unknown): string | undefined {\n for (let at: unknown = error, hops = 0; hops < 4; hops++) {\n if (typeof at !== \"object\" || at === null) return undefined;\n const code: unknown = Reflect.get(at, \"code\");\n if (typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code)) return code;\n at = Reflect.get(at, \"cause\");\n }\n return undefined;\n}\n\n/**\n * A serialization failure or a deadlock: the transaction lost a race, and\n * running it again may succeed.\n */\nfunction isSerializationFailure(error: unknown): boolean {\n const code = sqlStateOf(error);\n return code === \"40001\" || code === \"40P01\";\n}\n\n/**\n * `@vercel/functions`' pool attaching, imported only on Vercel, at connect.\n *\n * An optional peer: an app outside Vercel never installs it, so the import is\n * dynamic and its failure is a warning (`loadVercelPoolAttacher`), never a\n * module that fails to load. The adapter is a server external package\n * (`withNextly`'s `serverExternalPackages`), so Node resolves this at run time;\n * the comments keep a bundler that bundles the adapter anyway from requiring\n * the package at build time. The `db-connections` subpath loads the attaching\n * alone, not the package's other helpers.\n */\nfunction loadVercelDbConnections(): Promise<unknown> {\n return import(\n /* webpackIgnore: true */ /* turbopackIgnore: true */ \"@vercel/functions/db-connections\"\n );\n}\n\n/**\n * Delay helper for retry logic.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n// Node 20+ defaults the Happy Eyeballs per-address connection-attempt timeout\n// to 250ms. For consumers connecting from a region with RTT > 250ms to their\n// database (typical transcontinental: Pakistan→Singapore is ~310ms),\n// every TCP attempt is killed mid-handshake and the pg driver reports\n// ETIMEDOUT after exhausting all DNS-resolved addresses — even though the\n// network is fine.\n//\n// We bump the timeout to 5000ms on first adapter connect. This is process-\n// global state but the change is purely permissive (only increases the\n// per-address budget; cannot break anything that worked at 250ms). If the\n// process has already set a higher value, we leave it alone.\n//\n// References:\n// https://nodejs.org/api/net.html#netsetdefaultautoselectfamilyattempttimeoutvalue\n// https://www.rfc-editor.org/rfc/rfc8305\nconst HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5000;\nlet happyEyeballsTimeoutApplied = false;\nfunction applyHappyEyeballsTimeoutOnce(): void {\n if (happyEyeballsTimeoutApplied) return;\n happyEyeballsTimeoutApplied = true;\n try {\n const current =\n typeof net.getDefaultAutoSelectFamilyAttemptTimeout === \"function\"\n ? net.getDefaultAutoSelectFamilyAttemptTimeout()\n : 0;\n if (current < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) {\n net.setDefaultAutoSelectFamilyAttemptTimeout(\n HAPPY_EYEBALLS_MIN_TIMEOUT_MS\n );\n }\n } catch {\n // Older Node versions (< 20) don't have these APIs. Swallow — the\n // 250ms default they have predates Happy Eyeballs anyway, so they\n // don't suffer this bug.\n }\n}\n\n/**\n * How a date column's wall clock is spelled out when a write reads its row\n * back: the stored value to the millisecond, with no zone for the driver to\n * shift.\n */\nconst PG_WALL_CLOCK_FORMAT = 'YYYY-MM-DD\"T\"HH24:MI:SS.MS';\n\n/**\n * The host a pooled client connected to, as node-postgres resolved it from its\n * options, the connection string, `PGHOST` and its default; `undefined` when\n * the client does not hold one.\n */\nfunction resolvedHost(client: object): string | undefined {\n return \"host\" in client &&\n typeof client.host === \"string\" &&\n client.host !== \"\"\n ? client.host\n : undefined;\n}\n\n/**\n * PostgreSQL database adapter for Nextly.\n *\n * @remarks\n * This class extends the base DrizzleAdapter to provide PostgreSQL-specific\n * functionality including:\n *\n * - Connection pooling with pg.Pool\n * - Transaction support with savepoints\n * - PostgreSQL-specific error codes\n * - JSONB and array type support\n * - Full-text search\n * - Automatic retry for serialization failures and deadlocks\n *\n * For most use cases, use the `createPostgresAdapter` factory function\n * instead of instantiating this class directly.\n *\n * @example\n * ```typescript\n * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = new PostgresAdapter({\n * url: 'postgres://user:pass@localhost:5432/mydb',\n * });\n *\n * await adapter.connect();\n *\n * // Use the adapter\n * const users = await adapter.select('users', {\n * where: { and: [{ column: 'status', op: '=', value: 'active' }] },\n * });\n *\n * await adapter.disconnect();\n * ```\n *\n * @public\n */\nexport class PostgresAdapter extends DrizzleAdapter {\n // getDrizzle memoization: drizzle v1's constructor builds a relational\n // query builder per table in the relations config (~40 tables), and the\n // service layer resolves an instance on every db access — construct once\n // per relations object (identity-stable: the schema registry caches it\n // and hands out a NEW object on invalidation, which naturally misses\n // this cache and produces a fresh instance).\n private drizzleByRelations = new WeakMap<AnyRelations, unknown>();\n private drizzleBare: unknown;\n\n /**\n * The database dialect - always 'postgresql' for this adapter.\n */\n public readonly dialect = \"postgresql\" as const;\n\n /**\n * Adapter configuration.\n */\n protected readonly config: PostgresAdapterConfig;\n\n /**\n * Connection pool instance.\n */\n private pool: Pool | null = null;\n\n /**\n * Connection state flag.\n */\n private connected = false;\n\n /**\n * Auto-detected provider (Neon, Supabase, or standard).\n * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.\n */\n private detectedProvider: PostgresProvider = \"standard\";\n\n /**\n * Provider-specific connection defaults. Applied as fallbacks when\n * user config doesn't specify a value.\n */\n private providerDefaults: ProviderDefaults = getProviderDefaults(\"standard\");\n\n /**\n * Creates a new PostgreSQL adapter instance.\n *\n * @param config - Adapter configuration\n */\n constructor(config: PostgresAdapterConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Establishes a connection to the PostgreSQL database.\n *\n * @remarks\n * This method initializes the connection pool and verifies connectivity\n * by executing a simple query. It is idempotent - calling it multiple\n * times will not create multiple pools.\n *\n * @throws {DatabaseError} If connection fails\n */\n async connect(): Promise<void> {\n // Fix Node 20+ Happy Eyeballs default before constructing the pool —\n // see applyHappyEyeballsTimeoutOnce above.\n applyHappyEyeballsTimeoutOnce();\n\n if (this.connected && this.pool) {\n return;\n }\n\n // Auto-detect provider from URL and apply defaults. Inside Vercel\n // functions the pool size and idle timeout are the serverless ones\n // (`getProviderDefaults`), which the config still overrides field by field\n // in `buildPoolConfig`.\n const url = this.config.url || \"\";\n const serverless = isVercelFunction();\n this.detectedProvider = detectPostgresProvider(\n url,\n process.env.DB_PROVIDER\n );\n this.providerDefaults = getProviderDefaults(this.detectedProvider, {\n serverless,\n });\n\n // Log detected provider for developer awareness\n if (this.config.logger?.info) {\n const source = process.env.DB_PROVIDER ? \"(explicit)\" : \"(auto-detected)\";\n const pool = serverless ? \", Vercel pool defaults\" : \"\";\n this.config.logger.info(\n `PostgreSQL provider: ${this.detectedProvider} ${source}${pool}`,\n {}\n );\n }\n\n // On Vercel, what hands each pool built below to `attachDatabasePool`;\n // loaded once here, so a connect that retries warns at most once.\n const attachPool = await loadVercelPoolAttacher({\n load: loadVercelDbConnections,\n dialect: \"PostgreSQL\",\n logger: this.config.logger,\n });\n\n // Node.js network error codes that are safe to retry (transient failures).\n // These cover cloud databases (e.g. Neon) waking from auto-suspend, brief\n // network hiccups, and DNS resolution races during build parallelism.\n const retryableNodeCodes = new Set([\n \"ETIMEDOUT\",\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n ]);\n\n // Use provider-specific retry count (Neon needs more for cold starts)\n const maxAttempts = this.providerDefaults.retryAttempts;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const poolConfig = this.buildPoolConfig();\n // A request that waits out connectionTimeoutMillis for a connection\n // fails as busy, not as an unexplained driver error.\n this.pool = reportPoolWaitTimeout(\n new Pool(poolConfig),\n poolConfig.connectionTimeoutMillis\n );\n\n // Handle pool errors (background errors on idle clients)\n this.pool.on(\"error\", (err: Error) => {\n // Log through adapter logger if configured\n if (this.config.logger?.error) {\n this.config.logger.error(err, {\n context: \"pool_error\",\n message: \"Unexpected error on idle client\",\n });\n }\n // Client is automatically removed from pool, no action needed\n });\n\n // Attached as soon as it exists, as Vercel's docs say, so the smoke\n // test's own connection is one `@vercel/functions` waits on as well:\n // attached after it, that connection would sit idle untracked, and an\n // instance suspended right after connecting would keep it open.\n attachPool?.(this.pool);\n\n // Verify connection with smoke test, then check dialect version.\n // Why: F17 hard-fails at connect on unsupported PG versions (<15.0)\n // so users see a clear upgrade pointer instead of cryptic errors\n // mid-apply later. The version query runs inside the existing retry\n // loop's try block, so transient network failures (Neon cold start,\n // EAI_AGAIN) continue to retry; only confirmed version mismatch\n // surfaces as UnsupportedDialectVersionError and exits the loop.\n const client = await this.pool.connect();\n try {\n await client.query(\"SELECT 1\");\n // Before anything writes. `search_path` naming a schema that is not\n // there does not fail — it falls through to whatever else is on the\n // path — so the first migration would create its tables in `public`\n // and the setting would appear to do nothing. A read-only\n // connection and `next build`, which writes nothing to the\n // database, only check that it is there.\n if (this.config.schema && isNextBuildPhase()) {\n // A schema the build does not find is a database the deploy has\n // not migrated, which the message says how to fix.\n await assertSchemaExists(\n client,\n this.config.schema,\n \"Run `nextly migrate` before `next build`.\"\n );\n } else if (this.config.schema && this.config.readOnly) {\n await assertSchemaExists(client, this.config.schema);\n } else if (this.config.schema) {\n await ensureSchemaExists(client, this.config.schema);\n }\n await checkDialectVersion(client, \"postgresql\", {\n // Why: route any future variant warnings through the adapter's\n // logger. PG has no recognized variants today, but this keeps\n // the integration symmetric with MySQL.\n onWarning: msg => this.config.logger?.warn?.(msg),\n });\n this.connected = true;\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"PostgreSQL connection established\", {\n host: this.config.host ?? \"from URL\",\n database: this.config.database ?? \"from URL\",\n });\n }\n\n return; // Success — exit retry loop\n } finally {\n client.release();\n }\n } catch (error) {\n // Clean up the failed pool before deciding whether to retry\n if (this.pool) {\n await this.pool.end().catch(() => {});\n this.pool = null;\n }\n\n const nodeError = error as { code?: string };\n const isRetryable =\n nodeError.code != null && retryableNodeCodes.has(nodeError.code);\n\n if (isRetryable && attempt < maxAttempts) {\n // Exponential back-off with jitter: ~1 s, ~2 s, ~3 s, ~4 s\n const waitMs = 1000 * attempt;\n const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;\n if (this.config.logger?.warn) {\n this.config.logger.warn(msg);\n } else {\n console.warn(`[PostgresAdapter] ${msg}`);\n }\n await delay(waitMs);\n continue;\n }\n\n // Non-retryable error or exhausted retries — surface to caller\n throw this.classifyError(error);\n }\n }\n }\n\n /**\n * Closes the database connection and releases all pool resources.\n *\n * @remarks\n * This method is idempotent - calling it multiple times is safe.\n * It waits for all checked-out clients to be returned before shutting down.\n */\n async disconnect(): Promise<void> {\n // Detach the pool FIRST, then drop the memoized drizzle instances —\n // this closes the repopulation window where a concurrent getDrizzle()\n // call during the (async) pool.end() could cache an instance wrapping\n // the closing pool.\n const pool = this.pool;\n this.pool = null;\n this.drizzleBare = undefined;\n this.drizzleByRelations = new WeakMap();\n if (!pool) {\n return;\n }\n\n try {\n await pool.end();\n\n if (this.config.logger?.info) {\n this.config.logger.info(\"PostgreSQL connection closed\");\n }\n } finally {\n this.connected = false;\n }\n }\n\n /**\n * Checks if the adapter is currently connected.\n *\n * @returns True if connected and pool is available\n */\n override isConnected(): boolean {\n return this.connected && this.pool !== null;\n }\n\n /**\n * Runs `work` on one client taken from the pool, outside a transaction,\n * each statement committing as it runs, so connection-scoped state a\n * statement sets (a temporary table, a session setting, an advisory lock)\n * is still there for the next. The client is closed afterwards, whether\n * `work` finished or threw, never handed back to the pool: that state ends\n * with it instead of reaching a later caller. No `SessionOptions` field\n * changes anything on PostgreSQL: strict mode is MySQL's, and PostgreSQL\n * refuses an overlong value already.\n */\n override async withSession<T>(\n work: (session: StatementSession) => Promise<T>,\n _options?: SessionOptions\n ): Promise<T> {\n // A precondition: before any connection is taken.\n this.refuseSessionInTransaction();\n const pool = this.ensurePool();\n // A checkout, taken from the pool like `executeQuery`'s queries are.\n this.notePoolAccess();\n let client: PoolClient;\n try {\n client = await pool.connect();\n } catch (error) {\n throw this.classifyError(error);\n }\n try {\n return await work({\n execute: async <R = unknown>(\n statement: string,\n params: SqlParam[] = []\n ): Promise<R[]> => {\n const startTime = Date.now();\n try {\n const result = await client.query(statement, params as unknown[]);\n if (this.config.logger?.query) {\n this.config.logger.query(\n statement,\n params,\n Date.now() - startTime\n );\n }\n return result.rows as R[];\n } catch (error) {\n throw this.classifyError(error, statement);\n }\n },\n });\n } finally {\n client.release(true);\n }\n }\n\n /**\n * Executes a raw SQL query.\n *\n * @param sql - SQL statement with $1, $2, ... placeholders\n * @param params - Query parameters\n * @returns Array of result rows\n *\n * @throws {DatabaseError} If query execution fails\n */\n async executeQuery<T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> {\n const pool = this.ensurePool();\n const startTime = Date.now();\n\n // Transient network errors that are safe to retry at the query level.\n // These occur when Neon auto-suspends between the pool smoke-test and the\n // actual query, or when multiple build workers compete for cold-start.\n const retryableNodeCodes = new Set([\n \"ETIMEDOUT\",\n \"ECONNRESET\",\n \"ECONNREFUSED\",\n ]);\n const maxQueryAttempts = 3;\n\n for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) {\n try {\n // Outside the calling flow's transaction, if it has one (`notePoolAccess`).\n this.notePoolAccess(sql);\n const result = await pool.query(sql, params as unknown[]);\n\n // Log query if logger configured\n if (this.config.logger?.query) {\n const durationMs = Date.now() - startTime;\n this.config.logger.query(sql, params, durationMs);\n }\n\n return result.rows as T[];\n } catch (error) {\n const nodeError = error as { code?: string };\n const isRetryable =\n nodeError.code != null && retryableNodeCodes.has(nodeError.code);\n\n if (isRetryable && attempt < maxQueryAttempts) {\n const waitMs = 500 * attempt;\n console.warn(\n `[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`\n );\n await delay(waitMs);\n continue;\n }\n\n throw this.classifyError(error, sql);\n }\n }\n\n // Unreachable — loop always returns or throws\n throw this.classifyError(new Error(\"executeQuery: exhausted retries\"));\n }\n\n /**\n * Executes a callback within a database transaction.\n *\n * @remarks\n * PostgreSQL supports full ACID transactions with savepoints.\n * If the callback throws, the transaction is rolled back.\n *\n * Supports automatic retry for serialization failures (40001) and\n * deadlocks (40P01) when `retryCount` is specified in options.\n *\n * An error carrying the Nextly application brand is not classified: it is the\n * application refusing the write, so it arrives at the caller as it was\n * thrown. It is retried only when `retryWhen` accepts it, which is asked\n * first, of every error; a refusal re-run is otherwise the same refusal.\n * Every other error, including an unbranded one raised by the callback, is\n * retried when it is a serialization failure or deadlock and classified on\n * the way out.\n *\n * A call made inside another transaction's work joins it, on its client,\n * as a savepoint: released when the callback resolves, rolled back to when\n * it throws, so its failure undoes only its own part. A serialization\n * failure or deadlock inside a joined part fails the whole transaction,\n * which only a retry of the outermost one can answer. A joined call keeps\n * the outer's options and is never retried itself.\n *\n * @param callback - Function to execute within the transaction\n * @param options - Transaction options (isolation level, timeout, retry)\n * @returns The result of the callback\n *\n * @throws {DatabaseError} If the transaction itself fails after all retries,\n * or if the callback threw an error that does not carry the application brand\n * @throws The callback's own error, unchanged, when it carries that brand\n */\n transaction<T>(\n callback: (ctx: TransactionContext) => Promise<T>,\n options?: TransactionOptions\n ): Promise<T> {\n return this.openOrJoin(callback, options, {\n run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),\n retryable: isSerializationFailure,\n describe: error => {\n const code = sqlStateOf(error);\n return { label: code ?? \"a retryable error\", detail: { code } };\n },\n logger: this.config.logger,\n });\n }\n\n /** One attempt at an outermost transaction, on a client of its own. */\n private async runAttempt<T>(\n callback: (ctx: TransactionContext) => Promise<T>,\n options: TransactionOptions | undefined,\n openedAt: string | undefined\n ) {\n const pool = this.ensurePool();\n // A checkout, taken from the pool like `executeQuery`'s queries are.\n this.notePoolAccess();\n // Read before the checkout, in the calling flow (`withTransactionBounds`).\n const bounds = this.transactionBounds();\n const client = await pool.connect();\n // Set when the ROLLBACK failed. The client may then still be inside the\n // transaction, so it is destroyed rather than pooled: the next request\n // handed it would otherwise write into a transaction nobody commits.\n let discard: Error | true | undefined;\n // A bounded transaction's session may be ended by the server while no\n // statement runs on it (`idle_in_transaction_session_timeout`), and\n // node-postgres reports that as an `error` event on the checked-out\n // client, which has no listener while checked out: unheard, it would end\n // the process. Heard here, the transaction's next statement fails, and\n // the client is destroyed rather than pooled.\n const sessionEnded = (error: Error) => {\n discard = error;\n };\n if (bounds?.idleMs !== undefined) client.on(\"error\", sessionEnded);\n const settled = await this.settleOutermost(\n {\n context: this.createTransactionContext(client),\n join: this.joinSteps(client),\n openedAt,\n begin: () => this.beginTransaction(client, options, bounds),\n // A transaction a failed statement aborted is not refused at COMMIT:\n // PostgreSQL rolls it back and answers with the ROLLBACK command tag,\n // raising nothing. A callback that caught its failed statement and\n // returned would otherwise be told its writes committed when none of\n // them were kept, so that answer is an error.\n commit: async () => {\n const committed = await client.query(\"COMMIT\");\n if (committed?.command === \"ROLLBACK\") {\n throw createDatabaseError({\n kind: \"query\",\n code: \"25P02\",\n message:\n \"The transaction was rolled back, not committed: a statement in it failed, and PostgreSQL ends such a transaction with a rollback when asked to commit.\",\n });\n }\n },\n // A failure is recorded for the release and rethrown, so the base\n // knows the ROLLBACK is unconfirmed.\n rollback: async () => {\n await client.query(\"ROLLBACK\").catch((rollbackError: unknown) => {\n discard = rollbackError instanceof Error ? rollbackError : true;\n throw rollbackError;\n });\n },\n },\n callback,\n options\n );\n if (bounds?.idleMs !== undefined) {\n client.removeListener(\"error\", sessionEnded);\n }\n // node-postgres destroys a client released with an error or `true`, and\n // pools one released with nothing. Released before anything held runs,\n // so an effect that opens a transaction takes one client, not two.\n client.release(discard);\n return settled;\n }\n\n /**\n * How a call made inside a transaction on `client` joins it: a savepoint\n * each, on `client`, named for its depth.\n */\n private joinSteps(client: PoolClient) {\n return this.joinStepsOn(\n () => this.createTransactionContext(client),\n relations =>\n relations ? drizzle({ client, relations }) : drizzle({ client }),\n (context, depth) => {\n const name = this.escapeIdentifier(`nextly_sp_${depth}`);\n return {\n context,\n begin: async () => {\n await client.query(`SAVEPOINT ${name}`);\n },\n commit: async () => {\n await client.query(`RELEASE SAVEPOINT ${name}`);\n },\n rollback: async () => {\n await client.query(`ROLLBACK TO SAVEPOINT ${name}`);\n await client.query(`RELEASE SAVEPOINT ${name}`);\n },\n // Only a retry of the outermost transaction can answer these.\n dooms: isSerializationFailure,\n };\n }\n );\n }\n\n /**\n * Returns the database capabilities for PostgreSQL.\n *\n * @remarks\n * PostgreSQL has the most comprehensive feature set of all supported\n * databases, including JSONB, arrays, full-text search, and more.\n */\n getCapabilities(): DatabaseCapabilities {\n return {\n dialect: \"postgresql\",\n supportsJsonb: true,\n supportsJson: true,\n supportsArrays: true,\n supportsGeneratedColumns: true,\n supportsFts: true,\n supportsIlike: true,\n supportsReturning: true,\n supportsSavepoints: true,\n supportsOnConflict: true,\n maxParamsPerQuery: 65535, // PostgreSQL limit\n maxIdentifierLength: 63, // PostgreSQL default\n };\n }\n\n /**\n * The schema set as `search_path` on every pooled connection.\n *\n * @remarks\n * Answers with the same test `buildPoolConfig` applies, so an empty string\n * reports `undefined` exactly as it sets no `search_path`: the value\n * reported is the one the connections actually use.\n *\n * @returns The configured schema, or `undefined` when the server's default\n * `search_path` applies\n */\n getConfiguredSchema(): string | undefined {\n return this.config.schema ? this.config.schema : undefined;\n }\n\n /**\n * Returns connection pool statistics.\n *\n * @returns Pool stats or null if not connected\n */\n override getPoolStats(): PoolStats | null {\n if (!this.pool) {\n return null;\n }\n\n return {\n total: this.pool.totalCount,\n idle: this.pool.idleCount,\n waiting: this.pool.waitingCount,\n active: this.pool.totalCount - this.pool.idleCount,\n };\n }\n\n /**\n * The connection as a health check reads it, on one pooled client: the\n * server's version, and that client's own row in `pg_stat_ssl`, which says\n * whether the session's connection is encrypted. The query is timed for the\n * round trip.\n *\n * @remarks\n * The row and the client's own socket are weighed by `encryptionOf`: behind\n * a connection pooler such as PgBouncer the row describes the pooler's own\n * connection to the server, which can be plain inside the provider's\n * network while this client's socket is TLS. The socket is read as it is,\n * never inferred from the `ssl` setting.\n *\n * Whether the database is on this machine is judged from the host the\n * client connected to, as node-postgres resolved it (its options, the\n * connection string, `PGHOST`, its default); before a client is had, from\n * the configured address alone. The address never leaves this method. Any\n * failure answers `\"unknown\"`.\n */\n override async inspectConnection(): Promise<ConnectionInspection> {\n let local = this.isLocalHost(this.configuredHost());\n let client: PoolClient | undefined;\n try {\n client = await this.ensurePool().connect();\n local = this.isLocalHost(resolvedHost(client) ?? this.configuredHost());\n const started = performance.now();\n const result = await client.query<{\n version: string | null;\n ssl: boolean | null;\n }>(\n \"SELECT current_setting('server_version') AS version, \" +\n \"(SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()) AS ssl\"\n );\n const roundTripMs = Math.max(0, Math.round(performance.now() - started));\n const row = result.rows[0];\n const version = row?.version?.split(\" \")[0];\n return {\n encryption: this.encryptionOf({\n session: typeof row?.ssl === \"boolean\" ? row.ssl : undefined,\n ownSocketTls: this.ownSocketIsTls(client),\n }),\n local,\n roundTripMs,\n ...(version ? { serverVersion: version } : {}),\n };\n } catch {\n return { encryption: \"unknown\", local };\n } finally {\n client?.release();\n }\n }\n\n /**\n * The host this adapter is configured with: the connection string's when one\n * is set, else the `host` option. `undefined` when it names none, which is\n * judged remote, or when the connection string cannot be read.\n */\n private configuredHost(): string | undefined {\n const configured = this.config.url\n ? this.hostOfUrl(this.config.url)\n : (this.config.host ?? \"\");\n return configured === \"\" ? undefined : configured;\n }\n\n /**\n * Override insertMany for bulk insert optimization.\n *\n * @remarks\n * Uses a single multi-row INSERT statement for better performance\n * when inserting multiple records.\n */\n override async insertMany<T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> {\n if (data.length === 0) {\n return [];\n }\n\n // For single record, use parent implementation\n if (data.length === 1) {\n const result = await this.insert<T>(table, data[0], options);\n return [result];\n }\n\n // Refused as the single-row insert is: a table this instance never\n // registered may not match what its code would write.\n this.resolvedTableObject(table);\n\n // Build multi-row INSERT\n const columns = Object.keys(data[0]);\n const params: SqlParam[] = [];\n const valuesClauses: string[] = [];\n\n for (let i = 0; i < data.length; i++) {\n const record = data[i];\n const placeholders: string[] = [];\n\n for (const col of columns) {\n params.push(record[col] as SqlParam);\n placeholders.push(`$${params.length}`);\n }\n\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n const columnList = columns\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(\", \")}`;\n\n // Add RETURNING clause\n if (options?.returning) {\n const returning =\n options.returning === \"*\"\n ? \"*\"\n : options.returning.map(col => this.escapeIdentifier(col)).join(\", \");\n sql += ` RETURNING ${returning}`;\n }\n\n try {\n return await this.executeQuery<T>(sql, params);\n } catch (error) {\n throw this.handleQueryError(error, \"insertMany\", table);\n }\n }\n\n // ============================================================\n // Protected Helper Methods\n // ============================================================\n\n /**\n * Ensures pool is connected and returns it.\n *\n * @throws {DatabaseError} If not connected\n */\n private ensurePool(): Pool {\n if (!this.pool) {\n throw createDatabaseError({\n kind: \"connection\",\n message: \"PostgresAdapter is not connected. Call connect() first.\",\n });\n }\n return this.pool;\n }\n\n /**\n * Return the typed Drizzle instance for PostgreSQL.\n * Guarded for server-only usage and requires an active connection.\n *\n * @param schema - Optional schema for relational queries (db.query.*)\n * @returns Drizzle ORM instance wrapping the pg pool connection\n * @throws {Error} If called in browser or not connected\n */\n getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T {\n if (typeof window !== \"undefined\") {\n throw new Error(\"getDrizzle() is server-only\");\n }\n const pool = this.ensurePool();\n // drizzle v1 removed the positional (client, config) form — the object\n // form is REQUIRED (positional silently treats the client as config).\n // `relations` (defineRelations output, assembled by Nextly's schema\n // registry) is what powers db.query in v1; a bare instance serves the\n // select-builder CRUD paths.\n if (!relations) {\n this.drizzleBare ??= this.poolDrizzle(pool);\n return this.drizzleBare as T;\n }\n let cached = this.drizzleByRelations.get(relations);\n if (!cached) {\n cached = this.poolDrizzle(pool, relations);\n this.drizzleByRelations.set(relations, cached);\n }\n return cached as T;\n }\n\n /**\n * A Drizzle handle on the pool, for `getDrizzle`.\n *\n * Its `transaction` runs on a client this adapter checks out and returns\n * itself (`pinDrizzleTransactions`): node-postgres destroys a client\n * released with `true`, which is what happens when no ROLLBACK could be\n * confirmed on it. And it counts for `transactionOpenInFlow`, as the\n * adapter's does.\n */\n private poolDrizzle(pool: Pool, relations?: AnyRelations) {\n const onClient = (client: Pool | PoolClient) =>\n relations ? drizzle({ client, relations }) : drizzle({ client });\n // The handle's own queries go to the pool, so it is handed a view of the\n // pool that reports them (`observedPool`).\n const reported = this.observedPool(pool, [\"query\"]);\n // Its transactions join the one the calling flow is inside, as the\n // adapter's `transaction()` does, and open one of this adapter's\n // otherwise (`joiningHandle`).\n return this.joiningHandle(\n onClient(reported),\n async () => {\n const client = await pool.connect();\n return {\n drizzle: onClient(client),\n rollback: () => client.query(\"ROLLBACK\"),\n release: dirty => client.release(dirty),\n join: this.joinSteps(client),\n };\n },\n relations\n );\n }\n\n /**\n * Builds pg Pool configuration from adapter config.\n */\n private buildPoolConfig(): PoolConfig {\n const config: PoolConfig = {};\n\n // Connection string or explicit options\n if (this.config.url) {\n config.connectionString = this.config.url;\n } else {\n if (this.config.host) config.host = this.config.host;\n if (this.config.port) config.port = this.config.port;\n if (this.config.database) config.database = this.config.database;\n if (this.config.user) config.user = this.config.user;\n if (this.config.password) config.password = this.config.password;\n }\n\n // Pool settings (user config > provider defaults > hardcoded defaults)\n config.min =\n this.config.pool?.min ??\n this.providerDefaults.poolMin ??\n DEFAULT_POOL_CONFIG.min;\n config.max =\n this.config.pool?.max ??\n this.providerDefaults.poolMax ??\n DEFAULT_POOL_CONFIG.max;\n config.idleTimeoutMillis =\n this.config.pool?.idleTimeoutMs ??\n this.providerDefaults.idleTimeoutMs ??\n DEFAULT_POOL_CONFIG.idleTimeoutMs;\n config.connectionTimeoutMillis =\n this.config.pool?.connectionTimeoutMs ??\n this.providerDefaults.connectionTimeoutMs ??\n DEFAULT_POOL_CONFIG.connectionTimeoutMs;\n\n // TCP keepalive - prevents cloud databases (e.g. Neon) from silently\n // dropping idle connections between the pool smoke-test and the first\n // real query, which manifests as ETIMEDOUT on the query itself.\n config.keepAlive = true;\n config.keepAliveInitialDelayMillis = 10000;\n\n // SSL configuration (user config > provider default)\n if (this.config.ssl) {\n if (typeof this.config.ssl === \"boolean\") {\n config.ssl = this.config.ssl;\n } else {\n if (this.config.ssl.rejectUnauthorized === false) {\n console.warn(\n \"[nextly/adapter-postgres] ssl.rejectUnauthorized is set to false — \" +\n \"TLS certificates will not be validated. This is unsafe on untrusted networks. \" +\n \"Provide a trusted `ca` cert instead, or remove the rejectUnauthorized override.\"\n );\n }\n config.ssl = {\n rejectUnauthorized: this.config.ssl.rejectUnauthorized,\n ca: this.config.ssl.ca,\n cert: this.config.ssl.cert,\n key: this.config.ssl.key,\n };\n }\n } else if (this.providerDefaults.ssl) {\n // Provider requires SSL but user didn't explicitly configure it.\n // Default to validating certs; the user can opt out by setting\n // `ssl: { rejectUnauthorized: false }` explicitly (which logs a warning above).\n config.ssl = { rejectUnauthorized: true };\n }\n\n // PostgreSQL-specific options\n if (this.config.applicationName) {\n config.application_name = this.config.applicationName;\n }\n\n // The schema every unqualified name resolves in, set as a STARTUP option\n // rather than by issuing `SET search_path`. A SET belongs to whichever\n // pooled connection ran it, so the next checkout would see the default\n // again — and the query that noticed would be whichever one happened to\n // land on a fresh connection, which is the least reproducible failure\n // this setting could have.\n //\n // Validated before it gets here: the value is interpolated, and a startup\n // option is not a place to discover that it needed quoting.\n if (this.config.schema) {\n config.options = `-c search_path=${assertSchemaName(this.config.schema)}`;\n }\n\n // User config beats provider default; both beat \"unset\".\n // Why: provider.ts:58 declared a Neon statementTimeoutMs default but the\n // adapter previously ignored it, leaving stuck queries to pin pool slots\n // indefinitely. Wire the fallback chain here so the declared defaults\n // actually fire.\n const effectiveStatementTimeout =\n this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;\n if (effectiveStatementTimeout !== undefined) {\n config.statement_timeout = effectiveStatementTimeout;\n }\n\n if (this.config.queryTimeout) {\n config.query_timeout = this.config.queryTimeout;\n }\n\n return config;\n }\n\n /**\n * Begins a transaction with the specified options.\n */\n private async beginTransaction(\n client: PoolClient,\n options?: TransactionOptions,\n bounds?: TransactionBounds\n ): Promise<void> {\n let beginSql = \"BEGIN\";\n\n // Add isolation level if specified\n if (options?.isolationLevel) {\n const isolationMap: Record<string, string> = {\n \"read uncommitted\": \"READ UNCOMMITTED\",\n \"read committed\": \"READ COMMITTED\",\n \"repeatable read\": \"REPEATABLE READ\",\n serializable: \"SERIALIZABLE\",\n };\n const level = isolationMap[options.isolationLevel];\n if (level) {\n beginSql += ` ISOLATION LEVEL ${level}`;\n }\n }\n\n // Add read-only mode if specified\n if (options?.readOnly) {\n beginSql += \" READ ONLY\";\n }\n\n await client.query(beginSql);\n\n // Set statement timeout if specified\n if (options?.timeoutMs) {\n await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);\n }\n\n // The scope's bounds (`withTransactionBounds`), for this transaction\n // alone: SET LOCAL ends with it, so the pooled session keeps its own\n // settings. Whole milliseconds, checked when the scope was entered.\n if (bounds?.lockWaitMs !== undefined) {\n await client.query(`SET LOCAL lock_timeout = ${bounds.lockWaitMs}`);\n }\n if (bounds?.idleMs !== undefined) {\n await client.query(\n `SET LOCAL idle_in_transaction_session_timeout = ${bounds.idleMs}`\n );\n }\n }\n\n /**\n * Creates a TransactionContext for the given client.\n */\n /**\n * The RETURNING entries that spell each date column's wall clock out as\n * text, one per alias `dateWallClockAliases` chose. `to_char` renders the\n * stored value without a zone, which is the only form node-postgres cannot\n * shift on the way back.\n */\n private wallClockSpelling(\n aliases: ReadonlyArray<{ sqlName: string; alias: string }>\n ): string {\n return aliases\n .map(\n a =>\n `to_char(${this.escapeIdentifier(a.sqlName)}, '${PG_WALL_CLOCK_FORMAT}') AS ${this.escapeIdentifier(a.alias)}`\n )\n .join(\", \");\n }\n\n /** A `Date` on an undeclared key is spelled as a date field's column spells it. */\n protected override undeclaredDateColumn(): {\n mapToDriverValue(value: unknown): unknown;\n } {\n return DATE_FIELD_COLUMN;\n }\n\n /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */\n protected override compositePrimaryKey(\n tableObj: Record<string, unknown>\n ): object[] {\n return getTableConfig(tableObj as unknown as PgTable).primaryKeys.flatMap(\n key => key.columns\n );\n }\n\n private createTransactionContext(client: PoolClient): TransactionContext {\n // Bind a Drizzle instance to this transaction's checked-out client so the\n // delegated CRUD methods run inside the transaction and see its uncommitted\n // rows. getDrizzle() wraps the pool, which would use a different connection.\n // Built lazily and memoized: transactions that use only raw execute/insert\n // never construct it.\n const txHandles = this.transactionDrizzleHandles(relations =>\n relations ? drizzle({ client, relations }) : drizzle({ client })\n );\n const txDb = txHandles.bare;\n return {\n drizzleWithRelations: txHandles.withRelations,\n\n execute: async <T = unknown>(\n sql: string,\n params: SqlParam[] = []\n ): Promise<T[]> => {\n const result = await client.query(sql, params as unknown[]);\n return result.rows as T[];\n },\n\n // Run on the transaction-bound Drizzle instance rather than the pool, so\n // the statement is part of this transaction and sees its uncommitted rows.\n runStatement: async (statement: SQL): Promise<void> => {\n await txDb().execute(statement);\n },\n\n // node-postgres answers `{ rows }`; the transaction-bound instance keeps\n // the read inside this transaction so it sees its uncommitted writes.\n queryStatement: async <T = Record<string, unknown>>(\n statement: SQL\n ): Promise<T[]> => {\n const result = await txDb().execute(statement);\n return result.rows as T[];\n },\n\n lockRow: async (table: string, id: SqlParam): Promise<void> => {\n const idColumn = this.escapeIdentifier(\"id\");\n await client.query(\n `SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} ` +\n `WHERE ${idColumn} = $1 FOR UPDATE`,\n [id] as unknown[]\n );\n },\n\n insert: async <T = unknown>(\n table: string,\n data: Record<string, unknown>,\n options?: InsertOptions\n ): Promise<T> => {\n // Refused before any statement, as the pooled insert is: a rejected\n // statement would abort the caller's whole transaction.\n const tableObj = this.resolvedTableObject(table);\n const mapped = this.mapRowToRawSql(tableObj, data);\n const columns = Object.keys(mapped);\n const values = Object.values(mapped);\n const placeholders = values.map((_, i) => `$${i + 1}`).join(\", \");\n\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES (${placeholders})`;\n\n const ret = options?.returning;\n const returningEmpty = Array.isArray(ret) && ret.length === 0;\n // Each returned timestamp's wall clock, spelled out by the database.\n // node-postgres turns one into a `Date` in the LOCAL zone before this\n // code sees it, and that conversion cannot be undone: a wall clock\n // inside a daylight-saving gap is normalized away.\n const aliases = returningEmpty\n ? []\n : this.dateWallClockAliases(tableObj, ret ?? \"*\");\n if (!returningEmpty) {\n const returning =\n !ret || ret === \"*\"\n ? \"*\"\n : this.mapColumnNamesToSql(tableObj, ret)\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n const spelled = this.wallClockSpelling(aliases);\n sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : \"\"}`;\n }\n\n const result = await client.query(sql, values);\n // Return JS property-named keys AND dates read as the UTC the statement\n // wrote, to match the non-transactional insert.\n return this.mapRowFromRawSql(tableObj, result.rows[0] as T, aliases);\n },\n\n insertMany: async <T = unknown>(\n table: string,\n data: Record<string, unknown>[],\n options?: InsertOptions\n ): Promise<T[]> => {\n if (data.length === 0) return [];\n\n // Refused before any statement, as `insert` above is.\n const tableObj = this.resolvedTableObject(table);\n const mappedRecords = data.map(r => this.mapRowToRawSql(tableObj, r));\n const columns = Object.keys(mappedRecords[0]);\n const params: unknown[] = [];\n const valuesClauses: string[] = [];\n\n for (const record of mappedRecords) {\n const placeholders: string[] = [];\n for (const col of columns) {\n params.push(record[col]);\n placeholders.push(`$${params.length}`);\n }\n valuesClauses.push(`(${placeholders.join(\", \")})`);\n }\n\n let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map(c => this.escapeIdentifier(c)).join(\", \")}) VALUES ${valuesClauses.join(\", \")}`;\n\n const ret = options?.returning;\n const returningEmpty = Array.isArray(ret) && ret.length === 0;\n const aliases = returningEmpty\n ? []\n : this.dateWallClockAliases(tableObj, ret ?? \"*\");\n if (!returningEmpty) {\n const returning =\n !ret || ret === \"*\"\n ? \"*\"\n : this.mapColumnNamesToSql(tableObj, ret)\n .map(col => this.escapeIdentifier(col))\n .join(\", \");\n const spelled = this.wallClockSpelling(aliases);\n sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : \"\"}`;\n }\n\n const result = await client.query(sql, params);\n return (result.rows as T[]).map(r =>\n this.mapRowFromRawSql(tableObj, r, aliases)\n );\n },\n\n // Adapter-built, as `insert` above is; `transactionUpdate` says why.\n // A column the model does not declare binds natively, except a `Date`,\n // spelled as a date field's column spells it (as this path's insert\n // spells one), and a structured value, sent as JSON\n // (`bindUnmodeledStructuredAsJson`).\n update: this.transactionUpdate(\n txDb,\n async statement => (await txDb().execute(statement)).rows,\n // Structured values as JSON text: node-postgres would spell an array\n // as a PostgreSQL array literal, which no JSON column accepts.\n value => this.bindUnmodeledStructuredAsJson(value)\n ),\n\n ...this.createTransactionForwarders(txDb),\n\n // Savepoints on this transaction's connection, the effects held for the\n // transaction scoped to each (`contextSavepointMethods`).\n ...this.contextSavepointMethods(async statement => {\n await client.query(statement);\n }),\n };\n }\n\n /**\n * Classifies a PostgreSQL error into a DatabaseError.\n *\n * @param error - Original error from pg\n * @param sql - SQL statement that caused the error (optional)\n * @returns DatabaseError with proper classification\n */\n protected override classifyError(\n error: unknown,\n sql?: string\n ): DatabaseError {\n // Why short-circuit on existing DatabaseError: F17's\n // UnsupportedDialectVersionError is already a typed DatabaseError with\n // kind: \"unsupported_version\" plus detectedVersion/requiredVersion\n // fields. Re-wrapping it here would erase those fields and re-tag it\n // as kind: \"unknown\".\n if (isDatabaseError(error)) return error;\n\n // Classified from node-postgres's own error, which Drizzle puts on `cause`\n // when it wraps a failed query (`driverErrorIn`); it is the one carrying\n // the SQLSTATE `code`.\n const pgError = this.driverErrorIn<{\n code?: string;\n message?: string;\n constraint?: string;\n table?: string;\n column?: string;\n detail?: string;\n hint?: string;\n severity?: string;\n cause?: unknown;\n }>(\n error,\n candidate => typeof candidate.code === \"string\" && candidate.code !== \"\"\n );\n\n // Determine error kind from PostgreSQL error code\n const kind: DatabaseErrorKind =\n (pgError.code && PG_ERROR_CODES[pgError.code]) || \"unknown\";\n\n // Build error message\n let message = pgError.message ?? String(error);\n if (sql && kind === \"query\") {\n message = `Query failed: ${message}`;\n }\n\n return createDatabaseError({\n kind,\n message,\n code: pgError.code,\n constraint: pgError.constraint,\n table: pgError.table,\n column: pgError.column,\n detail: pgError.detail,\n hint: pgError.hint,\n cause: error instanceof Error ? error : undefined,\n });\n }\n}\n\n/**\n * Creates a PostgreSQL database adapter instance.\n *\n * @remarks\n * This is the recommended way to create a PostgreSQL adapter.\n * The adapter is not connected after creation - call `connect()` to\n * establish the database connection.\n *\n * @param config - Adapter configuration\n * @returns A new PostgresAdapter instance\n *\n * @example\n * Simple usage:\n * ```typescript\n * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * });\n *\n * await adapter.connect();\n * ```\n *\n * @example\n * With full configuration:\n * ```typescript\n * const adapter = createPostgresAdapter({\n * url: process.env.DATABASE_URL!,\n * pool: {\n * min: 5,\n * max: 20,\n * idleTimeoutMs: 30000,\n * connectionTimeoutMs: 10000,\n * },\n * ssl: {\n * rejectUnauthorized: true,\n * ca: process.env.CA_CERT,\n * },\n * applicationName: 'my-app',\n * statementTimeout: 30000,\n * });\n * ```\n *\n * @public\n */\nexport function createPostgresAdapter(\n config: PostgresAdapterConfig\n): PostgresAdapter {\n return new PostgresAdapter(config);\n}\n\n/**\n * Type guard to check if a value is a PostgresAdapter instance.\n *\n * @param value - Value to check\n * @returns True if value is a PostgresAdapter\n *\n * @example\n * ```typescript\n * import { isPostgresAdapter } from '@nextlyhq/adapter-postgres';\n *\n * if (isPostgresAdapter(adapter)) {\n * // TypeScript knows adapter is PostgresAdapter\n * console.log(adapter.dialect); // 'postgresql'\n * }\n * ```\n *\n * @public\n */\nexport function isPostgresAdapter(value: unknown): value is PostgresAdapter {\n return value instanceof PostgresAdapter;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,6BAA6B;;AASnC,SAAS,WAAW,OAAc,SAAwB;CACxD,IAAI,MAAM,YAAY,4BACpB,QAAA,GAAOA,gCAAAA,qBAAAA,CAAqB,SAAS,KAAK;CAE5C,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,sBACd,MACA,SACM;CACN,MAAM,QAAQ,WAAW;CACzB,MAAM,UAAU,KAAK,QAAQ,KAAK,IAAI;CAGtC,MAAM,WAAW,aAA+B;EAC9C,IAAI,UACF,OAAO,SAAS,KAAK,QAAQ,SAC3B,SAAS,OAAO,WAAW,KAAK,KAAK,GAAG,QAAQ,IAAI,CACtD;EAEF,OAAQ,QAAQ,CAAC,CAAyB,OAAO,UAAiB;GAChE,MAAM,WAAW,OAAO,KAAK;EAC/B,CAAC;CACH;CACA,KAAK,UAAU;CACf,OAAO;AACT;;ACnDA,SAAgB,uBACd,KACA,kBACkB;CAElB,IAAI,kBAAkB;EACpB,MAAM,aAAa,iBAAiB,YAAY;EAChD,IACE,eAAe,UACf,eAAe,cACf,eAAe,YAEf,OAAO;CAEX;CAGA,IAAI,IAAI,SAAS,YAAY,KAAK,IAAI,SAAS,OAAO,GACpD,OAAO;CAET,IAAI,IAAI,SAAS,YAAY,KAAK,IAAI,SAAS,WAAW,GACxD,OAAO;CAGT,OAAO;AACT;AAiBA,SAAgB,oBACd,UACA,UAAmC,CAAC,GAClB;CAClB,MAAM,WAAW,oBAAoB,QAAQ;CAC7C,IAAI,CAAC,QAAQ,YAAY,OAAO;CAChC,OAAO;EACL,GAAG;EACH,SAASC,qCAAAA,yBAAyB;EAClC,SAASA,qCAAAA,yBAAyB;EAClC,eAAeA,qCAAAA,yBAAyB;CAC1C;AACF;AAGA,SAAS,oBAAoB,U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