@prisma-next/driver-postgres 0.3.0-dev.4 → 0.3.0-dev.41

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.
@@ -0,0 +1,403 @@
1
+ import type {
2
+ SqlConnection,
3
+ SqlDriver,
4
+ SqlDriverState,
5
+ SqlExecuteRequest,
6
+ SqlExplainResult,
7
+ SqlQueryable,
8
+ SqlQueryResult,
9
+ SqlTransaction,
10
+ } from '@prisma-next/sql-relational-core/ast';
11
+ import type {
12
+ Client,
13
+ QueryResult as PgQueryResult,
14
+ PoolClient,
15
+ Pool as PoolType,
16
+ QueryResultRow,
17
+ } from 'pg';
18
+ import { Pool } from 'pg';
19
+ import Cursor from 'pg-cursor';
20
+ import { callbackToPromise } from './callback-to-promise';
21
+ import { isAlreadyConnectedError, isPostgresError, normalizePgError } from './normalize-error';
22
+
23
+ export type QueryResult<T extends QueryResultRow = QueryResultRow> = PgQueryResult<T>;
24
+
25
+ export type PostgresBinding =
26
+ | { readonly kind: 'url'; readonly url: string }
27
+ | { readonly kind: 'pgPool'; readonly pool: PoolType }
28
+ | { readonly kind: 'pgClient'; readonly client: Client };
29
+
30
+ export interface PostgresCursorOptions {
31
+ readonly batchSize?: number;
32
+ readonly disabled?: boolean;
33
+ }
34
+
35
+ interface PostgresDriverOptions {
36
+ readonly connect: { client: Client } | { pool: PoolType };
37
+ readonly cursor?: PostgresCursorOptions | undefined;
38
+ }
39
+
40
+ export type PostgresDriverCreateOptions = Omit<PostgresDriverOptions, 'connect'>;
41
+
42
+ const DEFAULT_BATCH_SIZE = 100;
43
+
44
+ type ConnectionOptions =
45
+ | { readonly cursorDisabled: true }
46
+ | { readonly cursorBatchSize: number; readonly cursorDisabled: false };
47
+
48
+ class AsyncMutex {
49
+ #queue = Promise.resolve();
50
+
51
+ async lock(): Promise<() => void> {
52
+ const previous = this.#queue;
53
+ let releaseLock: (() => void) | undefined;
54
+ this.#queue = new Promise<void>((resolve) => {
55
+ releaseLock = resolve;
56
+ });
57
+ await previous;
58
+ return () => {
59
+ releaseLock?.();
60
+ releaseLock = undefined;
61
+ };
62
+ }
63
+ }
64
+
65
+ abstract class PostgresQueryable<C extends PoolClient | Client = PoolClient | Client>
66
+ implements SqlQueryable
67
+ {
68
+ abstract acquireClient(): Promise<C>;
69
+ abstract releaseClient(client: C): Promise<void>;
70
+
71
+ protected readonly options: ConnectionOptions;
72
+
73
+ constructor(options: ConnectionOptions) {
74
+ this.options = options;
75
+ }
76
+
77
+ async *execute<Row = Record<string, unknown>>(request: SqlExecuteRequest): AsyncIterable<Row> {
78
+ const client = await this.acquireClient();
79
+ try {
80
+ if (!this.options.cursorDisabled) {
81
+ try {
82
+ for await (const row of this.executeWithCursor(
83
+ client,
84
+ request.sql,
85
+ request.params,
86
+ this.options.cursorBatchSize,
87
+ )) {
88
+ yield row as Row;
89
+ }
90
+ return;
91
+ } catch (cursorError) {
92
+ if (!(cursorError instanceof Error)) {
93
+ throw cursorError;
94
+ }
95
+ // Check if this is a pg error - if so, normalize and throw
96
+ // Otherwise, fall back to buffered mode for cursor-specific errors
97
+ if (isPostgresError(cursorError)) {
98
+ throw normalizePgError(cursorError);
99
+ }
100
+ // Not a pg error - cursor-specific error, fall back to buffered mode
101
+ }
102
+ }
103
+
104
+ for await (const row of this.executeBuffered(client, request.sql, request.params)) {
105
+ yield row as Row;
106
+ }
107
+ } catch (error) {
108
+ throw normalizePgError(error);
109
+ } finally {
110
+ await this.releaseClient(client);
111
+ }
112
+ }
113
+
114
+ async explain(request: SqlExecuteRequest): Promise<SqlExplainResult> {
115
+ // SQL is generated by Prisma Next planners (or validated raw paths), so
116
+ // EXPLAIN prefixing preserves the same statement semantics.
117
+ const text = `EXPLAIN (FORMAT JSON) ${request.sql}`;
118
+ const client = await this.acquireClient();
119
+ try {
120
+ const result = await client
121
+ .query(text, request.params as unknown[] | undefined)
122
+ .catch(rethrowNormalizedError);
123
+ return { rows: result.rows as ReadonlyArray<Record<string, unknown>> };
124
+ } finally {
125
+ await this.releaseClient(client);
126
+ }
127
+ }
128
+
129
+ async query<Row = Record<string, unknown>>(
130
+ sql: string,
131
+ params?: readonly unknown[],
132
+ ): Promise<SqlQueryResult<Row>> {
133
+ const client = await this.acquireClient();
134
+ try {
135
+ const result = await client
136
+ .query(sql, params as unknown[] | undefined)
137
+ .catch(rethrowNormalizedError);
138
+ return result as unknown as SqlQueryResult<Row>;
139
+ } finally {
140
+ await this.releaseClient(client);
141
+ }
142
+ }
143
+
144
+ private async *executeWithCursor(
145
+ client: PoolClient | Client,
146
+ sql: string,
147
+ params: readonly unknown[] | undefined,
148
+ cursorBatchSize: number,
149
+ ): AsyncIterable<Record<string, unknown>> {
150
+ const cursor = client.query(new Cursor(sql, params as unknown[] | undefined));
151
+
152
+ try {
153
+ while (true) {
154
+ const rows = await readCursor(cursor, cursorBatchSize);
155
+ if (rows.length === 0) {
156
+ break;
157
+ }
158
+
159
+ for (const row of rows) {
160
+ yield row;
161
+ }
162
+ }
163
+ } finally {
164
+ await closeCursor(cursor);
165
+ }
166
+ }
167
+
168
+ private async *executeBuffered(
169
+ client: PoolClient | Client,
170
+ sql: string,
171
+ params: readonly unknown[] | undefined,
172
+ ): AsyncIterable<Record<string, unknown>> {
173
+ const result = await client.query(sql, params as unknown[] | undefined);
174
+ for (const row of result.rows as Record<string, unknown>[]) {
175
+ yield row;
176
+ }
177
+ }
178
+ }
179
+
180
+ class PostgresConnectionImpl extends PostgresQueryable implements SqlConnection {
181
+ #connection: PoolClient | Client;
182
+ #onRelease: (() => void) | undefined;
183
+
184
+ constructor(connection: PoolClient | Client, options: ConnectionOptions, onRelease?: () => void) {
185
+ super(options);
186
+ this.#connection = connection;
187
+ this.#onRelease = onRelease;
188
+ }
189
+
190
+ override acquireClient(): Promise<PoolClient | Client> {
191
+ return Promise.resolve(this.#connection);
192
+ }
193
+
194
+ override releaseClient(_client: PoolClient | Client): Promise<void> {
195
+ return Promise.resolve();
196
+ }
197
+
198
+ async beginTransaction(): Promise<SqlTransaction> {
199
+ await this.#connection.query('BEGIN').catch(rethrowNormalizedError);
200
+ return new PostgresTransactionImpl(this.#connection, this.options);
201
+ }
202
+
203
+ async release(): Promise<void> {
204
+ if ('release' in this.#connection) {
205
+ this.#connection.release();
206
+ }
207
+ this.#onRelease?.();
208
+ this.#onRelease = undefined;
209
+ }
210
+ }
211
+
212
+ class PostgresTransactionImpl extends PostgresQueryable implements SqlTransaction {
213
+ #connection: PoolClient | Client;
214
+
215
+ constructor(connection: PoolClient | Client, options: ConnectionOptions) {
216
+ super(options);
217
+ this.#connection = connection;
218
+ }
219
+
220
+ override acquireClient(): Promise<PoolClient | Client> {
221
+ return Promise.resolve(this.#connection);
222
+ }
223
+
224
+ override releaseClient(_client: PoolClient | Client): Promise<void> {
225
+ return Promise.resolve();
226
+ }
227
+
228
+ async commit(): Promise<void> {
229
+ await this.#connection.query('COMMIT').catch(rethrowNormalizedError);
230
+ }
231
+
232
+ async rollback(): Promise<void> {
233
+ await this.#connection.query('ROLLBACK').catch(rethrowNormalizedError);
234
+ }
235
+ }
236
+
237
+ class PostgresPoolDriverImpl
238
+ extends PostgresQueryable<PoolClient>
239
+ implements SqlDriver<PostgresBinding>
240
+ {
241
+ private readonly pool: PoolType;
242
+ #closed = false;
243
+
244
+ constructor(options: PostgresDriverOptions & { connect: { pool: PoolType } }) {
245
+ super({
246
+ cursorBatchSize: options.cursor?.batchSize ?? DEFAULT_BATCH_SIZE,
247
+ cursorDisabled: options.cursor?.disabled ?? false,
248
+ });
249
+ this.pool = options.connect.pool;
250
+ }
251
+
252
+ get state(): SqlDriverState {
253
+ return this.#closed ? 'closed' : 'connected';
254
+ }
255
+
256
+ // Bound drivers are created via createBoundDriverFromBinding with pool already
257
+ // configured; connect is intentionally no-op.
258
+ async connect(_binding: PostgresBinding): Promise<void> {}
259
+
260
+ async acquireConnection(): Promise<SqlConnection> {
261
+ const client = await this.acquireClient();
262
+ return new PostgresConnectionImpl(client, this.options);
263
+ }
264
+
265
+ async close(): Promise<void> {
266
+ if (this.#closed) {
267
+ return;
268
+ }
269
+ this.#closed = true;
270
+ await this.pool.end();
271
+ }
272
+
273
+ async acquireClient(): Promise<PoolClient> {
274
+ return this.pool.connect();
275
+ }
276
+
277
+ async releaseClient(client: PoolClient): Promise<void> {
278
+ client.release();
279
+ }
280
+ }
281
+
282
+ class PostgresDirectDriverImpl
283
+ extends PostgresQueryable<Client>
284
+ implements SqlDriver<PostgresBinding>
285
+ {
286
+ private readonly directClient: Client;
287
+ readonly #connectionMutex = new AsyncMutex();
288
+ #closed = false;
289
+ #connected = false;
290
+ #connectPromise: Promise<void> | undefined;
291
+
292
+ constructor(options: PostgresDriverOptions & { connect: { client: Client } }) {
293
+ super({
294
+ cursorBatchSize: options.cursor?.batchSize ?? DEFAULT_BATCH_SIZE,
295
+ cursorDisabled: options.cursor?.disabled ?? false,
296
+ });
297
+ this.directClient = options.connect.client;
298
+ }
299
+
300
+ get state(): SqlDriverState {
301
+ return this.#closed ? 'closed' : 'connected';
302
+ }
303
+
304
+ // Bound drivers are created via createBoundDriverFromBinding with client already
305
+ // configured; connect is intentionally no-op.
306
+ async connect(_binding: PostgresBinding): Promise<void> {}
307
+
308
+ async acquireConnection(): Promise<SqlConnection> {
309
+ const releaseLease = await this.#connectionMutex.lock();
310
+ try {
311
+ const client = await this.acquireClient();
312
+ return new PostgresConnectionImpl(client, this.options, releaseLease);
313
+ } catch (error) {
314
+ releaseLease();
315
+ throw error;
316
+ }
317
+ }
318
+
319
+ async close(): Promise<void> {
320
+ const releaseLease = await this.#connectionMutex.lock();
321
+ try {
322
+ if (this.#closed) {
323
+ return;
324
+ }
325
+ this.#closed = true;
326
+ await this.directClient.end();
327
+ this.#connected = false;
328
+ } finally {
329
+ releaseLease();
330
+ }
331
+ }
332
+
333
+ async acquireClient(): Promise<Client> {
334
+ if (this.#connected) {
335
+ return this.directClient;
336
+ }
337
+ if (this.#connectPromise !== undefined) {
338
+ await this.#connectPromise;
339
+ return this.directClient;
340
+ }
341
+
342
+ this.#connectPromise = (async () => {
343
+ try {
344
+ await this.directClient.connect();
345
+ } catch (error: unknown) {
346
+ if (!isAlreadyConnectedError(error)) {
347
+ throw error;
348
+ }
349
+ } finally {
350
+ this.#connectPromise = undefined;
351
+ }
352
+ this.#connected = true;
353
+ })();
354
+ await this.#connectPromise;
355
+
356
+ return this.directClient;
357
+ }
358
+
359
+ async releaseClient(_client: Client): Promise<void> {}
360
+ }
361
+
362
+ export function createBoundDriverFromBinding(
363
+ binding: PostgresBinding,
364
+ cursorOpts: PostgresDriverCreateOptions['cursor'],
365
+ ): SqlDriver<PostgresBinding> {
366
+ switch (binding.kind) {
367
+ case 'url': {
368
+ const pool = new Pool({
369
+ connectionString: binding.url,
370
+ connectionTimeoutMillis: 20_000,
371
+ idleTimeoutMillis: 30_000,
372
+ });
373
+ return new PostgresPoolDriverImpl({
374
+ connect: { pool },
375
+ cursor: cursorOpts,
376
+ });
377
+ }
378
+ case 'pgPool':
379
+ return new PostgresPoolDriverImpl({
380
+ connect: { pool: binding.pool },
381
+ cursor: cursorOpts,
382
+ });
383
+ case 'pgClient':
384
+ return new PostgresDirectDriverImpl({
385
+ connect: { client: binding.client },
386
+ cursor: cursorOpts,
387
+ });
388
+ }
389
+ }
390
+
391
+ function readCursor<Row>(cursor: Cursor<Row>, size: number): Promise<Row[]> {
392
+ return callbackToPromise<Row[]>((cb) => {
393
+ cursor.read(size, (err, rows) => cb(err, rows));
394
+ });
395
+ }
396
+
397
+ function closeCursor(cursor: Cursor<unknown>): Promise<void> {
398
+ return callbackToPromise((cb) => cursor.close(cb));
399
+ }
400
+
401
+ function rethrowNormalizedError(error: unknown): never {
402
+ throw normalizePgError(error);
403
+ }
@@ -1,116 +0,0 @@
1
- // src/core/descriptor-meta.ts
2
- var postgresDriverDescriptorMeta = {
3
- kind: "driver",
4
- familyId: "sql",
5
- targetId: "postgres",
6
- id: "postgres",
7
- version: "0.0.1",
8
- capabilities: {}
9
- };
10
-
11
- // src/normalize-error.ts
12
- import { SqlConnectionError, SqlQueryError } from "@prisma-next/sql-errors";
13
- function isConnectionError(error) {
14
- const code = error.code;
15
- if (code) {
16
- if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EHOSTUNREACH") {
17
- return true;
18
- }
19
- }
20
- const message = error.message.toLowerCase();
21
- if (message.includes("connection terminated") || message.includes("connection closed") || message.includes("connection refused") || message.includes("connection timeout") || message.includes("connection reset")) {
22
- return true;
23
- }
24
- return false;
25
- }
26
- function isTransientConnectionError(error) {
27
- const code = error.code;
28
- if (code) {
29
- if (code === "ETIMEDOUT" || code === "ECONNRESET") {
30
- return true;
31
- }
32
- if (code === "ECONNREFUSED") {
33
- return false;
34
- }
35
- }
36
- const message = error.message.toLowerCase();
37
- if (message.includes("timeout") || message.includes("connection reset")) {
38
- return true;
39
- }
40
- return false;
41
- }
42
- var PG_ERROR_PROPERTIES = [
43
- "constraint",
44
- "table",
45
- "column",
46
- "hint",
47
- "internalPosition",
48
- "internalQuery",
49
- "where",
50
- "schema",
51
- "routine"
52
- ];
53
- function isPostgresError(error) {
54
- if (!(error instanceof Error)) {
55
- return false;
56
- }
57
- const pgError = error;
58
- if (pgError.code && isPostgresSqlState(pgError.code)) {
59
- return true;
60
- }
61
- return PG_ERROR_PROPERTIES.some((prop) => pgError[prop] !== void 0);
62
- }
63
- function isAlreadyConnectedError(error) {
64
- if (!(error instanceof Error)) {
65
- return false;
66
- }
67
- const message = error.message.toLowerCase();
68
- return message.includes("already") && message.includes("connected");
69
- }
70
- function isPostgresSqlState(code) {
71
- if (!code) {
72
- return false;
73
- }
74
- return /^[A-Z0-9]{5}$/.test(code);
75
- }
76
- function normalizePgError(error) {
77
- if (!(error instanceof Error)) {
78
- return new Error(String(error));
79
- }
80
- const pgError = error;
81
- if (isPostgresSqlState(pgError.code)) {
82
- const sqlState = pgError.code;
83
- const options = {
84
- cause: error,
85
- sqlState
86
- };
87
- if (pgError.constraint !== void 0) {
88
- options.constraint = pgError.constraint;
89
- }
90
- if (pgError.table !== void 0) {
91
- options.table = pgError.table;
92
- }
93
- if (pgError.column !== void 0) {
94
- options.column = pgError.column;
95
- }
96
- if (pgError.detail !== void 0) {
97
- options.detail = pgError.detail;
98
- }
99
- return new SqlQueryError(error.message, options);
100
- }
101
- if (isConnectionError(error)) {
102
- return new SqlConnectionError(error.message, {
103
- cause: error,
104
- transient: isTransientConnectionError(error)
105
- });
106
- }
107
- return error;
108
- }
109
-
110
- export {
111
- postgresDriverDescriptorMeta,
112
- isPostgresError,
113
- isAlreadyConnectedError,
114
- normalizePgError
115
- };
116
- //# sourceMappingURL=chunk-GGJ2L556.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/core/descriptor-meta.ts","../../src/normalize-error.ts"],"sourcesContent":["export const postgresDriverDescriptorMeta = {\n kind: 'driver',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {},\n} as const;\n","import { SqlConnectionError, SqlQueryError } from '@prisma-next/sql-errors';\n\n/**\n * Postgres error shape from the pg library.\n *\n * Note: The pg library doesn't export a DatabaseError type or interface, but errors\n * thrown by pg.query() and pg.Client have this shape at runtime. We define this\n * interface to match the actual runtime structure documented in the pg library\n * (https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/errors.js).\n *\n * The @types/pg package also doesn't provide comprehensive error type definitions,\n * so we define our own interface based on the runtime error properties.\n */\ninterface PostgresError extends Error {\n readonly code?: string;\n readonly constraint?: string;\n readonly table?: string;\n readonly column?: string;\n readonly detail?: string;\n readonly hint?: string;\n readonly position?: string;\n readonly internalPosition?: string;\n readonly internalQuery?: string;\n readonly where?: string;\n readonly schema?: string;\n readonly file?: string;\n readonly line?: string;\n readonly routine?: string;\n}\n\n/**\n * Checks if an error is a connection-related error.\n */\nfunction isConnectionError(error: Error): boolean {\n const code = (error as { code?: string }).code;\n if (code) {\n // Node.js error codes for connection issues\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ECONNREFUSED' ||\n code === 'ENOTFOUND' ||\n code === 'EHOSTUNREACH'\n ) {\n return true;\n }\n }\n\n // Check error message for connection-related strings\n const message = error.message.toLowerCase();\n if (\n message.includes('connection terminated') ||\n message.includes('connection closed') ||\n message.includes('connection refused') ||\n message.includes('connection timeout') ||\n message.includes('connection reset')\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Checks if a connection error is transient (might succeed on retry).\n */\nfunction isTransientConnectionError(error: Error): boolean {\n const code = (error as { code?: string }).code;\n if (code) {\n // Timeouts and connection resets are often transient\n if (code === 'ETIMEDOUT' || code === 'ECONNRESET') {\n return true;\n }\n // Connection refused is usually not transient (server is down)\n if (code === 'ECONNREFUSED') {\n return false;\n }\n }\n\n const message = error.message.toLowerCase();\n if (message.includes('timeout') || message.includes('connection reset')) {\n return true;\n }\n\n return false;\n}\n\n/**\n * PostgreSQL-specific error properties that indicate an error originated from pg library.\n * These properties are not present on Node.js system errors.\n * Excludes generic properties like 'detail', 'file', 'line', and 'position' that could appear on any error.\n */\nconst PG_ERROR_PROPERTIES = [\n 'constraint',\n 'table',\n 'column',\n 'hint',\n 'internalPosition',\n 'internalQuery',\n 'where',\n 'schema',\n 'routine',\n] as const;\n\n/**\n * Type predicate to check if an error is a Postgres error from the pg library.\n *\n * Distinguishes pg library errors from Node.js system errors by checking for:\n * - SQLSTATE codes (5-character alphanumeric codes like '23505', '42601')\n * - pg-specific properties (constraint, table, column, hint, etc.) that Node.js errors don't have\n *\n * Node.js system errors (ECONNREFUSED, ETIMEDOUT, etc.) are excluded to prevent false positives.\n */\nexport function isPostgresError(error: unknown): error is PostgresError {\n if (!(error instanceof Error)) {\n return false;\n }\n\n const pgError = error as PostgresError;\n\n // Check for SQLSTATE code (5-character alphanumeric) - primary indicator of pg errors\n if (pgError.code && isPostgresSqlState(pgError.code)) {\n return true;\n }\n\n // Check for pg-specific properties that Node.js system errors don't have\n // These properties indicate the error originated from pg library query execution\n return PG_ERROR_PROPERTIES.some((prop) => pgError[prop] !== undefined);\n}\n\n/**\n * Checks if an error is an \"already connected\" error from pg.Client.connect().\n * When calling connect() on an already-connected client, pg throws an error that can be safely ignored.\n */\nexport function isAlreadyConnectedError(error: unknown): error is Error {\n if (!(error instanceof Error)) {\n return false;\n }\n const message = error.message.toLowerCase();\n return message.includes('already') && message.includes('connected');\n}\n\n/**\n * Checks if an error code is a Postgres SQLSTATE (5-character alphanumeric code).\n * SQLSTATE codes are standardized SQL error codes (e.g., '23505' for unique violation).\n */\nfunction isPostgresSqlState(code: string | undefined): boolean {\n if (!code) {\n return false;\n }\n // Postgres SQLSTATE codes are 5-character alphanumeric strings\n // Examples: '23505' (unique violation), '42501' (insufficient privilege), '42601' (syntax error)\n return /^[A-Z0-9]{5}$/.test(code);\n}\n\n/**\n * Normalizes a Postgres error into a SQL-shared error type.\n *\n * - Postgres SQLSTATE errors (5-char codes like '23505') → SqlQueryError\n * - Connection errors (ECONNRESET, ETIMEDOUT, etc.) → SqlConnectionError\n * - Unknown errors → returns the original error as-is\n *\n * The original error is preserved via Error.cause to maintain stack traces.\n *\n * @param error - The error to normalize (typically from pg library)\n * @returns SqlQueryError for query-related failures\n * @returns SqlConnectionError for connection-related failures\n * @returns The original error if it cannot be normalized\n */\nexport function normalizePgError(error: unknown): SqlQueryError | SqlConnectionError | Error {\n if (!(error instanceof Error)) {\n // Wrap non-Error values in an Error object\n return new Error(String(error));\n }\n\n const pgError = error as PostgresError;\n\n // Check for Postgres SQLSTATE (query errors)\n if (isPostgresSqlState(pgError.code)) {\n // isPostgresSqlState ensures code is defined and is a valid SQLSTATE\n // biome-ignore lint/style/noNonNullAssertion: isPostgresSqlState guarantees code is defined\n const sqlState = pgError.code!;\n const options: {\n cause: Error;\n sqlState: string;\n constraint?: string;\n table?: string;\n column?: string;\n detail?: string;\n } = {\n cause: error,\n sqlState,\n };\n if (pgError.constraint !== undefined) {\n options.constraint = pgError.constraint;\n }\n if (pgError.table !== undefined) {\n options.table = pgError.table;\n }\n if (pgError.column !== undefined) {\n options.column = pgError.column;\n }\n if (pgError.detail !== undefined) {\n options.detail = pgError.detail;\n }\n return new SqlQueryError(error.message, options);\n }\n\n // Check for connection errors\n if (isConnectionError(error)) {\n return new SqlConnectionError(error.message, {\n cause: error,\n transient: isTransientConnectionError(error),\n });\n }\n\n // Unknown error - return as-is to preserve original error and stack trace\n return error;\n}\n"],"mappings":";AAAO,IAAM,+BAA+B;AAAA,EAC1C,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,cAAc,CAAC;AACjB;;;ACPA,SAAS,oBAAoB,qBAAqB;AAiClD,SAAS,kBAAkB,OAAuB;AAChD,QAAM,OAAQ,MAA4B;AAC1C,MAAI,MAAM;AAER,QACE,SAAS,gBACT,SAAS,eACT,SAAS,kBACT,SAAS,eACT,SAAS,gBACT;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAGA,QAAM,UAAU,MAAM,QAAQ,YAAY;AAC1C,MACE,QAAQ,SAAS,uBAAuB,KACxC,QAAQ,SAAS,mBAAmB,KACpC,QAAQ,SAAS,oBAAoB,KACrC,QAAQ,SAAS,oBAAoB,KACrC,QAAQ,SAAS,kBAAkB,GACnC;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAKA,SAAS,2BAA2B,OAAuB;AACzD,QAAM,OAAQ,MAA4B;AAC1C,MAAI,MAAM;AAER,QAAI,SAAS,eAAe,SAAS,cAAc;AACjD,aAAO;AAAA,IACT;AAEA,QAAI,SAAS,gBAAgB;AAC3B,aAAO;AAAA,IACT;AAAA,EACF;AAEA,QAAM,UAAU,MAAM,QAAQ,YAAY;AAC1C,MAAI,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS,kBAAkB,GAAG;AACvE,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAOA,IAAM,sBAAsB;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAWO,SAAS,gBAAgB,OAAwC;AACtE,MAAI,EAAE,iBAAiB,QAAQ;AAC7B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU;AAGhB,MAAI,QAAQ,QAAQ,mBAAmB,QAAQ,IAAI,GAAG;AACpD,WAAO;AAAA,EACT;AAIA,SAAO,oBAAoB,KAAK,CAAC,SAAS,QAAQ,IAAI,MAAM,MAAS;AACvE;AAMO,SAAS,wBAAwB,OAAgC;AACtE,MAAI,EAAE,iBAAiB,QAAQ;AAC7B,WAAO;AAAA,EACT;AACA,QAAM,UAAU,MAAM,QAAQ,YAAY;AAC1C,SAAO,QAAQ,SAAS,SAAS,KAAK,QAAQ,SAAS,WAAW;AACpE;AAMA,SAAS,mBAAmB,MAAmC;AAC7D,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,EACT;AAGA,SAAO,gBAAgB,KAAK,IAAI;AAClC;AAgBO,SAAS,iBAAiB,OAA4D;AAC3F,MAAI,EAAE,iBAAiB,QAAQ;AAE7B,WAAO,IAAI,MAAM,OAAO,KAAK,CAAC;AAAA,EAChC;AAEA,QAAM,UAAU;AAGhB,MAAI,mBAAmB,QAAQ,IAAI,GAAG;AAGpC,UAAM,WAAW,QAAQ;AACzB,UAAM,UAOF;AAAA,MACF,OAAO;AAAA,MACP;AAAA,IACF;AACA,QAAI,QAAQ,eAAe,QAAW;AACpC,cAAQ,aAAa,QAAQ;AAAA,IAC/B;AACA,QAAI,QAAQ,UAAU,QAAW;AAC/B,cAAQ,QAAQ,QAAQ;AAAA,IAC1B;AACA,QAAI,QAAQ,WAAW,QAAW;AAChC,cAAQ,SAAS,QAAQ;AAAA,IAC3B;AACA,QAAI,QAAQ,WAAW,QAAW;AAChC,cAAQ,SAAS,QAAQ;AAAA,IAC3B;AACA,WAAO,IAAI,cAAc,MAAM,SAAS,OAAO;AAAA,EACjD;AAGA,MAAI,kBAAkB,KAAK,GAAG;AAC5B,WAAO,IAAI,mBAAmB,MAAM,SAAS;AAAA,MAC3C,OAAO;AAAA,MACP,WAAW,2BAA2B,KAAK;AAAA,IAC7C,CAAC;AAAA,EACH;AAGA,SAAO;AACT;","names":[]}
@@ -1,27 +0,0 @@
1
- import { ControlDriverDescriptor, ControlDriverInstance } from '@prisma-next/core-control-plane/types';
2
- import { Client } from 'pg';
3
-
4
- /**
5
- * Postgres control driver instance for control-plane operations.
6
- * Implements ControlDriverInstance<'sql', 'postgres'> for database queries.
7
- */
8
- declare class PostgresControlDriver implements ControlDriverInstance<'sql', 'postgres'> {
9
- private readonly client;
10
- readonly familyId: "sql";
11
- readonly targetId: "postgres";
12
- /**
13
- * @deprecated Use targetId instead
14
- */
15
- readonly target: "postgres";
16
- constructor(client: Client);
17
- query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{
18
- readonly rows: Row[];
19
- }>;
20
- close(): Promise<void>;
21
- }
22
- /**
23
- * Postgres driver descriptor for CLI config.
24
- */
25
- declare const postgresDriverDescriptor: ControlDriverDescriptor<'sql', 'postgres', PostgresControlDriver>;
26
-
27
- export { PostgresControlDriver, postgresDriverDescriptor as default };
@@ -1,66 +0,0 @@
1
- import {
2
- normalizePgError,
3
- postgresDriverDescriptorMeta
4
- } from "./chunk-GGJ2L556.js";
5
-
6
- // src/exports/control.ts
7
- import { errorRuntime } from "@prisma-next/core-control-plane/errors";
8
- import { SqlQueryError } from "@prisma-next/sql-errors";
9
- import { redactDatabaseUrl } from "@prisma-next/utils/redact-db-url";
10
- import { Client } from "pg";
11
- var PostgresControlDriver = class {
12
- constructor(client) {
13
- this.client = client;
14
- }
15
- familyId = "sql";
16
- targetId = "postgres";
17
- /**
18
- * @deprecated Use targetId instead
19
- */
20
- target = "postgres";
21
- async query(sql, params) {
22
- try {
23
- const result = await this.client.query(sql, params);
24
- return { rows: result.rows };
25
- } catch (error) {
26
- throw normalizePgError(error);
27
- }
28
- }
29
- async close() {
30
- await this.client.end();
31
- }
32
- };
33
- var postgresDriverDescriptor = {
34
- ...postgresDriverDescriptorMeta,
35
- async create(url) {
36
- const client = new Client({ connectionString: url });
37
- try {
38
- await client.connect();
39
- return new PostgresControlDriver(client);
40
- } catch (error) {
41
- const normalized = normalizePgError(error);
42
- const redacted = redactDatabaseUrl(url);
43
- try {
44
- await client.end();
45
- } catch {
46
- }
47
- const codeFromSqlState = SqlQueryError.is(normalized) ? normalized.sqlState : void 0;
48
- const causeCode = "cause" in normalized && normalized.cause ? normalized.cause.code : void 0;
49
- const code = codeFromSqlState ?? causeCode;
50
- throw errorRuntime("Database connection failed", {
51
- why: normalized.message,
52
- fix: "Verify the database URL, ensure the database is reachable, and confirm credentials/permissions",
53
- meta: {
54
- ...typeof code !== "undefined" ? { code } : {},
55
- ...redacted
56
- }
57
- });
58
- }
59
- }
60
- };
61
- var control_default = postgresDriverDescriptor;
62
- export {
63
- PostgresControlDriver,
64
- control_default as default
65
- };
66
- //# sourceMappingURL=control.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/exports/control.ts"],"sourcesContent":["import { errorRuntime } from '@prisma-next/core-control-plane/errors';\nimport type {\n ControlDriverDescriptor,\n ControlDriverInstance,\n} from '@prisma-next/core-control-plane/types';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { redactDatabaseUrl } from '@prisma-next/utils/redact-db-url';\nimport { Client } from 'pg';\nimport { postgresDriverDescriptorMeta } from '../core/descriptor-meta';\nimport { normalizePgError } from '../normalize-error';\n\n/**\n * Postgres control driver instance for control-plane operations.\n * Implements ControlDriverInstance<'sql', 'postgres'> for database queries.\n */\nexport class PostgresControlDriver implements ControlDriverInstance<'sql', 'postgres'> {\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n /**\n * @deprecated Use targetId instead\n */\n readonly target = 'postgres' as const;\n\n constructor(private readonly client: Client) {}\n\n async query<Row = Record<string, unknown>>(\n sql: string,\n params?: readonly unknown[],\n ): Promise<{ readonly rows: Row[] }> {\n try {\n const result = await this.client.query(sql, params as unknown[] | undefined);\n return { rows: result.rows as Row[] };\n } catch (error) {\n throw normalizePgError(error);\n }\n }\n\n async close(): Promise<void> {\n await this.client.end();\n }\n}\n\n/**\n * Postgres driver descriptor for CLI config.\n */\nconst postgresDriverDescriptor: ControlDriverDescriptor<'sql', 'postgres', PostgresControlDriver> =\n {\n ...postgresDriverDescriptorMeta,\n async create(url: string): Promise<PostgresControlDriver> {\n const client = new Client({ connectionString: url });\n try {\n await client.connect();\n return new PostgresControlDriver(client);\n } catch (error) {\n const normalized = normalizePgError(error);\n const redacted = redactDatabaseUrl(url);\n try {\n await client.end();\n } catch {\n // ignore\n }\n\n const codeFromSqlState = SqlQueryError.is(normalized) ? normalized.sqlState : undefined;\n const causeCode =\n 'cause' in normalized && normalized.cause\n ? (normalized.cause as { code?: unknown }).code\n : undefined;\n const code = codeFromSqlState ?? causeCode;\n\n throw errorRuntime('Database connection failed', {\n why: normalized.message,\n fix: 'Verify the database URL, ensure the database is reachable, and confirm credentials/permissions',\n meta: {\n ...(typeof code !== 'undefined' ? { code } : {}),\n ...redacted,\n },\n });\n }\n },\n };\n\nexport default postgresDriverDescriptor;\n"],"mappings":";;;;;;AAAA,SAAS,oBAAoB;AAK7B,SAAS,qBAAqB;AAC9B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AAQhB,IAAM,wBAAN,MAAgF;AAAA,EAQrF,YAA6B,QAAgB;AAAhB;AAAA,EAAiB;AAAA,EAPrC,WAAW;AAAA,EACX,WAAW;AAAA;AAAA;AAAA;AAAA,EAIX,SAAS;AAAA,EAIlB,MAAM,MACJ,KACA,QACmC;AACnC,QAAI;AACF,YAAM,SAAS,MAAM,KAAK,OAAO,MAAM,KAAK,MAA+B;AAC3E,aAAO,EAAE,MAAM,OAAO,KAAc;AAAA,IACtC,SAAS,OAAO;AACd,YAAM,iBAAiB,KAAK;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,QAAuB;AAC3B,UAAM,KAAK,OAAO,IAAI;AAAA,EACxB;AACF;AAKA,IAAM,2BACJ;AAAA,EACE,GAAG;AAAA,EACH,MAAM,OAAO,KAA6C;AACxD,UAAM,SAAS,IAAI,OAAO,EAAE,kBAAkB,IAAI,CAAC;AACnD,QAAI;AACF,YAAM,OAAO,QAAQ;AACrB,aAAO,IAAI,sBAAsB,MAAM;AAAA,IACzC,SAAS,OAAO;AACd,YAAM,aAAa,iBAAiB,KAAK;AACzC,YAAM,WAAW,kBAAkB,GAAG;AACtC,UAAI;AACF,cAAM,OAAO,IAAI;AAAA,MACnB,QAAQ;AAAA,MAER;AAEA,YAAM,mBAAmB,cAAc,GAAG,UAAU,IAAI,WAAW,WAAW;AAC9E,YAAM,YACJ,WAAW,cAAc,WAAW,QAC/B,WAAW,MAA6B,OACzC;AACN,YAAM,OAAO,oBAAoB;AAEjC,YAAM,aAAa,8BAA8B;AAAA,QAC/C,KAAK,WAAW;AAAA,QAChB,KAAK;AAAA,QACL,MAAM;AAAA,UACJ,GAAI,OAAO,SAAS,cAAc,EAAE,KAAK,IAAI,CAAC;AAAA,UAC9C,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEF,IAAO,kBAAQ;","names":[]}
@@ -1,36 +0,0 @@
1
- import { RuntimeDriverDescriptor, RuntimeDriverInstance } from '@prisma-next/core-execution-plane/types';
2
- import { SqlDriver } from '@prisma-next/sql-relational-core/ast';
3
- import { Client, Pool, QueryResultRow, QueryResult as QueryResult$1 } from 'pg';
4
-
5
- type QueryResult<T extends QueryResultRow = QueryResultRow> = QueryResult$1<T>;
6
- interface PostgresDriverOptions {
7
- readonly connect: {
8
- client: Client;
9
- } | {
10
- pool: Pool;
11
- };
12
- readonly cursor?: {
13
- readonly batchSize?: number;
14
- readonly disabled?: boolean;
15
- } | undefined;
16
- }
17
- interface CreatePostgresDriverOptions {
18
- readonly cursor?: PostgresDriverOptions['cursor'];
19
- readonly poolFactory?: typeof Pool;
20
- }
21
- declare function createPostgresDriver(connectionString: string, options?: CreatePostgresDriverOptions): SqlDriver;
22
- declare function createPostgresDriverFromOptions(options: PostgresDriverOptions): SqlDriver;
23
-
24
- /**
25
- * Postgres runtime driver instance interface.
26
- * SqlDriver provides SQL-specific methods (execute, explain, close).
27
- * RuntimeDriverInstance provides target identification (familyId, targetId).
28
- * We use intersection type to combine both interfaces.
29
- */
30
- type PostgresRuntimeDriver = RuntimeDriverInstance<'sql', 'postgres'> & SqlDriver;
31
- /**
32
- * Postgres driver descriptor for runtime plane.
33
- */
34
- declare const postgresRuntimeDriverDescriptor: RuntimeDriverDescriptor<'sql', 'postgres', PostgresRuntimeDriver>;
35
-
36
- export { type CreatePostgresDriverOptions, type PostgresDriverOptions, type PostgresRuntimeDriver, type QueryResult, createPostgresDriver, createPostgresDriverFromOptions, postgresRuntimeDriverDescriptor as default };