@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,162 @@
1
+ import type {
2
+ RuntimeDriverDescriptor,
3
+ RuntimeDriverInstance,
4
+ } from '@prisma-next/core-execution-plane/types';
5
+ import type {
6
+ SqlConnection,
7
+ SqlDriver,
8
+ SqlExecuteRequest,
9
+ SqlExplainResult,
10
+ SqlQueryResult,
11
+ } from '@prisma-next/sql-relational-core/ast';
12
+ import { postgresDriverDescriptorMeta } from '../core/descriptor-meta';
13
+ import {
14
+ createBoundDriverFromBinding,
15
+ type PostgresBinding,
16
+ type PostgresDriverCreateOptions,
17
+ } from '../postgres-driver';
18
+
19
+ export type PostgresRuntimeDriver = RuntimeDriverInstance<'sql', 'postgres'> &
20
+ SqlDriver<PostgresBinding>;
21
+
22
+ const USE_BEFORE_CONNECT_MESSAGE =
23
+ 'Postgres driver not connected. Call connect(binding) before acquireConnection or execute.';
24
+ const ALREADY_CONNECTED_MESSAGE =
25
+ 'Postgres driver already connected. Call close() before reconnecting with a new binding.';
26
+
27
+ interface DriverRuntimeError extends Error {
28
+ readonly code: 'DRIVER.NOT_CONNECTED' | 'DRIVER.ALREADY_CONNECTED';
29
+ readonly category: 'RUNTIME';
30
+ readonly severity: 'error';
31
+ readonly details?: Record<string, unknown>;
32
+ }
33
+
34
+ function driverError(
35
+ code: DriverRuntimeError['code'],
36
+ message: string,
37
+ details?: Record<string, unknown>,
38
+ ): DriverRuntimeError {
39
+ const error = new Error(message) as DriverRuntimeError;
40
+ Object.defineProperty(error, 'name', {
41
+ value: 'RuntimeError',
42
+ configurable: true,
43
+ });
44
+ return Object.assign(error, {
45
+ code,
46
+ category: 'RUNTIME' as const,
47
+ severity: 'error' as const,
48
+ message,
49
+ details,
50
+ });
51
+ }
52
+
53
+ function unboundExecute<Row>(): AsyncIterable<Row> {
54
+ return {
55
+ [Symbol.asyncIterator]() {
56
+ return {
57
+ async next() {
58
+ throw driverError('DRIVER.NOT_CONNECTED', USE_BEFORE_CONNECT_MESSAGE);
59
+ },
60
+ };
61
+ },
62
+ };
63
+ }
64
+
65
+ class PostgresUnboundDriverImpl implements PostgresRuntimeDriver {
66
+ readonly familyId = 'sql' as const;
67
+ readonly targetId = 'postgres' as const;
68
+
69
+ #delegate: SqlDriver<PostgresBinding> | null = null;
70
+ #closed = false;
71
+ #cursorOpts: PostgresDriverCreateOptions['cursor'];
72
+
73
+ constructor(cursorOpts?: PostgresDriverCreateOptions['cursor']) {
74
+ this.#cursorOpts = cursorOpts;
75
+ }
76
+
77
+ get state(): 'unbound' | 'connected' | 'closed' {
78
+ if (this.#delegate !== null) {
79
+ return 'connected';
80
+ }
81
+ if (this.#closed) {
82
+ return 'closed';
83
+ }
84
+ return 'unbound';
85
+ }
86
+
87
+ #requireDelegate(): SqlDriver<PostgresBinding> {
88
+ const delegate = this.#delegate;
89
+ if (delegate === null) {
90
+ throw driverError('DRIVER.NOT_CONNECTED', USE_BEFORE_CONNECT_MESSAGE);
91
+ }
92
+ return delegate;
93
+ }
94
+
95
+ async connect(binding: PostgresBinding): Promise<void> {
96
+ if (this.#delegate !== null) {
97
+ throw driverError('DRIVER.ALREADY_CONNECTED', ALREADY_CONNECTED_MESSAGE, {
98
+ bindingKind: binding.kind,
99
+ });
100
+ }
101
+ this.#delegate = createBoundDriverFromBinding(binding, this.#cursorOpts);
102
+ this.#closed = false;
103
+ }
104
+
105
+ async acquireConnection(): Promise<SqlConnection> {
106
+ const delegate = this.#requireDelegate();
107
+ return delegate.acquireConnection();
108
+ }
109
+
110
+ async close(): Promise<void> {
111
+ const delegate = this.#delegate;
112
+ if (delegate !== null) {
113
+ this.#delegate = null;
114
+ await delegate.close();
115
+ }
116
+ this.#closed = true;
117
+ }
118
+
119
+ execute<Row = Record<string, unknown>>(request: SqlExecuteRequest): AsyncIterable<Row> {
120
+ const delegate = this.#delegate;
121
+ if (delegate === null) {
122
+ return unboundExecute<Row>();
123
+ }
124
+ return delegate.execute<Row>(request);
125
+ }
126
+
127
+ async explain(request: SqlExecuteRequest): Promise<SqlExplainResult> {
128
+ const delegate = this.#requireDelegate();
129
+ const explain = delegate.explain;
130
+ if (explain === undefined) {
131
+ throw driverError('DRIVER.NOT_CONNECTED', USE_BEFORE_CONNECT_MESSAGE);
132
+ }
133
+ return explain.call(delegate, request);
134
+ }
135
+
136
+ async query<Row = Record<string, unknown>>(
137
+ sql: string,
138
+ params?: readonly unknown[],
139
+ ): Promise<SqlQueryResult<Row>> {
140
+ const delegate = this.#requireDelegate();
141
+ return delegate.query<Row>(sql, params);
142
+ }
143
+ }
144
+
145
+ const postgresRuntimeDriverDescriptor: RuntimeDriverDescriptor<
146
+ 'sql',
147
+ 'postgres',
148
+ PostgresDriverCreateOptions,
149
+ PostgresRuntimeDriver
150
+ > = {
151
+ ...postgresDriverDescriptorMeta,
152
+ create(options?: PostgresDriverCreateOptions): PostgresRuntimeDriver {
153
+ return new PostgresUnboundDriverImpl(options?.cursor);
154
+ },
155
+ };
156
+
157
+ export default postgresRuntimeDriverDescriptor;
158
+ export type {
159
+ PostgresBinding,
160
+ PostgresDriverCreateOptions,
161
+ QueryResult,
162
+ } from '../postgres-driver';
@@ -0,0 +1,219 @@
1
+ import { SqlConnectionError, SqlQueryError } from '@prisma-next/sql-errors';
2
+
3
+ /**
4
+ * Postgres error shape from the pg library.
5
+ *
6
+ * Note: The pg library doesn't export a DatabaseError type or interface, but errors
7
+ * thrown by pg.query() and pg.Client have this shape at runtime. We define this
8
+ * interface to match the actual runtime structure documented in the pg library
9
+ * (https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/errors.js).
10
+ *
11
+ * The @types/pg package also doesn't provide comprehensive error type definitions,
12
+ * so we define our own interface based on the runtime error properties.
13
+ */
14
+ interface PostgresError extends Error {
15
+ readonly code?: string;
16
+ readonly constraint?: string;
17
+ readonly table?: string;
18
+ readonly column?: string;
19
+ readonly detail?: string;
20
+ readonly hint?: string;
21
+ readonly position?: string;
22
+ readonly internalPosition?: string;
23
+ readonly internalQuery?: string;
24
+ readonly where?: string;
25
+ readonly schema?: string;
26
+ readonly file?: string;
27
+ readonly line?: string;
28
+ readonly routine?: string;
29
+ }
30
+
31
+ /**
32
+ * Checks if an error is a connection-related error.
33
+ */
34
+ function isConnectionError(error: Error): boolean {
35
+ const code = (error as { code?: string }).code;
36
+ if (code) {
37
+ // Node.js error codes for connection issues
38
+ if (
39
+ code === 'ECONNRESET' ||
40
+ code === 'ETIMEDOUT' ||
41
+ code === 'ECONNREFUSED' ||
42
+ code === 'ENOTFOUND' ||
43
+ code === 'EHOSTUNREACH'
44
+ ) {
45
+ return true;
46
+ }
47
+ }
48
+
49
+ // Check error message for connection-related strings
50
+ const message = error.message.toLowerCase();
51
+ if (
52
+ message.includes('connection terminated') ||
53
+ message.includes('connection closed') ||
54
+ message.includes('connection refused') ||
55
+ message.includes('connection timeout') ||
56
+ message.includes('connection reset')
57
+ ) {
58
+ return true;
59
+ }
60
+
61
+ return false;
62
+ }
63
+
64
+ /**
65
+ * Checks if a connection error is transient (might succeed on retry).
66
+ */
67
+ function isTransientConnectionError(error: Error): boolean {
68
+ const code = (error as { code?: string }).code;
69
+ if (code) {
70
+ // Timeouts and connection resets are often transient
71
+ if (code === 'ETIMEDOUT' || code === 'ECONNRESET') {
72
+ return true;
73
+ }
74
+ // Connection refused is usually not transient (server is down)
75
+ if (code === 'ECONNREFUSED') {
76
+ return false;
77
+ }
78
+ }
79
+
80
+ const message = error.message.toLowerCase();
81
+ if (message.includes('timeout') || message.includes('connection reset')) {
82
+ return true;
83
+ }
84
+
85
+ return false;
86
+ }
87
+
88
+ /**
89
+ * PostgreSQL-specific error properties that indicate an error originated from pg library.
90
+ * These properties are not present on Node.js system errors.
91
+ * Excludes generic properties like 'detail', 'file', 'line', and 'position' that could appear on any error.
92
+ */
93
+ const PG_ERROR_PROPERTIES = [
94
+ 'constraint',
95
+ 'table',
96
+ 'column',
97
+ 'hint',
98
+ 'internalPosition',
99
+ 'internalQuery',
100
+ 'where',
101
+ 'schema',
102
+ 'routine',
103
+ ] as const;
104
+
105
+ /**
106
+ * Type predicate to check if an error is a Postgres error from the pg library.
107
+ *
108
+ * Distinguishes pg library errors from Node.js system errors by checking for:
109
+ * - SQLSTATE codes (5-character alphanumeric codes like '23505', '42601')
110
+ * - pg-specific properties (constraint, table, column, hint, etc.) that Node.js errors don't have
111
+ *
112
+ * Node.js system errors (ECONNREFUSED, ETIMEDOUT, etc.) are excluded to prevent false positives.
113
+ */
114
+ export function isPostgresError(error: unknown): error is PostgresError {
115
+ if (!(error instanceof Error)) {
116
+ return false;
117
+ }
118
+
119
+ const pgError = error as PostgresError;
120
+
121
+ // Check for SQLSTATE code (5-character alphanumeric) - primary indicator of pg errors
122
+ if (pgError.code && isPostgresSqlState(pgError.code)) {
123
+ return true;
124
+ }
125
+
126
+ // Check for pg-specific properties that Node.js system errors don't have
127
+ // These properties indicate the error originated from pg library query execution
128
+ return PG_ERROR_PROPERTIES.some((prop) => pgError[prop] !== undefined);
129
+ }
130
+
131
+ /**
132
+ * Checks if an error is an "already connected" error from pg.Client.connect().
133
+ * When calling connect() on an already-connected client, pg throws an error that can be safely ignored.
134
+ */
135
+ export function isAlreadyConnectedError(error: unknown): error is Error {
136
+ if (!(error instanceof Error)) {
137
+ return false;
138
+ }
139
+ const message = error.message.toLowerCase();
140
+ return message.includes('already') && message.includes('connected');
141
+ }
142
+
143
+ /**
144
+ * Checks if an error code is a Postgres SQLSTATE (5-character alphanumeric code).
145
+ * SQLSTATE codes are standardized SQL error codes (e.g., '23505' for unique violation).
146
+ */
147
+ function isPostgresSqlState(code: string | undefined): boolean {
148
+ if (!code) {
149
+ return false;
150
+ }
151
+ // Postgres SQLSTATE codes are 5-character alphanumeric strings
152
+ // Examples: '23505' (unique violation), '42501' (insufficient privilege), '42601' (syntax error)
153
+ return /^[A-Z0-9]{5}$/.test(code);
154
+ }
155
+
156
+ /**
157
+ * Normalizes a Postgres error into a SQL-shared error type.
158
+ *
159
+ * - Postgres SQLSTATE errors (5-char codes like '23505') → SqlQueryError
160
+ * - Connection errors (ECONNRESET, ETIMEDOUT, etc.) → SqlConnectionError
161
+ * - Unknown errors → returns the original error as-is
162
+ *
163
+ * The original error is preserved via Error.cause to maintain stack traces.
164
+ *
165
+ * @param error - The error to normalize (typically from pg library)
166
+ * @returns SqlQueryError for query-related failures
167
+ * @returns SqlConnectionError for connection-related failures
168
+ * @returns The original error if it cannot be normalized
169
+ */
170
+ export function normalizePgError(error: unknown): SqlQueryError | SqlConnectionError | Error {
171
+ if (!(error instanceof Error)) {
172
+ // Wrap non-Error values in an Error object
173
+ return new Error(String(error));
174
+ }
175
+
176
+ const pgError = error as PostgresError;
177
+
178
+ // Check for Postgres SQLSTATE (query errors)
179
+ if (isPostgresSqlState(pgError.code)) {
180
+ // isPostgresSqlState ensures code is defined and is a valid SQLSTATE
181
+ // biome-ignore lint/style/noNonNullAssertion: isPostgresSqlState guarantees code is defined
182
+ const sqlState = pgError.code!;
183
+ const options: {
184
+ cause: Error;
185
+ sqlState: string;
186
+ constraint?: string;
187
+ table?: string;
188
+ column?: string;
189
+ detail?: string;
190
+ } = {
191
+ cause: error,
192
+ sqlState,
193
+ };
194
+ if (pgError.constraint !== undefined) {
195
+ options.constraint = pgError.constraint;
196
+ }
197
+ if (pgError.table !== undefined) {
198
+ options.table = pgError.table;
199
+ }
200
+ if (pgError.column !== undefined) {
201
+ options.column = pgError.column;
202
+ }
203
+ if (pgError.detail !== undefined) {
204
+ options.detail = pgError.detail;
205
+ }
206
+ return new SqlQueryError(error.message, options);
207
+ }
208
+
209
+ // Check for connection errors
210
+ if (isConnectionError(error)) {
211
+ return new SqlConnectionError(error.message, {
212
+ cause: error,
213
+ transient: isTransientConnectionError(error),
214
+ });
215
+ }
216
+
217
+ // Unknown error - return as-is to preserve original error and stack trace
218
+ return error;
219
+ }