@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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ PostgreSQL driver for Prisma Next.
12
12
 
13
13
  The PostgreSQL driver provides transport and connection management for PostgreSQL databases. It implements the `SqlDriver` interface for executing SQL statements, explaining queries, and managing connections.
14
14
 
15
- Drivers are transport-agnostic: they own pooling, connection management, and transport protocol (TCP, HTTP, etc.), but contain no dialect-specific logic. All dialect behavior lives in adapters.
15
+ In Prisma Next, "driver" refers to the Prisma Next interface (not the underlying `pg` library). Drivers are transport-agnostic: they own pooling, connection management, and transport protocol (TCP, HTTP, etc.), but contain no dialect-specific logic. All dialect behavior lives in adapters. Instantiation is separate from connection; `create()` returns an unbound driver, `connect(binding)` binds at the boundary ([ADR 159](../../../../docs/architecture%20docs/adrs/ADR%20159%20-%20Driver%20Terminology%20and%20Lifecycle.md)).
16
16
 
17
17
  This package spans multiple planes:
18
18
  - **Migration plane** (`src/exports/control.ts`): Control plane entry point for driver descriptors
@@ -74,7 +74,7 @@ flowchart TD
74
74
 
75
75
  ## Dependencies
76
76
 
77
- - **`@prisma-next/sql-target`**: Driver SPI and SQL types
77
+ - **`@prisma-next/sql-contract`**: SQL contract types (via `@prisma-next/sql-contract/types`)
78
78
 
79
79
  ## Related Subsystems
80
80
 
@@ -82,32 +82,32 @@ flowchart TD
82
82
 
83
83
  ## Related ADRs
84
84
 
85
- - [ADR 005 - Thin Core Fat Targets](../../docs/architecture%20docs/adrs/ADR%20005%20-%20Thin%20Core%20Fat%20Targets.md)
86
- - [ADR 016 - Adapter SPI for Lowering](../../docs/architecture%20docs/adrs/ADR%20016%20-%20Adapter%20SPI%20for%20Lowering.md)
85
+ - [ADR 159 Driver Terminology and Lifecycle](../../../../docs/architecture%20docs/adrs/ADR%20159%20-%20Driver%20Terminology%20and%20Lifecycle.md)
86
+ - [ADR 005 Thin Core Fat Targets](../../../../docs/architecture%20docs/adrs/ADR%20005%20-%20Thin%20Core%20Fat%20Targets.md)
87
+ - [ADR 016 — Adapter SPI for Lowering](../../../../docs/architecture%20docs/adrs/ADR%20016%20-%20Adapter%20SPI%20for%20Lowering.md)
87
88
 
88
89
  ## Usage
89
90
 
91
+ Use the descriptor + connect lifecycle:
92
+
90
93
  ```typescript
91
- import { createPostgresDriver } from '@prisma-next/driver-postgres/runtime';
92
- import { createRuntime } from '@prisma-next/sql-runtime';
93
-
94
- const driver = createPostgresDriver({
95
- connectionString: process.env.DATABASE_URL,
96
- });
97
-
98
- const runtime = createRuntime({
99
- contract,
100
- adapter: postgresAdapter,
101
- driver,
102
- });
94
+ import postgresDriver from '@prisma-next/driver-postgres/runtime';
95
+
96
+ const driver = postgresDriver.create({ cursor: { batchSize: 100 } });
97
+ await driver.connect({ kind: 'url', url: process.env.DATABASE_URL });
98
+ // driver is now bound; use acquireConnection, query, execute, etc.
103
99
  ```
104
100
 
101
+ Binding variants:
102
+ - `{ kind: 'url', url }`: Driver creates a Pool from the connection string
103
+ - `{ kind: 'pgPool', pool }`: Use an existing pg Pool
104
+ - `{ kind: 'pgClient', client }`: Use an existing pg Client (direct connection)
105
+
105
106
  ## Exports
106
107
 
107
108
  - `./runtime`: Runtime entry point for driver implementation
108
- - `createPostgresDriver(connectionString, options?)`: Create driver from connection string
109
- - `createPostgresDriverFromOptions(options)`: Create driver from options object
110
- - Types: `PostgresDriverOptions`, `QueryResult`
109
+ - Default: `postgresRuntimeDriverDescriptor` — use `create()` for unbound driver, then `connect(binding)`
110
+ - Types: `PostgresBinding`, `PostgresDriverCreateOptions`, `QueryResult`
111
111
  - `./control`: Control plane entry point for driver descriptors
112
112
  - Default export: `DriverDescriptor` for use in `prisma-next.config.ts`
113
113
 
@@ -0,0 +1,30 @@
1
+ import { Client } from "pg";
2
+ import { ControlDriverDescriptor, ControlDriverInstance } from "@prisma-next/core-control-plane/types";
3
+
4
+ //#region src/exports/control.d.ts
5
+
6
+ /**
7
+ * Postgres control driver instance for control-plane operations.
8
+ * Implements ControlDriverInstance<'sql', 'postgres'> for database queries.
9
+ */
10
+ declare class PostgresControlDriver implements ControlDriverInstance<'sql', 'postgres'> {
11
+ private readonly client;
12
+ readonly familyId: "sql";
13
+ readonly targetId: "postgres";
14
+ /**
15
+ * @deprecated Use targetId instead
16
+ */
17
+ readonly target: "postgres";
18
+ constructor(client: Client);
19
+ query<Row = Record<string, unknown>>(sql: string, params?: readonly unknown[]): Promise<{
20
+ readonly rows: Row[];
21
+ }>;
22
+ close(): Promise<void>;
23
+ }
24
+ /**
25
+ * Postgres driver descriptor for CLI config.
26
+ */
27
+ declare const postgresDriverDescriptor: ControlDriverDescriptor<'sql', 'postgres', PostgresControlDriver>;
28
+ //#endregion
29
+ export { PostgresControlDriver, postgresDriverDescriptor as default };
30
+ //# sourceMappingURL=control.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control.d.mts","names":[],"sources":["../src/exports/control.ts"],"sourcesContent":[],"mappings":";;;;;;;AAgBA;;AAUoB,cAVP,qBAAA,YAAiC,qBAU1B,CAAA,KAAA,EAAA,UAAA,CAAA,CAAA;EAGU,iBAAA,MAAA;EAAzB,SAAA,QAAA,EAAA,KAAA;EASY,SAAA,QAAA,EAAA,UAAA;EAtB6B;;AAyB7C;;sBAjBsC;cAEnB,oEAGf;mBAAyB;;WASb;;;;;cAQX,0BAA0B,2CAA2C"}
@@ -0,0 +1,68 @@
1
+ import { i as postgresDriverDescriptorMeta, r as normalizePgError } from "./normalize-error-BU6yV-XB.mjs";
2
+ import { errorRuntime } from "@prisma-next/core-control-plane/errors";
3
+ import { SqlQueryError } from "@prisma-next/sql-errors";
4
+ import { ifDefined } from "@prisma-next/utils/defined";
5
+ import { redactDatabaseUrl } from "@prisma-next/utils/redact-db-url";
6
+ import { Client } from "pg";
7
+
8
+ //#region src/exports/control.ts
9
+ /**
10
+ * Postgres control driver instance for control-plane operations.
11
+ * Implements ControlDriverInstance<'sql', 'postgres'> for database queries.
12
+ */
13
+ var PostgresControlDriver = class {
14
+ familyId = "sql";
15
+ targetId = "postgres";
16
+ /**
17
+ * @deprecated Use targetId instead
18
+ */
19
+ target = "postgres";
20
+ constructor(client) {
21
+ this.client = client;
22
+ }
23
+ async query(sql, params) {
24
+ try {
25
+ return { rows: (await this.client.query(sql, params)).rows };
26
+ } catch (error) {
27
+ throw normalizePgError(error);
28
+ }
29
+ }
30
+ async close() {
31
+ await this.client.end();
32
+ }
33
+ };
34
+ /**
35
+ * Postgres driver descriptor for CLI config.
36
+ */
37
+ const postgresDriverDescriptor = {
38
+ ...postgresDriverDescriptorMeta,
39
+ async create(url) {
40
+ const client = new Client({ connectionString: url });
41
+ try {
42
+ await client.connect();
43
+ return new PostgresControlDriver(client);
44
+ } catch (error) {
45
+ const normalized = normalizePgError(error);
46
+ const redacted = redactDatabaseUrl(url);
47
+ try {
48
+ await client.end();
49
+ } catch {}
50
+ const codeFromSqlState = SqlQueryError.is(normalized) ? normalized.sqlState : void 0;
51
+ const causeCode = "cause" in normalized && normalized.cause ? normalized.cause.code : void 0;
52
+ const code = codeFromSqlState ?? causeCode;
53
+ throw errorRuntime("Database connection failed", {
54
+ why: normalized.message,
55
+ fix: "Verify the database URL, ensure the database is reachable, and confirm credentials/permissions",
56
+ meta: {
57
+ ...ifDefined("code", code),
58
+ ...redacted
59
+ }
60
+ });
61
+ }
62
+ }
63
+ };
64
+ var control_default = postgresDriverDescriptor;
65
+
66
+ //#endregion
67
+ export { PostgresControlDriver, control_default as default };
68
+ //# sourceMappingURL=control.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"control.mjs","names":["client: Client","postgresDriverDescriptor: ControlDriverDescriptor<'sql', 'postgres', PostgresControlDriver>"],"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 { ifDefined } from '@prisma-next/utils/defined';\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 ...ifDefined('code', code),\n ...redacted,\n },\n });\n }\n },\n };\n\nexport default postgresDriverDescriptor;\n"],"mappings":";;;;;;;;;;;;AAgBA,IAAa,wBAAb,MAAuF;CACrF,AAAS,WAAW;CACpB,AAAS,WAAW;;;;CAIpB,AAAS,SAAS;CAElB,YAAY,AAAiBA,QAAgB;EAAhB;;CAE7B,MAAM,MACJ,KACA,QACmC;AACnC,MAAI;AAEF,UAAO,EAAE,OADM,MAAM,KAAK,OAAO,MAAM,KAAK,OAAgC,EACtD,MAAe;WAC9B,OAAO;AACd,SAAM,iBAAiB,MAAM;;;CAIjC,MAAM,QAAuB;AAC3B,QAAM,KAAK,OAAO,KAAK;;;;;;AAO3B,MAAMC,2BACJ;CACE,GAAG;CACH,MAAM,OAAO,KAA6C;EACxD,MAAM,SAAS,IAAI,OAAO,EAAE,kBAAkB,KAAK,CAAC;AACpD,MAAI;AACF,SAAM,OAAO,SAAS;AACtB,UAAO,IAAI,sBAAsB,OAAO;WACjC,OAAO;GACd,MAAM,aAAa,iBAAiB,MAAM;GAC1C,MAAM,WAAW,kBAAkB,IAAI;AACvC,OAAI;AACF,UAAM,OAAO,KAAK;WACZ;GAIR,MAAM,mBAAmB,cAAc,GAAG,WAAW,GAAG,WAAW,WAAW;GAC9E,MAAM,YACJ,WAAW,cAAc,WAAW,QAC/B,WAAW,MAA6B,OACzC;GACN,MAAM,OAAO,oBAAoB;AAEjC,SAAM,aAAa,8BAA8B;IAC/C,KAAK,WAAW;IAChB,KAAK;IACL,MAAM;KACJ,GAAG,UAAU,QAAQ,KAAK;KAC1B,GAAG;KACJ;IACF,CAAC;;;CAGP;AAEH,sBAAe"}
@@ -0,0 +1,125 @@
1
+ import { SqlConnectionError, SqlQueryError } from "@prisma-next/sql-errors";
2
+
3
+ //#region src/core/descriptor-meta.ts
4
+ const postgresDriverDescriptorMeta = {
5
+ kind: "driver",
6
+ familyId: "sql",
7
+ targetId: "postgres",
8
+ id: "postgres",
9
+ version: "0.0.1",
10
+ capabilities: {}
11
+ };
12
+
13
+ //#endregion
14
+ //#region src/normalize-error.ts
15
+ /**
16
+ * Checks if an error is a connection-related error.
17
+ */
18
+ function isConnectionError(error) {
19
+ const code = error.code;
20
+ if (code) {
21
+ if (code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EHOSTUNREACH") return true;
22
+ }
23
+ const message = error.message.toLowerCase();
24
+ if (message.includes("connection terminated") || message.includes("connection closed") || message.includes("connection refused") || message.includes("connection timeout") || message.includes("connection reset")) return true;
25
+ return false;
26
+ }
27
+ /**
28
+ * Checks if a connection error is transient (might succeed on retry).
29
+ */
30
+ function isTransientConnectionError(error) {
31
+ const code = error.code;
32
+ if (code) {
33
+ if (code === "ETIMEDOUT" || code === "ECONNRESET") return true;
34
+ if (code === "ECONNREFUSED") return false;
35
+ }
36
+ const message = error.message.toLowerCase();
37
+ if (message.includes("timeout") || message.includes("connection reset")) return true;
38
+ return false;
39
+ }
40
+ /**
41
+ * PostgreSQL-specific error properties that indicate an error originated from pg library.
42
+ * These properties are not present on Node.js system errors.
43
+ * Excludes generic properties like 'detail', 'file', 'line', and 'position' that could appear on any error.
44
+ */
45
+ const PG_ERROR_PROPERTIES = [
46
+ "constraint",
47
+ "table",
48
+ "column",
49
+ "hint",
50
+ "internalPosition",
51
+ "internalQuery",
52
+ "where",
53
+ "schema",
54
+ "routine"
55
+ ];
56
+ /**
57
+ * Type predicate to check if an error is a Postgres error from the pg library.
58
+ *
59
+ * Distinguishes pg library errors from Node.js system errors by checking for:
60
+ * - SQLSTATE codes (5-character alphanumeric codes like '23505', '42601')
61
+ * - pg-specific properties (constraint, table, column, hint, etc.) that Node.js errors don't have
62
+ *
63
+ * Node.js system errors (ECONNREFUSED, ETIMEDOUT, etc.) are excluded to prevent false positives.
64
+ */
65
+ function isPostgresError(error) {
66
+ if (!(error instanceof Error)) return false;
67
+ const pgError = error;
68
+ if (pgError.code && isPostgresSqlState(pgError.code)) return true;
69
+ return PG_ERROR_PROPERTIES.some((prop) => pgError[prop] !== void 0);
70
+ }
71
+ /**
72
+ * Checks if an error is an "already connected" error from pg.Client.connect().
73
+ * When calling connect() on an already-connected client, pg throws an error that can be safely ignored.
74
+ */
75
+ function isAlreadyConnectedError(error) {
76
+ if (!(error instanceof Error)) return false;
77
+ const message = error.message.toLowerCase();
78
+ return message.includes("already") && message.includes("connected");
79
+ }
80
+ /**
81
+ * Checks if an error code is a Postgres SQLSTATE (5-character alphanumeric code).
82
+ * SQLSTATE codes are standardized SQL error codes (e.g., '23505' for unique violation).
83
+ */
84
+ function isPostgresSqlState(code) {
85
+ if (!code) return false;
86
+ return /^[A-Z0-9]{5}$/.test(code);
87
+ }
88
+ /**
89
+ * Normalizes a Postgres error into a SQL-shared error type.
90
+ *
91
+ * - Postgres SQLSTATE errors (5-char codes like '23505') → SqlQueryError
92
+ * - Connection errors (ECONNRESET, ETIMEDOUT, etc.) → SqlConnectionError
93
+ * - Unknown errors → returns the original error as-is
94
+ *
95
+ * The original error is preserved via Error.cause to maintain stack traces.
96
+ *
97
+ * @param error - The error to normalize (typically from pg library)
98
+ * @returns SqlQueryError for query-related failures
99
+ * @returns SqlConnectionError for connection-related failures
100
+ * @returns The original error if it cannot be normalized
101
+ */
102
+ function normalizePgError(error) {
103
+ if (!(error instanceof Error)) return new Error(String(error));
104
+ const pgError = error;
105
+ if (isPostgresSqlState(pgError.code)) {
106
+ const options = {
107
+ cause: error,
108
+ sqlState: pgError.code
109
+ };
110
+ if (pgError.constraint !== void 0) options.constraint = pgError.constraint;
111
+ if (pgError.table !== void 0) options.table = pgError.table;
112
+ if (pgError.column !== void 0) options.column = pgError.column;
113
+ if (pgError.detail !== void 0) options.detail = pgError.detail;
114
+ return new SqlQueryError(error.message, options);
115
+ }
116
+ if (isConnectionError(error)) return new SqlConnectionError(error.message, {
117
+ cause: error,
118
+ transient: isTransientConnectionError(error)
119
+ });
120
+ return error;
121
+ }
122
+
123
+ //#endregion
124
+ export { postgresDriverDescriptorMeta as i, isPostgresError as n, normalizePgError as r, isAlreadyConnectedError as t };
125
+ //# sourceMappingURL=normalize-error-BU6yV-XB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalize-error-BU6yV-XB.mjs","names":["options: {\n cause: Error;\n sqlState: string;\n constraint?: string;\n table?: string;\n column?: string;\n detail?: string;\n }"],"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":";;;AAAA,MAAa,+BAA+B;CAC1C,MAAM;CACN,UAAU;CACV,UAAU;CACV,IAAI;CACJ,SAAS;CACT,cAAc,EAAE;CACjB;;;;;;;AC0BD,SAAS,kBAAkB,OAAuB;CAChD,MAAM,OAAQ,MAA4B;AAC1C,KAAI,MAEF;MACE,SAAS,gBACT,SAAS,eACT,SAAS,kBACT,SAAS,eACT,SAAS,eAET,QAAO;;CAKX,MAAM,UAAU,MAAM,QAAQ,aAAa;AAC3C,KACE,QAAQ,SAAS,wBAAwB,IACzC,QAAQ,SAAS,oBAAoB,IACrC,QAAQ,SAAS,qBAAqB,IACtC,QAAQ,SAAS,qBAAqB,IACtC,QAAQ,SAAS,mBAAmB,CAEpC,QAAO;AAGT,QAAO;;;;;AAMT,SAAS,2BAA2B,OAAuB;CACzD,MAAM,OAAQ,MAA4B;AAC1C,KAAI,MAAM;AAER,MAAI,SAAS,eAAe,SAAS,aACnC,QAAO;AAGT,MAAI,SAAS,eACX,QAAO;;CAIX,MAAM,UAAU,MAAM,QAAQ,aAAa;AAC3C,KAAI,QAAQ,SAAS,UAAU,IAAI,QAAQ,SAAS,mBAAmB,CACrE,QAAO;AAGT,QAAO;;;;;;;AAQT,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,SAAgB,gBAAgB,OAAwC;AACtE,KAAI,EAAE,iBAAiB,OACrB,QAAO;CAGT,MAAM,UAAU;AAGhB,KAAI,QAAQ,QAAQ,mBAAmB,QAAQ,KAAK,CAClD,QAAO;AAKT,QAAO,oBAAoB,MAAM,SAAS,QAAQ,UAAU,OAAU;;;;;;AAOxE,SAAgB,wBAAwB,OAAgC;AACtE,KAAI,EAAE,iBAAiB,OACrB,QAAO;CAET,MAAM,UAAU,MAAM,QAAQ,aAAa;AAC3C,QAAO,QAAQ,SAAS,UAAU,IAAI,QAAQ,SAAS,YAAY;;;;;;AAOrE,SAAS,mBAAmB,MAAmC;AAC7D,KAAI,CAAC,KACH,QAAO;AAIT,QAAO,gBAAgB,KAAK,KAAK;;;;;;;;;;;;;;;;AAiBnC,SAAgB,iBAAiB,OAA4D;AAC3F,KAAI,EAAE,iBAAiB,OAErB,QAAO,IAAI,MAAM,OAAO,MAAM,CAAC;CAGjC,MAAM,UAAU;AAGhB,KAAI,mBAAmB,QAAQ,KAAK,EAAE;EAIpC,MAAMA,UAOF;GACF,OAAO;GACP,UAVe,QAAQ;GAWxB;AACD,MAAI,QAAQ,eAAe,OACzB,SAAQ,aAAa,QAAQ;AAE/B,MAAI,QAAQ,UAAU,OACpB,SAAQ,QAAQ,QAAQ;AAE1B,MAAI,QAAQ,WAAW,OACrB,SAAQ,SAAS,QAAQ;AAE3B,MAAI,QAAQ,WAAW,OACrB,SAAQ,SAAS,QAAQ;AAE3B,SAAO,IAAI,cAAc,MAAM,SAAS,QAAQ;;AAIlD,KAAI,kBAAkB,MAAM,CAC1B,QAAO,IAAI,mBAAmB,MAAM,SAAS;EAC3C,OAAO;EACP,WAAW,2BAA2B,MAAM;EAC7C,CAAC;AAIJ,QAAO"}
@@ -0,0 +1,36 @@
1
+ import { Client, Pool, QueryResult as QueryResult$1, QueryResultRow } from "pg";
2
+ import { RuntimeDriverDescriptor, RuntimeDriverInstance } from "@prisma-next/core-execution-plane/types";
3
+ import { SqlDriver } from "@prisma-next/sql-relational-core/ast";
4
+
5
+ //#region src/postgres-driver.d.ts
6
+ type QueryResult<T extends QueryResultRow = QueryResultRow> = QueryResult$1<T>;
7
+ type PostgresBinding = {
8
+ readonly kind: 'url';
9
+ readonly url: string;
10
+ } | {
11
+ readonly kind: 'pgPool';
12
+ readonly pool: Pool;
13
+ } | {
14
+ readonly kind: 'pgClient';
15
+ readonly client: Client;
16
+ };
17
+ interface PostgresCursorOptions {
18
+ readonly batchSize?: number;
19
+ readonly disabled?: boolean;
20
+ }
21
+ interface PostgresDriverOptions {
22
+ readonly connect: {
23
+ client: Client;
24
+ } | {
25
+ pool: Pool;
26
+ };
27
+ readonly cursor?: PostgresCursorOptions | undefined;
28
+ }
29
+ type PostgresDriverCreateOptions = Omit<PostgresDriverOptions, 'connect'>;
30
+ //#endregion
31
+ //#region src/exports/runtime.d.ts
32
+ type PostgresRuntimeDriver = RuntimeDriverInstance<'sql', 'postgres'> & SqlDriver<PostgresBinding>;
33
+ declare const postgresRuntimeDriverDescriptor: RuntimeDriverDescriptor<'sql', 'postgres', PostgresDriverCreateOptions, PostgresRuntimeDriver>;
34
+ //#endregion
35
+ export { type PostgresBinding, type PostgresDriverCreateOptions, PostgresRuntimeDriver, type QueryResult, postgresRuntimeDriverDescriptor as default };
36
+ //# sourceMappingURL=runtime.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/postgres-driver.ts","../src/exports/runtime.ts"],"sourcesContent":[],"mappings":";;;;;KAsBY,sBAAsB,iBAAiB,kBAAkB,cAAc;KAEvE,eAAA;;EAFA,SAAA,GAAA,EAAW,MAAA;CAAW,GAAA;EAAiB,SAAA,IAAA,EAAA,QAAA;EAAgC,SAAA,IAAA,EAIrC,IAJqC;CAAd,GAAA;EAAa,SAAA,IAAA,EAAA,UAAA;EAEtE,SAAA,MAAA,EAGsC,MAHvB;AAK3B,CAAA;AAKU,UALO,qBAAA,CAKc;EACD,SAAA,SAAA,CAAA,EAAA,MAAA;EAAmB,SAAA,QAAA,CAAA,EAAA,OAAA;;UADvC,qBAAA,CAE+B;EAG7B,SAAA,OAAA,EAAA;YAJkB;;UAAmB;ECjBrC,CAAA;EAAwB,SAAA,MAAA,CAAA,EDkBhB,qBClBgB,GAAA,SAAA;;AAClC,KDoBU,2BAAA,GAA8B,ICpBxC,CDoB6C,qBCpB7C,EAAA,SAAA,CAAA;;;KADU,qBAAA,GAAwB,2CAClC,UAAU;cA6HN,iCAAiC,2CAGrC,6BACA"}