@nextlyhq/adapter-postgres 0.0.2-alpha.8 → 0.0.2-alpha.81

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/dist/index.d.cts CHANGED
@@ -1,80 +1,11 @@
1
- import { DrizzleAdapter } from '@nextlyhq/adapter-drizzle';
2
- import { PostgresAdapterConfig, SqlParam, TransactionContext, TransactionOptions, DatabaseCapabilities, PoolStats, InsertOptions, DatabaseError } from '@nextlyhq/adapter-drizzle/types';
3
- export { AdapterLogger, PoolConfig as AdapterPoolConfig, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, PostgresAdapterConfig, SelectOptions, SqlParam, SslConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from '@nextlyhq/adapter-drizzle/types';
4
- import { NodePgDatabase } from 'drizzle-orm/node-postgres';
5
-
6
- /**
7
- * @nextlyhq/adapter-postgres
8
- *
9
- * PostgreSQL database adapter for Nextly.
10
- * Extends the base DrizzleAdapter from @nextlyhq/adapter-drizzle to provide
11
- * PostgreSQL-specific functionality.
12
- *
13
- * @remarks
14
- * This adapter uses the `pg` (node-postgres) driver for database connections
15
- * and integrates with Drizzle ORM for type-safe queries.
16
- *
17
- * Features:
18
- * - Connection pooling via pg.Pool
19
- * - Full transaction support with savepoints
20
- * - RETURNING clause support for all CRUD operations
21
- * - PostgreSQL-specific error classification
22
- * - JSONB support
23
- * - Full-text search capabilities
24
- * - Automatic retry for serialization failures and deadlocks
25
- *
26
- * @example
27
- * Simple usage with connection string:
28
- * ```typescript
29
- * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
30
- *
31
- * const adapter = createPostgresAdapter({
32
- * url: process.env.DATABASE_URL!,
33
- * });
34
- *
35
- * await adapter.connect();
36
- * ```
37
- *
38
- * @example
39
- * Full configuration:
40
- * ```typescript
41
- * import { createPostgresAdapter } from '@nextlyhq/adapter-postgres';
42
- *
43
- * const adapter = createPostgresAdapter({
44
- * url: process.env.DATABASE_URL!,
45
- * pool: {
46
- * min: 2,
47
- * max: 20,
48
- * idleTimeoutMs: 30000,
49
- * },
50
- * ssl: {
51
- * rejectUnauthorized: true,
52
- * },
53
- * applicationName: 'my-nextly-app',
54
- * });
55
- * ```
56
- *
57
- * @example
58
- * Using the adapter class directly:
59
- * ```typescript
60
- * import { PostgresAdapter } from '@nextlyhq/adapter-postgres';
61
- * import type { PostgresAdapterConfig } from '@nextlyhq/adapter-postgres';
62
- *
63
- * const config: PostgresAdapterConfig = {
64
- * url: process.env.DATABASE_URL!,
65
- * };
66
- *
67
- * const adapter = new PostgresAdapter(config);
68
- * await adapter.connect();
69
- * ```
70
- *
71
- * @packageDocumentation
72
- */
73
-
1
+ import { DrizzleAdapter } from "@nextlyhq/adapter-drizzle";
2
+ import { AdapterLogger, BaseAdapterConfig, ConnectionInspection, DatabaseCapabilities, DatabaseCapabilities as DatabaseCapabilities$1, DatabaseError, DatabaseError as DatabaseError$1, DatabaseErrorKind, DeleteOptions, InsertOptions, InsertOptions as InsertOptions$1, JoinSpec, OrderBySpec, PoolConfig as AdapterPoolConfig, PoolStats, PoolStats as PoolStats$1, PostgresAdapterConfig, PostgresAdapterConfig as PostgresAdapterConfig$1, SelectOptions, SessionOptions, SqlParam, SqlParam as SqlParam$1, SslConfig, StatementSession, TransactionContext, TransactionContext as TransactionContext$1, TransactionOptions, TransactionOptions as TransactionOptions$1, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator } from "@nextlyhq/adapter-drizzle/types";
3
+ import { AnyRelations } from "drizzle-orm";
4
+ import { NodePgDatabase } from "drizzle-orm/node-postgres";
74
5
  /**
75
6
  * Package version.
76
7
  */
77
- declare const VERSION = "0.1.0";
8
+ export declare const VERSION = "0.1.0";
78
9
  /**
79
10
  * PostgreSQL database adapter for Nextly.
80
11
  *
@@ -112,152 +43,246 @@ declare const VERSION = "0.1.0";
112
43
  *
113
44
  * @public
114
45
  */
115
- declare class PostgresAdapter extends DrizzleAdapter {
116
- /**
117
- * The database dialect - always 'postgresql' for this adapter.
118
- */
119
- readonly dialect: "postgresql";
120
- /**
121
- * Adapter configuration.
122
- */
123
- protected readonly config: PostgresAdapterConfig;
124
- /**
125
- * Connection pool instance.
126
- */
127
- private pool;
128
- /**
129
- * Connection state flag.
130
- */
131
- private connected;
132
- /**
133
- * Auto-detected provider (Neon, Supabase, or standard).
134
- * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
135
- */
136
- private detectedProvider;
137
- /**
138
- * Provider-specific connection defaults. Applied as fallbacks when
139
- * user config doesn't specify a value.
140
- */
141
- private providerDefaults;
142
- /**
143
- * Creates a new PostgreSQL adapter instance.
144
- *
145
- * @param config - Adapter configuration
146
- */
147
- constructor(config: PostgresAdapterConfig);
148
- /**
149
- * Establishes a connection to the PostgreSQL database.
150
- *
151
- * @remarks
152
- * This method initializes the connection pool and verifies connectivity
153
- * by executing a simple query. It is idempotent - calling it multiple
154
- * times will not create multiple pools.
155
- *
156
- * @throws {DatabaseError} If connection fails
157
- */
158
- connect(): Promise<void>;
159
- /**
160
- * Closes the database connection and releases all pool resources.
161
- *
162
- * @remarks
163
- * This method is idempotent - calling it multiple times is safe.
164
- * It waits for all checked-out clients to be returned before shutting down.
165
- */
166
- disconnect(): Promise<void>;
167
- /**
168
- * Checks if the adapter is currently connected.
169
- *
170
- * @returns True if connected and pool is available
171
- */
172
- isConnected(): boolean;
173
- /**
174
- * Executes a raw SQL query.
175
- *
176
- * @param sql - SQL statement with $1, $2, ... placeholders
177
- * @param params - Query parameters
178
- * @returns Array of result rows
179
- *
180
- * @throws {DatabaseError} If query execution fails
181
- */
182
- executeQuery<T = unknown>(sql: string, params?: SqlParam[]): Promise<T[]>;
183
- /**
184
- * Executes a callback within a database transaction.
185
- *
186
- * @remarks
187
- * PostgreSQL supports full ACID transactions with savepoints.
188
- * If the callback throws, the transaction is rolled back.
189
- *
190
- * Supports automatic retry for serialization failures (40001) and
191
- * deadlocks (40P01) when `retryCount` is specified in options.
192
- *
193
- * @param callback - Function to execute within the transaction
194
- * @param options - Transaction options (isolation level, timeout, retry)
195
- * @returns The result of the callback
196
- *
197
- * @throws {DatabaseError} If transaction fails after all retries
198
- */
199
- transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
200
- /**
201
- * Returns the database capabilities for PostgreSQL.
202
- *
203
- * @remarks
204
- * PostgreSQL has the most comprehensive feature set of all supported
205
- * databases, including JSONB, arrays, full-text search, and more.
206
- */
207
- getCapabilities(): DatabaseCapabilities;
208
- /**
209
- * Returns connection pool statistics.
210
- *
211
- * @returns Pool stats or null if not connected
212
- */
213
- getPoolStats(): PoolStats | null;
214
- /**
215
- * Override insertMany for bulk insert optimization.
216
- *
217
- * @remarks
218
- * Uses a single multi-row INSERT statement for better performance
219
- * when inserting multiple records.
220
- */
221
- insertMany<T = unknown>(table: string, data: Record<string, unknown>[], options?: InsertOptions): Promise<T[]>;
222
- /**
223
- * Ensures pool is connected and returns it.
224
- *
225
- * @throws {DatabaseError} If not connected
226
- */
227
- private ensurePool;
228
- /**
229
- * Return the typed Drizzle instance for PostgreSQL.
230
- * Guarded for server-only usage and requires an active connection.
231
- *
232
- * @param schema - Optional schema for relational queries (db.query.*)
233
- * @returns Drizzle ORM instance wrapping the pg pool connection
234
- * @throws {Error} If called in browser or not connected
235
- */
236
- getDrizzle<T = NodePgDatabase<any>>(schema?: Record<string, unknown>): T;
237
- /**
238
- * Builds pg Pool configuration from adapter config.
239
- */
240
- private buildPoolConfig;
241
- /**
242
- * Begins a transaction with the specified options.
243
- */
244
- private beginTransaction;
245
- /**
246
- * Creates a TransactionContext for the given client.
247
- */
248
- private createTransactionContext;
249
- /**
250
- * Classifies a PostgreSQL error into a DatabaseError.
251
- *
252
- * @param error - Original error from pg
253
- * @param sql - SQL statement that caused the error (optional)
254
- * @returns DatabaseError with proper classification
255
- */
256
- private classifyError;
257
- /**
258
- * Override handleQueryError to use PostgreSQL-specific classification.
259
- */
260
- protected handleQueryError(error: unknown, operation: string, table: string): DatabaseError;
46
+ export declare class PostgresAdapter extends DrizzleAdapter {
47
+ private drizzleByRelations;
48
+ private drizzleBare;
49
+ /**
50
+ * The database dialect - always 'postgresql' for this adapter.
51
+ */
52
+ readonly dialect: "postgresql";
53
+ /**
54
+ * Adapter configuration.
55
+ */
56
+ protected readonly config: PostgresAdapterConfig$1;
57
+ /**
58
+ * Connection pool instance.
59
+ */
60
+ private pool;
61
+ /**
62
+ * Connection state flag.
63
+ */
64
+ private connected;
65
+ /**
66
+ * Auto-detected provider (Neon, Supabase, or standard).
67
+ * Set during connect() from DATABASE_URL pattern or DB_PROVIDER env var.
68
+ */
69
+ private detectedProvider;
70
+ /**
71
+ * Provider-specific connection defaults. Applied as fallbacks when
72
+ * user config doesn't specify a value.
73
+ */
74
+ private providerDefaults;
75
+ /**
76
+ * Creates a new PostgreSQL adapter instance.
77
+ *
78
+ * @param config - Adapter configuration
79
+ */
80
+ constructor(config: PostgresAdapterConfig$1);
81
+ /**
82
+ * Establishes a connection to the PostgreSQL database.
83
+ *
84
+ * @remarks
85
+ * This method initializes the connection pool and verifies connectivity
86
+ * by executing a simple query. It is idempotent - calling it multiple
87
+ * times will not create multiple pools.
88
+ *
89
+ * @throws {DatabaseError} If connection fails
90
+ */
91
+ connect(): Promise<void>;
92
+ /**
93
+ * Closes the database connection and releases all pool resources.
94
+ *
95
+ * @remarks
96
+ * This method is idempotent - calling it multiple times is safe.
97
+ * It waits for all checked-out clients to be returned before shutting down.
98
+ */
99
+ disconnect(): Promise<void>;
100
+ /**
101
+ * Checks if the adapter is currently connected.
102
+ *
103
+ * @returns True if connected and pool is available
104
+ */
105
+ override isConnected(): boolean;
106
+ /**
107
+ * Runs `work` on one client taken from the pool, outside a transaction,
108
+ * each statement committing as it runs, so connection-scoped state a
109
+ * statement sets (a temporary table, a session setting, an advisory lock)
110
+ * is still there for the next. The client is closed afterwards, whether
111
+ * `work` finished or threw, never handed back to the pool: that state ends
112
+ * with it instead of reaching a later caller. No `SessionOptions` field
113
+ * changes anything on PostgreSQL: strict mode is MySQL's, and PostgreSQL
114
+ * refuses an overlong value already.
115
+ */
116
+ override withSession<T>(work: (session: StatementSession) => Promise<T>, _options?: SessionOptions): Promise<T>;
117
+ /**
118
+ * Executes a raw SQL query.
119
+ *
120
+ * @param sql - SQL statement with $1, $2, ... placeholders
121
+ * @param params - Query parameters
122
+ * @returns Array of result rows
123
+ *
124
+ * @throws {DatabaseError} If query execution fails
125
+ */
126
+ executeQuery<T = unknown>(sql: string, params?: SqlParam$1[]): Promise<T[]>;
127
+ /**
128
+ * Executes a callback within a database transaction.
129
+ *
130
+ * @remarks
131
+ * PostgreSQL supports full ACID transactions with savepoints.
132
+ * If the callback throws, the transaction is rolled back.
133
+ *
134
+ * Supports automatic retry for serialization failures (40001) and
135
+ * deadlocks (40P01) when `retryCount` is specified in options.
136
+ *
137
+ * An error carrying the Nextly application brand is not classified: it is the
138
+ * application refusing the write, so it arrives at the caller as it was
139
+ * thrown. It is retried only when `retryWhen` accepts it, which is asked
140
+ * first, of every error; a refusal re-run is otherwise the same refusal.
141
+ * Every other error, including an unbranded one raised by the callback, is
142
+ * retried when it is a serialization failure or deadlock and classified on
143
+ * the way out.
144
+ *
145
+ * A call made inside another transaction's work joins it, on its client,
146
+ * as a savepoint: released when the callback resolves, rolled back to when
147
+ * it throws, so its failure undoes only its own part. A serialization
148
+ * failure or deadlock inside a joined part fails the whole transaction,
149
+ * which only a retry of the outermost one can answer. A joined call keeps
150
+ * the outer's options and is never retried itself.
151
+ *
152
+ * @param callback - Function to execute within the transaction
153
+ * @param options - Transaction options (isolation level, timeout, retry)
154
+ * @returns The result of the callback
155
+ *
156
+ * @throws {DatabaseError} If the transaction itself fails after all retries,
157
+ * or if the callback threw an error that does not carry the application brand
158
+ * @throws The callback's own error, unchanged, when it carries that brand
159
+ */
160
+ transaction<T>(callback: (ctx: TransactionContext$1) => Promise<T>, options?: TransactionOptions$1): Promise<T>;
161
+ /** One attempt at an outermost transaction, on a client of its own. */
162
+ private runAttempt;
163
+ /**
164
+ * How a call made inside a transaction on `client` joins it: a savepoint
165
+ * each, on `client`, named for its depth.
166
+ */
167
+ private joinSteps;
168
+ /**
169
+ * Returns the database capabilities for PostgreSQL.
170
+ *
171
+ * @remarks
172
+ * PostgreSQL has the most comprehensive feature set of all supported
173
+ * databases, including JSONB, arrays, full-text search, and more.
174
+ */
175
+ getCapabilities(): DatabaseCapabilities$1;
176
+ /**
177
+ * The schema set as `search_path` on every pooled connection.
178
+ *
179
+ * @remarks
180
+ * Answers with the same test `buildPoolConfig` applies, so an empty string
181
+ * reports `undefined` exactly as it sets no `search_path`: the value
182
+ * reported is the one the connections actually use.
183
+ *
184
+ * @returns The configured schema, or `undefined` when the server's default
185
+ * `search_path` applies
186
+ */
187
+ getConfiguredSchema(): string | undefined;
188
+ /**
189
+ * Returns connection pool statistics.
190
+ *
191
+ * @returns Pool stats or null if not connected
192
+ */
193
+ override getPoolStats(): PoolStats$1 | null;
194
+ /**
195
+ * The connection as a health check reads it, on one pooled client: the
196
+ * server's version, and that client's own row in `pg_stat_ssl`, which says
197
+ * whether the session's connection is encrypted. The query is timed for the
198
+ * round trip.
199
+ *
200
+ * @remarks
201
+ * The row and the client's own socket are weighed by `encryptionOf`: behind
202
+ * a connection pooler such as PgBouncer the row describes the pooler's own
203
+ * connection to the server, which can be plain inside the provider's
204
+ * network while this client's socket is TLS. The socket is read as it is,
205
+ * never inferred from the `ssl` setting.
206
+ *
207
+ * Whether the database is on this machine is judged from the host the
208
+ * client connected to, as node-postgres resolved it (its options, the
209
+ * connection string, `PGHOST`, its default); before a client is had, from
210
+ * the configured address alone. The address never leaves this method. Any
211
+ * failure answers `"unknown"`.
212
+ */
213
+ override inspectConnection(): Promise<ConnectionInspection>;
214
+ /**
215
+ * The host this adapter is configured with: the connection string's when one
216
+ * is set, else the `host` option. `undefined` when it names none, which is
217
+ * judged remote, or when the connection string cannot be read.
218
+ */
219
+ private configuredHost;
220
+ /**
221
+ * Override insertMany for bulk insert optimization.
222
+ *
223
+ * @remarks
224
+ * Uses a single multi-row INSERT statement for better performance
225
+ * when inserting multiple records.
226
+ */
227
+ override insertMany<T = unknown>(table: string, data: Record<string, unknown>[], options?: InsertOptions$1): Promise<T[]>;
228
+ /**
229
+ * Ensures pool is connected and returns it.
230
+ *
231
+ * @throws {DatabaseError} If not connected
232
+ */
233
+ private ensurePool;
234
+ /**
235
+ * Return the typed Drizzle instance for PostgreSQL.
236
+ * Guarded for server-only usage and requires an active connection.
237
+ *
238
+ * @param schema - Optional schema for relational queries (db.query.*)
239
+ * @returns Drizzle ORM instance wrapping the pg pool connection
240
+ * @throws {Error} If called in browser or not connected
241
+ */
242
+ getDrizzle<T = NodePgDatabase<AnyRelations>>(relations?: AnyRelations): T;
243
+ /**
244
+ * A Drizzle handle on the pool, for `getDrizzle`.
245
+ *
246
+ * Its `transaction` runs on a client this adapter checks out and returns
247
+ * itself (`pinDrizzleTransactions`): node-postgres destroys a client
248
+ * released with `true`, which is what happens when no ROLLBACK could be
249
+ * confirmed on it. And it counts for `transactionOpenInFlow`, as the
250
+ * adapter's does.
251
+ */
252
+ private poolDrizzle;
253
+ /**
254
+ * Builds pg Pool configuration from adapter config.
255
+ */
256
+ private buildPoolConfig;
257
+ /**
258
+ * Begins a transaction with the specified options.
259
+ */
260
+ private beginTransaction;
261
+ /**
262
+ * Creates a TransactionContext for the given client.
263
+ */
264
+ /**
265
+ * The RETURNING entries that spell each date column's wall clock out as
266
+ * text, one per alias `dateWallClockAliases` chose. `to_char` renders the
267
+ * stored value without a zone, which is the only form node-postgres cannot
268
+ * shift on the way back.
269
+ */
270
+ private wallClockSpelling;
271
+ /** A `Date` on an undeclared key is spelled as a date field's column spells it. */
272
+ protected override undeclaredDateColumn(): {
273
+ mapToDriverValue(value: unknown): unknown;
274
+ };
275
+ /** A table-level `primaryKey({ columns })`, read through the PostgreSQL table config. */
276
+ protected override compositePrimaryKey(tableObj: Record<string, unknown>): object[];
277
+ private createTransactionContext;
278
+ /**
279
+ * Classifies a PostgreSQL error into a DatabaseError.
280
+ *
281
+ * @param error - Original error from pg
282
+ * @param sql - SQL statement that caused the error (optional)
283
+ * @returns DatabaseError with proper classification
284
+ */
285
+ protected override classifyError(error: unknown, sql?: string): DatabaseError$1;
261
286
  }
262
287
  /**
263
288
  * Creates a PostgreSQL database adapter instance.
@@ -304,7 +329,7 @@ declare class PostgresAdapter extends DrizzleAdapter {
304
329
  *
305
330
  * @public
306
331
  */
307
- declare function createPostgresAdapter(config: PostgresAdapterConfig): PostgresAdapter;
332
+ export declare function createPostgresAdapter(config: PostgresAdapterConfig$1): PostgresAdapter;
308
333
  /**
309
334
  * Type guard to check if a value is a PostgresAdapter instance.
310
335
  *
@@ -323,6 +348,6 @@ declare function createPostgresAdapter(config: PostgresAdapterConfig): PostgresA
323
348
  *
324
349
  * @public
325
350
  */
326
- declare function isPostgresAdapter(value: unknown): value is PostgresAdapter;
327
-
328
- export { PostgresAdapter, VERSION, createPostgresAdapter, isPostgresAdapter };
351
+ export declare function isPostgresAdapter(value: unknown): value is PostgresAdapter;
352
+ export type { AdapterLogger, AdapterPoolConfig, BaseAdapterConfig, DatabaseCapabilities, DatabaseError, DatabaseErrorKind, DeleteOptions, InsertOptions, JoinSpec, OrderBySpec, PoolStats, PostgresAdapterConfig, SelectOptions, SqlParam, SslConfig, TransactionContext, TransactionOptions, UpdateOptions, UpsertOptions, WhereClause, WhereCondition, WhereOperator };
353
+ //# sourceMappingURL=index.d.cts.map