@prisma-next/driver-postgres 0.3.0-dev.6 → 0.3.0-dev.64

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.
@@ -1,8 +1,12 @@
1
1
  import type {
2
+ SqlConnection,
2
3
  SqlDriver,
4
+ SqlDriverState,
3
5
  SqlExecuteRequest,
4
6
  SqlExplainResult,
7
+ SqlQueryable,
5
8
  SqlQueryResult,
9
+ SqlTransaction,
6
10
  } from '@prisma-next/sql-relational-core/ast';
7
11
  import type {
8
12
  Client,
@@ -18,47 +22,69 @@ import { isAlreadyConnectedError, isPostgresError, normalizePgError } from './no
18
22
 
19
23
  export type QueryResult<T extends QueryResultRow = QueryResultRow> = PgQueryResult<T>;
20
24
 
21
- export interface PostgresDriverOptions {
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 {
22
36
  readonly connect: { client: Client } | { pool: PoolType };
23
- readonly cursor?:
24
- | {
25
- readonly batchSize?: number;
26
- readonly disabled?: boolean;
27
- }
28
- | undefined;
37
+ readonly cursor?: PostgresCursorOptions | undefined;
29
38
  }
30
39
 
40
+ export type PostgresDriverCreateOptions = Omit<PostgresDriverOptions, 'connect'>;
41
+
31
42
  const DEFAULT_BATCH_SIZE = 100;
32
43
 
33
- class PostgresDriverImpl implements SqlDriver {
34
- private readonly pool: PoolType | undefined;
35
- private readonly directClient: Client | undefined;
36
- private readonly cursorBatchSize: number;
37
- private readonly cursorDisabled: boolean;
38
-
39
- constructor(options: PostgresDriverOptions) {
40
- if ('client' in options.connect) {
41
- this.directClient = options.connect.client;
42
- } else if ('pool' in options.connect) {
43
- this.pool = options.connect.pool;
44
- } else {
45
- throw new Error('PostgresDriver requires a pool or client');
46
- }
44
+ type ConnectionOptions =
45
+ | { readonly cursorDisabled: true }
46
+ | { readonly cursorBatchSize: number; readonly cursorDisabled: false };
47
+
48
+ class AsyncMutex {
49
+ #queue = Promise.resolve();
47
50
 
48
- this.cursorBatchSize = options.cursor?.batchSize ?? DEFAULT_BATCH_SIZE;
49
- this.cursorDisabled = options.cursor?.disabled ?? false;
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
+ };
50
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>;
51
70
 
52
- async connect(): Promise<void> {
53
- // No-op: caller controls connecting the underlying client or pool
71
+ protected readonly options: ConnectionOptions;
72
+
73
+ constructor(options: ConnectionOptions) {
74
+ this.options = options;
54
75
  }
55
76
 
56
77
  async *execute<Row = Record<string, unknown>>(request: SqlExecuteRequest): AsyncIterable<Row> {
57
78
  const client = await this.acquireClient();
58
79
  try {
59
- if (!this.cursorDisabled) {
80
+ if (!this.options.cursorDisabled) {
60
81
  try {
61
- for await (const row of this.executeWithCursor(client, request.sql, request.params)) {
82
+ for await (const row of this.executeWithCursor(
83
+ client,
84
+ request.sql,
85
+ request.params,
86
+ this.options.cursorBatchSize,
87
+ )) {
62
88
  yield row as Row;
63
89
  }
64
90
  return;
@@ -86,13 +112,15 @@ class PostgresDriverImpl implements SqlDriver {
86
112
  }
87
113
 
88
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.
89
117
  const text = `EXPLAIN (FORMAT JSON) ${request.sql}`;
90
118
  const client = await this.acquireClient();
91
119
  try {
92
- const result = await client.query(text, request.params as unknown[] | undefined);
120
+ const result = await client
121
+ .query(text, request.params as unknown[] | undefined)
122
+ .catch(rethrowNormalizedError);
93
123
  return { rows: result.rows as ReadonlyArray<Record<string, unknown>> };
94
- } catch (error) {
95
- throw normalizePgError(error);
96
124
  } finally {
97
125
  await this.releaseClient(client);
98
126
  }
@@ -104,80 +132,26 @@ class PostgresDriverImpl implements SqlDriver {
104
132
  ): Promise<SqlQueryResult<Row>> {
105
133
  const client = await this.acquireClient();
106
134
  try {
107
- const result = await client.query(sql, params as unknown[] | undefined);
135
+ const result = await client
136
+ .query(sql, params as unknown[] | undefined)
137
+ .catch(rethrowNormalizedError);
108
138
  return result as unknown as SqlQueryResult<Row>;
109
- } catch (error) {
110
- throw normalizePgError(error);
111
139
  } finally {
112
140
  await this.releaseClient(client);
113
141
  }
114
142
  }
115
143
 
116
- async close(): Promise<void> {
117
- if (this.pool) {
118
- // Check if pool is already closed to avoid "Called end on pool more than once" error
119
- // pg Pool has an 'ended' property that indicates if the pool has been closed
120
- if (!(this.pool as { ended?: boolean }).ended) {
121
- await this.pool.end();
122
- }
123
- }
124
- if (this.directClient) {
125
- const client = this.directClient as Client & { _ending?: boolean };
126
- if (!client._ending) {
127
- await client.end();
128
- }
129
- }
130
- }
131
-
132
- private async acquireClient(): Promise<PoolClient | Client> {
133
- if (this.pool) {
134
- return this.pool.connect();
135
- }
136
- if (this.directClient) {
137
- // Check if client is already connected before attempting to connect
138
- // This prevents hanging when the database only supports a single connection
139
- // pg's Client has internal connection state that we can check
140
- const client = this.directClient as Client & {
141
- _ending?: boolean;
142
- _connection?: unknown;
143
- };
144
- const isConnected =
145
- client._connection !== undefined && client._connection !== null && !client._ending;
146
-
147
- // Only connect if not already connected
148
- // If caller provided a connected client (e.g., in tests), use it as-is
149
- if (!isConnected) {
150
- try {
151
- await this.directClient.connect();
152
- } catch (error: unknown) {
153
- // If already connected, pg throws an error - ignore it and proceed
154
- // Re-throw other errors (actual connection failures)
155
- if (!isAlreadyConnectedError(error)) {
156
- throw error;
157
- }
158
- }
159
- }
160
- return this.directClient;
161
- }
162
- throw new Error('PostgresDriver requires a pool or client');
163
- }
164
-
165
- private async releaseClient(client: PoolClient | Client): Promise<void> {
166
- if (this.pool) {
167
- (client as PoolClient).release();
168
- }
169
- }
170
-
171
144
  private async *executeWithCursor(
172
145
  client: PoolClient | Client,
173
146
  sql: string,
174
147
  params: readonly unknown[] | undefined,
148
+ cursorBatchSize: number,
175
149
  ): AsyncIterable<Record<string, unknown>> {
176
150
  const cursor = client.query(new Cursor(sql, params as unknown[] | undefined));
177
151
 
178
152
  try {
179
153
  while (true) {
180
- const rows = await readCursor(cursor, this.cursorBatchSize);
154
+ const rows = await readCursor(cursor, cursorBatchSize);
181
155
  if (rows.length === 0) {
182
156
  break;
183
157
  }
@@ -203,25 +177,215 @@ class PostgresDriverImpl implements SqlDriver {
203
177
  }
204
178
  }
205
179
 
206
- export interface CreatePostgresDriverOptions {
207
- readonly cursor?: PostgresDriverOptions['cursor'];
208
- readonly poolFactory?: typeof Pool;
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
+ }
209
210
  }
210
211
 
211
- export function createPostgresDriver(
212
- connectionString: string,
213
- options?: CreatePostgresDriverOptions,
214
- ): SqlDriver {
215
- const PoolImpl: typeof Pool = options?.poolFactory ?? Pool;
216
- const pool = new PoolImpl({ connectionString });
217
- return new PostgresDriverImpl({
218
- connect: { pool },
219
- cursor: options?.cursor,
220
- });
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
+ }
221
235
  }
222
236
 
223
- export function createPostgresDriverFromOptions(options: PostgresDriverOptions): SqlDriver {
224
- return new PostgresDriverImpl(options);
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
+ }
225
389
  }
226
390
 
227
391
  function readCursor<Row>(cursor: Cursor<Row>, size: number): Promise<Row[]> {
@@ -233,3 +397,7 @@ function readCursor<Row>(cursor: Cursor<Row>, size: number): Promise<Row[]> {
233
397
  function closeCursor(cursor: Cursor<unknown>): Promise<void> {
234
398
  return callbackToPromise((cb) => cursor.close(cb));
235
399
  }
400
+
401
+ function rethrowNormalizedError(error: unknown): never {
402
+ throw normalizePgError(error);
403
+ }
@@ -1,7 +0,0 @@
1
- /**
2
- * Wraps a Node-style callback function into a Promise.
3
- * Supports both (err) => void and (err, result) => void patterns.
4
- */
5
- export declare function callbackToPromise(fn: (callback: (err: Error | null | undefined) => void) => void): Promise<void>;
6
- export declare function callbackToPromise<T>(fn: (callback: (err: Error | null | undefined, result: T) => void) => void): Promise<T>;
7
- //# sourceMappingURL=callback-to-promise.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"callback-to-promise.d.ts","sourceRoot":"","sources":["../src/callback-to-promise.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,GAAG,SAAS,KAAK,IAAI,KAAK,IAAI,GAC9D,OAAO,CAAC,IAAI,CAAC,CAAC;AACjB,wBAAgB,iBAAiB,CAAC,CAAC,EACjC,EAAE,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,GAAG,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,CAAC,KAAK,IAAI,KAAK,IAAI,GACzE,OAAO,CAAC,CAAC,CAAC,CAAC"}
@@ -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-M4WUUVS5.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,9 +0,0 @@
1
- export declare const postgresDriverDescriptorMeta: {
2
- readonly kind: "driver";
3
- readonly familyId: "sql";
4
- readonly targetId: "postgres";
5
- readonly id: "postgres";
6
- readonly version: "0.0.1";
7
- readonly capabilities: {};
8
- };
9
- //# sourceMappingURL=descriptor-meta.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"descriptor-meta.d.ts","sourceRoot":"","sources":["../../src/core/descriptor-meta.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,4BAA4B;;;;;;;CAO/B,CAAC"}
@@ -1,26 +0,0 @@
1
- import type { ControlDriverDescriptor, ControlDriverInstance } from '@prisma-next/core-control-plane/types';
2
- import { Client } from 'pg';
3
- /**
4
- * Postgres control driver instance for control-plane operations.
5
- * Implements ControlDriverInstance<'sql', 'postgres'> for database queries.
6
- */
7
- export declare class PostgresControlDriver implements ControlDriverInstance<'sql', 'postgres'> {
8
- private readonly client;
9
- readonly familyId: "sql";
10
- readonly targetId: "postgres";
11
- /**
12
- * @deprecated Use targetId instead
13
- */
14
- readonly target: "postgres";
15
- constructor(client: Client);
16
- query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{
17
- readonly rows: Row[];
18
- }>;
19
- close(): Promise<void>;
20
- }
21
- /**
22
- * Postgres driver descriptor for CLI config.
23
- */
24
- declare const postgresDriverDescriptor: ControlDriverDescriptor<'sql', 'postgres', PostgresControlDriver>;
25
- export default postgresDriverDescriptor;
26
- //# sourceMappingURL=control.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"control.d.ts","sourceRoot":"","sources":["../../src/exports/control.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,uBAAuB,EACvB,qBAAqB,EACtB,MAAM,uCAAuC,CAAC;AAG/C,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AAI5B;;;GAGG;AACH,qBAAa,qBAAsB,YAAW,qBAAqB,CAAC,KAAK,EAAE,UAAU,CAAC;IAQxE,OAAO,CAAC,QAAQ,CAAC,MAAM;IAPnC,QAAQ,CAAC,QAAQ,EAAG,KAAK,CAAU;IACnC,QAAQ,CAAC,QAAQ,EAAG,UAAU,CAAU;IACxC;;OAEG;IACH,QAAQ,CAAC,MAAM,EAAG,UAAU,CAAU;gBAET,MAAM,EAAE,MAAM;IAErC,KAAK,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACvC,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAC1B,OAAO,CAAC;QAAE,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,CAAA;KAAE,CAAC;IAS9B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAG7B;AAED;;GAEG;AACH,QAAA,MAAM,wBAAwB,EAAE,uBAAuB,CAAC,KAAK,EAAE,UAAU,EAAE,qBAAqB,CAkC7F,CAAC;AAEJ,eAAe,wBAAwB,CAAC"}