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