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

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,692 +1,1175 @@
1
- import * as net from 'net';
2
- import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
3
- import { createDatabaseError, isDatabaseError } from '@nextlyhq/adapter-drizzle/types';
4
- import { checkDialectVersion } from '@nextlyhq/adapter-drizzle/version-check';
5
- import { drizzle } from 'drizzle-orm/node-postgres';
6
- import { Pool } from 'pg';
7
-
8
- // src/index.ts
9
-
1
+ import * as net from "node:net";
2
+ import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
3
+ import { isNextBuildPhase } from "@nextlyhq/adapter-drizzle/build-phase";
4
+ import { assertSchemaName } from "@nextlyhq/adapter-drizzle/schema-name";
5
+ import { SERVERLESS_POOL_DEFAULTS, isVercelFunction, loadVercelPoolAttacher } from "@nextlyhq/adapter-drizzle/serverless";
6
+ import { createDatabaseError, isDatabaseError, poolWaitTimeoutError } from "@nextlyhq/adapter-drizzle/types";
7
+ import { checkDialectVersion } from "@nextlyhq/adapter-drizzle/version-check";
8
+ import { drizzle } from "drizzle-orm/node-postgres";
9
+ import { getTableConfig, pgTable, timestamp } from "drizzle-orm/pg-core";
10
+ import { Pool } from "pg";
11
+ // src/pool-wait.ts
12
+ /**
13
+ * The bounded wait for a pooled connection, reported as the adapters' own
14
+ * "pool wait timeout" error.
15
+ *
16
+ * pg-pool already bounds the wait: a request that finds every connection in
17
+ * use waits at most `connectionTimeoutMillis`, then is removed from the queue
18
+ * and fails. It fails with a plain `Error` that has no code, though, so
19
+ * nothing downstream could tell it from any other driver failure, and a
20
+ * caller got an internal error for a database that was only busy. This gives
21
+ * that one failure the code core answers with "database busy".
22
+ *
23
+ * Only the wait for a connection already in the pool: a new connection that
24
+ * cannot be opened in time is pg-pool's other timeout ("Connection terminated
25
+ * due to connection timeout"), a database that cannot be reached rather than
26
+ * one that is busy, and stays as it was.
27
+ */
28
+ /**
29
+ * pg-pool's message for a request that waited its bound in the queue. The
30
+ * error carries nothing else to recognise it by; the pool-wait integration
31
+ * test runs against the installed pg-pool, so a reworded message fails there.
32
+ */
33
+ const QUEUE_WAIT_TIMEOUT_MESSAGE = "timeout exceeded when trying to connect";
34
+ /** The error a caller should see for one pg-pool raised. */
35
+ function translated(error, boundMs) {
36
+ if (error.message === QUEUE_WAIT_TIMEOUT_MESSAGE) return poolWaitTimeoutError(boundMs, error);
37
+ return error;
38
+ }
39
+ /**
40
+ * Makes `pool` report a request that waited past `boundMs` for a connection
41
+ * with the pool-wait timeout error, and returns it. `boundMs` is the pool's
42
+ * own `connectionTimeoutMillis`, unset when the pool has none.
43
+ *
44
+ * Replaces the pool's own `connect`, which its `query` also goes through, so
45
+ * every path to a connection reports the same way: the adapter's statements,
46
+ * its transactions, and the Drizzle handle core services query through.
47
+ */
48
+ function reportPoolWaitTimeout(pool, boundMs) {
49
+ const bound = boundMs ?? 0;
50
+ const connect = pool.connect.bind(pool);
51
+ const bounded = (callback) => {
52
+ if (callback) return connect((err, client, done) => callback(err && translated(err, bound), client, done));
53
+ return connect().catch((error) => {
54
+ throw translated(error, bound);
55
+ });
56
+ };
57
+ pool.connect = bounded;
58
+ return pool;
59
+ }
10
60
  // src/provider.ts
11
61
  function detectPostgresProvider(url, explicitProvider) {
12
- if (explicitProvider) {
13
- const normalized = explicitProvider.toLowerCase();
14
- if (normalized === "neon" || normalized === "supabase" || normalized === "standard") {
15
- return normalized;
16
- }
17
- }
18
- if (url.includes(".neon.tech") || url.includes("neon.")) {
19
- return "neon";
20
- }
21
- if (url.includes(".supabase.") || url.includes("supabase.")) {
22
- return "supabase";
23
- }
24
- return "standard";
62
+ if (explicitProvider) {
63
+ const normalized = explicitProvider.toLowerCase();
64
+ if (normalized === "neon" || normalized === "supabase" || normalized === "standard") return normalized;
65
+ }
66
+ if (url.includes(".neon.tech") || url.includes("neon.")) return "neon";
67
+ if (url.includes(".supabase.") || url.includes("supabase.")) return "supabase";
68
+ return "standard";
25
69
  }
26
- function getProviderDefaults(provider) {
27
- switch (provider) {
28
- case "neon":
29
- return {
30
- ssl: true,
31
- poolMax: 5,
32
- poolMin: 0,
33
- idleTimeoutMs: 1e4,
34
- connectionTimeoutMs: 2e4,
35
- statementTimeoutMs: 3e4,
36
- retryAttempts: 5
37
- };
38
- case "supabase":
39
- return {
40
- ssl: true,
41
- poolMax: 5,
42
- poolMin: 0,
43
- idleTimeoutMs: 3e4,
44
- connectionTimeoutMs: 15e3,
45
- statementTimeoutMs: 15e3,
46
- retryAttempts: 3
47
- };
48
- case "standard":
49
- default:
50
- return {
51
- ssl: false,
52
- poolMax: 10,
53
- poolMin: 0,
54
- idleTimeoutMs: 3e4,
55
- connectionTimeoutMs: 15e3,
56
- statementTimeoutMs: 15e3,
57
- retryAttempts: 3
58
- };
59
- }
70
+ function getProviderDefaults(provider, options = {}) {
71
+ const defaults = providerOwnDefaults(provider);
72
+ if (!options.serverless) return defaults;
73
+ return {
74
+ ...defaults,
75
+ poolMax: SERVERLESS_POOL_DEFAULTS.max,
76
+ poolMin: SERVERLESS_POOL_DEFAULTS.min,
77
+ idleTimeoutMs: SERVERLESS_POOL_DEFAULTS.idleTimeoutMs
78
+ };
79
+ }
80
+ function providerOwnDefaults(provider) {
81
+ switch (provider) {
82
+ case "neon": return {
83
+ ssl: true,
84
+ poolMax: 5,
85
+ poolMin: 0,
86
+ idleTimeoutMs: 1e4,
87
+ connectionTimeoutMs: 2e4,
88
+ statementTimeoutMs: 3e4,
89
+ retryAttempts: 5
90
+ };
91
+ case "supabase": return {
92
+ ssl: true,
93
+ poolMax: 5,
94
+ poolMin: 0,
95
+ idleTimeoutMs: 3e4,
96
+ connectionTimeoutMs: 15e3,
97
+ statementTimeoutMs: 15e3,
98
+ retryAttempts: 3
99
+ };
100
+ default: return {
101
+ ssl: false,
102
+ poolMax: 10,
103
+ poolMin: 0,
104
+ idleTimeoutMs: 3e4,
105
+ connectionTimeoutMs: 15e3,
106
+ statementTimeoutMs: 15e3,
107
+ retryAttempts: 3
108
+ };
109
+ }
60
110
  }
61
-
62
111
  // src/index.ts
63
- var VERSION = "0.1.0";
64
- var DEFAULT_POOL_CONFIG = {
65
- min: 0,
66
- max: 5,
67
- idleTimeoutMs: 3e4,
68
- connectionTimeoutMs: 15e3
112
+ /**
113
+ * @nextlyhq/adapter-postgres
114
+ *
115
+ * PostgreSQL database adapter for Nextly.
116
+ * Extends the base DrizzleAdapter from @nextlyhq/adapter-drizzle to provide
117
+ * PostgreSQL-specific functionality.
118
+ *
119
+ * @remarks
120
+ * This adapter uses the `pg` (node-postgres) driver for database connections
121
+ * and integrates with Drizzle ORM for type-safe queries.
122
+ *
123
+ * Features:
124
+ * - Connection pooling via pg.Pool
125
+ * - Full transaction support with savepoints
126
+ * - RETURNING clause support for all CRUD operations
127
+ * - PostgreSQL-specific error classification
128
+ * - JSONB support
129
+ * - Full-text search capabilities
130
+ * - Automatic retry for serialization failures and deadlocks
131
+ *
132
+ * @example
133
+ * Simple usage with connection string:
134
+ * ```typescript
135
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
136
+ *
137
+ * const adapter = createPostgresAdapter({
138
+ * url: process.env.DATABASE_URL!,
139
+ * });
140
+ *
141
+ * await adapter.connect();
142
+ * ```
143
+ *
144
+ * @example
145
+ * Full configuration:
146
+ * ```typescript
147
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
148
+ *
149
+ * const adapter = createPostgresAdapter({
150
+ * url: process.env.DATABASE_URL!,
151
+ * pool: {
152
+ * min: 2,
153
+ * max: 20,
154
+ * idleTimeoutMs: 30000,
155
+ * },
156
+ * ssl: {
157
+ * rejectUnauthorized: true,
158
+ * },
159
+ * applicationName: 'my-nextly-app',
160
+ * });
161
+ * ```
162
+ *
163
+ * @example
164
+ * Using the adapter class directly:
165
+ * ```typescript
166
+ * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';
167
+ * import type { PostgresAdapterConfig } from '@nextlyhq/adapter-postgres';
168
+ *
169
+ * const config: PostgresAdapterConfig = {
170
+ * url: process.env.DATABASE_URL!,
171
+ * };
172
+ *
173
+ * const adapter = new PostgresAdapter(config);
174
+ * await adapter.connect();
175
+ * ```
176
+ *
177
+ * @packageDocumentation
178
+ */
179
+ /**
180
+ * A date field's column as the schema generator declares it on PostgreSQL:
181
+ * `timestamp`, without a time zone. Its encoder writes the UTC wall clock,
182
+ * which is what a `Date` bound to an undeclared key is spelled as.
183
+ */
184
+ const DATE_FIELD_COLUMN = pgTable("nextly_date_field", { at: timestamp("at") }).at;
185
+ /**
186
+ * Package version.
187
+ */
188
+ const VERSION = "0.1.0";
189
+ /**
190
+ * Default pool configuration values.
191
+ *
192
+ * min: 0 – Never eagerly create background connections. This is critical
193
+ * for cold-start recovery (e.g. Neon auto-suspend): after the
194
+ * initial smoke-test connection, the pool won't immediately try
195
+ * to create additional connections that might still fail while
196
+ * the DB is waking up.
197
+ *
198
+ * max: 5 – Conservative default to avoid overwhelming cloud databases
199
+ * (Neon free-tier limit is ~25-30 simultaneous connections).
200
+ * With Next.js spawning up to 7 build workers this keeps the
201
+ * total connection count safely under typical limits.
202
+ */
203
+ const DEFAULT_POOL_CONFIG = {
204
+ min: 0,
205
+ max: 5,
206
+ idleTimeoutMs: 3e4,
207
+ connectionTimeoutMs: 15e3
69
208
  };
70
- var PG_ERROR_CODES = {
71
- // Class 08 - Connection Exception
72
- "08000": "connection",
73
- "08003": "connection",
74
- "08006": "connection",
75
- "08001": "connection",
76
- "08004": "connection",
77
- "08007": "connection",
78
- "08P01": "connection",
79
- // Class 23 - Integrity Constraint Violation
80
- "23000": "constraint",
81
- "23001": "constraint",
82
- "23502": "not_null_violation",
83
- "23503": "foreign_key_violation",
84
- "23505": "unique_violation",
85
- "23514": "check_violation",
86
- "23P01": "constraint",
87
- // Class 40 - Transaction Rollback
88
- "40000": "query",
89
- "40001": "serialization_failure",
90
- "40002": "constraint",
91
- "40003": "query",
92
- "40P01": "deadlock",
93
- // Class 57 - Operator Intervention
94
- "57014": "timeout",
95
- "57P01": "connection",
96
- "57P02": "connection",
97
- "57P03": "connection"
209
+ /**
210
+ * PostgreSQL error codes mapping to DatabaseErrorKind.
211
+ *
212
+ * @see https://www.postgresql.org/docs/current/errcodes-appendix.html
213
+ */
214
+ const PG_ERROR_CODES = {
215
+ "08000": "connection",
216
+ "08003": "connection",
217
+ "08006": "connection",
218
+ "08001": "connection",
219
+ "08004": "connection",
220
+ "08007": "connection",
221
+ "08P01": "connection",
222
+ "23000": "constraint",
223
+ "23001": "constraint",
224
+ "23502": "not_null_violation",
225
+ "23503": "foreign_key_violation",
226
+ "23505": "unique_violation",
227
+ "23514": "check_violation",
228
+ "23P01": "constraint",
229
+ "40000": "query",
230
+ "40001": "serialization_failure",
231
+ "40002": "constraint",
232
+ "40003": "query",
233
+ "40P01": "deadlock",
234
+ "53300": "connection",
235
+ "57014": "timeout",
236
+ "57P01": "connection",
237
+ "57P02": "connection",
238
+ "57P03": "connection",
239
+ "57P05": "connection"
98
240
  };
241
+ /**
242
+ * Create the configured schema when the database does not have it yet.
243
+ *
244
+ * Looked up before it is created, because `CREATE SCHEMA IF NOT EXISTS` is not
245
+ * a no-op for a schema that exists: PostgreSQL checks the database-level
246
+ * `CREATE` privilege before it checks for the schema, so a role that may use
247
+ * and create objects in `public` but may not create schemas would fail to
248
+ * connect over a schema that is already there. Reading `pg_namespace` needs no
249
+ * privilege, so only a schema that is genuinely missing asks for one.
250
+ *
251
+ * Created inside a transaction holding an advisory lock on the schema's name,
252
+ * and looked up again once the lock is held. `IF NOT EXISTS` alone is not safe
253
+ * against itself: two processes connecting at the same moment can both pass its
254
+ * check, and the second to commit fails with a unique violation on
255
+ * `pg_namespace_nspname_index`, which fails its connect. The transaction-scoped
256
+ * lock makes the second wait for the first to commit, and its lookup, a new
257
+ * statement with a new snapshot, then finds the schema. The transaction is
258
+ * read committed whatever the database's or role's default: at repeatable
259
+ * read or serializable the snapshot is fixed by the first statement, the lock
260
+ * wait, so the lookup would miss the schema and the CREATE that followed would
261
+ * ask for the database privilege the first paragraph avoids. Released by the commit
262
+ * or rollback, so it never outlives this one connection's transaction, and a
263
+ * transaction-mode pooler keeps all of it on one server connection.
264
+ */
265
+ async function ensureSchemaExists(client, schema) {
266
+ const name = assertSchemaName(schema);
267
+ if (await schemaExists(client, name)) return;
268
+ await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
269
+ try {
270
+ await client.query("SELECT pg_advisory_xact_lock(hashtext('nextly:create-schema'), hashtext($1))", [name]);
271
+ if (!await schemaExists(client, name)) await client.query(`CREATE SCHEMA IF NOT EXISTS ${name}`);
272
+ await client.query("COMMIT");
273
+ } catch (error) {
274
+ await client.query("ROLLBACK").catch(() => {});
275
+ throw error;
276
+ }
277
+ }
278
+ /** PostgreSQL's code for a schema that does not exist. */
279
+ const INVALID_SCHEMA_NAME = "3F000";
280
+ /**
281
+ * Fails, without creating it, when the database has no schema of this name:
282
+ * a read-only connect must not change the database, and a `search_path` that
283
+ * names a missing schema would quietly fall through to `public`.
284
+ */
285
+ async function assertSchemaExists(client, schema, remedy) {
286
+ const name = assertSchemaName(schema);
287
+ if (await schemaExists(client, name)) return;
288
+ throw createDatabaseError({
289
+ kind: "connection",
290
+ message: remedy === void 0 ? `schema "${name}" does not exist` : `schema "${name}" does not exist. ${remedy}`,
291
+ code: INVALID_SCHEMA_NAME
292
+ });
293
+ }
294
+ /** Whether the database has a schema of this name. Needs no privilege. */
295
+ async function schemaExists(client, name) {
296
+ return (await client.query("SELECT 1 FROM pg_namespace WHERE nspname = $1", [name])).rows.length > 0;
297
+ }
298
+ /**
299
+ * The SQLSTATE an error carries: its own, or that of the driver error it
300
+ * wraps, as a Drizzle query error does.
301
+ */
302
+ function sqlStateOf(error) {
303
+ for (let at = error, hops = 0; hops < 4; hops++) {
304
+ if (typeof at !== "object" || at === null) return void 0;
305
+ const code = Reflect.get(at, "code");
306
+ if (typeof code === "string" && /^[0-9A-Z]{5}$/.test(code)) return code;
307
+ at = Reflect.get(at, "cause");
308
+ }
309
+ }
310
+ /**
311
+ * A serialization failure or a deadlock: the transaction lost a race, and
312
+ * running it again may succeed.
313
+ */
314
+ function isSerializationFailure(error) {
315
+ const code = sqlStateOf(error);
316
+ return code === "40001" || code === "40P01";
317
+ }
318
+ /**
319
+ * `@vercel/functions`' pool attaching, imported only on Vercel, at connect.
320
+ *
321
+ * An optional peer: an app outside Vercel never installs it, so the import is
322
+ * dynamic and its failure is a warning (`loadVercelPoolAttacher`), never a
323
+ * module that fails to load. The adapter is a server external package
324
+ * (`withNextly`'s `serverExternalPackages`), so Node resolves this at run time;
325
+ * the comments keep a bundler that bundles the adapter anyway from requiring
326
+ * the package at build time. The `db-connections` subpath loads the attaching
327
+ * alone, not the package's other helpers.
328
+ */
329
+ function loadVercelDbConnections() {
330
+ return import(
331
+ /* webpackIgnore: true */
332
+ /* turbopackIgnore: true */
333
+ "@vercel/functions/db-connections"
334
+ );
335
+ }
336
+ /**
337
+ * Delay helper for retry logic.
338
+ */
99
339
  function delay(ms) {
100
- return new Promise((resolve) => setTimeout(resolve, ms));
340
+ return new Promise((resolve) => setTimeout(resolve, ms));
101
341
  }
102
- var HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5e3;
103
- var happyEyeballsTimeoutApplied = false;
342
+ const HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5e3;
343
+ let happyEyeballsTimeoutApplied = false;
104
344
  function applyHappyEyeballsTimeoutOnce() {
105
- if (happyEyeballsTimeoutApplied) return;
106
- happyEyeballsTimeoutApplied = true;
107
- try {
108
- const current = typeof net.getDefaultAutoSelectFamilyAttemptTimeout === "function" ? net.getDefaultAutoSelectFamilyAttemptTimeout() : 0;
109
- if (current < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) {
110
- net.setDefaultAutoSelectFamilyAttemptTimeout(
111
- HAPPY_EYEBALLS_MIN_TIMEOUT_MS
112
- );
113
- }
114
- } catch {
115
- }
345
+ if (happyEyeballsTimeoutApplied) return;
346
+ happyEyeballsTimeoutApplied = true;
347
+ try {
348
+ if ((typeof net.getDefaultAutoSelectFamilyAttemptTimeout === "function" ? net.getDefaultAutoSelectFamilyAttemptTimeout() : 0) < HAPPY_EYEBALLS_MIN_TIMEOUT_MS) net.setDefaultAutoSelectFamilyAttemptTimeout(HAPPY_EYEBALLS_MIN_TIMEOUT_MS);
349
+ } catch {}
350
+ }
351
+ /**
352
+ * How a date column's wall clock is spelled out when a write reads its row
353
+ * back: the stored value to the millisecond, with no zone for the driver to
354
+ * shift.
355
+ */
356
+ const PG_WALL_CLOCK_FORMAT = "YYYY-MM-DD\"T\"HH24:MI:SS.MS";
357
+ /**
358
+ * The host a pooled client connected to, as node-postgres resolved it from its
359
+ * options, the connection string, `PGHOST` and its default; `undefined` when
360
+ * the client does not hold one.
361
+ */
362
+ function resolvedHost(client) {
363
+ return "host" in client && typeof client.host === "string" && client.host !== "" ? client.host : void 0;
116
364
  }
365
+ /**
366
+ * PostgreSQL database adapter for Nextly.
367
+ *
368
+ * @remarks
369
+ * This class extends the base DrizzleAdapter to provide PostgreSQL-specific
370
+ * functionality including:
371
+ *
372
+ * - Connection pooling with pg.Pool
373
+ * - Transaction support with savepoints
374
+ * - PostgreSQL-specific error codes
375
+ * - JSONB and array type support
376
+ * - Full-text search
377
+ * - Automatic retry for serialization failures and deadlocks
378
+ *
379
+ * For most use cases, use the `createPostgresAdapter` factory function
380
+ * instead of instantiating this class directly.
381
+ *
382
+ * @example
383
+ * ```typescript
384
+ * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';
385
+ *
386
+ * const adapter = new PostgresAdapter({
387
+ * url: 'postgres://user:pass@localhost:5432/mydb',
388
+ * });
389
+ *
390
+ * await adapter.connect();
391
+ *
392
+ * // Use the adapter
393
+ * const users = await adapter.select('users', {
394
+ * where: { and: [{ column: 'status', op: '=', value: 'active' }] },
395
+ * });
396
+ *
397
+ * await adapter.disconnect();
398
+ * ```
399
+ *
400
+ * @public
401
+ */
117
402
  var PostgresAdapter = class extends DrizzleAdapter {
118
- /**
119
- * The database dialect - always 'postgresql' for this adapter.
120
- */
121
- dialect = "postgresql";
122
- /**
123
- * Adapter configuration.
124
- */
125
- config;
126
- /**
127
- * Connection pool instance.
128
- */
129
- pool = null;
130
- /**
131
- * Connection state flag.
132
- */
133
- connected = false;
134
- /**
135
- * Auto-detected provider (Neon, Supabase, or standard).
136
- * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
137
- */
138
- detectedProvider = "standard";
139
- /**
140
- * Provider-specific connection defaults. Applied as fallbacks when
141
- * user config doesn't specify a value.
142
- */
143
- providerDefaults = getProviderDefaults("standard");
144
- /**
145
- * Creates a new PostgreSQL adapter instance.
146
- *
147
- * @param config - Adapter configuration
148
- */
149
- constructor(config) {
150
- super();
151
- this.config = config;
152
- }
153
- /**
154
- * Establishes a connection to the PostgreSQL database.
155
- *
156
- * @remarks
157
- * This method initializes the connection pool and verifies connectivity
158
- * by executing a simple query. It is idempotent - calling it multiple
159
- * times will not create multiple pools.
160
- *
161
- * @throws {DatabaseError} If connection fails
162
- */
163
- async connect() {
164
- applyHappyEyeballsTimeoutOnce();
165
- if (this.connected && this.pool) {
166
- return;
167
- }
168
- const url = this.config.url || "";
169
- this.detectedProvider = detectPostgresProvider(
170
- url,
171
- process.env.DB_PROVIDER
172
- );
173
- this.providerDefaults = getProviderDefaults(this.detectedProvider);
174
- if (this.config.logger?.info) {
175
- const source = process.env.DB_PROVIDER ? "(explicit)" : "(auto-detected)";
176
- this.config.logger.info(
177
- `PostgreSQL provider: ${this.detectedProvider} ${source}`,
178
- {}
179
- );
180
- }
181
- const retryableNodeCodes = /* @__PURE__ */ new Set([
182
- "ETIMEDOUT",
183
- "ECONNREFUSED",
184
- "ECONNRESET",
185
- "ENOTFOUND",
186
- "EAI_AGAIN"
187
- ]);
188
- const maxAttempts = this.providerDefaults.retryAttempts;
189
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
190
- try {
191
- const poolConfig = this.buildPoolConfig();
192
- this.pool = new Pool(poolConfig);
193
- this.pool.on("error", (err) => {
194
- if (this.config.logger?.error) {
195
- this.config.logger.error(err, {
196
- context: "pool_error",
197
- message: "Unexpected error on idle client"
198
- });
199
- }
200
- });
201
- const client = await this.pool.connect();
202
- try {
203
- await client.query("SELECT 1");
204
- await checkDialectVersion(client, "postgresql", {
205
- // Why: route any future variant warnings through the adapter's
206
- // logger. PG has no recognized variants today, but this keeps
207
- // the integration symmetric with MySQL.
208
- onWarning: (msg) => this.config.logger?.warn?.(msg)
209
- });
210
- this.connected = true;
211
- if (this.config.logger?.info) {
212
- this.config.logger.info("PostgreSQL connection established", {
213
- host: this.config.host ?? "from URL",
214
- database: this.config.database ?? "from URL"
215
- });
216
- }
217
- return;
218
- } finally {
219
- client.release();
220
- }
221
- } catch (error) {
222
- if (this.pool) {
223
- await this.pool.end().catch(() => {
224
- });
225
- this.pool = null;
226
- }
227
- const nodeError = error;
228
- const isRetryable = nodeError.code != null && retryableNodeCodes.has(nodeError.code);
229
- if (isRetryable && attempt < maxAttempts) {
230
- const waitMs = 1e3 * attempt;
231
- const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;
232
- if (this.config.logger?.warn) {
233
- this.config.logger.warn(msg);
234
- } else {
235
- console.warn(`[PostgresAdapter] ${msg}`);
236
- }
237
- await delay(waitMs);
238
- continue;
239
- }
240
- throw this.classifyError(error);
241
- }
242
- }
243
- }
244
- /**
245
- * Closes the database connection and releases all pool resources.
246
- *
247
- * @remarks
248
- * This method is idempotent - calling it multiple times is safe.
249
- * It waits for all checked-out clients to be returned before shutting down.
250
- */
251
- async disconnect() {
252
- if (!this.pool) {
253
- return;
254
- }
255
- try {
256
- await this.pool.end();
257
- if (this.config.logger?.info) {
258
- this.config.logger.info("PostgreSQL connection closed");
259
- }
260
- } finally {
261
- this.pool = null;
262
- this.connected = false;
263
- }
264
- }
265
- /**
266
- * Checks if the adapter is currently connected.
267
- *
268
- * @returns True if connected and pool is available
269
- */
270
- isConnected() {
271
- return this.connected && this.pool !== null;
272
- }
273
- /**
274
- * Executes a raw SQL query.
275
- *
276
- * @param sql - SQL statement with $1, $2, ... placeholders
277
- * @param params - Query parameters
278
- * @returns Array of result rows
279
- *
280
- * @throws {DatabaseError} If query execution fails
281
- */
282
- async executeQuery(sql, params = []) {
283
- const pool = this.ensurePool();
284
- const startTime = Date.now();
285
- const retryableNodeCodes = /* @__PURE__ */ new Set([
286
- "ETIMEDOUT",
287
- "ECONNRESET",
288
- "ECONNREFUSED"
289
- ]);
290
- const maxQueryAttempts = 3;
291
- for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) {
292
- try {
293
- const result = await pool.query(sql, params);
294
- if (this.config.logger?.query) {
295
- const durationMs = Date.now() - startTime;
296
- this.config.logger.query(sql, params, durationMs);
297
- }
298
- return result.rows;
299
- } catch (error) {
300
- const nodeError = error;
301
- const isRetryable = nodeError.code != null && retryableNodeCodes.has(nodeError.code);
302
- if (isRetryable && attempt < maxQueryAttempts) {
303
- const waitMs = 500 * attempt;
304
- console.warn(
305
- `[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`
306
- );
307
- await delay(waitMs);
308
- continue;
309
- }
310
- throw this.classifyError(error, sql);
311
- }
312
- }
313
- throw this.classifyError(new Error("executeQuery: exhausted retries"));
314
- }
315
- /**
316
- * Executes a callback within a database transaction.
317
- *
318
- * @remarks
319
- * PostgreSQL supports full ACID transactions with savepoints.
320
- * If the callback throws, the transaction is rolled back.
321
- *
322
- * Supports automatic retry for serialization failures (40001) and
323
- * deadlocks (40P01) when `retryCount` is specified in options.
324
- *
325
- * @param callback - Function to execute within the transaction
326
- * @param options - Transaction options (isolation level, timeout, retry)
327
- * @returns The result of the callback
328
- *
329
- * @throws {DatabaseError} If transaction fails after all retries
330
- */
331
- async transaction(callback, options) {
332
- const pool = this.ensurePool();
333
- const maxAttempts = (options?.retryCount ?? 0) + 1;
334
- const retryDelayMs = options?.retryDelayMs ?? 100;
335
- let lastError;
336
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
337
- const client = await pool.connect();
338
- const startTime = Date.now();
339
- try {
340
- await this.beginTransaction(client, options);
341
- const ctx = this.createTransactionContext(client);
342
- const result = await callback(ctx);
343
- await client.query("COMMIT");
344
- if (this.config.logger?.debug) {
345
- const durationMs = Date.now() - startTime;
346
- this.config.logger.debug("Transaction committed", {
347
- attempt,
348
- durationMs
349
- });
350
- }
351
- return result;
352
- } catch (error) {
353
- await client.query("ROLLBACK").catch(() => {
354
- });
355
- lastError = error;
356
- const pgError = error;
357
- const isRetryable = pgError.code === "40001" || // serialization_failure
358
- pgError.code === "40P01";
359
- if (isRetryable && attempt < maxAttempts) {
360
- if (this.config.logger?.warn) {
361
- this.config.logger.warn(
362
- `Transaction failed with ${pgError.code}, retrying (${attempt}/${maxAttempts})`,
363
- { code: pgError.code, attempt }
364
- );
365
- }
366
- await delay(retryDelayMs * attempt);
367
- continue;
368
- }
369
- throw this.classifyError(error);
370
- } finally {
371
- client.release();
372
- }
373
- }
374
- throw this.classifyError(lastError);
375
- }
376
- /**
377
- * Returns the database capabilities for PostgreSQL.
378
- *
379
- * @remarks
380
- * PostgreSQL has the most comprehensive feature set of all supported
381
- * databases, including JSONB, arrays, full-text search, and more.
382
- */
383
- getCapabilities() {
384
- return {
385
- dialect: "postgresql",
386
- supportsJsonb: true,
387
- supportsJson: true,
388
- supportsArrays: true,
389
- supportsGeneratedColumns: true,
390
- supportsFts: true,
391
- supportsIlike: true,
392
- supportsReturning: true,
393
- supportsSavepoints: true,
394
- supportsOnConflict: true,
395
- maxParamsPerQuery: 65535,
396
- // PostgreSQL limit
397
- maxIdentifierLength: 63
398
- // PostgreSQL default
399
- };
400
- }
401
- /**
402
- * Returns connection pool statistics.
403
- *
404
- * @returns Pool stats or null if not connected
405
- */
406
- getPoolStats() {
407
- if (!this.pool) {
408
- return null;
409
- }
410
- return {
411
- total: this.pool.totalCount,
412
- idle: this.pool.idleCount,
413
- waiting: this.pool.waitingCount,
414
- active: this.pool.totalCount - this.pool.idleCount
415
- };
416
- }
417
- /**
418
- * Override insertMany for bulk insert optimization.
419
- *
420
- * @remarks
421
- * Uses a single multi-row INSERT statement for better performance
422
- * when inserting multiple records.
423
- */
424
- async insertMany(table, data, options) {
425
- if (data.length === 0) {
426
- return [];
427
- }
428
- if (data.length === 1) {
429
- const result = await this.insert(table, data[0], options);
430
- return [result];
431
- }
432
- const columns = Object.keys(data[0]);
433
- const params = [];
434
- const valuesClauses = [];
435
- for (let i = 0; i < data.length; i++) {
436
- const record = data[i];
437
- const placeholders = [];
438
- for (const col of columns) {
439
- params.push(record[col]);
440
- placeholders.push(`$${params.length}`);
441
- }
442
- valuesClauses.push(`(${placeholders.join(", ")})`);
443
- }
444
- const columnList = columns.map((col) => this.escapeIdentifier(col)).join(", ");
445
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(", ")}`;
446
- if (options?.returning) {
447
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
448
- sql += ` RETURNING ${returning}`;
449
- }
450
- try {
451
- return await this.executeQuery(sql, params);
452
- } catch (error) {
453
- throw this.handleQueryError(error, "insertMany", table);
454
- }
455
- }
456
- // ============================================================
457
- // Protected Helper Methods
458
- // ============================================================
459
- /**
460
- * Ensures pool is connected and returns it.
461
- *
462
- * @throws {DatabaseError} If not connected
463
- */
464
- ensurePool() {
465
- if (!this.pool) {
466
- throw createDatabaseError({
467
- kind: "connection",
468
- message: "PostgresAdapter is not connected. Call connect() first."
469
- });
470
- }
471
- return this.pool;
472
- }
473
- /**
474
- * Return the typed Drizzle instance for PostgreSQL.
475
- * Guarded for server-only usage and requires an active connection.
476
- *
477
- * @param schema - Optional schema for relational queries (db.query.*)
478
- * @returns Drizzle ORM instance wrapping the pg pool connection
479
- * @throws {Error} If called in browser or not connected
480
- */
481
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
482
- getDrizzle(schema) {
483
- if (typeof window !== "undefined") {
484
- throw new Error("getDrizzle() is server-only");
485
- }
486
- const pool = this.ensurePool();
487
- return schema ? drizzle(pool, { schema }) : drizzle(pool);
488
- }
489
- /**
490
- * Builds pg Pool configuration from adapter config.
491
- */
492
- buildPoolConfig() {
493
- const config = {};
494
- if (this.config.url) {
495
- config.connectionString = this.config.url;
496
- } else {
497
- if (this.config.host) config.host = this.config.host;
498
- if (this.config.port) config.port = this.config.port;
499
- if (this.config.database) config.database = this.config.database;
500
- if (this.config.user) config.user = this.config.user;
501
- if (this.config.password) config.password = this.config.password;
502
- }
503
- config.min = this.config.pool?.min ?? this.providerDefaults.poolMin ?? DEFAULT_POOL_CONFIG.min;
504
- config.max = this.config.pool?.max ?? this.providerDefaults.poolMax ?? DEFAULT_POOL_CONFIG.max;
505
- config.idleTimeoutMillis = this.config.pool?.idleTimeoutMs ?? this.providerDefaults.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;
506
- config.connectionTimeoutMillis = this.config.pool?.connectionTimeoutMs ?? this.providerDefaults.connectionTimeoutMs ?? DEFAULT_POOL_CONFIG.connectionTimeoutMs;
507
- config.keepAlive = true;
508
- config.keepAliveInitialDelayMillis = 1e4;
509
- if (this.config.ssl) {
510
- if (typeof this.config.ssl === "boolean") {
511
- config.ssl = this.config.ssl;
512
- } else {
513
- if (this.config.ssl.rejectUnauthorized === false) {
514
- console.warn(
515
- "[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."
516
- );
517
- }
518
- config.ssl = {
519
- rejectUnauthorized: this.config.ssl.rejectUnauthorized,
520
- ca: this.config.ssl.ca,
521
- cert: this.config.ssl.cert,
522
- key: this.config.ssl.key
523
- };
524
- }
525
- } else if (this.providerDefaults.ssl) {
526
- config.ssl = { rejectUnauthorized: true };
527
- }
528
- if (this.config.applicationName) {
529
- config.application_name = this.config.applicationName;
530
- }
531
- const effectiveStatementTimeout = this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;
532
- if (effectiveStatementTimeout !== void 0) {
533
- config.statement_timeout = effectiveStatementTimeout;
534
- }
535
- if (this.config.queryTimeout) {
536
- config.query_timeout = this.config.queryTimeout;
537
- }
538
- return config;
539
- }
540
- /**
541
- * Begins a transaction with the specified options.
542
- */
543
- async beginTransaction(client, options) {
544
- let beginSql = "BEGIN";
545
- if (options?.isolationLevel) {
546
- const isolationMap = {
547
- "read uncommitted": "READ UNCOMMITTED",
548
- "read committed": "READ COMMITTED",
549
- "repeatable read": "REPEATABLE READ",
550
- serializable: "SERIALIZABLE"
551
- };
552
- const level = isolationMap[options.isolationLevel];
553
- if (level) {
554
- beginSql += ` ISOLATION LEVEL ${level}`;
555
- }
556
- }
557
- if (options?.readOnly) {
558
- beginSql += " READ ONLY";
559
- }
560
- await client.query(beginSql);
561
- if (options?.timeoutMs) {
562
- await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);
563
- }
564
- }
565
- /**
566
- * Creates a TransactionContext for the given client.
567
- */
568
- createTransactionContext(client) {
569
- return {
570
- execute: async (sql, params = []) => {
571
- const result = await client.query(sql, params);
572
- return result.rows;
573
- },
574
- insert: async (table, data, options) => {
575
- const columns = Object.keys(data);
576
- const values = Object.values(data);
577
- const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
578
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
579
- if (options?.returning) {
580
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
581
- sql += ` RETURNING ${returning}`;
582
- } else {
583
- sql += " RETURNING *";
584
- }
585
- const result = await client.query(sql, values);
586
- return result.rows[0];
587
- },
588
- insertMany: async (table, data, options) => {
589
- if (data.length === 0) return [];
590
- const columns = Object.keys(data[0]);
591
- const params = [];
592
- const valuesClauses = [];
593
- for (const record of data) {
594
- const placeholders = [];
595
- for (const col of columns) {
596
- params.push(record[col]);
597
- placeholders.push(`$${params.length}`);
598
- }
599
- valuesClauses.push(`(${placeholders.join(", ")})`);
600
- }
601
- let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
602
- if (options?.returning) {
603
- const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
604
- sql += ` RETURNING ${returning}`;
605
- } else {
606
- sql += " RETURNING *";
607
- }
608
- const result = await client.query(sql, params);
609
- return result.rows;
610
- },
611
- // TransactionContext CRUD methods delegate to the adapter's CRUD
612
- // which uses Drizzle query API via the TableResolver.
613
- // The Drizzle transaction is handled at a higher level.
614
- select: async (table, options) => {
615
- return this.select(table, options);
616
- },
617
- selectOne: async (table, options) => {
618
- return this.selectOne(table, options);
619
- },
620
- update: async (table, data, where, options) => {
621
- return this.update(table, data, where, options);
622
- },
623
- delete: async (table, where, _options) => {
624
- return this.delete(table, where);
625
- },
626
- upsert: async (table, data, options) => {
627
- return this.upsert(table, data, options);
628
- },
629
- savepoint: async (name) => {
630
- await client.query(`SAVEPOINT ${this.escapeIdentifier(name)}`);
631
- },
632
- rollbackToSavepoint: async (name) => {
633
- await client.query(
634
- `ROLLBACK TO SAVEPOINT ${this.escapeIdentifier(name)}`
635
- );
636
- },
637
- releaseSavepoint: async (name) => {
638
- await client.query(`RELEASE SAVEPOINT ${this.escapeIdentifier(name)}`);
639
- }
640
- };
641
- }
642
- /**
643
- * Classifies a PostgreSQL error into a DatabaseError.
644
- *
645
- * @param error - Original error from pg
646
- * @param sql - SQL statement that caused the error (optional)
647
- * @returns DatabaseError with proper classification
648
- */
649
- classifyError(error, sql) {
650
- if (isDatabaseError(error)) return error;
651
- const pgError = error;
652
- const kind = pgError.code && PG_ERROR_CODES[pgError.code] || "unknown";
653
- let message = pgError.message ?? String(error);
654
- if (sql && kind === "query") {
655
- message = `Query failed: ${message}`;
656
- }
657
- return createDatabaseError({
658
- kind,
659
- message,
660
- code: pgError.code,
661
- constraint: pgError.constraint,
662
- table: pgError.table,
663
- column: pgError.column,
664
- detail: pgError.detail,
665
- hint: pgError.hint,
666
- cause: error instanceof Error ? error : void 0
667
- });
668
- }
669
- /**
670
- * Override handleQueryError to use PostgreSQL-specific classification.
671
- */
672
- handleQueryError(error, operation, table) {
673
- const dbError = this.classifyError(error);
674
- if (!dbError.message.includes(operation)) {
675
- dbError.message = `${operation} operation failed on table '${table}': ${dbError.message}`;
676
- }
677
- if (!dbError.table) {
678
- dbError.table = table;
679
- }
680
- return dbError;
681
- }
403
+ drizzleByRelations = /* @__PURE__ */ new WeakMap();
404
+ drizzleBare;
405
+ /**
406
+ * The database dialect - always 'postgresql' for this adapter.
407
+ */
408
+ dialect = "postgresql";
409
+ /**
410
+ * Adapter configuration.
411
+ */
412
+ config;
413
+ /**
414
+ * Connection pool instance.
415
+ */
416
+ pool = null;
417
+ /**
418
+ * Connection state flag.
419
+ */
420
+ connected = false;
421
+ /**
422
+ * Auto-detected provider (Neon, Supabase, or standard).
423
+ * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
424
+ */
425
+ detectedProvider = "standard";
426
+ /**
427
+ * Provider-specific connection defaults. Applied as fallbacks when
428
+ * user config doesn't specify a value.
429
+ */
430
+ providerDefaults = getProviderDefaults("standard");
431
+ /**
432
+ * Creates a new PostgreSQL adapter instance.
433
+ *
434
+ * @param config - Adapter configuration
435
+ */
436
+ constructor(config) {
437
+ super();
438
+ this.config = config;
439
+ }
440
+ /**
441
+ * Establishes a connection to the PostgreSQL database.
442
+ *
443
+ * @remarks
444
+ * This method initializes the connection pool and verifies connectivity
445
+ * by executing a simple query. It is idempotent - calling it multiple
446
+ * times will not create multiple pools.
447
+ *
448
+ * @throws {DatabaseError} If connection fails
449
+ */
450
+ async connect() {
451
+ applyHappyEyeballsTimeoutOnce();
452
+ if (this.connected && this.pool) return;
453
+ const url = this.config.url || "";
454
+ const serverless = isVercelFunction();
455
+ this.detectedProvider = detectPostgresProvider(url, process.env.DB_PROVIDER);
456
+ this.providerDefaults = getProviderDefaults(this.detectedProvider, { serverless });
457
+ if (this.config.logger?.info) {
458
+ const source = process.env.DB_PROVIDER ? "(explicit)" : "(auto-detected)";
459
+ const pool = serverless ? ", Vercel pool defaults" : "";
460
+ this.config.logger.info(`PostgreSQL provider: ${this.detectedProvider} ${source}${pool}`, {});
461
+ }
462
+ const attachPool = await loadVercelPoolAttacher({
463
+ load: loadVercelDbConnections,
464
+ dialect: "PostgreSQL",
465
+ logger: this.config.logger
466
+ });
467
+ const retryableNodeCodes = /* @__PURE__ */ new Set([
468
+ "ETIMEDOUT",
469
+ "ECONNREFUSED",
470
+ "ECONNRESET",
471
+ "ENOTFOUND",
472
+ "EAI_AGAIN"
473
+ ]);
474
+ const maxAttempts = this.providerDefaults.retryAttempts;
475
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
476
+ const poolConfig = this.buildPoolConfig();
477
+ this.pool = reportPoolWaitTimeout(new Pool(poolConfig), poolConfig.connectionTimeoutMillis);
478
+ this.pool.on("error", (err) => {
479
+ if (this.config.logger?.error) this.config.logger.error(err, {
480
+ context: "pool_error",
481
+ message: "Unexpected error on idle client"
482
+ });
483
+ });
484
+ attachPool?.(this.pool);
485
+ const client = await this.pool.connect();
486
+ try {
487
+ await client.query("SELECT 1");
488
+ if (this.config.schema && isNextBuildPhase()) await assertSchemaExists(client, this.config.schema, "Run `nextly migrate` before `next build`.");
489
+ else if (this.config.schema && this.config.readOnly) await assertSchemaExists(client, this.config.schema);
490
+ else if (this.config.schema) await ensureSchemaExists(client, this.config.schema);
491
+ await checkDialectVersion(client, "postgresql", { onWarning: (msg) => this.config.logger?.warn?.(msg) });
492
+ this.connected = true;
493
+ if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection established", {
494
+ host: this.config.host ?? "from URL",
495
+ database: this.config.database ?? "from URL"
496
+ });
497
+ return;
498
+ } finally {
499
+ client.release();
500
+ }
501
+ } catch (error) {
502
+ if (this.pool) {
503
+ await this.pool.end().catch(() => {});
504
+ this.pool = null;
505
+ }
506
+ const nodeError = error;
507
+ if (nodeError.code != null && retryableNodeCodes.has(nodeError.code) && attempt < maxAttempts) {
508
+ const waitMs = 1e3 * attempt;
509
+ const msg = `PostgreSQL connection attempt ${attempt}/${maxAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`;
510
+ if (this.config.logger?.warn) this.config.logger.warn(msg);
511
+ else console.warn(`[PostgresAdapter] ${msg}`);
512
+ await delay(waitMs);
513
+ continue;
514
+ }
515
+ throw this.classifyError(error);
516
+ }
517
+ }
518
+ /**
519
+ * Closes the database connection and releases all pool resources.
520
+ *
521
+ * @remarks
522
+ * This method is idempotent - calling it multiple times is safe.
523
+ * It waits for all checked-out clients to be returned before shutting down.
524
+ */
525
+ async disconnect() {
526
+ const pool = this.pool;
527
+ this.pool = null;
528
+ this.drizzleBare = void 0;
529
+ this.drizzleByRelations = /* @__PURE__ */ new WeakMap();
530
+ if (!pool) return;
531
+ try {
532
+ await pool.end();
533
+ if (this.config.logger?.info) this.config.logger.info("PostgreSQL connection closed");
534
+ } finally {
535
+ this.connected = false;
536
+ }
537
+ }
538
+ /**
539
+ * Checks if the adapter is currently connected.
540
+ *
541
+ * @returns True if connected and pool is available
542
+ */
543
+ isConnected() {
544
+ return this.connected && this.pool !== null;
545
+ }
546
+ /**
547
+ * Runs `work` on one client taken from the pool, outside a transaction,
548
+ * each statement committing as it runs, so connection-scoped state a
549
+ * statement sets (a temporary table, a session setting, an advisory lock)
550
+ * is still there for the next. The client is closed afterwards, whether
551
+ * `work` finished or threw, never handed back to the pool: that state ends
552
+ * with it instead of reaching a later caller. No `SessionOptions` field
553
+ * changes anything on PostgreSQL: strict mode is MySQL's, and PostgreSQL
554
+ * refuses an overlong value already.
555
+ */
556
+ async withSession(work, _options) {
557
+ this.refuseSessionInTransaction();
558
+ const pool = this.ensurePool();
559
+ this.notePoolAccess();
560
+ let client;
561
+ try {
562
+ client = await pool.connect();
563
+ } catch (error) {
564
+ throw this.classifyError(error);
565
+ }
566
+ try {
567
+ return await work({ execute: async (statement, params = []) => {
568
+ const startTime = Date.now();
569
+ try {
570
+ const result = await client.query(statement, params);
571
+ if (this.config.logger?.query) this.config.logger.query(statement, params, Date.now() - startTime);
572
+ return result.rows;
573
+ } catch (error) {
574
+ throw this.classifyError(error, statement);
575
+ }
576
+ } });
577
+ } finally {
578
+ client.release(true);
579
+ }
580
+ }
581
+ /**
582
+ * Executes a raw SQL query.
583
+ *
584
+ * @param sql - SQL statement with $1, $2, ... placeholders
585
+ * @param params - Query parameters
586
+ * @returns Array of result rows
587
+ *
588
+ * @throws {DatabaseError} If query execution fails
589
+ */
590
+ async executeQuery(sql, params = []) {
591
+ const pool = this.ensurePool();
592
+ const startTime = Date.now();
593
+ const retryableNodeCodes = /* @__PURE__ */ new Set([
594
+ "ETIMEDOUT",
595
+ "ECONNRESET",
596
+ "ECONNREFUSED"
597
+ ]);
598
+ const maxQueryAttempts = 3;
599
+ for (let attempt = 1; attempt <= maxQueryAttempts; attempt++) try {
600
+ this.notePoolAccess(sql);
601
+ const result = await pool.query(sql, params);
602
+ if (this.config.logger?.query) {
603
+ const durationMs = Date.now() - startTime;
604
+ this.config.logger.query(sql, params, durationMs);
605
+ }
606
+ return result.rows;
607
+ } catch (error) {
608
+ const nodeError = error;
609
+ if (nodeError.code != null && retryableNodeCodes.has(nodeError.code) && attempt < maxQueryAttempts) {
610
+ const waitMs = 500 * attempt;
611
+ console.warn(`[PostgresAdapter] Query attempt ${attempt}/${maxQueryAttempts} failed with ${nodeError.code}, retrying in ${waitMs}ms...`);
612
+ await delay(waitMs);
613
+ continue;
614
+ }
615
+ throw this.classifyError(error, sql);
616
+ }
617
+ throw this.classifyError(/* @__PURE__ */ new Error("executeQuery: exhausted retries"));
618
+ }
619
+ /**
620
+ * Executes a callback within a database transaction.
621
+ *
622
+ * @remarks
623
+ * PostgreSQL supports full ACID transactions with savepoints.
624
+ * If the callback throws, the transaction is rolled back.
625
+ *
626
+ * Supports automatic retry for serialization failures (40001) and
627
+ * deadlocks (40P01) when `retryCount` is specified in options.
628
+ *
629
+ * An error carrying the Nextly application brand is not classified: it is the
630
+ * application refusing the write, so it arrives at the caller as it was
631
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
632
+ * first, of every error; a refusal re-run is otherwise the same refusal.
633
+ * Every other error, including an unbranded one raised by the callback, is
634
+ * retried when it is a serialization failure or deadlock and classified on
635
+ * the way out.
636
+ *
637
+ * A call made inside another transaction's work joins it, on its client,
638
+ * as a savepoint: released when the callback resolves, rolled back to when
639
+ * it throws, so its failure undoes only its own part. A serialization
640
+ * failure or deadlock inside a joined part fails the whole transaction,
641
+ * which only a retry of the outermost one can answer. A joined call keeps
642
+ * the outer's options and is never retried itself.
643
+ *
644
+ * @param callback - Function to execute within the transaction
645
+ * @param options - Transaction options (isolation level, timeout, retry)
646
+ * @returns The result of the callback
647
+ *
648
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
649
+ * or if the callback threw an error that does not carry the application brand
650
+ * @throws The callback's own error, unchanged, when it carries that brand
651
+ */
652
+ transaction(callback, options) {
653
+ return this.openOrJoin(callback, options, {
654
+ run: (_attempt, openedAt) => this.runAttempt(callback, options, openedAt),
655
+ retryable: isSerializationFailure,
656
+ describe: (error) => {
657
+ const code = sqlStateOf(error);
658
+ return {
659
+ label: code ?? "a retryable error",
660
+ detail: { code }
661
+ };
662
+ },
663
+ logger: this.config.logger
664
+ });
665
+ }
666
+ /** One attempt at an outermost transaction, on a client of its own. */
667
+ async runAttempt(callback, options, openedAt) {
668
+ const pool = this.ensurePool();
669
+ this.notePoolAccess();
670
+ const bounds = this.transactionBounds();
671
+ const client = await pool.connect();
672
+ let discard;
673
+ const sessionEnded = (error) => {
674
+ discard = error;
675
+ };
676
+ if (bounds?.idleMs !== void 0) client.on("error", sessionEnded);
677
+ const settled = await this.settleOutermost({
678
+ context: this.createTransactionContext(client),
679
+ join: this.joinSteps(client),
680
+ openedAt,
681
+ begin: () => this.beginTransaction(client, options, bounds),
682
+ commit: async () => {
683
+ if ((await client.query("COMMIT"))?.command === "ROLLBACK") throw createDatabaseError({
684
+ kind: "query",
685
+ code: "25P02",
686
+ 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."
687
+ });
688
+ },
689
+ rollback: async () => {
690
+ await client.query("ROLLBACK").catch((rollbackError) => {
691
+ discard = rollbackError instanceof Error ? rollbackError : true;
692
+ throw rollbackError;
693
+ });
694
+ }
695
+ }, callback, options);
696
+ if (bounds?.idleMs !== void 0) client.removeListener("error", sessionEnded);
697
+ client.release(discard);
698
+ return settled;
699
+ }
700
+ /**
701
+ * How a call made inside a transaction on `client` joins it: a savepoint
702
+ * each, on `client`, named for its depth.
703
+ */
704
+ joinSteps(client) {
705
+ return this.joinStepsOn(() => this.createTransactionContext(client), (relations) => relations ? drizzle({
706
+ client,
707
+ relations
708
+ }) : drizzle({ client }), (context, depth) => {
709
+ const name = this.escapeIdentifier(`nextly_sp_${depth}`);
710
+ return {
711
+ context,
712
+ begin: async () => {
713
+ await client.query(`SAVEPOINT ${name}`);
714
+ },
715
+ commit: async () => {
716
+ await client.query(`RELEASE SAVEPOINT ${name}`);
717
+ },
718
+ rollback: async () => {
719
+ await client.query(`ROLLBACK TO SAVEPOINT ${name}`);
720
+ await client.query(`RELEASE SAVEPOINT ${name}`);
721
+ },
722
+ dooms: isSerializationFailure
723
+ };
724
+ });
725
+ }
726
+ /**
727
+ * Returns the database capabilities for PostgreSQL.
728
+ *
729
+ * @remarks
730
+ * PostgreSQL has the most comprehensive feature set of all supported
731
+ * databases, including JSONB, arrays, full-text search, and more.
732
+ */
733
+ getCapabilities() {
734
+ return {
735
+ dialect: "postgresql",
736
+ supportsJsonb: true,
737
+ supportsJson: true,
738
+ supportsArrays: true,
739
+ supportsGeneratedColumns: true,
740
+ supportsFts: true,
741
+ supportsIlike: true,
742
+ supportsReturning: true,
743
+ supportsSavepoints: true,
744
+ supportsOnConflict: true,
745
+ maxParamsPerQuery: 65535,
746
+ maxIdentifierLength: 63
747
+ };
748
+ }
749
+ /**
750
+ * The schema set as `search_path` on every pooled connection.
751
+ *
752
+ * @remarks
753
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
754
+ * reports `undefined` exactly as it sets no `search_path`: the value
755
+ * reported is the one the connections actually use.
756
+ *
757
+ * @returns The configured schema, or `undefined` when the server's default
758
+ * `search_path` applies
759
+ */
760
+ getConfiguredSchema() {
761
+ return this.config.schema ? this.config.schema : void 0;
762
+ }
763
+ /**
764
+ * Returns connection pool statistics.
765
+ *
766
+ * @returns Pool stats or null if not connected
767
+ */
768
+ getPoolStats() {
769
+ if (!this.pool) return null;
770
+ return {
771
+ total: this.pool.totalCount,
772
+ idle: this.pool.idleCount,
773
+ waiting: this.pool.waitingCount,
774
+ active: this.pool.totalCount - this.pool.idleCount
775
+ };
776
+ }
777
+ /**
778
+ * The connection as a health check reads it, on one pooled client: the
779
+ * server's version, and that client's own row in `pg_stat_ssl`, which says
780
+ * whether the session's connection is encrypted. The query is timed for the
781
+ * round trip.
782
+ *
783
+ * @remarks
784
+ * The row and the client's own socket are weighed by `encryptionOf`: behind
785
+ * a connection pooler such as PgBouncer the row describes the pooler's own
786
+ * connection to the server, which can be plain inside the provider's
787
+ * network while this client's socket is TLS. The socket is read as it is,
788
+ * never inferred from the `ssl` setting.
789
+ *
790
+ * Whether the database is on this machine is judged from the host the
791
+ * client connected to, as node-postgres resolved it (its options, the
792
+ * connection string, `PGHOST`, its default); before a client is had, from
793
+ * the configured address alone. The address never leaves this method. Any
794
+ * failure answers `"unknown"`.
795
+ */
796
+ async inspectConnection() {
797
+ let local = this.isLocalHost(this.configuredHost());
798
+ let client;
799
+ try {
800
+ client = await this.ensurePool().connect();
801
+ local = this.isLocalHost(resolvedHost(client) ?? this.configuredHost());
802
+ const started = performance.now();
803
+ const result = await client.query("SELECT current_setting('server_version') AS version, (SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()) AS ssl");
804
+ const roundTripMs = Math.max(0, Math.round(performance.now() - started));
805
+ const row = result.rows[0];
806
+ const version = row?.version?.split(" ")[0];
807
+ return {
808
+ encryption: this.encryptionOf({
809
+ session: typeof row?.ssl === "boolean" ? row.ssl : void 0,
810
+ ownSocketTls: this.ownSocketIsTls(client)
811
+ }),
812
+ local,
813
+ roundTripMs,
814
+ ...version ? { serverVersion: version } : {}
815
+ };
816
+ } catch {
817
+ return {
818
+ encryption: "unknown",
819
+ local
820
+ };
821
+ } finally {
822
+ client?.release();
823
+ }
824
+ }
825
+ /**
826
+ * The host this adapter is configured with: the connection string's when one
827
+ * is set, else the `host` option. `undefined` when it names none, which is
828
+ * judged remote, or when the connection string cannot be read.
829
+ */
830
+ configuredHost() {
831
+ const configured = this.config.url ? this.hostOfUrl(this.config.url) : this.config.host ?? "";
832
+ return configured === "" ? void 0 : configured;
833
+ }
834
+ /**
835
+ * Override insertMany for bulk insert optimization.
836
+ *
837
+ * @remarks
838
+ * Uses a single multi-row INSERT statement for better performance
839
+ * when inserting multiple records.
840
+ */
841
+ async insertMany(table, data, options) {
842
+ if (data.length === 0) return [];
843
+ if (data.length === 1) return [await this.insert(table, data[0], options)];
844
+ this.resolvedTableObject(table);
845
+ const columns = Object.keys(data[0]);
846
+ const params = [];
847
+ const valuesClauses = [];
848
+ for (let i = 0; i < data.length; i++) {
849
+ const record = data[i];
850
+ const placeholders = [];
851
+ for (const col of columns) {
852
+ params.push(record[col]);
853
+ placeholders.push(`$${params.length}`);
854
+ }
855
+ valuesClauses.push(`(${placeholders.join(", ")})`);
856
+ }
857
+ const columnList = columns.map((col) => this.escapeIdentifier(col)).join(", ");
858
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columnList}) VALUES ${valuesClauses.join(", ")}`;
859
+ if (options?.returning) {
860
+ const returning = options.returning === "*" ? "*" : options.returning.map((col) => this.escapeIdentifier(col)).join(", ");
861
+ sql += ` RETURNING ${returning}`;
862
+ }
863
+ try {
864
+ return await this.executeQuery(sql, params);
865
+ } catch (error) {
866
+ throw this.handleQueryError(error, "insertMany", table);
867
+ }
868
+ }
869
+ /**
870
+ * Ensures pool is connected and returns it.
871
+ *
872
+ * @throws {DatabaseError} If not connected
873
+ */
874
+ ensurePool() {
875
+ if (!this.pool) throw createDatabaseError({
876
+ kind: "connection",
877
+ message: "PostgresAdapter is not connected. Call connect() first."
878
+ });
879
+ return this.pool;
880
+ }
881
+ /**
882
+ * Return the typed Drizzle instance for PostgreSQL.
883
+ * Guarded for server-only usage and requires an active connection.
884
+ *
885
+ * @param schema - Optional schema for relational queries (db.query.*)
886
+ * @returns Drizzle ORM instance wrapping the pg pool connection
887
+ * @throws {Error} If called in browser or not connected
888
+ */
889
+ getDrizzle(relations) {
890
+ if (typeof window !== "undefined") throw new Error("getDrizzle() is server-only");
891
+ const pool = this.ensurePool();
892
+ if (!relations) {
893
+ this.drizzleBare ??= this.poolDrizzle(pool);
894
+ return this.drizzleBare;
895
+ }
896
+ let cached = this.drizzleByRelations.get(relations);
897
+ if (!cached) {
898
+ cached = this.poolDrizzle(pool, relations);
899
+ this.drizzleByRelations.set(relations, cached);
900
+ }
901
+ return cached;
902
+ }
903
+ /**
904
+ * A Drizzle handle on the pool, for `getDrizzle`.
905
+ *
906
+ * Its `transaction` runs on a client this adapter checks out and returns
907
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
908
+ * released with `true`, which is what happens when no ROLLBACK could be
909
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
910
+ * adapter's does.
911
+ */
912
+ poolDrizzle(pool, relations) {
913
+ const onClient = (client) => relations ? drizzle({
914
+ client,
915
+ relations
916
+ }) : drizzle({ client });
917
+ const reported = this.observedPool(pool, ["query"]);
918
+ return this.joiningHandle(onClient(reported), async () => {
919
+ const client = await pool.connect();
920
+ return {
921
+ drizzle: onClient(client),
922
+ rollback: () => client.query("ROLLBACK"),
923
+ release: (dirty) => client.release(dirty),
924
+ join: this.joinSteps(client)
925
+ };
926
+ }, relations);
927
+ }
928
+ /**
929
+ * Builds pg Pool configuration from adapter config.
930
+ */
931
+ buildPoolConfig() {
932
+ const config = {};
933
+ if (this.config.url) config.connectionString = this.config.url;
934
+ else {
935
+ if (this.config.host) config.host = this.config.host;
936
+ if (this.config.port) config.port = this.config.port;
937
+ if (this.config.database) config.database = this.config.database;
938
+ if (this.config.user) config.user = this.config.user;
939
+ if (this.config.password) config.password = this.config.password;
940
+ }
941
+ config.min = this.config.pool?.min ?? this.providerDefaults.poolMin ?? DEFAULT_POOL_CONFIG.min;
942
+ config.max = this.config.pool?.max ?? this.providerDefaults.poolMax ?? DEFAULT_POOL_CONFIG.max;
943
+ config.idleTimeoutMillis = this.config.pool?.idleTimeoutMs ?? this.providerDefaults.idleTimeoutMs ?? DEFAULT_POOL_CONFIG.idleTimeoutMs;
944
+ config.connectionTimeoutMillis = this.config.pool?.connectionTimeoutMs ?? this.providerDefaults.connectionTimeoutMs ?? DEFAULT_POOL_CONFIG.connectionTimeoutMs;
945
+ config.keepAlive = true;
946
+ config.keepAliveInitialDelayMillis = 1e4;
947
+ if (this.config.ssl) {
948
+ if (typeof this.config.ssl === "boolean") config.ssl = this.config.ssl;
949
+ else {
950
+ 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.");
951
+ config.ssl = {
952
+ rejectUnauthorized: this.config.ssl.rejectUnauthorized,
953
+ ca: this.config.ssl.ca,
954
+ cert: this.config.ssl.cert,
955
+ key: this.config.ssl.key
956
+ };
957
+ }
958
+ } else if (this.providerDefaults.ssl) config.ssl = { rejectUnauthorized: true };
959
+ if (this.config.applicationName) config.application_name = this.config.applicationName;
960
+ if (this.config.schema) config.options = `-c search_path=${assertSchemaName(this.config.schema)}`;
961
+ const effectiveStatementTimeout = this.config.statementTimeout ?? this.providerDefaults.statementTimeoutMs;
962
+ if (effectiveStatementTimeout !== void 0) config.statement_timeout = effectiveStatementTimeout;
963
+ if (this.config.queryTimeout) config.query_timeout = this.config.queryTimeout;
964
+ return config;
965
+ }
966
+ /**
967
+ * Begins a transaction with the specified options.
968
+ */
969
+ async beginTransaction(client, options, bounds) {
970
+ let beginSql = "BEGIN";
971
+ if (options?.isolationLevel) {
972
+ const level = {
973
+ "read uncommitted": "READ UNCOMMITTED",
974
+ "read committed": "READ COMMITTED",
975
+ "repeatable read": "REPEATABLE READ",
976
+ serializable: "SERIALIZABLE"
977
+ }[options.isolationLevel];
978
+ if (level) beginSql += ` ISOLATION LEVEL ${level}`;
979
+ }
980
+ if (options?.readOnly) beginSql += " READ ONLY";
981
+ await client.query(beginSql);
982
+ if (options?.timeoutMs) await client.query(`SET LOCAL statement_timeout = ${options.timeoutMs}`);
983
+ if (bounds?.lockWaitMs !== void 0) await client.query(`SET LOCAL lock_timeout = ${bounds.lockWaitMs}`);
984
+ if (bounds?.idleMs !== void 0) await client.query(`SET LOCAL idle_in_transaction_session_timeout = ${bounds.idleMs}`);
985
+ }
986
+ /**
987
+ * Creates a TransactionContext for the given client.
988
+ */
989
+ /**
990
+ * The RETURNING entries that spell each date column's wall clock out as
991
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
992
+ * stored value without a zone, which is the only form node-postgres cannot
993
+ * shift on the way back.
994
+ */
995
+ wallClockSpelling(aliases) {
996
+ return aliases.map((a) => `to_char(${this.escapeIdentifier(a.sqlName)}, '${PG_WALL_CLOCK_FORMAT}') AS ${this.escapeIdentifier(a.alias)}`).join(", ");
997
+ }
998
+ /** A `Date` on an undeclared key is spelled as a date field's column spells it. */
999
+ undeclaredDateColumn() {
1000
+ return DATE_FIELD_COLUMN;
1001
+ }
1002
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
1003
+ compositePrimaryKey(tableObj) {
1004
+ return getTableConfig(tableObj).primaryKeys.flatMap((key) => key.columns);
1005
+ }
1006
+ createTransactionContext(client) {
1007
+ const txHandles = this.transactionDrizzleHandles((relations) => relations ? drizzle({
1008
+ client,
1009
+ relations
1010
+ }) : drizzle({ client }));
1011
+ const txDb = txHandles.bare;
1012
+ return {
1013
+ drizzleWithRelations: txHandles.withRelations,
1014
+ execute: async (sql, params = []) => {
1015
+ return (await client.query(sql, params)).rows;
1016
+ },
1017
+ runStatement: async (statement) => {
1018
+ await txDb().execute(statement);
1019
+ },
1020
+ queryStatement: async (statement) => {
1021
+ return (await txDb().execute(statement)).rows;
1022
+ },
1023
+ lockRow: async (table, id) => {
1024
+ const idColumn = this.escapeIdentifier("id");
1025
+ await client.query(`SELECT ${idColumn} FROM ${this.escapeIdentifier(table)} WHERE ${idColumn} = $1 FOR UPDATE`, [id]);
1026
+ },
1027
+ insert: async (table, data, options) => {
1028
+ const tableObj = this.resolvedTableObject(table);
1029
+ const mapped = this.mapRowToRawSql(tableObj, data);
1030
+ const columns = Object.keys(mapped);
1031
+ const values = Object.values(mapped);
1032
+ const placeholders = values.map((_, i) => `$${i + 1}`).join(", ");
1033
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES (${placeholders})`;
1034
+ const ret = options?.returning;
1035
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
1036
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
1037
+ if (!returningEmpty) {
1038
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
1039
+ const spelled = this.wallClockSpelling(aliases);
1040
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
1041
+ }
1042
+ const result = await client.query(sql, values);
1043
+ return this.mapRowFromRawSql(tableObj, result.rows[0], aliases);
1044
+ },
1045
+ insertMany: async (table, data, options) => {
1046
+ if (data.length === 0) return [];
1047
+ const tableObj = this.resolvedTableObject(table);
1048
+ const mappedRecords = data.map((r) => this.mapRowToRawSql(tableObj, r));
1049
+ const columns = Object.keys(mappedRecords[0]);
1050
+ const params = [];
1051
+ const valuesClauses = [];
1052
+ for (const record of mappedRecords) {
1053
+ const placeholders = [];
1054
+ for (const col of columns) {
1055
+ params.push(record[col]);
1056
+ placeholders.push(`$${params.length}`);
1057
+ }
1058
+ valuesClauses.push(`(${placeholders.join(", ")})`);
1059
+ }
1060
+ let sql = `INSERT INTO ${this.escapeIdentifier(table)} (${columns.map((c) => this.escapeIdentifier(c)).join(", ")}) VALUES ${valuesClauses.join(", ")}`;
1061
+ const ret = options?.returning;
1062
+ const returningEmpty = Array.isArray(ret) && ret.length === 0;
1063
+ const aliases = returningEmpty ? [] : this.dateWallClockAliases(tableObj, ret ?? "*");
1064
+ if (!returningEmpty) {
1065
+ const returning = !ret || ret === "*" ? "*" : this.mapColumnNamesToSql(tableObj, ret).map((col) => this.escapeIdentifier(col)).join(", ");
1066
+ const spelled = this.wallClockSpelling(aliases);
1067
+ sql += ` RETURNING ${returning}${spelled ? `, ${spelled}` : ""}`;
1068
+ }
1069
+ return (await client.query(sql, params)).rows.map((r) => this.mapRowFromRawSql(tableObj, r, aliases));
1070
+ },
1071
+ update: this.transactionUpdate(txDb, async (statement) => (await txDb().execute(statement)).rows, (value) => this.bindUnmodeledStructuredAsJson(value)),
1072
+ ...this.createTransactionForwarders(txDb),
1073
+ ...this.contextSavepointMethods(async (statement) => {
1074
+ await client.query(statement);
1075
+ })
1076
+ };
1077
+ }
1078
+ /**
1079
+ * Classifies a PostgreSQL error into a DatabaseError.
1080
+ *
1081
+ * @param error - Original error from pg
1082
+ * @param sql - SQL statement that caused the error (optional)
1083
+ * @returns DatabaseError with proper classification
1084
+ */
1085
+ classifyError(error, sql) {
1086
+ if (isDatabaseError(error)) return error;
1087
+ const pgError = this.driverErrorIn(error, (candidate) => typeof candidate.code === "string" && candidate.code !== "");
1088
+ const kind = pgError.code && PG_ERROR_CODES[pgError.code] || "unknown";
1089
+ let message = pgError.message ?? String(error);
1090
+ if (sql && kind === "query") message = `Query failed: ${message}`;
1091
+ return createDatabaseError({
1092
+ kind,
1093
+ message,
1094
+ code: pgError.code,
1095
+ constraint: pgError.constraint,
1096
+ table: pgError.table,
1097
+ column: pgError.column,
1098
+ detail: pgError.detail,
1099
+ hint: pgError.hint,
1100
+ cause: error instanceof Error ? error : void 0
1101
+ });
1102
+ }
682
1103
  };
1104
+ /**
1105
+ * Creates a PostgreSQL database adapter instance.
1106
+ *
1107
+ * @remarks
1108
+ * This is the recommended way to create a PostgreSQL adapter.
1109
+ * The adapter is not connected after creation - call `connect()` to
1110
+ * establish the database connection.
1111
+ *
1112
+ * @param config - Adapter configuration
1113
+ * @returns A new PostgresAdapter instance
1114
+ *
1115
+ * @example
1116
+ * Simple usage:
1117
+ * ```typescript
1118
+ * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
1119
+ *
1120
+ * const adapter = createPostgresAdapter({
1121
+ * url: process.env.DATABASE_URL!,
1122
+ * });
1123
+ *
1124
+ * await adapter.connect();
1125
+ * ```
1126
+ *
1127
+ * @example
1128
+ * With full configuration:
1129
+ * ```typescript
1130
+ * const adapter = createPostgresAdapter({
1131
+ * url: process.env.DATABASE_URL!,
1132
+ * pool: {
1133
+ * min: 5,
1134
+ * max: 20,
1135
+ * idleTimeoutMs: 30000,
1136
+ * connectionTimeoutMs: 10000,
1137
+ * },
1138
+ * ssl: {
1139
+ * rejectUnauthorized: true,
1140
+ * ca: process.env.CA_CERT,
1141
+ * },
1142
+ * applicationName: 'my-app',
1143
+ * statementTimeout: 30000,
1144
+ * });
1145
+ * ```
1146
+ *
1147
+ * @public
1148
+ */
683
1149
  function createPostgresAdapter(config) {
684
- return new PostgresAdapter(config);
1150
+ return new PostgresAdapter(config);
685
1151
  }
1152
+ /**
1153
+ * Type guard to check if a value is a PostgresAdapter instance.
1154
+ *
1155
+ * @param value - Value to check
1156
+ * @returns True if value is a PostgresAdapter
1157
+ *
1158
+ * @example
1159
+ * ```typescript
1160
+ * import { isPostgresAdapter } from '@nextlyhq/adapter-postgres';
1161
+ *
1162
+ * if (isPostgresAdapter(adapter)) {
1163
+ * // TypeScript knows adapter is PostgresAdapter
1164
+ * console.log(adapter.dialect); // 'postgresql'
1165
+ * }
1166
+ * ```
1167
+ *
1168
+ * @public
1169
+ */
686
1170
  function isPostgresAdapter(value) {
687
- return value instanceof PostgresAdapter;
1171
+ return value instanceof PostgresAdapter;
688
1172
  }
689
-
690
1173
  export { PostgresAdapter, VERSION, createPostgresAdapter, isPostgresAdapter };
691
- //# sourceMappingURL=index.mjs.map
1174
+
692
1175
  //# sourceMappingURL=index.mjs.map