@nextlyhq/adapter-drizzle 0.0.2-alpha.6 → 0.0.2-alpha.62

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,68 +1,49 @@
1
+ import { AnyRelations, SQL } from 'drizzle-orm';
2
+ import { T as TransactionContext, S as SelectOptions, W as WhereClause, U as UpdateOptions, D as DeleteOptions, e as UpsertOptions, f as TransactionOptions, g as DatabaseCapabilities, P as PoolStats, I as InsertOptions, a as Migration, d as MigrationResult } from './migration-BnT96HFp.js';
1
3
  import { S as SupportedDialect, a as SqlParam, T as TableResolver } from './core-CVO7WYDj.js';
2
- import { T as TransactionContext, e as TransactionOptions, D as DatabaseCapabilities, P as PoolStats, S as SelectOptions, I as InsertOptions, W as WhereClause, U as UpdateOptions, f as DeleteOptions, g as UpsertOptions, a as Migration, d as MigrationResult } from './migration-Qe70wDOC.js';
3
4
  import { T as TableDefinition, C as CreateTableOptions, D as DropTableOptions, A as AlterTableOperation, a as AlterTableOptions } from './schema-BIQ0YQZ_.js';
4
- import { D as DatabaseErrorKind, a as DatabaseError } from './error-um1d_3Uo.js';
5
+ import { D as DatabaseErrorKind, a as DatabaseError } from './error-BrdknH2s.js';
5
6
 
6
7
  /**
7
- * Base database adapter abstract class.
8
+ * Transaction CRUD forwarder helper for database adapters.
8
9
  *
9
10
  * @remarks
10
- * This abstract class provides the foundation for all dialect-specific database adapters
11
- * (PostgreSQL, MySQL, SQLite). It defines required abstract methods that must be implemented
12
- * by subclasses, while providing default implementations for CRUD operations and query building.
13
- *
14
- * Dialect adapters can override any default method to provide optimized implementations.
11
+ * Encapsulates the delegation pattern where a transaction context forwards its
12
+ * CRUD methods to the adapter's implementation while passing the transaction-bound
13
+ * Drizzle executor.
15
14
  *
16
15
  * @packageDocumentation
17
16
  */
18
17
 
19
18
  /**
20
- * Abstract base class for database adapters.
19
+ * Interface representing an adapter that can execute CRUD operations with an optional executor.
20
+ */
21
+ interface TransactionCrudDelegator {
22
+ select<T = unknown>(table: string, options?: SelectOptions, executor?: unknown): Promise<T[]>;
23
+ selectOne<T = unknown>(table: string, options?: SelectOptions, executor?: unknown): Promise<T | null>;
24
+ update<T = unknown>(table: string, data: Record<string, unknown>, where: WhereClause, options?: UpdateOptions, executor?: unknown): Promise<T[]>;
25
+ updateCount(table: string, data: Record<string, unknown>, where: WhereClause, executor?: unknown): Promise<number>;
26
+ delete(table: string, where: WhereClause, options?: DeleteOptions, executor?: unknown): Promise<number>;
27
+ upsert<T = unknown>(table: string, data: Record<string, unknown>, options: UpsertOptions, executor?: unknown): Promise<T>;
28
+ }
29
+ /**
30
+ * Transaction context CRUD methods provided by the forwarder.
31
+ */
32
+ type TransactionCrudForwarders = Pick<TransactionContext, "select" | "selectOne" | "update" | "updateCount" | "delete" | "upsert" | "getDrizzle">;
33
+
34
+ /**
35
+ * Base database adapter abstract class.
21
36
  *
22
37
  * @remarks
23
- * All dialect-specific adapters must extend this class and implement the abstract methods.
24
- * Default implementations are provided for CRUD operations, which can be overridden for
25
- * optimization or dialect-specific behavior.
26
- *
27
- * ## Required Implementations
28
- *
29
- * Subclasses must implement:
30
- * - `dialect` - Database dialect identifier
31
- * - `connect()` - Establish database connection
32
- * - `disconnect()` - Close database connection
33
- * - `executeQuery()` - Execute raw SQL query
34
- * - `transaction()` - Execute operations within a transaction
35
- * - `getCapabilities()` - Report database feature support
36
- *
37
- * ## Optional Overrides
38
- *
39
- * Subclasses can override default CRUD methods for optimization:
40
- * - `select()`, `selectOne()` - Custom query optimization
41
- * - `insert()`, `insertMany()` - Bulk insert optimization
42
- * - `update()`, `delete()` - Custom update/delete logic
43
- * - `upsert()` - Dialect-specific upsert syntax
44
- *
45
- * @example
46
- * ```typescript
47
- * export class PostgresAdapter extends DrizzleAdapter {
48
- * readonly dialect = 'postgresql' as const;
49
- *
50
- * async connect() {
51
- * this.pool = new Pool({ connectionString: this.config.url });
52
- * // ... connection logic
53
- * }
54
- *
55
- * async executeQuery<T>(sql: string, params?: SqlParam[]) {
56
- * const result = await this.pool.query(sql, params);
57
- * return result.rows as T[];
58
- * }
38
+ * This abstract class provides the foundation for all dialect-specific database adapters
39
+ * (PostgreSQL, MySQL, SQLite). It defines required abstract methods that must be implemented
40
+ * by subclasses, while providing default implementations for CRUD operations and query building.
59
41
  *
60
- * // ... other required methods
61
- * }
62
- * ```
42
+ * Dialect adapters can override any default method to provide optimized implementations.
63
43
  *
64
- * @public
44
+ * @packageDocumentation
65
45
  */
46
+
66
47
  declare abstract class DrizzleAdapter {
67
48
  /**
68
49
  * Database dialect identifier.
@@ -106,11 +87,29 @@ declare abstract class DrizzleAdapter {
106
87
  * The transaction is automatically committed on success or rolled back on error.
107
88
  * Supports nested transactions via savepoints on databases that support them.
108
89
  *
90
+ * Two kinds of error leave this method, and a caller has to be able to tell
91
+ * them apart. An error carrying the Nextly application brand — see
92
+ * `isApplicationError` — arrives exactly as it was thrown, because that is
93
+ * the application refusing the write rather than the database failing to
94
+ * perform it, and rewriting it would discard the code and payload the caller
95
+ * is meant to act on.
96
+ *
97
+ * Everything else arrives as a `DatabaseError` with its kind classified, and
98
+ * that deliberately includes an unbranded error the callback itself threw:
99
+ * the brand is the only thing distinguishing a deliberate refusal from a
100
+ * driver failure that surfaced through callback code, and guessing from the
101
+ * throw site would put raw driver text on the wire under a caller's own
102
+ * error shape.
103
+ *
104
+ * The rollback is the same either way.
105
+ *
109
106
  * @param callback - Function to execute within transaction
110
107
  * @param options - Transaction options
111
108
  * @returns Result from the callback
112
109
  *
113
- * @throws {DatabaseError} If transaction fails
110
+ * @throws {DatabaseError} If the transaction itself fails, or if the callback
111
+ * threw an error that does not carry the application brand
112
+ * @throws The callback's own error, unchanged, when it carries that brand
114
113
  */
115
114
  abstract transaction<T>(callback: (ctx: TransactionContext) => Promise<T>, options?: TransactionOptions): Promise<T>;
116
115
  /**
@@ -136,17 +135,18 @@ declare abstract class DrizzleAdapter {
136
135
  * - Consistent error handling
137
136
  * - Proper connection pooling
138
137
  *
139
- * @param schema - Optional schema object for typed queries
138
+ * @param relations - Optional drizzle v1 relations config (defineRelations
139
+ * output) that enables the typed relational query API on the instance
140
140
  * @returns Raw Drizzle ORM database instance
141
141
  *
142
142
  * @example
143
143
  * ```typescript
144
144
  * // For legacy code that needs direct Drizzle access
145
- * const db = adapter.getDrizzle(mySchemas);
145
+ * const db = adapter.getDrizzle(myRelations); // defineRelations output
146
146
  * const result = await db.insert(users).values({ ... }).returning();
147
147
  * ```
148
148
  */
149
- abstract getDrizzle<T = unknown>(schema?: Record<string, unknown>): T;
149
+ abstract getDrizzle<T = unknown>(relations?: AnyRelations): T;
150
150
  /**
151
151
  * Table resolver for looking up Drizzle table objects by name.
152
152
  * When set, CRUD methods use Drizzle's query API instead of raw SQL.
@@ -167,6 +167,27 @@ declare abstract class DrizzleAdapter {
167
167
  * Returns null if no resolver is set or table is not found.
168
168
  */
169
169
  protected getTableObject(tableName: string): unknown;
170
+ /**
171
+ * Run a Drizzle-built statement and return its rows.
172
+ *
173
+ * @remarks
174
+ * The CRUD methods resolve their table through the schema registry and reject
175
+ * any name it does not declare, which leaves no way to read from a table the
176
+ * ORM does not know — one mid-rename, above all — except by assembling SQL and
177
+ * quoting identifiers by hand. This takes Drizzle's `sql` template instead, so
178
+ * the dialect in use decides the quoting and the parameter binding.
179
+ *
180
+ * Concrete rather than abstract so existing adapters keep working unchanged.
181
+ * The three drivers disagree about both the call and the result: node-postgres
182
+ * returns `{ rows }`, mysql2 a `[rows, fields]` tuple, and better-sqlite3 has
183
+ * no `execute` at all and answers `all`. Keeping that here rather than at each
184
+ * call site is the point — a caller reasoning about it would be reasoning
185
+ * about a driver it cannot see.
186
+ *
187
+ * @param statement - Drizzle `sql` template to run
188
+ * @returns Rows the statement produced
189
+ */
190
+ queryStatement<T = Record<string, unknown>>(statement: SQL): Promise<T[]>;
170
191
  /**
171
192
  * Map data keys from SQL column names (snake_case) to Drizzle JS property names (camelCase).
172
193
  * Drizzle schemas define columns as e.g. `createdAt: timestamp("created_at")` — the JS
@@ -174,6 +195,131 @@ declare abstract class DrizzleAdapter {
174
195
  * because they match the DB column names. This method maps them to the JS names Drizzle expects.
175
196
  */
176
197
  protected mapDataToColumnNames(tableObj: unknown, data: Record<string, unknown>): Record<string, unknown>;
198
+ /**
199
+ * Map data keys from Drizzle JS property names to SQL column names for the
200
+ * raw-SQL transaction insert path. The transaction context builds INSERT
201
+ * statements from Object.keys(data) used directly as column identifiers, so a
202
+ * table whose Drizzle property names differ from its SQL column names
203
+ * (camelCase core tables like nextly_versions) needs its keys translated
204
+ * first. For tables whose property names already equal their column names
205
+ * (the dynamic dc_/single_/comp_ tables) every lookup is identity, so
206
+ * existing callers are unaffected.
207
+ */
208
+ protected mapKeysToSqlColumns(tableObj: unknown, data: Record<string, unknown>): Record<string, unknown>;
209
+ /**
210
+ * Map a list of column identifiers (Drizzle property names) to their SQL
211
+ * column names, for the raw-SQL transaction insert paths that build a
212
+ * RETURNING clause from `options.returning`. Same identity behavior as
213
+ * `mapKeysToSqlColumns`: names that are already SQL columns (the dynamic
214
+ * dc_/single_/comp_ tables) pass through unchanged.
215
+ */
216
+ protected mapColumnNamesToSql(tableObj: unknown, names: string[]): string[];
217
+ /**
218
+ * Remap a raw-SQL result row's KEYS from SQL column names to Drizzle property
219
+ * names, so the raw-SQL transaction insert paths return the same key casing
220
+ * as the non-transactional (Drizzle) insert. Keys only - values are left
221
+ * untouched, so this does not change how JSON/date columns are decoded. For
222
+ * tables whose property names already equal their SQL columns (the dynamic
223
+ * dc_/single_/comp_ tables) every lookup is identity, so existing callers see
224
+ * no change.
225
+ */
226
+ protected mapRowKeysToJs<T = unknown>(tableObj: unknown, row: T): T;
227
+ /**
228
+ * Decode a raw-SQL result row's DATE column values the way a Drizzle query
229
+ * would, so a write answers with the same representation a read of the same
230
+ * column gives.
231
+ *
232
+ * A Drizzle query path runs every value through its column definition; a
233
+ * raw-SQL path does not, so a dialect that stores a timestamp as a number
234
+ * answers a write with that number while every read answers a `Date`. Only
235
+ * date columns are touched, and a value that is already a `Date` is left
236
+ * alone, so a driver that decodes on its own is unaffected.
237
+ *
238
+ * Runs after {@link mapRowKeysToJs}: keys are Drizzle property names by then,
239
+ * which is what the table definition is keyed by.
240
+ */
241
+ protected mapDateValuesFromDriver<T = unknown>(tableObj: unknown, row: T): T;
242
+ /**
243
+ * Encode a row's DATE values the way a Drizzle query would before binding
244
+ * them, so what lands in the column does not depend on the server's timezone.
245
+ *
246
+ * A column declared without a time zone stores a wall clock and records
247
+ * nothing about which zone it belongs to, so both ends have to agree. Drizzle
248
+ * writes UTC and reads UTC. A driver handed a `Date` writes the LOCAL wall
249
+ * clock instead, and the same row then reads back shifted by the offset --
250
+ * on a UTC server the two agree and nothing is visibly wrong, which is why
251
+ * this survives CI.
252
+ *
253
+ * Only date columns are touched. A value that is not a `Date` is left as it
254
+ * is, so a caller that already encoded one is not encoded twice.
255
+ *
256
+ * Keys may be spelled either way at this point, so both the Drizzle property
257
+ * name and the SQL column name resolve.
258
+ */
259
+ protected mapDateValuesToDriver(tableObj: unknown, data: Record<string, unknown>): Record<string, unknown>;
260
+ /**
261
+ * Bring a row about to be written through a raw-SQL statement into the shape
262
+ * a Drizzle query would have bound: SQL column names for keys, encoded values
263
+ * for date columns.
264
+ *
265
+ * The mirror of {@link mapRowFromRawSql}. The raw-SQL write paths exist
266
+ * because a dialect needs SQL a Drizzle query cannot express, not because
267
+ * their callers want different values in the table.
268
+ */
269
+ protected mapRowToRawSql(tableObj: unknown, data: Record<string, unknown>): Record<string, unknown>;
270
+ /**
271
+ * Bring a raw-SQL result row into the shape a Drizzle query would have
272
+ * produced: Drizzle property names for keys, decoded values for date columns.
273
+ *
274
+ * The raw-SQL write paths exist because a dialect needs SQL a Drizzle query
275
+ * cannot express, not because their callers want a different row shape, so
276
+ * every one of them ends here.
277
+ */
278
+ protected mapRowFromRawSql<T = unknown>(tableObj: unknown, row: T, aliases?: ReadonlyArray<{
279
+ alias: string;
280
+ jsName: string;
281
+ }>): T;
282
+ /**
283
+ * The date columns a statement is about to return, and the alias each one's
284
+ * wall clock is spelled out under.
285
+ *
286
+ * A driver turns a timestamp into a `Date` using ITS zone before any of this
287
+ * code runs, and that conversion is lossy: a wall clock inside a
288
+ * daylight-saving gap is a local time that does not exist, so the driver
289
+ * normalizes it and the original is gone. Asking the database for the wall
290
+ * clock as text alongside the row is the only way to read it exactly.
291
+ *
292
+ * `"*"` covers every date column; a projection covers only the ones it asked
293
+ * for, so a caller still gets back what it requested and nothing more.
294
+ */
295
+ protected dateWallClockAliases(tableObj: unknown, returning: string[] | "*" | undefined): Array<{
296
+ sqlName: string;
297
+ alias: string;
298
+ jsName: string;
299
+ }>;
300
+ /**
301
+ * Replace each date in a row with the wall clock the database spelled out,
302
+ * read as UTC, and drop the aliases that carried it.
303
+ *
304
+ * The statement writes a UTC wall clock, so reading one back as UTC is what
305
+ * makes a write and a later read agree. Whatever the column actually stored
306
+ * is what arrives -- a column keeping only whole seconds reports whole
307
+ * seconds -- because this is the database's own text, not a value
308
+ * reconstructed from the one that was bound.
309
+ */
310
+ protected applyWallClockAliases<T>(row: T, aliases: ReadonlyArray<{
311
+ alias: string;
312
+ jsName: string;
313
+ }>): T;
314
+ /**
315
+ * Build a Drizzle column projection object (`{ propertyName: column }`) from a
316
+ * requested column list, used by `select` (columns) and `insert` (returning).
317
+ * A requested name resolves against either the Drizzle property name
318
+ * (camelCase) or the SQL column name (snake_case); the projection is keyed by
319
+ * the property name so the row shape matches a full select. Returns undefined
320
+ * for `"*"` or when nothing resolves, so callers fall back to all columns.
321
+ */
322
+ protected buildColumnProjection(tableObj: unknown, names: string[] | "*" | undefined): Record<string, unknown> | undefined;
177
323
  /**
178
324
  * Check if the adapter is currently connected.
179
325
  *
@@ -286,7 +432,7 @@ declare abstract class DrizzleAdapter {
286
432
  * });
287
433
  * ```
288
434
  */
289
- select<T = unknown>(table: string, options?: SelectOptions): Promise<T[]>;
435
+ select<T = unknown>(table: string, options?: SelectOptions, executor?: unknown): Promise<T[]>;
290
436
  /**
291
437
  * Select a single record from a table.
292
438
  *
@@ -307,7 +453,7 @@ declare abstract class DrizzleAdapter {
307
453
  * });
308
454
  * ```
309
455
  */
310
- selectOne<T = unknown>(table: string, options?: SelectOptions): Promise<T | null>;
456
+ selectOne<T = unknown>(table: string, options?: SelectOptions, executor?: unknown): Promise<T | null>;
311
457
  /**
312
458
  * Insert a single record into a table.
313
459
  *
@@ -378,7 +524,24 @@ declare abstract class DrizzleAdapter {
378
524
  * );
379
525
  * ```
380
526
  */
381
- update<T = unknown>(table: string, data: Record<string, unknown>, where: WhereClause, options?: UpdateOptions): Promise<T[]>;
527
+ update<T = unknown>(table: string, data: Record<string, unknown>, where: WhereClause, options?: UpdateOptions, executor?: unknown): Promise<T[]>;
528
+ /**
529
+ * Update records in a table and report how many rows the statement affected.
530
+ *
531
+ * The count is the whole return value, mirroring `delete`. `update` cannot answer this: without
532
+ * `returning` it discards the driver's count, and WITH `returning` on a dialect that lacks
533
+ * RETURNING it re-SELECTs using the same WHERE — so a conditional update that just changed a
534
+ * column named in that WHERE reads back zero rows and a write that landed reports as unmatched.
535
+ * Reading the driver's own count has no second query to disagree with the first.
536
+ *
537
+ * 🔴 MySQL reports CHANGED rows, not matched rows: an UPDATE that matches a row but writes values
538
+ * identical to what it holds counts zero. A caller using this as a compare-and-set must therefore
539
+ * include a column the write always moves — a version bump, a timestamp with enough resolution —
540
+ * so that matched implies changed. Postgres (`rowCount`) and SQLite (`changes`) count matched
541
+ * rows and do not need the precaution, which is exactly why it cannot be dropped: the dialect
542
+ * where the distinction exists is the one with no RETURNING to fall back on.
543
+ */
544
+ updateCount(table: string, data: Record<string, unknown>, where: WhereClause, executor?: unknown): Promise<number>;
382
545
  /**
383
546
  * Delete records from a table.
384
547
  *
@@ -401,7 +564,7 @@ declare abstract class DrizzleAdapter {
401
564
  * console.log(`Deleted ${count} users`);
402
565
  * ```
403
566
  */
404
- delete(table: string, where: WhereClause, _options?: DeleteOptions): Promise<number>;
567
+ delete(table: string, where: WhereClause, _options?: DeleteOptions, executor?: unknown): Promise<number>;
405
568
  /**
406
569
  * Upsert (INSERT or UPDATE) a record.
407
570
  *
@@ -429,7 +592,7 @@ declare abstract class DrizzleAdapter {
429
592
  * });
430
593
  * ```
431
594
  */
432
- upsert<T = unknown>(table: string, data: Record<string, unknown>, options: UpsertOptions): Promise<T>;
595
+ upsert<T = unknown>(table: string, data: Record<string, unknown>, options: UpsertOptions, executor?: unknown): Promise<T>;
433
596
  /**
434
597
  * Run pending migrations.
435
598
  *
@@ -572,12 +735,35 @@ declare abstract class DrizzleAdapter {
572
735
  * @protected
573
736
  */
574
737
  protected createDatabaseError(kind: DatabaseErrorKind, message: string, cause?: Error): DatabaseError;
738
+ /**
739
+ * Helper to create transaction context CRUD forwarding methods.
740
+ *
741
+ * @param txDb - Thunk returning the transaction-bound Drizzle executor
742
+ * @returns Object providing forwarded CRUD and getDrizzle methods
743
+ *
744
+ * @protected
745
+ */
746
+ protected createTransactionForwarders(txDb: () => unknown): TransactionCrudForwarders;
747
+ /**
748
+ * Classify an error into a DatabaseError.
749
+ *
750
+ * @remarks
751
+ * Subclasses can override this method to add dialect-specific error code classification.
752
+ *
753
+ * @param error - Original error
754
+ * @param sql - SQL statement that caused the error (optional)
755
+ * @returns DatabaseError instance
756
+ *
757
+ * @protected
758
+ */
759
+ protected classifyError(error: unknown, sql?: string): DatabaseError;
575
760
  /**
576
761
  * Handle query errors and convert to DatabaseError.
577
762
  *
578
763
  * @remarks
579
764
  * Protected helper for consistent error handling across CRUD operations.
580
- * Subclasses can override to add dialect-specific error classification.
765
+ * Delegates to `classifyError` and attaches operation and table context if not present.
766
+ * Subclasses override `classifyError` to provide dialect-specific error code classification.
581
767
  *
582
768
  * @param error - Original error
583
769
  * @param operation - Operation that failed
@@ -589,4 +775,4 @@ declare abstract class DrizzleAdapter {
589
775
  protected handleQueryError(error: unknown, operation: string, table: string): DatabaseError;
590
776
  }
591
777
 
592
- export { DrizzleAdapter as D };
778
+ export { DrizzleAdapter as D, type TransactionCrudDelegator as T, type TransactionCrudForwarders as a };