bun-types 1.2.21-canary.20250819T140628 → 1.2.21-canary.20250821T140634

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/sql.d.ts ADDED
@@ -0,0 +1,805 @@
1
+ import type * as BunSQLite from "bun:sqlite";
2
+
3
+ declare module "bun" {
4
+ /**
5
+ * Represents a reserved connection from the connection pool Extends SQL with
6
+ * additional release functionality
7
+ */
8
+ interface ReservedSQL extends SQL, Disposable {
9
+ /**
10
+ * Releases the client back to the connection pool
11
+ */
12
+ release(): void;
13
+ }
14
+
15
+ /**
16
+ * Represents a client within a transaction context Extends SQL with savepoint
17
+ * functionality
18
+ */
19
+ interface TransactionSQL extends SQL {
20
+ /**
21
+ * Creates a savepoint within the current transaction
22
+ */
23
+ savepoint<T>(name: string, fn: SQL.SavepointContextCallback<T>): Promise<T>;
24
+ savepoint<T>(fn: SQL.SavepointContextCallback<T>): Promise<T>;
25
+
26
+ /**
27
+ * The reserve method pulls out a connection from the pool, and returns a
28
+ * client that wraps the single connection.
29
+ *
30
+ * Using reserve() inside of a transaction will return a brand new
31
+ * connection, not one related to the transaction. This matches the
32
+ * behaviour of the `postgres` package.
33
+ */
34
+ reserve(): Promise<ReservedSQL>;
35
+ }
36
+
37
+ namespace SQL {
38
+ class SQLError extends Error {
39
+ constructor(message: string);
40
+ }
41
+
42
+ class PostgresError extends SQLError {
43
+ public readonly code: string;
44
+ public readonly errno: string | undefined;
45
+ public readonly detail: string | undefined;
46
+ public readonly hint: string | undefined;
47
+ public readonly severity: string | undefined;
48
+ public readonly position: string | undefined;
49
+ public readonly internalPosition: string | undefined;
50
+ public readonly internalQuery: string | undefined;
51
+ public readonly where: string | undefined;
52
+ public readonly schema: string | undefined;
53
+ public readonly table: string | undefined;
54
+ public readonly column: string | undefined;
55
+ public readonly dataType: string | undefined;
56
+ public readonly constraint: string | undefined;
57
+ public readonly file: string | undefined;
58
+ public readonly line: string | undefined;
59
+ public readonly routine: string | undefined;
60
+
61
+ constructor(
62
+ message: string,
63
+ options: {
64
+ code: string;
65
+ errno?: string | undefined;
66
+ detail?: string;
67
+ hint?: string | undefined;
68
+ severity?: string | undefined;
69
+ position?: string | undefined;
70
+ internalPosition?: string;
71
+ internalQuery?: string;
72
+ where?: string | undefined;
73
+ schema?: string;
74
+ table?: string | undefined;
75
+ column?: string | undefined;
76
+ dataType?: string | undefined;
77
+ constraint?: string;
78
+ file?: string | undefined;
79
+ line?: string | undefined;
80
+ routine?: string | undefined;
81
+ },
82
+ );
83
+ }
84
+
85
+ class SQLiteError extends SQLError {
86
+ public readonly code: string;
87
+ public readonly errno: number;
88
+ public readonly byteOffset?: number | undefined;
89
+
90
+ constructor(message: string, options: { code: string; errno: number; byteOffset?: number | undefined });
91
+ }
92
+
93
+ type AwaitPromisesArray<T extends Array<PromiseLike<any>>> = {
94
+ [K in keyof T]: Awaited<T[K]>;
95
+ };
96
+
97
+ type ContextCallbackResult<T> = T extends Array<PromiseLike<any>> ? AwaitPromisesArray<T> : Awaited<T>;
98
+ type ContextCallback<T, SQL> = (sql: SQL) => Bun.MaybePromise<T>;
99
+
100
+ interface SQLiteOptions extends BunSQLite.DatabaseOptions {
101
+ adapter?: "sqlite";
102
+
103
+ /**
104
+ * Specify the path to the database file
105
+ *
106
+ * Examples:
107
+ *
108
+ * - `sqlite://:memory:`
109
+ * - `sqlite://./path/to/database.db`
110
+ * - `sqlite:///Users/bun/projects/my-app/database.db`
111
+ * - `./dev.db`
112
+ * - `:memory:`
113
+ *
114
+ * @default ":memory:"
115
+ */
116
+ filename?: URL | ":memory:" | (string & {}) | undefined;
117
+
118
+ /**
119
+ * Callback executed when a connection attempt completes (SQLite)
120
+ * Receives an Error on failure, or null on success.
121
+ */
122
+ onconnect?: ((err: Error | null) => void) | undefined;
123
+
124
+ /**
125
+ * Callback executed when a connection is closed (SQLite)
126
+ * Receives the closing Error or null.
127
+ */
128
+ onclose?: ((err: Error | null) => void) | undefined;
129
+ }
130
+
131
+ interface PostgresOptions {
132
+ /**
133
+ * Connection URL (can be string or URL object)
134
+ */
135
+ url?: URL | string | undefined;
136
+
137
+ /**
138
+ * Database server hostname
139
+ * @default "localhost"
140
+ */
141
+ host?: string | undefined;
142
+
143
+ /**
144
+ * Database server hostname (alias for host)
145
+ * @deprecated Prefer {@link host}
146
+ * @default "localhost"
147
+ */
148
+ hostname?: string | undefined;
149
+
150
+ /**
151
+ * Database server port number
152
+ * @default 5432
153
+ */
154
+ port?: number | string | undefined;
155
+
156
+ /**
157
+ * Database user for authentication
158
+ * @default "postgres"
159
+ */
160
+ username?: string | undefined;
161
+
162
+ /**
163
+ * Database user for authentication (alias for username)
164
+ * @deprecated Prefer {@link username}
165
+ * @default "postgres"
166
+ */
167
+ user?: string | undefined;
168
+
169
+ /**
170
+ * Database password for authentication
171
+ * @default ""
172
+ */
173
+ password?: string | (() => MaybePromise<string>) | undefined;
174
+
175
+ /**
176
+ * Database password for authentication (alias for password)
177
+ * @deprecated Prefer {@link password}
178
+ * @default ""
179
+ */
180
+ pass?: string | (() => MaybePromise<string>) | undefined;
181
+
182
+ /**
183
+ * Name of the database to connect to
184
+ * @default The username value
185
+ */
186
+ database?: string | undefined;
187
+
188
+ /**
189
+ * Name of the database to connect to (alias for database)
190
+ * @deprecated Prefer {@link database}
191
+ * @default The username value
192
+ */
193
+ db?: string | undefined;
194
+
195
+ /**
196
+ * Database adapter/driver to use
197
+ * @default "postgres"
198
+ */
199
+ adapter?: "postgres";
200
+
201
+ /**
202
+ * Maximum time in seconds to wait for connection to become available
203
+ * @default 0 (no timeout)
204
+ */
205
+ idleTimeout?: number | undefined;
206
+
207
+ /**
208
+ * Maximum time in seconds to wait for connection to become available (alias for idleTimeout)
209
+ * @deprecated Prefer {@link idleTimeout}
210
+ * @default 0 (no timeout)
211
+ */
212
+ idle_timeout?: number | undefined;
213
+
214
+ /**
215
+ * Maximum time in seconds to wait when establishing a connection
216
+ * @default 30
217
+ */
218
+ connectionTimeout?: number | undefined;
219
+
220
+ /**
221
+ * Maximum time in seconds to wait when establishing a connection (alias for connectionTimeout)
222
+ * @deprecated Prefer {@link connectionTimeout}
223
+ * @default 30
224
+ */
225
+ connection_timeout?: number | undefined;
226
+
227
+ /**
228
+ * Maximum time in seconds to wait when establishing a connection (alias
229
+ * for connectionTimeout)
230
+ * @deprecated Prefer {@link connectionTimeout}
231
+ * @default 30
232
+ */
233
+ connectTimeout?: number | undefined;
234
+
235
+ /**
236
+ * Maximum time in seconds to wait when establishing a connection (alias
237
+ * for connectionTimeout)
238
+ * @deprecated Prefer {@link connectionTimeout}
239
+ * @default 30
240
+ */
241
+ connect_timeout?: number | undefined;
242
+
243
+ /**
244
+ * Maximum lifetime in seconds of a connection
245
+ * @default 0 (no maximum lifetime)
246
+ */
247
+ maxLifetime?: number | undefined;
248
+
249
+ /**
250
+ * Maximum lifetime in seconds of a connection (alias for maxLifetime)
251
+ * @deprecated Prefer {@link maxLifetime}
252
+ * @default 0 (no maximum lifetime)
253
+ */
254
+ max_lifetime?: number | undefined;
255
+
256
+ /**
257
+ * Whether to use TLS/SSL for the connection
258
+ * @default false
259
+ */
260
+ tls?: TLSOptions | boolean | undefined;
261
+
262
+ /**
263
+ * Whether to use TLS/SSL for the connection (alias for tls)
264
+ * @default false
265
+ */
266
+ ssl?: TLSOptions | boolean | undefined;
267
+
268
+ // `.path` is currently unsupported in Bun, the implementation is
269
+ // incomplete.
270
+ //
271
+ // /**
272
+ // * Unix domain socket path for connection
273
+ // * @default ""
274
+ // */
275
+ // path?: string | undefined;
276
+
277
+ /**
278
+ * Callback executed when a connection attempt completes
279
+ * Receives an Error on failure, or null on success.
280
+ */
281
+ onconnect?: ((err: Error | null) => void) | undefined;
282
+
283
+ /**
284
+ * Callback executed when a connection is closed
285
+ * Receives the closing Error or null.
286
+ */
287
+ onclose?: ((err: Error | null) => void) | undefined;
288
+
289
+ /**
290
+ * Postgres client runtime configuration options
291
+ *
292
+ * @see https://www.postgresql.org/docs/current/runtime-config-client.html
293
+ */
294
+ connection?: Record<string, string | boolean | number> | undefined;
295
+
296
+ /**
297
+ * Maximum number of connections in the pool
298
+ * @default 10
299
+ */
300
+ max?: number | undefined;
301
+
302
+ /**
303
+ * By default values outside i32 range are returned as strings. If this is
304
+ * true, values outside i32 range are returned as BigInts.
305
+ * @default false
306
+ */
307
+ bigint?: boolean | undefined;
308
+
309
+ /**
310
+ * Automatic creation of prepared statements
311
+ * @default true
312
+ */
313
+ prepare?: boolean | undefined;
314
+ }
315
+
316
+ /**
317
+ * Configuration options for SQL client connection and behavior
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * const config: Bun.SQL.Options = {
322
+ * host: 'localhost',
323
+ * port: 5432,
324
+ * user: 'dbuser',
325
+ * password: 'secretpass',
326
+ * database: 'myapp',
327
+ * idleTimeout: 30,
328
+ * max: 20,
329
+ * onconnect: (client) => {
330
+ * console.log('Connected to database');
331
+ * }
332
+ * };
333
+ * ```
334
+ */
335
+ type Options = SQLiteOptions | PostgresOptions;
336
+
337
+ /**
338
+ * Represents a SQL query that can be executed, with additional control
339
+ * methods Extends Promise to allow for async/await usage
340
+ */
341
+ interface Query<T> extends Promise<T> {
342
+ /**
343
+ * Indicates if the query is currently executing
344
+ */
345
+ active: boolean;
346
+
347
+ /**
348
+ * Indicates if the query has been cancelled
349
+ */
350
+ cancelled: boolean;
351
+
352
+ /**
353
+ * Cancels the executing query
354
+ */
355
+ cancel(): Query<T>;
356
+
357
+ /**
358
+ * Executes the query as a simple query, no parameters are allowed but can
359
+ * execute multiple commands separated by semicolons
360
+ */
361
+ simple(): Query<T>;
362
+
363
+ /**
364
+ * Executes the query
365
+ */
366
+ execute(): Query<T>;
367
+
368
+ /**
369
+ * Returns the raw query result
370
+ */
371
+ raw(): Query<T>;
372
+
373
+ /**
374
+ * Returns only the values from the query result
375
+ */
376
+ values(): Query<T>;
377
+ }
378
+
379
+ /**
380
+ * Callback function type for transaction contexts
381
+ * @param sql Function to execute SQL queries within the transaction
382
+ */
383
+ type TransactionContextCallback<T> = ContextCallback<T, TransactionSQL>;
384
+
385
+ /**
386
+ * Callback function type for savepoint contexts
387
+ * @param sql Function to execute SQL queries within the savepoint
388
+ */
389
+ type SavepointContextCallback<T> = ContextCallback<T, SavepointSQL>;
390
+
391
+ /**
392
+ * SQL.Helper represents a parameter or serializable
393
+ * value inside of a query.
394
+ *
395
+ * @example
396
+ * ```ts
397
+ * const helper = sql(users, 'id');
398
+ * await sql`insert into users ${helper}`;
399
+ * ```
400
+ */
401
+ interface Helper<T> {
402
+ readonly value: T[];
403
+ readonly columns: (keyof T)[];
404
+ }
405
+ }
406
+
407
+ interface SQL extends AsyncDisposable {
408
+ /**
409
+ * Executes a SQL query using template literals
410
+ * @example
411
+ * ```ts
412
+ * const [user] = await sql<Users[]>`select * from users where id = ${1}`;
413
+ * ```
414
+ */
415
+ <T = any>(strings: TemplateStringsArray, ...values: unknown[]): SQL.Query<T>;
416
+
417
+ /**
418
+ * Execute a SQL query using a string
419
+ *
420
+ * @example
421
+ * ```ts
422
+ * const users = await sql<User[]>`SELECT * FROM users WHERE id = ${1}`;
423
+ * ```
424
+ */
425
+ <T = any>(string: string): SQL.Query<T>;
426
+
427
+ /**
428
+ * Helper function for inserting an object into a query
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * // Insert an object
433
+ * const result = await sql`insert into users ${sql(users)} returning *`;
434
+ *
435
+ * // Or pick specific columns
436
+ * const result = await sql`insert into users ${sql(users, "id", "name")} returning *`;
437
+ *
438
+ * // Or a single object
439
+ * const result = await sql`insert into users ${sql(user)} returning *`;
440
+ * ```
441
+ */
442
+ <T extends { [Key in PropertyKey]: unknown }>(obj: T | T[] | readonly T[]): SQL.Helper<T>; // Contributor note: This is the same as the signature below with the exception of the columns and the Pick<T, Keys>
443
+
444
+ /**
445
+ * Helper function for inserting an object into a query, supporting specific columns
446
+ *
447
+ * @example
448
+ * ```ts
449
+ * // Insert an object
450
+ * const result = await sql`insert into users ${sql(users)} returning *`;
451
+ *
452
+ * // Or pick specific columns
453
+ * const result = await sql`insert into users ${sql(users, "id", "name")} returning *`;
454
+ *
455
+ * // Or a single object
456
+ * const result = await sql`insert into users ${sql(user)} returning *`;
457
+ * ```
458
+ */
459
+ <T extends { [Key in PropertyKey]: unknown }, Keys extends keyof T = keyof T>(
460
+ obj: T | T[] | readonly T[],
461
+ ...columns: readonly Keys[]
462
+ ): SQL.Helper<Pick<T, Keys>>; // Contributor note: This is the same as the signature above with the exception of this signature tracking keys
463
+
464
+ /**
465
+ * Helper function for inserting any serializable value into a query
466
+ *
467
+ * @example
468
+ * ```ts
469
+ * const result = await sql`SELECT * FROM users WHERE id IN ${sql([1, 2, 3])}`;
470
+ * ```
471
+ */
472
+ <T>(value: T): SQL.Helper<T>;
473
+ }
474
+
475
+ /**
476
+ * Main SQL client interface providing connection and transaction management
477
+ */
478
+ class SQL {
479
+ /**
480
+ * Creates a new SQL client instance
481
+ *
482
+ * @param connectionString - The connection string for the SQL client
483
+ *
484
+ * @example
485
+ * ```ts
486
+ * const sql = new SQL("postgres://localhost:5432/mydb");
487
+ * const sql = new SQL(new URL("postgres://localhost:5432/mydb"));
488
+ * ```
489
+ */
490
+ constructor(connectionString: string | URL);
491
+
492
+ /**
493
+ * Creates a new SQL client instance with options
494
+ *
495
+ * @param connectionString - The connection string for the SQL client
496
+ * @param options - The options for the SQL client
497
+ *
498
+ * @example
499
+ * ```ts
500
+ * const sql = new SQL("postgres://localhost:5432/mydb", { idleTimeout: 1000 });
501
+ * ```
502
+ */
503
+ constructor(
504
+ connectionString: string | URL,
505
+ options: Bun.__internal.DistributedOmit<SQL.Options, "url" | "filename">,
506
+ );
507
+
508
+ /**
509
+ * Creates a new SQL client instance with options
510
+ *
511
+ * @param options - The options for the SQL client
512
+ *
513
+ * @example
514
+ * ```ts
515
+ * const sql = new SQL({ url: "postgres://localhost:5432/mydb", idleTimeout: 1000 });
516
+ * ```
517
+ */
518
+ constructor(options?: SQL.Options);
519
+
520
+ /**
521
+ * Current client options
522
+ */
523
+ options: Bun.__internal.DistributedMerge<SQL.Options>;
524
+
525
+ /**
526
+ * Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL
527
+ *
528
+ * @param name - The name of the distributed transaction
529
+ *
530
+ * @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
531
+ *
532
+ * @example
533
+ * ```ts
534
+ * await sql.commitDistributed("my_distributed_transaction");
535
+ * ```
536
+ */
537
+ commitDistributed(name: string): Promise<void>;
538
+
539
+ /**
540
+ * Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL
541
+ *
542
+ * @param name - The name of the distributed transaction
543
+ *
544
+ * @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
545
+ *
546
+ * @example
547
+ * ```ts
548
+ * await sql.rollbackDistributed("my_distributed_transaction");
549
+ * ```
550
+ */
551
+ rollbackDistributed(name: string): Promise<void>;
552
+
553
+ /** Waits for the database connection to be established
554
+ *
555
+ * @example
556
+ * ```ts
557
+ * await sql.connect();
558
+ * ```
559
+ */
560
+ connect(): Promise<SQL>;
561
+
562
+ /**
563
+ * Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.
564
+ *
565
+ * @param options - The options for the close
566
+ *
567
+ * @example
568
+ * ```ts
569
+ * await sql.close({ timeout: 1 });
570
+ * ```
571
+ */
572
+ close(options?: { timeout?: number }): Promise<void>;
573
+
574
+ /**
575
+ * Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.
576
+ * This is an alias of {@link SQL.close}
577
+ *
578
+ * @param options - The options for the close
579
+ *
580
+ * @example
581
+ * ```ts
582
+ * await sql.end({ timeout: 1 });
583
+ * ```
584
+ */
585
+ end(options?: { timeout?: number }): Promise<void>;
586
+
587
+ /**
588
+ * Flushes any pending operations
589
+ *
590
+ * @throws {Error} If the adapter does not support flushing (e.g., SQLite)
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * sql.flush();
595
+ * ```
596
+ */
597
+ flush(): void;
598
+
599
+ /**
600
+ * The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.
601
+ *
602
+ * This can be used for running queries on an isolated connection.
603
+ * Calling reserve in a reserved Sql will return a new reserved connection, not the same connection (behavior matches postgres package).
604
+ *
605
+ * @throws {Error} If the adapter does not support connection pooling (e.g., SQLite)s
606
+ *
607
+ * @example
608
+ * ```ts
609
+ * const reserved = await sql.reserve();
610
+ * await reserved`select * from users`;
611
+ * await reserved.release();
612
+ * // with in a production scenario would be something more like
613
+ * const reserved = await sql.reserve();
614
+ * try {
615
+ * // ... queries
616
+ * } finally {
617
+ * await reserved.release();
618
+ * }
619
+ *
620
+ * // Bun supports Symbol.dispose and Symbol.asyncDispose
621
+ * // always release after context (safer)
622
+ * using reserved = await sql.reserve()
623
+ * await reserved`select * from users`
624
+ * ```
625
+ */
626
+ reserve(): Promise<ReservedSQL>;
627
+
628
+ /**
629
+ * Begins a new transaction.
630
+ *
631
+ * Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function.
632
+ * BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
633
+ * @example
634
+ * const [user, account] = await sql.begin(async sql => {
635
+ * const [user] = await sql`
636
+ * insert into users (
637
+ * name
638
+ * ) values (
639
+ * 'Murray'
640
+ * )
641
+ * returning *
642
+ * `
643
+ * const [account] = await sql`
644
+ * insert into accounts (
645
+ * user_id
646
+ * ) values (
647
+ * ${ user.user_id }
648
+ * )
649
+ * returning *
650
+ * `
651
+ * return [user, account]
652
+ * })
653
+ */
654
+ begin<const T>(fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
655
+
656
+ /**
657
+ * Begins a new transaction with options.
658
+ *
659
+ * Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function.
660
+ * BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
661
+ * @example
662
+ * const [user, account] = await sql.begin("read write", async sql => {
663
+ * const [user] = await sql`
664
+ * insert into users (
665
+ * name
666
+ * ) values (
667
+ * 'Murray'
668
+ * )
669
+ * returning *
670
+ * `
671
+ * const [account] = await sql`
672
+ * insert into accounts (
673
+ * user_id
674
+ * ) values (
675
+ * ${ user.user_id }
676
+ * )
677
+ * returning *
678
+ * `
679
+ * return [user, account]
680
+ * })
681
+ */
682
+ begin<const T>(options: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
683
+
684
+ /**
685
+ * Alternative method to begin a transaction.
686
+ *
687
+ * Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function.
688
+ * BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
689
+ * @alias begin
690
+ * @example
691
+ * const [user, account] = await sql.transaction(async sql => {
692
+ * const [user] = await sql`
693
+ * insert into users (
694
+ * name
695
+ * ) values (
696
+ * 'Murray'
697
+ * )
698
+ * returning *
699
+ * `
700
+ * const [account] = await sql`
701
+ * insert into accounts (
702
+ * user_id
703
+ * ) values (
704
+ * ${ user.user_id }
705
+ * )
706
+ * returning *
707
+ * `
708
+ * return [user, account]
709
+ * })
710
+ */
711
+ transaction<const T>(fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
712
+
713
+ /**
714
+ * Alternative method to begin a transaction with options
715
+ * Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function.
716
+ * BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
717
+ *
718
+ * @alias {@link begin}
719
+ *
720
+ * @example
721
+ * const [user, account] = await sql.transaction("read write", async sql => {
722
+ * const [user] = await sql`
723
+ * insert into users (
724
+ * name
725
+ * ) values (
726
+ * 'Murray'
727
+ * )
728
+ * returning *
729
+ * `
730
+ * const [account] = await sql`
731
+ * insert into accounts (
732
+ * user_id
733
+ * ) values (
734
+ * ${ user.user_id }
735
+ * )
736
+ * returning *
737
+ * `
738
+ * return [user, account]
739
+ * });
740
+ */
741
+ transaction<const T>(options: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
742
+
743
+ /**
744
+ * Begins a distributed transaction
745
+ * Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks.
746
+ * In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks.
747
+ * beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well.
748
+ * PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection.
749
+ * These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.
750
+ *
751
+ * @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
752
+ *
753
+ * @example
754
+ * await sql.beginDistributed("numbers", async sql => {
755
+ * await sql`create table if not exists numbers (a int)`;
756
+ * await sql`insert into numbers values(1)`;
757
+ * });
758
+ * // later you can call
759
+ * await sql.commitDistributed("numbers");
760
+ * // or await sql.rollbackDistributed("numbers");
761
+ */
762
+ beginDistributed<const T>(
763
+ name: string,
764
+ fn: SQL.TransactionContextCallback<T>,
765
+ ): Promise<SQL.ContextCallbackResult<T>>;
766
+
767
+ /** Alternative method to begin a distributed transaction
768
+ * @alias {@link beginDistributed}
769
+ */
770
+ distributed<const T>(name: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
771
+
772
+ /**If you know what you're doing, you can use unsafe to pass any string you'd like.
773
+ * Please note that this can lead to SQL injection if you're not careful.
774
+ * You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.
775
+ * @example
776
+ * const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
777
+ */
778
+ unsafe<T = any>(string: string, values?: any[]): SQL.Query<T>;
779
+
780
+ /**
781
+ * Reads a file and uses the contents as a query.
782
+ * Optional parameters can be used if the file includes $1, $2, etc
783
+ * @example
784
+ * const result = await sql.file("query.sql", [1, 2, 3]);
785
+ */
786
+ file<T = any>(filename: string, values?: any[]): SQL.Query<T>;
787
+ }
788
+
789
+ /**
790
+ * SQL client
791
+ */
792
+ const sql: SQL;
793
+
794
+ /**
795
+ * SQL client for PostgreSQL
796
+ *
797
+ * @deprecated Prefer {@link Bun.sql}
798
+ */
799
+ const postgres: SQL;
800
+
801
+ /**
802
+ * Represents a savepoint within a transaction
803
+ */
804
+ interface SavepointSQL extends SQL {}
805
+ }