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