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