@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/README.md +5 -5
- package/dist/index.cjs +1179 -695
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +249 -224
- package/dist/index.d.ts +249 -224
- package/dist/index.mjs +1156 -673
- package/dist/index.mjs.map +1 -1
- package/package.json +25 -20
package/dist/index.cjs
CHANGED
|
@@ -1,717 +1,1201 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
var
|
|
4
|
-
var
|
|
5
|
-
var
|
|
6
|
-
var
|
|
7
|
-
var
|
|
8
|
-
var
|
|
9
|
-
|
|
10
|
-
function
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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
|
-
|
|
363
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
123
364
|
}
|
|
124
|
-
|
|
125
|
-
|
|
365
|
+
const HAPPY_EYEBALLS_MIN_TIMEOUT_MS = 5e3;
|
|
366
|
+
let happyEyeballsTimeoutApplied = false;
|
|
126
367
|
function applyHappyEyeballsTimeoutOnce() {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1200
|
+
|
|
717
1201
|
//# sourceMappingURL=index.cjs.map
|