@nextlyhq/adapter-postgres 0.0.2-alpha.7 → 0.0.2-alpha.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,674 +1,932 @@
1
- import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
- import { createDatabaseError, isDatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
- import { checkDialectVersion } from '@nextlyhq/adapter-drizzle/version-check';
4
- import { drizzle } from 'drizzle-orm/node-postgres';
5
- import { Pool } from 'pg';
6
-
7
- // src/index.ts
8
-
1
+ import * as net from "node:net";
2
+ import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
3
+ import { assertSchemaName } from "@nextlyhq/adapter-drizzle/schema-name";
4
+ import { createDatabaseError, isApplicationError, isDatabaseError, poolWaitTimeoutError } from "@nextlyhq/adapter-drizzle/types";
5
+ import { checkDialectVersion } from "@nextlyhq/adapter-drizzle/version-check";
6
+ import { drizzle } from "drizzle-orm/node-postgres";
7
+ import { getTableConfig } from "drizzle-orm/pg-core";
8
+ import { Pool } from "pg";
9
+ // src/pool-wait.ts
10
+ /**
11
+ * The bounded wait for a pooled connection, reported as the adapters' own
12
+ * "pool wait timeout" error.
13
+ *
14
+ * pg-pool already bounds the wait: a request that finds every connection in
15
+ * use waits at most `connectionTimeoutMillis`, then is removed from the queue
16
+ * and fails. It fails with a plain `Error` that has no code, though, so
17
+ * nothing downstream could tell it from any other driver failure, and a
18
+ * caller got an internal error for a database that was only busy. This gives
19
+ * that one failure the code core answers with "database busy".
20
+ *
21
+ * Only the wait for a connection already in the pool: a new connection that
22
+ * cannot be opened in time is pg-pool's other timeout ("Connection terminated
23
+ * due to connection timeout"), a database that cannot be reached rather than
24
+ * one that is busy, and stays as it was.
25
+ */
26
+ /**
27
+ * pg-pool's message for a request that waited its bound in the queue. The
28
+ * error carries nothing else to recognise it by; the pool-wait integration
29
+ * test runs against the installed pg-pool, so a reworded message fails there.
30
+ */
31
+ const QUEUE_WAIT_TIMEOUT_MESSAGE = "timeout exceeded when trying to connect";
32
+ /** The error a caller should see for one pg-pool raised. */
33
+ function translated(error, boundMs) {
34
+ if (error.message === QUEUE_WAIT_TIMEOUT_MESSAGE) return poolWaitTimeoutError(boundMs, error);
35
+ return error;
36
+ }
37
+ /**
38
+ * Makes `pool` report a request that waited past `boundMs` for a connection
39
+ * with the pool-wait timeout error, and returns it. `boundMs` is the pool's
40
+ * own `connectionTimeoutMillis`, unset when the pool has none.
41
+ *
42
+ * Replaces the pool's own `connect`, which its `query` also goes through, so
43
+ * every path to a connection reports the same way: the adapter's statements,
44
+ * its transactions, and the Drizzle handle core services query through.
45
+ */
46
+ function reportPoolWaitTimeout(pool, boundMs) {
47
+ const bound = boundMs ?? 0;
48
+ const connect = pool.connect.bind(pool);
49
+ const bounded = (callback) => {
50
+ if (callback) return connect((err, client, done) => callback(err && translated(err, bound), client, done));
51
+ return connect().catch((error) => {
52
+ throw translated(error, bound);
53
+ });
54
+ };
55
+ pool.connect = bounded;
56
+ return pool;
57
+ }
9
58
  // src/provider.ts
10
59
  function detectPostgresProvider(url, explicitProvider) {
11
- if (explicitProvider) {
12
- const normalized = explicitProvider.toLowerCase();
13
- if (normalized === "neon" || normalized === "supabase" || normalized === "standard") {
14
- return normalized;
15
- }
16
- }
17
- if (url.includes(".neon.tech") || url.includes("neon.")) {
18
- return "neon";
19
- }
20
- if (url.includes(".supabase.") || url.includes("supabase.")) {
21
- return "supabase";
22
- }
23
- return "standard";
60
+ if (explicitProvider) {
61
+ const normalized = explicitProvider.toLowerCase();
62
+ if (normalized === "neon" || normalized === "supabase" || normalized === "standard") return normalized;
63
+ }
64
+ if (url.includes(".neon.tech") || url.includes("neon.")) return "neon";
65
+ if (url.includes(".supabase.") || url.includes("supabase.")) return "supabase";
66
+ return "standard";
24
67
  }
25
68
  function getProviderDefaults(provider) {
26
- switch (provider) {
27
- case "neon":
28
- return {
29
- ssl: true,
30
- poolMax: 5,
31
- poolMin: 0,
32
- idleTimeoutMs: 1e4,
33
- connectionTimeoutMs: 2e4,
34
- statementTimeoutMs: 3e4,
35
- retryAttempts: 5
36
- };
37
- case "supabase":
38
- return {
39
- ssl: true,
40
- poolMax: 5,
41
- poolMin: 0,
42
- idleTimeoutMs: 3e4,
43
- connectionTimeoutMs: 15e3,
44
- statementTimeoutMs: 15e3,
45
- retryAttempts: 3
46
- };
47
- case "standard":
48
- default:
49
- return {
50
- ssl: false,
51
- poolMax: 10,
52
- poolMin: 0,
53
- idleTimeoutMs: 3e4,
54
- connectionTimeoutMs: 15e3,
55
- statementTimeoutMs: 15e3,
56
- retryAttempts: 3
57
- };
58
- }
69
+ switch (provider) {
70
+ case "neon": return {
71
+ ssl: true,
72
+ poolMax: 5,
73
+ poolMin: 0,
74
+ idleTimeoutMs: 1e4,
75
+ connectionTimeoutMs: 2e4,
76
+ statementTimeoutMs: 3e4,
77
+ retryAttempts: 5
78
+ };
79
+ case "supabase": return {
80
+ ssl: true,
81
+ poolMax: 5,
82
+ poolMin: 0,
83
+ idleTimeoutMs: 3e4,
84
+ connectionTimeoutMs: 15e3,
85
+ statementTimeoutMs: 15e3,
86
+ retryAttempts: 3
87
+ };
88
+ default: return {
89
+ ssl: false,
90
+ poolMax: 10,
91
+ poolMin: 0,
92
+ idleTimeoutMs: 3e4,
93
+ connectionTimeoutMs: 15e3,
94
+ statementTimeoutMs: 15e3,
95
+ retryAttempts: 3
96
+ };
97
+ }
59
98
  }
60
-
61
99
  // src/index.ts
62
- var VERSION = "0.1.0";
63
- var DEFAULT_POOL_CONFIG = {
64
- min: 0,
65
- max: 5,
66
- idleTimeoutMs: 3e4,
67
- connectionTimeoutMs: 15e3
100
+ /**
101
+ * @nextlyhq/adapter-postgres
102
+ *
103
+ * PostgreSQL database adapter for Nextly.
104
+ * Extends the base DrizzleAdapter from @nextlyhq/adapter-drizzle to provide
105
+ * PostgreSQL-specific functionality.
106
+ *
107
+ * @remarks
108
+ * This adapter uses the `pg` (node-postgres) driver for database connections
109
+ * and integrates with Drizzle ORM for type-safe queries.
110
+ *
111
+ * Features:
112
+ * - Connection pooling via pg.Pool
113
+ * - Full transaction support with savepoints
114
+ * - RETURNING clause support for all CRUD operations
115
+ * - PostgreSQL-specific error classification
116
+ * - JSONB support
117
+ * - Full-text search capabilities
118
+ * - Automatic retry for serialization failures and deadlocks
119
+ *
120
+ * @example
121
+ * Simple usage with connection string:
122
+ * ```typescript
123
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
124
+ *
125
+ * const adapter = createPostgresAdapter({
126
+ * url: process.env.DATABASE_URL!,
127
+ * });
128
+ *
129
+ * await adapter.connect();
130
+ * ```
131
+ *
132
+ * @example
133
+ * Full configuration:
134
+ * ```typescript
135
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
136
+ *
137
+ * const adapter = createPostgresAdapter({
138
+ * url: process.env.DATABASE_URL!,
139
+ * pool: {
140
+ * min: 2,
141
+ * max: 20,
142
+ * idleTimeoutMs: 30000,
143
+ * },
144
+ * ssl: {
145
+ * rejectUnauthorized: true,
146
+ * },
147
+ * applicationName: 'my-nextly-app',
148
+ * });
149
+ * ```
150
+ *
151
+ * @example
152
+ * Using the adapter class directly:
153
+ * ```typescript
154
+ * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';
155
+ * import type { PostgresAdapterConfig } from '@nextlyhq/adapter-postgres';
156
+ *
157
+ * const config: PostgresAdapterConfig = {
158
+ * url: process.env.DATABASE_URL!,
159
+ * };
160
+ *
161
+ * const adapter = new PostgresAdapter(config);
162
+ * await adapter.connect();
163
+ * ```
164
+ *
165
+ * @packageDocumentation
166
+ */
167
+ /**
168
+ * Package version.
169
+ */
170
+ const VERSION = "0.1.0";
171
+ /**
172
+ * Default pool configuration values.
173
+ *
174
+ * min: 0 – Never eagerly create background connections. This is critical
175
+ * for cold-start recovery (e.g. Neon auto-suspend): after the
176
+ * initial smoke-test connection, the pool won't immediately try
177
+ * to create additional connections that might still fail while
178
+ * the DB is waking up.
179
+ *
180
+ * max: 5 – Conservative default to avoid overwhelming cloud databases
181
+ * (Neon free-tier limit is ~25-30 simultaneous connections).
182
+ * With Next.js spawning up to 7 build workers this keeps the
183
+ * total connection count safely under typical limits.
184
+ */
185
+ const DEFAULT_POOL_CONFIG = {
186
+ min: 0,
187
+ max: 5,
188
+ idleTimeoutMs: 3e4,
189
+ connectionTimeoutMs: 15e3
68
190
  };
69
- var PG_ERROR_CODES = {
70
- // Class 08 - Connection Exception
71
- "08000": "connection",
72
- "08003": "connection",
73
- "08006": "connection",
74
- "08001": "connection",
75
- "08004": "connection",
76
- "08007": "connection",
77
- "08P01": "connection",
78
- // Class 23 - Integrity Constraint Violation
79
- "23000": "constraint",
80
- "23001": "constraint",
81
- "23502": "not_null_violation",
82
- "23503": "foreign_key_violation",
83
- "23505": "unique_violation",
84
- "23514": "check_violation",
85
- "23P01": "constraint",
86
- // Class 40 - Transaction Rollback
87
- "40000": "query",
88
- "40001": "serialization_failure",
89
- "40002": "constraint",
90
- "40003": "query",
91
- "40P01": "deadlock",
92
- // Class 57 - Operator Intervention
93
- "57014": "timeout",
94
- "57P01": "connection",
95
- "57P02": "connection",
96
- "57P03": "connection"
191
+ /**
192
+ * PostgreSQL error codes mapping to DatabaseErrorKind.
193
+ *
194
+ * @see https://www.postgresql.org/docs/current/errcodes-appendix.html
195
+ */
196
+ const PG_ERROR_CODES = {
197
+ "08000": "connection",
198
+ "08003": "connection",
199
+ "08006": "connection",
200
+ "08001": "connection",
201
+ "08004": "connection",
202
+ "08007": "connection",
203
+ "08P01": "connection",
204
+ "23000": "constraint",
205
+ "23001": "constraint",
206
+ "23502": "not_null_violation",
207
+ "23503": "foreign_key_violation",
208
+ "23505": "unique_violation",
209
+ "23514": "check_violation",
210
+ "23P01": "constraint",
211
+ "40000": "query",
212
+ "40001": "serialization_failure",
213
+ "40002": "constraint",
214
+ "40003": "query",
215
+ "40P01": "deadlock",
216
+ "57014": "timeout",
217
+ "57P01": "connection",
218
+ "57P02": "connection",
219
+ "57P03": "connection"
97
220
  };
221
+ /**
222
+ * Create the configured schema when the database does not have it yet.
223
+ *
224
+ * Looked up before it is created, because `CREATE SCHEMA IF NOT EXISTS` is not
225
+ * a no-op for a schema that exists: PostgreSQL checks the database-level
226
+ * `CREATE` privilege before it checks for the schema, so a role that may use
227
+ * and create objects in `public` but may not create schemas would fail to
228
+ * connect over a schema that is already there. Reading `pg_namespace` needs no
229
+ * privilege, so only a schema that is genuinely missing asks for one.
230
+ */
231
+ async function ensureSchemaExists(client, schema) {
232
+ const name = assertSchemaName(schema);
233
+ if ((await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0) return;
234
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
235
+ }
236
+ /**
237
+ * Delay helper for retry logic.
238
+ */
98
239
  function delay(ms) {
99
- return new Promise((resolve) => setTimeout(resolve, ms));
240
+ return new Promise((resolve) => setTimeout(resolve, ms));
241
+ }
242
+ const HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5e3;
243
+ let happyEyeballsTimeoutApplied = false;
244
+ function applyHappyEyeballsTimeoutOnce() {
245
+ if (happyEyeballsTimeoutApplied) return;
246
+ happyEyeballsTimeoutApplied = true;
247
+ try {
248
+ if ((typeof net.getDefaultAutoSelectFamilyAttemptTimeout === "function" ? net.getDefaultAutoSelectFamilyAttemptTimeout() : 0) < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) net.setDefaultAutoSelectFamilyAttemptTimeout(HAPPY_EYEBALLS_MIN_TIMEOUT_MS);
249
+ } catch {}
100
250
  }
251
+ /**
252
+ * How a date column's wall clock is spelled out when a write reads its row
253
+ * back: the stored value to the millisecond, with no zone for the driver to
254
+ * shift.
255
+ */
256
+ const PG_WALL_CLOCK_FORMAT = "YYYY-MM-DD\"T\"HH24:MI:SS.MS";
257
+ /**
258
+ * PostgreSQL database adapter for Nextly.
259
+ *
260
+ * @remarks
261
+ * This class extends the base DrizzleAdapter to provide PostgreSQL-specific
262
+ * functionality including:
263
+ *
264
+ * - Connection pooling with pg.Pool
265
+ * - Transaction support with savepoints
266
+ * - PostgreSQL-specific error codes
267
+ * - JSONB and array type support
268
+ * - Full-text search
269
+ * - Automatic retry for serialization failures and deadlocks
270
+ *
271
+ * For most use cases, use the `createPostgresAdapter` factory function
272
+ * instead of instantiating this class directly.
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';
277
+ *
278
+ * const adapter = new PostgresAdapter({
279
+ * url: 'postgres://user:pass@localhost:5432/mydb',
280
+ * });
281
+ *
282
+ * await adapter.connect();
283
+ *
284
+ * // Use the adapter
285
+ * const users = await adapter.select('users', {
286
+ * where: { and: [{ column: 'status', op: '=', value: 'active' }] },
287
+ * });
288
+ *
289
+ * await adapter.disconnect();
290
+ * ```
291
+ *
292
+ * @public
293
+ */
101
294
  var PostgresAdapter = class extends DrizzleAdapter {
102
- /**
103
- * The database dialect - always 'postgresql' for this adapter.
104
- */
105
- dialect = "postgresql";
106
- /**
107
- * Adapter configuration.
108
- */
109
- config;
110
- /**
111
- * Connection pool instance.
112
- */
113
- pool = null;
114
- /**
115
- * Connection state flag.
116
- */
117
- connected = false;
118
- /**
119
- * Auto-detected provider (Neon, Supabase, or standard).
120
- * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
121
- */
122
- detectedProvider = "standard";
123
- /**
124
- * Provider-specific connection defaults. Applied as fallbacks when
125
- * user config doesn't specify a value.
126
- */
127
- providerDefaults = getProviderDefaults("standard");
128
- /**
129
- * Creates a new PostgreSQL adapter instance.
130
- *
131
- * @param config - Adapter configuration
132
- */
133
- constructor(config) {
134
- super();
135
- this.config = config;
136
- }
137
- /**
138
- * Establishes a connection to the PostgreSQL database.
139
- *
140
- * @remarks
141
- * This method initializes the connection pool and verifies connectivity
142
- * by executing a simple query. It is idempotent - calling it multiple
143
- * times will not create multiple pools.
144
- *
145
- * @throws {DatabaseError} If connection fails
146
- */
147
- async connect() {
148
- if (this.connected && this.pool) {
149
- return;
150
- }
151
- const url = this.config.url || "";
152
- this.detectedProvider = detectPostgresProvider(
153
- url,
154
- process.env.DB_PROVIDER
155
- );
156
- this.providerDefaults = getProviderDefaults(this.detectedProvider);
157
- if (this.config.logger?.info) {
158
- const source = process.env.DB_PROVIDER ? "(explicit)" : "(auto-detected)";
159
- this.config.logger.info(
160
- `PostgreSQL provider: ${this.detectedProvider} ${source}`,
161
- {}
162
- );
163
- }
164
- const retryableNodeCodes = /* @__PURE__ */ new Set([
165
- "ETIMEDOUT",
166
- "ECONNREFUSED",
167
- "ECONNRESET",
168
- "ENOTFOUND",
169
- "EAI_AGAIN"
170
- ]);
171
- const maxAttempts = this.providerDefaults.retryAttempts;
172
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
173
- try {
174
- const poolConfig = this.buildPoolConfig();
175
- this.pool = new Pool(poolConfig);
176
- this.pool.on("error", (err) => {
177
- if (this.config.logger?.error) {
178
- this.config.logger.error(err, {
179
- context: "pool_error",
180
- message: "Unexpected error on idle client"
181
- });
182
- }
183
- });
184
- const client = await this.pool.connect();
185
- try {
186
- await client.query("SELECT 1");
187
- await checkDialectVersion(client, "postgresql", {
188
- // Why: route any future variant warnings through the adapter's
189
- // logger. PG has no recognized variants today, but this keeps
190
- // the integration symmetric with MySQL.
191
- onWarning: (msg) => this.config.logger?.warn?.(msg)
192
- });
193
- this.connected = true;
194
- if (this.config.logger?.info) {
195
- this.config.logger.info("PostgreSQL connection established", {
196
- host: this.config.host ?? "from URL",
197
- database: this.config.database ?? "from URL"
198
- });
199
- }
200
- return;
201
- } finally {
202
- client.release();
203
- }
204
- } catch (error) {
205
- if (this.pool) {
206
- await this.pool.end().catch(() => {
207
- });
208
- this.pool = null;
209
- }
210
- const nodeError = error;
211
- const isRetryable = nodeError.code != null && retryableNodeCodes.has(nodeError.code);
212
- if (isRetryable && attempt < maxAttempts) {
213
- const waitMs = 1e3 * attempt;
214
- const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;
215
- if (this.config.logger?.warn) {
216
- this.config.logger.warn(msg);
217
- } else {
218
- console.warn(`[PostgresAdapter] ${msg}`);
219
- }
220
- await delay(waitMs);
221
- continue;
222
- }
223
- throw this.classifyError(error);
224
- }
225
- }
226
- }
227
- /**
228
- * Closes the database connection and releases all pool resources.
229
- *
230
- * @remarks
231
- * This method is idempotent - calling it multiple times is safe.
232
- * It waits for all checked-out clients to be returned before shutting down.
233
- */
234
- async disconnect() {
235
- if (!this.pool) {
236
- return;
237
- }
238
- try {
239
- await this.pool.end();
240
- if (this.config.logger?.info) {
241
- this.config.logger.info("PostgreSQL connection closed");
242
- }
243
- } finally {
244
- this.pool = null;
245
- this.connected = false;
246
- }
247
- }
248
- /**
249
- * Checks if the adapter is currently connected.
250
- *
251
- * @returns True if connected and pool is available
252
- */
253
- isConnected() {
254
- return this.connected && this.pool !== null;
255
- }
256
- /**
257
- * Executes a raw SQL query.
258
- *
259
- * @param sql - SQL statement with $1, $2, ... placeholders
260
- * @param params - Query parameters
261
- * @returns Array of result rows
262
- *
263
- * @throws {DatabaseError} If query execution fails
264
- */
265
- async executeQuery(sql, params = []) {
266
- const pool = this.ensurePool();
267
- const startTime = Date.now();
268
- const retryableNodeCodes = /* @__PURE__ */ new Set([
269
- "ETIMEDOUT",
270
- "ECONNRESET",
271
- "ECONNREFUSED"
272
- ]);
273
- const maxQueryAttempts = 3;
274
- for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) {
275
- try {
276
- const result = await pool.query(sql, params);
277
- if (this.config.logger?.query) {
278
- const durationMs = Date.now() - startTime;
279
- this.config.logger.query(sql, params, durationMs);
280
- }
281
- return result.rows;
282
- } catch (error) {
283
- const nodeError = error;
284
- const isRetryable = nodeError.code != null && retryableNodeCodes.has(nodeError.code);
285
- if (isRetryable && attempt < maxQueryAttempts) {
286
- const waitMs = 500 * attempt;
287
- console.warn(
288
- `[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`
289
- );
290
- await delay(waitMs);
291
- continue;
292
- }
293
- throw this.classifyError(error, sql);
294
- }
295
- }
296
- throw this.classifyError(new Error("executeQuery: exhausted retries"));
297
- }
298
- /**
299
- * Executes a callback within a database transaction.
300
- *
301
- * @remarks
302
- * PostgreSQL supports full ACID transactions with savepoints.
303
- * If the callback throws, the transaction is rolled back.
304
- *
305
- * Supports automatic retry for serialization failures (40001) and
306
- * deadlocks (40P01) when `retryCount` is specified in options.
307
- *
308
- * @param callback - Function to execute within the transaction
309
- * @param options - Transaction options (isolation level, timeout, retry)
310
- * @returns The result of the callback
311
- *
312
- * @throws {DatabaseError} If transaction fails after all retries
313
- */
314
- async transaction(callback, options) {
315
- const pool = this.ensurePool();
316
- const maxAttempts = (options?.retryCount ?? 0) + 1;
317
- const retryDelayMs = options?.retryDelayMs ?? 100;
318
- let lastError;
319
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
320
- const client = await pool.connect();
321
- const startTime = Date.now();
322
- try {
323
- await this.beginTransaction(client, options);
324
- const ctx = this.createTransactionContext(client);
325
- const result = await callback(ctx);
326
- await client.query("COMMIT");
327
- if (this.config.logger?.debug) {
328
- const durationMs = Date.now() - startTime;
329
- this.config.logger.debug("Transaction committed", {
330
- attempt,
331
- durationMs
332
- });
333
- }
334
- return result;
335
- } catch (error) {
336
- await client.query("ROLLBACK").catch(() => {
337
- });
338
- lastError = error;
339
- const pgError = error;
340
- const isRetryable = pgError.code === "40001" || // serialization_failure
341
- pgError.code === "40P01";
342
- if (isRetryable && attempt < maxAttempts) {
343
- if (this.config.logger?.warn) {
344
- this.config.logger.warn(
345
- `Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`,
346
- { code: pgError.code, attempt }
347
- );
348
- }
349
- await delay(retryDelayMs * attempt);
350
- continue;
351
- }
352
- throw this.classifyError(error);
353
- } finally {
354
- client.release();
355
- }
356
- }
357
- throw this.classifyError(lastError);
358
- }
359
- /**
360
- * Returns the database capabilities for PostgreSQL.
361
- *
362
- * @remarks
363
- * PostgreSQL has the most comprehensive feature set of all supported
364
- * databases, including JSONB, arrays, full-text search, and more.
365
- */
366
- getCapabilities() {
367
- return {
368
- dialect: "postgresql",
369
- supportsJsonb: true,
370
- supportsJson: true,
371
- supportsArrays: true,
372
- supportsGeneratedColumns: true,
373
- supportsFts: true,
374
- supportsIlike: true,
375
- supportsReturning: true,
376
- supportsSavepoints: true,
377
- supportsOnConflict: true,
378
- maxParamsPerQuery: 65535,
379
- // PostgreSQL limit
380
- maxIdentifierLength: 63
381
- // PostgreSQL default
382
- };
383
- }
384
- /**
385
- * Returns connection pool statistics.
386
- *
387
- * @returns Pool stats or null if not connected
388
- */
389
- getPoolStats() {
390
- if (!this.pool) {
391
- return null;
392
- }
393
- return {
394
- total: this.pool.totalCount,
395
- idle: this.pool.idleCount,
396
- waiting: this.pool.waitingCount,
397
- active: this.pool.totalCount - this.pool.idleCount
398
- };
399
- }
400
- /**
401
- * Override insertMany for bulk insert optimization.
402
- *
403
- * @remarks
404
- * Uses a single multi-row INSERT statement for better performance
405
- * when inserting multiple records.
406
- */
407
- async insertMany(table, data, options) {
408
- if (data.length === 0) {
409
- return [];
410
- }
411
- if (data.length === 1) {
412
- const result = await this.insert(table, data[0], options);
413
- return [result];
414
- }
415
- const columns = Object.keys(data[0]);
416
- const params = [];
417
- const valuesClauses = [];
418
- for (let i = 0; i < data.length; i++) {
419
- const record = data[i];
420
- const placeholders = [];
421
- for (const col of columns) {
422
- params.push(record[col]);
423
- placeholders.push(`$${params.length}`);
424
- }
425
- valuesClauses.push(`(${placeholders.join(", ")})`);
426
- }
427
- const columnList = columns.map((col) => this.escapeIdentifier(col)).join(", ");
428
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(", ")}`;
429
- if (options?.returning) {
430
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
431
- sql += ` RETURNING ${returning}`;
432
- }
433
- try {
434
- return await this.executeQuery(sql, params);
435
- } catch (error) {
436
- throw this.handleQueryError(error, "insertMany", table);
437
- }
438
- }
439
- // ============================================================
440
- // Protected Helper Methods
441
- // ============================================================
442
- /**
443
- * Ensures pool is connected and returns it.
444
- *
445
- * @throws {DatabaseError} If not connected
446
- */
447
- ensurePool() {
448
- if (!this.pool) {
449
- throw createDatabaseError({
450
- kind: "connection",
451
- message: "PostgresAdapter is not connected. Call connect() first."
452
- });
453
- }
454
- return this.pool;
455
- }
456
- /**
457
- * Return the typed Drizzle instance for PostgreSQL.
458
- * Guarded for server-only usage and requires an active connection.
459
- *
460
- * @param schema - Optional schema for relational queries (db.query.*)
461
- * @returns Drizzle ORM instance wrapping the pg pool connection
462
- * @throws {Error} If called in browser or not connected
463
- */
464
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
465
- getDrizzle(schema) {
466
- if (typeof window !== "undefined") {
467
- throw new Error("getDrizzle() is server-only");
468
- }
469
- const pool = this.ensurePool();
470
- return schema ? drizzle(pool, { schema }) : drizzle(pool);
471
- }
472
- /**
473
- * Builds pg Pool configuration from adapter config.
474
- */
475
- buildPoolConfig() {
476
- const config = {};
477
- if (this.config.url) {
478
- config.connectionString = this.config.url;
479
- } else {
480
- if (this.config.host) config.host = this.config.host;
481
- if (this.config.port) config.port = this.config.port;
482
- if (this.config.database) config.database = this.config.database;
483
- if (this.config.user) config.user = this.config.user;
484
- if (this.config.password) config.password = this.config.password;
485
- }
486
- config.min = this.config.pool?.min ?? this.providerDefaults.poolMin ?? DEFAULT_POOL_CONFIG.min;
487
- config.max = this.config.pool?.max ?? this.providerDefaults.poolMax ?? DEFAULT_POOL_CONFIG.max;
488
- config.idleTimeoutMillis = this.config.pool?.idleTimeoutMs ?? this.providerDefaults.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;
489
- config.connectionTimeoutMillis = this.config.pool?.connectionTimeoutMs ?? this.providerDefaults.connectionTimeoutMs ?? DEFAULT_POOL_CONFIG.connectionTimeoutMs;
490
- config.keepAlive = true;
491
- config.keepAliveInitialDelayMillis = 1e4;
492
- if (this.config.ssl) {
493
- if (typeof this.config.ssl === "boolean") {
494
- config.ssl = this.config.ssl;
495
- } else {
496
- if (this.config.ssl.rejectUnauthorized === false) {
497
- console.warn(
498
- "[nextly/adapter-postgres] ssl.rejectUnauthorized is set to false \u2014 TLS certificates will not be validated. This is unsafe on untrusted networks. Provide a trusted `ca` cert instead, or remove the rejectUnauthorized override."
499
- );
500
- }
501
- config.ssl = {
502
- rejectUnauthorized: this.config.ssl.rejectUnauthorized,
503
- ca: this.config.ssl.ca,
504
- cert: this.config.ssl.cert,
505
- key: this.config.ssl.key
506
- };
507
- }
508
- } else if (this.providerDefaults.ssl) {
509
- config.ssl = { rejectUnauthorized: true };
510
- }
511
- if (this.config.applicationName) {
512
- config.application_name = this.config.applicationName;
513
- }
514
- if (this.config.statementTimeout) {
515
- config.statement_timeout = this.config.statementTimeout;
516
- }
517
- if (this.config.queryTimeout) {
518
- config.query_timeout = this.config.queryTimeout;
519
- }
520
- return config;
521
- }
522
- /**
523
- * Begins a transaction with the specified options.
524
- */
525
- async beginTransaction(client, options) {
526
- let beginSql = "BEGIN";
527
- if (options?.isolationLevel) {
528
- const isolationMap = {
529
- "read uncommitted": "READ UNCOMMITTED",
530
- "read committed": "READ COMMITTED",
531
- "repeatable read": "REPEATABLE READ",
532
- serializable: "SERIALIZABLE"
533
- };
534
- const level = isolationMap[options.isolationLevel];
535
- if (level) {
536
- beginSql += ` ISOLATION LEVEL ${level}`;
537
- }
538
- }
539
- if (options?.readOnly) {
540
- beginSql += " READ ONLY";
541
- }
542
- await client.query(beginSql);
543
- if (options?.timeoutMs) {
544
- await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);
545
- }
546
- }
547
- /**
548
- * Creates a TransactionContext for the given client.
549
- */
550
- createTransactionContext(client) {
551
- return {
552
- execute: async (sql, params = []) => {
553
- const result = await client.query(sql, params);
554
- return result.rows;
555
- },
556
- insert: async (table, data, options) => {
557
- const columns = Object.keys(data);
558
- const values = Object.values(data);
559
- const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
560
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
561
- if (options?.returning) {
562
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
563
- sql += ` RETURNING ${returning}`;
564
- } else {
565
- sql += " RETURNING *";
566
- }
567
- const result = await client.query(sql, values);
568
- return result.rows[0];
569
- },
570
- insertMany: async (table, data, options) => {
571
- if (data.length === 0) return [];
572
- const columns = Object.keys(data[0]);
573
- const params = [];
574
- const valuesClauses = [];
575
- for (const record of data) {
576
- const placeholders = [];
577
- for (const col of columns) {
578
- params.push(record[col]);
579
- placeholders.push(`$${params.length}`);
580
- }
581
- valuesClauses.push(`(${placeholders.join(", ")})`);
582
- }
583
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
584
- if (options?.returning) {
585
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
586
- sql += ` RETURNING ${returning}`;
587
- } else {
588
- sql += " RETURNING *";
589
- }
590
- const result = await client.query(sql, params);
591
- return result.rows;
592
- },
593
- // TransactionContext CRUD methods delegate to the adapter's CRUD
594
- // which uses Drizzle query API via the TableResolver.
595
- // The Drizzle transaction is handled at a higher level.
596
- select: async (table, options) => {
597
- return this.select(table, options);
598
- },
599
- selectOne: async (table, options) => {
600
- return this.selectOne(table, options);
601
- },
602
- update: async (table, data, where, options) => {
603
- return this.update(table, data, where, options);
604
- },
605
- delete: async (table, where, _options) => {
606
- return this.delete(table, where);
607
- },
608
- upsert: async (table, data, options) => {
609
- return this.upsert(table, data, options);
610
- },
611
- savepoint: async (name) => {
612
- await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
613
- },
614
- rollbackToSavepoint: async (name) => {
615
- await client.query(
616
- `ROLLBACK TO SAVEPOINT ${this.escapeIdentifier(name)}`
617
- );
618
- },
619
- releaseSavepoint: async (name) => {
620
- await client.query(`RELEASE SAVEPOINT ${this.escapeIdentifier(name)}`);
621
- }
622
- };
623
- }
624
- /**
625
- * Classifies a PostgreSQL error into a DatabaseError.
626
- *
627
- * @param error - Original error from pg
628
- * @param sql - SQL statement that caused the error (optional)
629
- * @returns DatabaseError with proper classification
630
- */
631
- classifyError(error, sql) {
632
- if (isDatabaseError(error)) return error;
633
- const pgError = error;
634
- const kind = pgError.code && PG_ERROR_CODES[pgError.code] || "unknown";
635
- let message = pgError.message ?? String(error);
636
- if (sql && kind === "query") {
637
- message = `Query failed: ${message}`;
638
- }
639
- return createDatabaseError({
640
- kind,
641
- message,
642
- code: pgError.code,
643
- constraint: pgError.constraint,
644
- table: pgError.table,
645
- column: pgError.column,
646
- detail: pgError.detail,
647
- hint: pgError.hint,
648
- cause: error instanceof Error ? error : void 0
649
- });
650
- }
651
- /**
652
- * Override handleQueryError to use PostgreSQL-specific classification.
653
- */
654
- handleQueryError(error, operation, table) {
655
- const dbError = this.classifyError(error);
656
- if (!dbError.message.includes(operation)) {
657
- dbError.message = `${operation} operation failed on table '${table}': ${dbError.message}`;
658
- }
659
- if (!dbError.table) {
660
- dbError.table = table;
661
- }
662
- return dbError;
663
- }
295
+ drizzleByRelations = /* @__PURE__ */ new WeakMap();
296
+ drizzleBare;
297
+ /**
298
+ * The database dialect - always 'postgresql' for this adapter.
299
+ */
300
+ dialect = "postgresql";
301
+ /**
302
+ * Adapter configuration.
303
+ */
304
+ config;
305
+ /**
306
+ * Connection pool instance.
307
+ */
308
+ pool = null;
309
+ /**
310
+ * Connection state flag.
311
+ */
312
+ connected = false;
313
+ /**
314
+ * Auto-detected provider (Neon, Supabase, or standard).
315
+ * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
316
+ */
317
+ detectedProvider = "standard";
318
+ /**
319
+ * Provider-specific connection defaults. Applied as fallbacks when
320
+ * user config doesn't specify a value.
321
+ */
322
+ providerDefaults = getProviderDefaults("standard");
323
+ /**
324
+ * Creates a new PostgreSQL adapter instance.
325
+ *
326
+ * @param config - Adapter configuration
327
+ */
328
+ constructor(config) {
329
+ super();
330
+ this.config = config;
331
+ }
332
+ /**
333
+ * Establishes a connection to the PostgreSQL database.
334
+ *
335
+ * @remarks
336
+ * This method initializes the connection pool and verifies connectivity
337
+ * by executing a simple query. It is idempotent - calling it multiple
338
+ * times will not create multiple pools.
339
+ *
340
+ * @throws {DatabaseError} If connection fails
341
+ */
342
+ async connect() {
343
+ applyHappyEyeballsTimeoutOnce();
344
+ if (this.connected && this.pool) return;
345
+ const url = this.config.url || "";
346
+ this.detectedProvider = detectPostgresProvider(url, process.env.DB_PROVIDER);
347
+ this.providerDefaults = getProviderDefaults(this.detectedProvider);
348
+ if (this.config.logger?.info) {
349
+ const source = process.env.DB_PROVIDER ? "(explicit)" : "(auto-detected)";
350
+ this.config.logger.info(`PostgreSQL provider: ${this.detectedProvider} ${source}`, {});
351
+ }
352
+ const retryableNodeCodes = /* @__PURE__ */ new Set([
353
+ "ETIMEDOUT",
354
+ "ECONNREFUSED",
355
+ "ECONNRESET",
356
+ "ENOTFOUND",
357
+ "EAI_AGAIN"
358
+ ]);
359
+ const maxAttempts = this.providerDefaults.retryAttempts;
360
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
361
+ const poolConfig = this.buildPoolConfig();
362
+ this.pool = reportPoolWaitTimeout(new Pool(poolConfig), poolConfig.connectionTimeoutMillis);
363
+ this.pool.on("error", (err) => {
364
+ if (this.config.logger?.error) this.config.logger.error(err, {
365
+ context: "pool_error",
366
+ message: "Unexpected error on idle client"
367
+ });
368
+ });
369
+ const client = await this.pool.connect();
370
+ try {
371
+ await client.query("SELECT 1");
372
+ if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
373
+ await checkDialectVersion(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
374
+ this.connected = true;
375
+ if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
376
+ host: this.config.host ?? "from URL",
377
+ database: this.config.database ?? "from URL"
378
+ });
379
+ return;
380
+ } finally {
381
+ client.release();
382
+ }
383
+ } catch (error) {
384
+ if (this.pool) {
385
+ await this.pool.end().catch(() => {});
386
+ this.pool = null;
387
+ }
388
+ const nodeError = error;
389
+ if (nodeError.code != null && retryableNodeCodes.has(nodeError.code) && attempt < maxAttempts) {
390
+ const waitMs = 1e3 * attempt;
391
+ const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;
392
+ if (this.config.logger?.warn) this.config.logger.warn(msg);
393
+ else console.warn(`[PostgresAdapter] ${msg}`);
394
+ await delay(waitMs);
395
+ continue;
396
+ }
397
+ throw this.classifyError(error);
398
+ }
399
+ }
400
+ /**
401
+ * Closes the database connection and releases all pool resources.
402
+ *
403
+ * @remarks
404
+ * This method is idempotent - calling it multiple times is safe.
405
+ * It waits for all checked-out clients to be returned before shutting down.
406
+ */
407
+ async disconnect() {
408
+ const pool = this.pool;
409
+ this.pool = null;
410
+ this.drizzleBare = void 0;
411
+ this.drizzleByRelations = /* @__PURE__ */ new WeakMap();
412
+ if (!pool) return;
413
+ try {
414
+ await pool.end();
415
+ if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection closed");
416
+ } finally {
417
+ this.connected = false;
418
+ }
419
+ }
420
+ /**
421
+ * Checks if the adapter is currently connected.
422
+ *
423
+ * @returns True if connected and pool is available
424
+ */
425
+ isConnected() {
426
+ return this.connected && this.pool !== null;
427
+ }
428
+ /**
429
+ * Executes a raw SQL query.
430
+ *
431
+ * @param sql - SQL statement with $1, $2, ... placeholders
432
+ * @param params - Query parameters
433
+ * @returns Array of result rows
434
+ *
435
+ * @throws {DatabaseError} If query execution fails
436
+ */
437
+ async executeQuery(sql, params = []) {
438
+ const pool = this.ensurePool();
439
+ const startTime = Date.now();
440
+ const retryableNodeCodes = /* @__PURE__ */ new Set([
441
+ "ETIMEDOUT",
442
+ "ECONNRESET",
443
+ "ECONNREFUSED"
444
+ ]);
445
+ const maxQueryAttempts = 3;
446
+ for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) try {
447
+ this.notePoolAccess(sql);
448
+ const result = await pool.query(sql, params);
449
+ if (this.config.logger?.query) {
450
+ const durationMs = Date.now() - startTime;
451
+ this.config.logger.query(sql, params, durationMs);
452
+ }
453
+ return result.rows;
454
+ } catch (error) {
455
+ const nodeError = error;
456
+ if (nodeError.code != null && retryableNodeCodes.has(nodeError.code) && attempt < maxQueryAttempts) {
457
+ const waitMs = 500 * attempt;
458
+ console.warn(`[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`);
459
+ await delay(waitMs);
460
+ continue;
461
+ }
462
+ throw this.classifyError(error, sql);
463
+ }
464
+ throw this.classifyError(/* @__PURE__ */ new Error("executeQuery: exhausted retries"));
465
+ }
466
+ /**
467
+ * Executes a callback within a database transaction.
468
+ *
469
+ * @remarks
470
+ * PostgreSQL supports full ACID transactions with savepoints.
471
+ * If the callback throws, the transaction is rolled back.
472
+ *
473
+ * Supports automatic retry for serialization failures (40001) and
474
+ * deadlocks (40P01) when `retryCount` is specified in options.
475
+ *
476
+ * An error carrying the Nextly application brand is neither retried nor
477
+ * classified: it is the application refusing the write, so it arrives at the
478
+ * caller as it was thrown. Retrying it would repeat work whose verdict has
479
+ * already been given. Every other error, including an unbranded one raised by
480
+ * the callback, is retried when it is a serialization failure or deadlock and
481
+ * classified on the way out.
482
+ *
483
+ * @param callback - Function to execute within the transaction
484
+ * @param options - Transaction options (isolation level, timeout, retry)
485
+ * @returns The result of the callback
486
+ *
487
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
488
+ * or if the callback threw an error that does not carry the application brand
489
+ * @throws The callback's own error, unchanged, when it carries that brand
490
+ */
491
+ async transaction(callback, options) {
492
+ return this.runInFlowTransaction(() => this.runTransactionAttempts(callback, options));
493
+ }
494
+ /** The attempts `transaction` makes, each on a connection of its own. */
495
+ async runTransactionAttempts(callback, options) {
496
+ const pool = this.ensurePool();
497
+ const maxAttempts = (options?.retryCount ?? 0) + 1;
498
+ const retryDelayMs = options?.retryDelayMs ?? 100;
499
+ let lastError;
500
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
501
+ const client = await this.connectFlowTransaction(() => pool.connect());
502
+ const startTime = Date.now();
503
+ let discard;
504
+ try {
505
+ await this.beginTransaction(client, options);
506
+ const result = await callback(this.createTransactionContext(client));
507
+ if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw createDatabaseError({
508
+ kind: "query",
509
+ code: "25P02",
510
+ message: "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."
511
+ });
512
+ if (this.config.logger?.debug) {
513
+ const durationMs = Date.now() - startTime;
514
+ this.config.logger.debug("Transaction committed", {
515
+ attempt,
516
+ durationMs
517
+ });
518
+ }
519
+ return result;
520
+ } catch (error) {
521
+ await client.query("ROLLBACK").catch((rollbackError) => {
522
+ discard = rollbackError instanceof Error ? rollbackError : true;
523
+ });
524
+ lastError = error;
525
+ if (isApplicationError(error)) throw error;
526
+ const pgError = error;
527
+ if ((pgError.code === "40001" || pgError.code === "40P01") && attempt < maxAttempts) {
528
+ if (this.config.logger?.warn) this.config.logger.warn(`Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`, {
529
+ code: pgError.code,
530
+ attempt
531
+ });
532
+ await delay(retryDelayMs * attempt);
533
+ continue;
534
+ }
535
+ throw this.classifyError(error);
536
+ } finally {
537
+ client.release(discard);
538
+ }
539
+ }
540
+ throw this.classifyError(lastError);
541
+ }
542
+ /**
543
+ * Returns the database capabilities for PostgreSQL.
544
+ *
545
+ * @remarks
546
+ * PostgreSQL has the most comprehensive feature set of all supported
547
+ * databases, including JSONB, arrays, full-text search, and more.
548
+ */
549
+ getCapabilities() {
550
+ return {
551
+ dialect: "postgresql",
552
+ supportsJsonb: true,
553
+ supportsJson: true,
554
+ supportsArrays: true,
555
+ supportsGeneratedColumns: true,
556
+ supportsFts: true,
557
+ supportsIlike: true,
558
+ supportsReturning: true,
559
+ supportsSavepoints: true,
560
+ supportsOnConflict: true,
561
+ maxParamsPerQuery: 65535,
562
+ maxIdentifierLength: 63
563
+ };
564
+ }
565
+ /**
566
+ * The schema set as `search_path` on every pooled connection.
567
+ *
568
+ * @remarks
569
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
570
+ * reports `undefined` exactly as it sets no `search_path`: the value
571
+ * reported is the one the connections actually use.
572
+ *
573
+ * @returns The configured schema, or `undefined` when the server's default
574
+ * `search_path` applies
575
+ */
576
+ getConfiguredSchema() {
577
+ return this.config.schema ? this.config.schema : void 0;
578
+ }
579
+ /**
580
+ * Returns connection pool statistics.
581
+ *
582
+ * @returns Pool stats or null if not connected
583
+ */
584
+ getPoolStats() {
585
+ if (!this.pool) return null;
586
+ return {
587
+ total: this.pool.totalCount,
588
+ idle: this.pool.idleCount,
589
+ waiting: this.pool.waitingCount,
590
+ active: this.pool.totalCount - this.pool.idleCount
591
+ };
592
+ }
593
+ /**
594
+ * Override insertMany for bulk insert optimization.
595
+ *
596
+ * @remarks
597
+ * Uses a single multi-row INSERT statement for better performance
598
+ * when inserting multiple records.
599
+ */
600
+ async insertMany(table, data, options) {
601
+ if (data.length === 0) return [];
602
+ if (data.length === 1) return [await this.insert(table, data[0], options)];
603
+ const columns = Object.keys(data[0]);
604
+ const params = [];
605
+ const valuesClauses = [];
606
+ for (let i = 0; i < data.length; i++) {
607
+ const record = data[i];
608
+ const placeholders = [];
609
+ for (const col of columns) {
610
+ params.push(record[col]);
611
+ placeholders.push(`$${params.length}`);
612
+ }
613
+ valuesClauses.push(`(${placeholders.join(", ")})`);
614
+ }
615
+ const columnList = columns.map((col) => this.escapeIdentifier(col)).join(", ");
616
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(", ")}`;
617
+ if (options?.returning) {
618
+ const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
619
+ sql += ` RETURNING ${returning}`;
620
+ }
621
+ try {
622
+ return await this.executeQuery(sql, params);
623
+ } catch (error) {
624
+ throw this.handleQueryError(error, "insertMany", table);
625
+ }
626
+ }
627
+ /**
628
+ * Ensures pool is connected and returns it.
629
+ *
630
+ * @throws {DatabaseError} If not connected
631
+ */
632
+ ensurePool() {
633
+ if (!this.pool) throw createDatabaseError({
634
+ kind: "connection",
635
+ message: "PostgresAdapter is not connected. Call connect() first."
636
+ });
637
+ return this.pool;
638
+ }
639
+ /**
640
+ * Return the typed Drizzle instance for PostgreSQL.
641
+ * Guarded for server-only usage and requires an active connection.
642
+ *
643
+ * @param schema - Optional schema for relational queries (db.query.*)
644
+ * @returns Drizzle ORM instance wrapping the pg pool connection
645
+ * @throws {Error} If called in browser or not connected
646
+ */
647
+ getDrizzle(relations) {
648
+ if (typeof window !== "undefined") throw new Error("getDrizzle() is server-only");
649
+ const pool = this.ensurePool();
650
+ if (!relations) {
651
+ this.drizzleBare ??= this.poolDrizzle(pool);
652
+ return this.drizzleBare;
653
+ }
654
+ let cached = this.drizzleByRelations.get(relations);
655
+ if (!cached) {
656
+ cached = this.poolDrizzle(pool, relations);
657
+ this.drizzleByRelations.set(relations, cached);
658
+ }
659
+ return cached;
660
+ }
661
+ /**
662
+ * A Drizzle handle on the pool, for `getDrizzle`.
663
+ *
664
+ * Its `transaction` runs on a client this adapter checks out and returns
665
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
666
+ * released with `true`, which is what happens when no ROLLBACK could be
667
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
668
+ * adapter's does.
669
+ */
670
+ poolDrizzle(pool, relations) {
671
+ const onClient = (client) => relations ? drizzle({
672
+ client,
673
+ relations
674
+ }) : drizzle({ client });
675
+ const reported = this.observedPool(pool, ["query"]);
676
+ return this.trackFlowTransactions(this.pinDrizzleTransactions(onClient(reported), async () => {
677
+ const client = await this.connectFlowTransaction(() => pool.connect());
678
+ return {
679
+ drizzle: onClient(client),
680
+ rollback: () => client.query("ROLLBACK"),
681
+ release: (dirty) => client.release(dirty)
682
+ };
683
+ }));
684
+ }
685
+ /**
686
+ * Builds pg Pool configuration from adapter config.
687
+ */
688
+ buildPoolConfig() {
689
+ const config = {};
690
+ if (this.config.url) config.connectionString = this.config.url;
691
+ else {
692
+ if (this.config.host) config.host = this.config.host;
693
+ if (this.config.port) config.port = this.config.port;
694
+ if (this.config.database) config.database = this.config.database;
695
+ if (this.config.user) config.user = this.config.user;
696
+ if (this.config.password) config.password = this.config.password;
697
+ }
698
+ config.min = this.config.pool?.min ?? this.providerDefaults.poolMin ?? DEFAULT_POOL_CONFIG.min;
699
+ config.max = this.config.pool?.max ?? this.providerDefaults.poolMax ?? DEFAULT_POOL_CONFIG.max;
700
+ config.idleTimeoutMillis = this.config.pool?.idleTimeoutMs ?? this.providerDefaults.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;
701
+ config.connectionTimeoutMillis = this.config.pool?.connectionTimeoutMs ?? this.providerDefaults.connectionTimeoutMs ?? DEFAULT_POOL_CONFIG.connectionTimeoutMs;
702
+ config.keepAlive = true;
703
+ config.keepAliveInitialDelayMillis = 1e4;
704
+ if (this.config.ssl) {
705
+ if (typeof this.config.ssl === "boolean") config.ssl = this.config.ssl;
706
+ else {
707
+ if (this.config.ssl.rejectUnauthorized === false) console.warn("[nextly/adapter-postgres] ssl.rejectUnauthorized is set to false — TLS certificates will not be validated. This is unsafe on untrusted networks. Provide a trusted `ca` cert instead, or remove the rejectUnauthorized override.");
708
+ config.ssl = {
709
+ rejectUnauthorized: this.config.ssl.rejectUnauthorized,
710
+ ca: this.config.ssl.ca,
711
+ cert: this.config.ssl.cert,
712
+ key: this.config.ssl.key
713
+ };
714
+ }
715
+ } else if (this.providerDefaults.ssl) config.ssl = { rejectUnauthorized: true };
716
+ if (this.config.applicationName) config.application_name = this.config.applicationName;
717
+ if (this.config.schema) config.options = `-c search_path=${assertSchemaName(this.config.schema)}`;
718
+ const effectiveStatementTimeout = this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;
719
+ if (effectiveStatementTimeout !== void 0) config.statement_timeout = effectiveStatementTimeout;
720
+ if (this.config.queryTimeout) config.query_timeout = this.config.queryTimeout;
721
+ return config;
722
+ }
723
+ /**
724
+ * Begins a transaction with the specified options.
725
+ */
726
+ async beginTransaction(client, options) {
727
+ let beginSql = "BEGIN";
728
+ if (options?.isolationLevel) {
729
+ const level = {
730
+ "read uncommitted": "READ UNCOMMITTED",
731
+ "read committed": "READ COMMITTED",
732
+ "repeatable read": "REPEATABLE READ",
733
+ serializable: "SERIALIZABLE"
734
+ }[options.isolationLevel];
735
+ if (level) beginSql += ` ISOLATION LEVEL ${level}`;
736
+ }
737
+ if (options?.readOnly) beginSql += " READ ONLY";
738
+ await client.query(beginSql);
739
+ if (options?.timeoutMs) await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);
740
+ }
741
+ /**
742
+ * Creates a TransactionContext for the given client.
743
+ */
744
+ /**
745
+ * The RETURNING entries that spell each date column's wall clock out as
746
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
747
+ * stored value without a zone, which is the only form node-postgres cannot
748
+ * shift on the way back.
749
+ */
750
+ wallClockSpelling(aliases) {
751
+ return aliases.map((a) => `to_char(${this.escapeIdentifier(a.sqlName)}, '${PG_WALL_CLOCK_FORMAT}') AS ${this.escapeIdentifier(a.alias)}`).join(", ");
752
+ }
753
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
754
+ compositePrimaryKey(tableObj) {
755
+ return getTableConfig(tableObj).primaryKeys.flatMap((key) => key.columns);
756
+ }
757
+ createTransactionContext(client) {
758
+ const txHandles = this.transactionDrizzleHandles((relations) => relations ? drizzle({
759
+ client,
760
+ relations
761
+ }) : drizzle({ client }));
762
+ const txDb = txHandles.bare;
763
+ return {
764
+ drizzleWithRelations: txHandles.withRelations,
765
+ execute: async (sql, params = []) => {
766
+ return (await client.query(sql, params)).rows;
767
+ },
768
+ runStatement: async (statement) => {
769
+ await txDb().execute(statement);
770
+ },
771
+ queryStatement: async (statement) => {
772
+ return (await txDb().execute(statement)).rows;
773
+ },
774
+ lockRow: async (table, id) => {
775
+ const idColumn = this.escapeIdentifier("id");
776
+ await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
777
+ },
778
+ insert: async (table, data, options) => {
779
+ const mapped = this.mapRowToRawSql(this.getTableObject(table), data);
780
+ const columns = Object.keys(mapped);
781
+ const values = Object.values(mapped);
782
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
783
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
784
+ const ret = options?.returning;
785
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
786
+ const tableObj = this.getTableObject(table);
787
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
788
+ if (!returningEmpty) {
789
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
790
+ const spelled = this.wallClockSpelling(aliases);
791
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
792
+ }
793
+ const result = await client.query(sql, values);
794
+ return this.mapRowFromRawSql(tableObj, result.rows[0], aliases);
795
+ },
796
+ insertMany: async (table, data, options) => {
797
+ if (data.length === 0) return [];
798
+ const tableObj = this.getTableObject(table);
799
+ const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
800
+ const columns = Object.keys(mappedRecords[0]);
801
+ const params = [];
802
+ const valuesClauses = [];
803
+ for (const record of mappedRecords) {
804
+ const placeholders = [];
805
+ for (const col of columns) {
806
+ params.push(record[col]);
807
+ placeholders.push(`$${params.length}`);
808
+ }
809
+ valuesClauses.push(`(${placeholders.join(", ")})`);
810
+ }
811
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
812
+ const ret = options?.returning;
813
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
814
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
815
+ if (!returningEmpty) {
816
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
817
+ const spelled = this.wallClockSpelling(aliases);
818
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
819
+ }
820
+ return (await client.query(sql, params)).rows.map((r) => this.mapRowFromRawSql(tableObj, r, aliases));
821
+ },
822
+ update: this.transactionUpdate(txDb, async (statement) => (await txDb().execute(statement)).rows, (value) => this.bindUnmodeledStructuredAsJson(value)),
823
+ ...this.createTransactionForwarders(txDb),
824
+ savepoint: async (name) => {
825
+ await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
826
+ },
827
+ rollbackToSavepoint: async (name) => {
828
+ await client.query(`ROLLBACK TO SAVEPOINT ${this.escapeIdentifier(name)}`);
829
+ },
830
+ releaseSavepoint: async (name) => {
831
+ await client.query(`RELEASE SAVEPOINT ${this.escapeIdentifier(name)}`);
832
+ }
833
+ };
834
+ }
835
+ /**
836
+ * Classifies a PostgreSQL error into a DatabaseError.
837
+ *
838
+ * @param error - Original error from pg
839
+ * @param sql - SQL statement that caused the error (optional)
840
+ * @returns DatabaseError with proper classification
841
+ */
842
+ classifyError(error, sql) {
843
+ if (isDatabaseError(error)) return error;
844
+ const pgError = this.driverErrorIn(error, (candidate) => typeof candidate.code === "string" && candidate.code !== "");
845
+ const kind = pgError.code && PG_ERROR_CODES[pgError.code] || "unknown";
846
+ let message = pgError.message ?? String(error);
847
+ if (sql && kind === "query") message = `Query failed: ${message}`;
848
+ return createDatabaseError({
849
+ kind,
850
+ message,
851
+ code: pgError.code,
852
+ constraint: pgError.constraint,
853
+ table: pgError.table,
854
+ column: pgError.column,
855
+ detail: pgError.detail,
856
+ hint: pgError.hint,
857
+ cause: error instanceof Error ? error : void 0
858
+ });
859
+ }
664
860
  };
861
+ /**
862
+ * Creates a PostgreSQL database adapter instance.
863
+ *
864
+ * @remarks
865
+ * This is the recommended way to create a PostgreSQL adapter.
866
+ * The adapter is not connected after creation - call `connect()` to
867
+ * establish the database connection.
868
+ *
869
+ * @param config - Adapter configuration
870
+ * @returns A new PostgresAdapter instance
871
+ *
872
+ * @example
873
+ * Simple usage:
874
+ * ```typescript
875
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
876
+ *
877
+ * const adapter = createPostgresAdapter({
878
+ * url: process.env.DATABASE_URL!,
879
+ * });
880
+ *
881
+ * await adapter.connect();
882
+ * ```
883
+ *
884
+ * @example
885
+ * With full configuration:
886
+ * ```typescript
887
+ * const adapter = createPostgresAdapter({
888
+ * url: process.env.DATABASE_URL!,
889
+ * pool: {
890
+ * min: 5,
891
+ * max: 20,
892
+ * idleTimeoutMs: 30000,
893
+ * connectionTimeoutMs: 10000,
894
+ * },
895
+ * ssl: {
896
+ * rejectUnauthorized: true,
897
+ * ca: process.env.CA_CERT,
898
+ * },
899
+ * applicationName: 'my-app',
900
+ * statementTimeout: 30000,
901
+ * });
902
+ * ```
903
+ *
904
+ * @public
905
+ */
665
906
  function createPostgresAdapter(config) {
666
- return new PostgresAdapter(config);
907
+ return new PostgresAdapter(config);
667
908
  }
909
+ /**
910
+ * Type guard to check if a value is a PostgresAdapter instance.
911
+ *
912
+ * @param value - Value to check
913
+ * @returns True if value is a PostgresAdapter
914
+ *
915
+ * @example
916
+ * ```typescript
917
+ * import { isPostgresAdapter } from '@nextlyhq/adapter-postgres';
918
+ *
919
+ * if (isPostgresAdapter(adapter)) {
920
+ * // TypeScript knows adapter is PostgresAdapter
921
+ * console.log(adapter.dialect); // 'postgresql'
922
+ * }
923
+ * ```
924
+ *
925
+ * @public
926
+ */
668
927
  function isPostgresAdapter(value) {
669
- return value instanceof PostgresAdapter;
928
+ return value instanceof PostgresAdapter;
670
929
  }
671
-
672
930
  export { PostgresAdapter, VERSION, createPostgresAdapter, isPostgresAdapter };
673
- //# sourceMappingURL=index.mjs.map
931
+
674
932
  //# sourceMappingURL=index.mjs.map