@nextlyhq/adapter-postgres 0.0.2-alpha.68 → 0.0.2-alpha.69

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