@tursodatabase/serverless 1.1.1 → 1.1.2-pre.1

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.cjs ADDED
@@ -0,0 +1,1064 @@
1
+ 'use strict';
2
+
3
+ // src/async-lock.ts
4
+ var AsyncLock = class {
5
+ constructor() {
6
+ this.locked = false;
7
+ this.queue = [];
8
+ }
9
+ async acquire() {
10
+ if (!this.locked) {
11
+ this.locked = true;
12
+ return;
13
+ }
14
+ return new Promise((resolve) => {
15
+ this.queue.push(resolve);
16
+ });
17
+ }
18
+ release() {
19
+ const next = this.queue.shift();
20
+ if (next) {
21
+ next();
22
+ } else {
23
+ this.locked = false;
24
+ }
25
+ }
26
+ };
27
+
28
+ // src/error.ts
29
+ var DatabaseError = class _DatabaseError extends Error {
30
+ constructor(message, code, rawCode, cause) {
31
+ super(message);
32
+ this.name = "DatabaseError";
33
+ this.code = code;
34
+ this.rawCode = rawCode;
35
+ this.cause = cause;
36
+ Object.setPrototypeOf(this, _DatabaseError.prototype);
37
+ }
38
+ };
39
+ var TimeoutError = class _TimeoutError extends DatabaseError {
40
+ constructor(message = "Query timed out", cause) {
41
+ super(message, "TIMEOUT", void 0, cause);
42
+ this.name = "TimeoutError";
43
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
44
+ }
45
+ };
46
+
47
+ // src/protocol.ts
48
+ function encodeValue(value) {
49
+ if (value === null || value === void 0) {
50
+ return { type: "null" };
51
+ }
52
+ if (typeof value === "number") {
53
+ if (!Number.isFinite(value)) {
54
+ throw new Error("Only finite numbers (not Infinity or NaN) can be passed as arguments");
55
+ }
56
+ if (Number.isInteger(value)) {
57
+ return { type: "integer", value: value.toString() };
58
+ }
59
+ return { type: "float", value };
60
+ }
61
+ if (typeof value === "bigint") {
62
+ return { type: "integer", value: value.toString() };
63
+ }
64
+ if (typeof value === "boolean") {
65
+ return { type: "integer", value: value ? "1" : "0" };
66
+ }
67
+ if (typeof value === "string") {
68
+ return { type: "text", value };
69
+ }
70
+ if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
71
+ const base64 = btoa(String.fromCharCode(...new Uint8Array(value)));
72
+ return { type: "blob", base64 };
73
+ }
74
+ return { type: "text", value: String(value) };
75
+ }
76
+ function decodeValue(value, safeIntegers = false) {
77
+ switch (value.type) {
78
+ case "null":
79
+ return null;
80
+ case "integer":
81
+ if (safeIntegers) {
82
+ return BigInt(value.value);
83
+ }
84
+ return parseInt(value.value, 10);
85
+ case "float":
86
+ return value.value;
87
+ case "text":
88
+ return value.value;
89
+ case "blob":
90
+ if (value.base64 !== void 0 && value.base64 !== null) {
91
+ let b64 = value.base64;
92
+ while (b64.length % 4 !== 0) {
93
+ b64 += "=";
94
+ }
95
+ const binaryString = atob(b64);
96
+ const bytes = new Uint8Array(binaryString.length);
97
+ for (let i = 0; i < binaryString.length; i++) {
98
+ bytes[i] = binaryString.charCodeAt(i);
99
+ }
100
+ return Buffer.from(bytes);
101
+ }
102
+ return Buffer.alloc(0);
103
+ default:
104
+ return null;
105
+ }
106
+ }
107
+ var ENCRYPTION_KEY_HEADER = "x-turso-encryption-key";
108
+ function wrapAbortError(error) {
109
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
110
+ throw new TimeoutError("Query timed out");
111
+ }
112
+ throw error;
113
+ }
114
+ async function executeCursor(url, authToken, request, remoteEncryptionKey, signal) {
115
+ const headers = {
116
+ "Content-Type": "application/json"
117
+ };
118
+ if (authToken) {
119
+ headers["Authorization"] = `Bearer ${authToken}`;
120
+ }
121
+ if (remoteEncryptionKey) {
122
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
123
+ }
124
+ let response;
125
+ try {
126
+ response = await fetch(`${url}/v3/cursor`, {
127
+ method: "POST",
128
+ headers,
129
+ body: JSON.stringify(request),
130
+ signal
131
+ });
132
+ } catch (error) {
133
+ wrapAbortError(error);
134
+ }
135
+ if (!response.ok) {
136
+ let errorMessage = `HTTP error! status: ${response.status}`;
137
+ try {
138
+ const errorBody = await response.text();
139
+ const errorData = JSON.parse(errorBody);
140
+ if (errorData.message) {
141
+ errorMessage = errorData.message;
142
+ }
143
+ } catch {
144
+ }
145
+ throw new DatabaseError(errorMessage);
146
+ }
147
+ const reader = response.body?.getReader();
148
+ if (!reader) {
149
+ throw new DatabaseError("No response body");
150
+ }
151
+ const decoder = new TextDecoder();
152
+ let buffer = "";
153
+ let cursorResponse;
154
+ try {
155
+ while (!cursorResponse) {
156
+ const { done, value } = await reader.read();
157
+ if (done) break;
158
+ buffer += decoder.decode(value, { stream: true });
159
+ const newlineIndex = buffer.indexOf("\n");
160
+ if (newlineIndex !== -1) {
161
+ const line = buffer.slice(0, newlineIndex).trim();
162
+ buffer = buffer.slice(newlineIndex + 1);
163
+ if (line) {
164
+ cursorResponse = JSON.parse(line);
165
+ break;
166
+ }
167
+ }
168
+ }
169
+ } catch (error) {
170
+ reader.releaseLock();
171
+ wrapAbortError(error);
172
+ }
173
+ if (!cursorResponse) {
174
+ reader.releaseLock();
175
+ throw new DatabaseError("No cursor response received");
176
+ }
177
+ async function* parseEntries() {
178
+ try {
179
+ let newlineIndex;
180
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
181
+ const line = buffer.slice(0, newlineIndex).trim();
182
+ buffer = buffer.slice(newlineIndex + 1);
183
+ if (line) {
184
+ yield JSON.parse(line);
185
+ }
186
+ }
187
+ while (true) {
188
+ let readResult;
189
+ try {
190
+ readResult = await reader.read();
191
+ } catch (error) {
192
+ wrapAbortError(error);
193
+ }
194
+ if (readResult.done) break;
195
+ buffer += decoder.decode(readResult.value, { stream: true });
196
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
197
+ const line = buffer.slice(0, newlineIndex).trim();
198
+ buffer = buffer.slice(newlineIndex + 1);
199
+ if (line) {
200
+ yield JSON.parse(line);
201
+ }
202
+ }
203
+ }
204
+ if (buffer.trim()) {
205
+ yield JSON.parse(buffer.trim());
206
+ }
207
+ } finally {
208
+ reader.releaseLock();
209
+ }
210
+ }
211
+ return { response: cursorResponse, entries: parseEntries() };
212
+ }
213
+ async function executePipeline(url, authToken, request, remoteEncryptionKey, signal) {
214
+ const headers = {
215
+ "Content-Type": "application/json"
216
+ };
217
+ if (authToken) {
218
+ headers["Authorization"] = `Bearer ${authToken}`;
219
+ }
220
+ if (remoteEncryptionKey) {
221
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
222
+ }
223
+ let response;
224
+ try {
225
+ response = await fetch(`${url}/v3/pipeline`, {
226
+ method: "POST",
227
+ headers,
228
+ body: JSON.stringify(request),
229
+ signal
230
+ });
231
+ } catch (error) {
232
+ wrapAbortError(error);
233
+ }
234
+ if (!response.ok) {
235
+ throw new DatabaseError(`HTTP error! status: ${response.status}`);
236
+ }
237
+ return response.json();
238
+ }
239
+
240
+ // src/session.ts
241
+ function normalizeUrl(url) {
242
+ return url.replace(/^libsql:\/\//, "https://");
243
+ }
244
+ function isValidIdentifier(str) {
245
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(str);
246
+ }
247
+ var Session = class {
248
+ constructor(config) {
249
+ this.baton = null;
250
+ this.config = config;
251
+ this.baseUrl = normalizeUrl(config.url);
252
+ }
253
+ createAbortSignal(queryOptions) {
254
+ const timeout = queryOptions?.queryTimeout ?? this.config.defaultQueryTimeout;
255
+ if (timeout != null && timeout > 0) {
256
+ return AbortSignal.timeout(timeout);
257
+ }
258
+ return void 0;
259
+ }
260
+ /**
261
+ * Describe a SQL statement to get its column metadata.
262
+ *
263
+ * @param sql - The SQL statement to describe
264
+ * @returns Promise resolving to the statement description
265
+ */
266
+ async describe(sql, queryOptions) {
267
+ const request = {
268
+ baton: this.baton,
269
+ requests: [{
270
+ type: "describe",
271
+ sql
272
+ }]
273
+ };
274
+ let response;
275
+ try {
276
+ response = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
277
+ } catch (e) {
278
+ this.baton = null;
279
+ throw e;
280
+ }
281
+ this.baton = response.baton;
282
+ if (response.base_url) {
283
+ this.baseUrl = response.base_url;
284
+ }
285
+ if (response.results && response.results[0]) {
286
+ const result = response.results[0];
287
+ if (result.type === "error") {
288
+ throw new DatabaseError(result.error?.message || "Describe execution failed", result.error?.code);
289
+ }
290
+ if (result.response?.type === "describe" && result.response.result) {
291
+ return result.response.result;
292
+ }
293
+ }
294
+ throw new DatabaseError("Unexpected describe response");
295
+ }
296
+ /**
297
+ * Execute a SQL statement and return all results.
298
+ *
299
+ * @param sql - The SQL statement to execute
300
+ * @param args - Optional array of parameter values or object with named parameters
301
+ * @param safeIntegers - Whether to return integers as BigInt
302
+ * @returns Promise resolving to the complete result set
303
+ */
304
+ async execute(sql, args = [], safeIntegers = false, queryOptions) {
305
+ const { response, entries } = await this.executeRaw(sql, args, queryOptions);
306
+ const result = await this.processCursorEntries(entries, safeIntegers);
307
+ return result;
308
+ }
309
+ /**
310
+ * Execute a SQL statement and return the raw response and entries.
311
+ *
312
+ * @param sql - The SQL statement to execute
313
+ * @param args - Optional array of parameter values or object with named parameters
314
+ * @returns Promise resolving to the raw response and cursor entries
315
+ */
316
+ async executeRaw(sql, args = [], queryOptions) {
317
+ let positionalArgs = [];
318
+ let namedArgs = [];
319
+ if (Array.isArray(args)) {
320
+ positionalArgs = args.map(encodeValue);
321
+ } else {
322
+ const keys = Object.keys(args);
323
+ const isNumericKeys = keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
324
+ if (isNumericKeys) {
325
+ const sortedKeys = keys.sort((a, b) => parseInt(a) - parseInt(b));
326
+ const maxIndex = parseInt(sortedKeys[sortedKeys.length - 1]);
327
+ positionalArgs = new Array(maxIndex);
328
+ for (const key of sortedKeys) {
329
+ const index = parseInt(key) - 1;
330
+ positionalArgs[index] = encodeValue(args[key]);
331
+ }
332
+ for (let i = 0; i < positionalArgs.length; i++) {
333
+ if (positionalArgs[i] === void 0) {
334
+ positionalArgs[i] = { type: "null" };
335
+ }
336
+ }
337
+ } else {
338
+ namedArgs = Object.entries(args).map(([name, value]) => ({
339
+ name,
340
+ value: encodeValue(value)
341
+ }));
342
+ }
343
+ }
344
+ const request = {
345
+ baton: this.baton,
346
+ batch: {
347
+ steps: [{
348
+ stmt: {
349
+ sql,
350
+ args: positionalArgs,
351
+ named_args: namedArgs,
352
+ want_rows: true
353
+ }
354
+ }]
355
+ }
356
+ };
357
+ let result;
358
+ try {
359
+ result = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
360
+ } catch (e) {
361
+ this.baton = null;
362
+ throw e;
363
+ }
364
+ const { response, entries } = result;
365
+ this.baton = response.baton;
366
+ if (response.base_url) {
367
+ this.baseUrl = response.base_url;
368
+ }
369
+ return { response, entries };
370
+ }
371
+ /**
372
+ * Process cursor entries into a structured result.
373
+ *
374
+ * @param entries - Async generator of cursor entries
375
+ * @returns Promise resolving to the processed result
376
+ */
377
+ async processCursorEntries(entries, safeIntegers = false) {
378
+ let columns = [];
379
+ let columnTypes = [];
380
+ let rows = [];
381
+ let rowsAffected = 0;
382
+ let lastInsertRowid;
383
+ for await (const entry of entries) {
384
+ switch (entry.type) {
385
+ case "step_begin":
386
+ if (entry.cols) {
387
+ columns = entry.cols.map((col) => col.name);
388
+ columnTypes = entry.cols.map((col) => col.decltype || "");
389
+ }
390
+ break;
391
+ case "row":
392
+ if (entry.row) {
393
+ const decodedRow = entry.row.map((value) => decodeValue(value, safeIntegers));
394
+ const rowObject = this.createRowObject(decodedRow, columns);
395
+ rows.push(rowObject);
396
+ }
397
+ break;
398
+ case "step_end":
399
+ if (entry.affected_row_count !== void 0) {
400
+ rowsAffected = entry.affected_row_count;
401
+ }
402
+ if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
403
+ lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
404
+ }
405
+ break;
406
+ case "step_error":
407
+ case "error":
408
+ throw new DatabaseError(entry.error?.message || "SQL execution failed", entry.error?.code);
409
+ }
410
+ }
411
+ return {
412
+ columns,
413
+ columnTypes,
414
+ rows,
415
+ rowsAffected,
416
+ lastInsertRowid
417
+ };
418
+ }
419
+ /**
420
+ * Create a row object with both array and named property access.
421
+ *
422
+ * @param values - Array of column values
423
+ * @param columns - Array of column names
424
+ * @returns Row object with dual access patterns
425
+ */
426
+ createRowObject(values, columns) {
427
+ const row = [...values];
428
+ columns.forEach((column, index) => {
429
+ if (column && isValidIdentifier(column)) {
430
+ Object.defineProperty(row, column, {
431
+ value: values[index],
432
+ enumerable: false,
433
+ writable: false,
434
+ configurable: true
435
+ });
436
+ }
437
+ });
438
+ return row;
439
+ }
440
+ /**
441
+ * Execute multiple SQL statements in a batch.
442
+ *
443
+ * @param statements - Array of SQL statements to execute
444
+ * @returns Promise resolving to batch execution results
445
+ */
446
+ async batch(statements, queryOptions) {
447
+ const request = {
448
+ baton: this.baton,
449
+ batch: {
450
+ steps: statements.map((sql) => ({
451
+ stmt: {
452
+ sql,
453
+ args: [],
454
+ named_args: [],
455
+ want_rows: false
456
+ }
457
+ }))
458
+ }
459
+ };
460
+ let batchResult;
461
+ try {
462
+ batchResult = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
463
+ } catch (e) {
464
+ this.baton = null;
465
+ throw e;
466
+ }
467
+ const { response, entries } = batchResult;
468
+ this.baton = response.baton;
469
+ if (response.base_url) {
470
+ this.baseUrl = response.base_url;
471
+ }
472
+ let totalRowsAffected = 0;
473
+ let lastInsertRowid;
474
+ for await (const entry of entries) {
475
+ switch (entry.type) {
476
+ case "step_end":
477
+ if (entry.affected_row_count !== void 0) {
478
+ totalRowsAffected += entry.affected_row_count;
479
+ }
480
+ if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
481
+ lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
482
+ }
483
+ break;
484
+ case "step_error":
485
+ case "error":
486
+ throw new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
487
+ }
488
+ }
489
+ return {
490
+ rowsAffected: totalRowsAffected,
491
+ lastInsertRowid
492
+ };
493
+ }
494
+ /**
495
+ * Execute a sequence of SQL statements separated by semicolons.
496
+ *
497
+ * @param sql - SQL string containing multiple statements separated by semicolons
498
+ * @returns Promise resolving when all statements are executed
499
+ */
500
+ async sequence(sql, queryOptions) {
501
+ const request = {
502
+ baton: this.baton,
503
+ requests: [{
504
+ type: "sequence",
505
+ sql
506
+ }]
507
+ };
508
+ let seqResponse;
509
+ try {
510
+ seqResponse = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
511
+ } catch (e) {
512
+ this.baton = null;
513
+ throw e;
514
+ }
515
+ this.baton = seqResponse.baton;
516
+ if (seqResponse.base_url) {
517
+ this.baseUrl = seqResponse.base_url;
518
+ }
519
+ if (seqResponse.results && seqResponse.results[0]) {
520
+ const result = seqResponse.results[0];
521
+ if (result.type === "error") {
522
+ throw new DatabaseError(result.error?.message || "Sequence execution failed", result.error?.code);
523
+ }
524
+ }
525
+ }
526
+ /**
527
+ * Close the session.
528
+ *
529
+ * This sends a close request to the server to properly clean up the stream
530
+ * before resetting the local state.
531
+ */
532
+ async close() {
533
+ if (this.baton) {
534
+ try {
535
+ const request = {
536
+ baton: this.baton,
537
+ requests: [{
538
+ type: "close"
539
+ }]
540
+ };
541
+ await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
542
+ } catch {
543
+ }
544
+ }
545
+ this.baton = null;
546
+ this.baseUrl = "";
547
+ }
548
+ };
549
+
550
+ // src/statement.ts
551
+ var Statement = class _Statement {
552
+ constructor(sessionConfig, sql, columns) {
553
+ this.presentationMode = "expanded";
554
+ this.safeIntegerMode = false;
555
+ this.session = new Session(sessionConfig);
556
+ this.sql = sql;
557
+ this.columnMetadata = columns || [];
558
+ }
559
+ /**
560
+ * Create a Statement that shares an existing session and serializes execution
561
+ * through the given lock. Used by Connection.prepare() so prepared statements
562
+ * participate in the connection's transaction scope.
563
+ */
564
+ static fromSession(session, sql, columns, execLock) {
565
+ const stmt = Object.create(_Statement.prototype);
566
+ stmt.session = session;
567
+ stmt.sql = sql;
568
+ stmt.columnMetadata = columns || [];
569
+ stmt.presentationMode = "expanded";
570
+ stmt.safeIntegerMode = false;
571
+ stmt.execLock = execLock;
572
+ return stmt;
573
+ }
574
+ /**
575
+ * Whether the prepared statement returns data.
576
+ *
577
+ * This is `true` for SELECT queries and statements with RETURNING clause,
578
+ * and `false` for INSERT, UPDATE, DELETE statements without RETURNING.
579
+ *
580
+ * @example
581
+ * ```typescript
582
+ * const stmt = await conn.prepare(sql);
583
+ * if (stmt.reader) {
584
+ * return stmt.all(args); // SELECT-like query
585
+ * } else {
586
+ * return stmt.run(args); // INSERT/UPDATE/DELETE
587
+ * }
588
+ * ```
589
+ */
590
+ get reader() {
591
+ return this.columnMetadata.length > 0;
592
+ }
593
+ /**
594
+ * Enable raw mode to return arrays instead of objects.
595
+ *
596
+ * @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
597
+ * @returns This statement instance for chaining
598
+ *
599
+ * @example
600
+ * ```typescript
601
+ * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
602
+ * const row = await stmt.raw().get([1]);
603
+ * console.log(row); // [1, "Alice", "alice@example.org"]
604
+ * ```
605
+ */
606
+ raw(raw) {
607
+ this.presentationMode = raw === false ? "expanded" : "raw";
608
+ return this;
609
+ }
610
+ /**
611
+ * Enable pluck mode to return only the first column value from each row.
612
+ *
613
+ * @param pluck Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
614
+ * @returns This statement instance for chaining
615
+ *
616
+ * @example
617
+ * ```typescript
618
+ * const stmt = client.prepare("SELECT id FROM users");
619
+ * const ids = await stmt.pluck().all();
620
+ * console.log(ids); // [1, 2, 3, ...]
621
+ * ```
622
+ */
623
+ pluck(pluck) {
624
+ this.presentationMode = pluck === false ? "expanded" : "pluck";
625
+ return this;
626
+ }
627
+ /**
628
+ * Sets safe integers mode for this statement.
629
+ *
630
+ * @param toggle Whether to use safe integers. If you don't pass the parameter, safe integers mode is enabled.
631
+ * @returns This statement instance for chaining
632
+ */
633
+ safeIntegers(toggle) {
634
+ this.safeIntegerMode = toggle === false ? false : true;
635
+ return this;
636
+ }
637
+ /**
638
+ * Get column information for this statement.
639
+ *
640
+ * @returns Array of column metadata objects matching the native bindings format
641
+ *
642
+ * @example
643
+ * ```typescript
644
+ * const stmt = await client.prepare("SELECT id, name, email FROM users");
645
+ * const columns = stmt.columns();
646
+ * console.log(columns); // [{ name: 'id', type: 'INTEGER', column: null, database: null, table: null }, ...]
647
+ * ```
648
+ */
649
+ columns() {
650
+ return this.columnMetadata.map((col) => ({
651
+ name: col.name,
652
+ type: col.decltype
653
+ }));
654
+ }
655
+ async withLock(fn) {
656
+ if (!this.execLock) {
657
+ return await fn();
658
+ }
659
+ await this.execLock.acquire();
660
+ try {
661
+ return await fn();
662
+ } finally {
663
+ this.execLock.release();
664
+ }
665
+ }
666
+ /**
667
+ * Executes the prepared statement.
668
+ *
669
+ * @param args - Optional array of parameter values or object with named parameters
670
+ * @returns Promise resolving to the result of the statement
671
+ *
672
+ * @example
673
+ * ```typescript
674
+ * const stmt = client.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
675
+ * const result = await stmt.run(['John Doe', 'john.doe@example.com']);
676
+ * console.log(`Inserted user with ID ${result.lastInsertRowid}`);
677
+ * ```
678
+ */
679
+ async run(args, queryOptions) {
680
+ return await this.withLock(async () => {
681
+ const normalizedArgs = this.normalizeArgs(args);
682
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
683
+ return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
684
+ });
685
+ }
686
+ /**
687
+ * Execute the statement and return the first row.
688
+ *
689
+ * @param args - Optional array of parameter values or object with named parameters
690
+ * @returns Promise resolving to the first row or undefined if no results
691
+ *
692
+ * @example
693
+ * ```typescript
694
+ * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
695
+ * const user = await stmt.get([123]);
696
+ * if (user) {
697
+ * console.log(user.name);
698
+ * }
699
+ * ```
700
+ */
701
+ async get(args, queryOptions) {
702
+ return await this.withLock(async () => {
703
+ const normalizedArgs = this.normalizeArgs(args);
704
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
705
+ const row = result.rows[0];
706
+ if (!row) {
707
+ return void 0;
708
+ }
709
+ if (this.presentationMode === "pluck") {
710
+ return row[0];
711
+ }
712
+ if (this.presentationMode === "raw") {
713
+ return [...row];
714
+ }
715
+ const obj = {};
716
+ result.columns.forEach((col, i) => {
717
+ obj[col] = row[i];
718
+ });
719
+ return obj;
720
+ });
721
+ }
722
+ /**
723
+ * Execute the statement and return all rows.
724
+ *
725
+ * @param args - Optional array of parameter values or object with named parameters
726
+ * @returns Promise resolving to an array of all result rows
727
+ *
728
+ * @example
729
+ * ```typescript
730
+ * const stmt = client.prepare("SELECT * FROM users WHERE active = ?");
731
+ * const activeUsers = await stmt.all([true]);
732
+ * console.log(`Found ${activeUsers.length} active users`);
733
+ * ```
734
+ */
735
+ async all(args, queryOptions) {
736
+ return await this.withLock(async () => {
737
+ const normalizedArgs = this.normalizeArgs(args);
738
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
739
+ if (this.presentationMode === "pluck") {
740
+ return result.rows.map((row) => row[0]);
741
+ }
742
+ if (this.presentationMode === "raw") {
743
+ return result.rows.map((row) => [...row]);
744
+ }
745
+ return result.rows.map((row) => {
746
+ const obj = {};
747
+ result.columns.forEach((col, i) => {
748
+ obj[col] = row[i];
749
+ });
750
+ return obj;
751
+ });
752
+ });
753
+ }
754
+ /**
755
+ * Execute the statement and return an async iterator for streaming results.
756
+ *
757
+ * This method provides memory-efficient processing of large result sets
758
+ * by streaming rows one at a time instead of loading everything into memory.
759
+ *
760
+ * @param args - Optional array of parameter values or object with named parameters
761
+ * @returns AsyncGenerator that yields individual rows
762
+ *
763
+ * @example
764
+ * ```typescript
765
+ * const stmt = client.prepare("SELECT * FROM large_table WHERE category = ?");
766
+ * for await (const row of stmt.iterate(['electronics'])) {
767
+ * // Process each row individually
768
+ * console.log(row.id, row.name);
769
+ * }
770
+ * ```
771
+ */
772
+ async *iterate(args, queryOptions) {
773
+ if (this.execLock) {
774
+ const rows = await this.all(args, queryOptions);
775
+ for (const row of rows) {
776
+ yield row;
777
+ }
778
+ return;
779
+ }
780
+ const normalizedArgs = this.normalizeArgs(args);
781
+ const { entries } = await this.session.executeRaw(this.sql, normalizedArgs, queryOptions);
782
+ let columns = [];
783
+ for await (const entry of entries) {
784
+ switch (entry.type) {
785
+ case "step_begin":
786
+ if (entry.cols) {
787
+ columns = entry.cols.map((col) => col.name);
788
+ }
789
+ break;
790
+ case "row":
791
+ if (entry.row) {
792
+ const decodedRow = entry.row.map((value) => decodeValue(value, this.safeIntegerMode));
793
+ if (this.presentationMode === "pluck") {
794
+ yield decodedRow[0];
795
+ } else if (this.presentationMode === "raw") {
796
+ yield decodedRow;
797
+ } else {
798
+ const obj = {};
799
+ columns.forEach((col, i) => {
800
+ obj[col] = decodedRow[i];
801
+ });
802
+ yield obj;
803
+ }
804
+ }
805
+ break;
806
+ case "step_error":
807
+ case "error":
808
+ throw new DatabaseError(entry.error?.message || "SQL execution failed");
809
+ }
810
+ }
811
+ }
812
+ /**
813
+ * Normalize arguments to handle both single values and arrays.
814
+ * Matches the behavior of the native bindings.
815
+ */
816
+ normalizeArgs(args) {
817
+ if (args === void 0) {
818
+ return [];
819
+ }
820
+ if (Array.isArray(args)) {
821
+ return args;
822
+ }
823
+ if (args !== null && typeof args === "object" && args.constructor === Object) {
824
+ return args;
825
+ }
826
+ return [args];
827
+ }
828
+ };
829
+
830
+ // src/connection.ts
831
+ var Connection = class {
832
+ constructor(config) {
833
+ this.isOpen = true;
834
+ this.defaultSafeIntegerMode = false;
835
+ this._inTransaction = false;
836
+ this.execLock = new AsyncLock();
837
+ if (!config.url) {
838
+ throw new Error("invalid config: url is required");
839
+ }
840
+ this.config = config;
841
+ this.session = new Session(config);
842
+ Object.defineProperty(this, "inTransaction", {
843
+ get: () => this._inTransaction,
844
+ enumerable: true
845
+ });
846
+ }
847
+ /**
848
+ * Whether the database is currently in a transaction.
849
+ */
850
+ get inTransaction() {
851
+ return this._inTransaction;
852
+ }
853
+ /**
854
+ * Prepare a SQL statement for execution.
855
+ *
856
+ * Prepared statements created from a Connection use the same underlying session so transaction boundaries are preserved.
857
+ * This method fetches column metadata using the describe functionality.
858
+ *
859
+ * @param sql - The SQL statement to prepare
860
+ * @returns A Promise that resolves to a Statement object with column metadata
861
+ *
862
+ * @example
863
+ * ```typescript
864
+ * const stmt = await client.prepare("SELECT * FROM users WHERE id = ?");
865
+ * const columns = stmt.columns();
866
+ * const user = await stmt.get([123]);
867
+ * ```
868
+ */
869
+ async prepare(sql) {
870
+ if (!this.isOpen) {
871
+ throw new TypeError("The database connection is not open");
872
+ }
873
+ const session = new Session(this.config);
874
+ const description = await session.describe(sql);
875
+ await session.close();
876
+ const stmt = Statement.fromSession(this.session, sql, description.cols, this.execLock);
877
+ if (this.defaultSafeIntegerMode) {
878
+ stmt.safeIntegers(true);
879
+ }
880
+ return stmt;
881
+ }
882
+ /**
883
+ * Execute a SQL statement and return all results.
884
+ *
885
+ * @param sql - The SQL statement to execute
886
+ * @param args - Optional array of parameter values
887
+ * @returns Promise resolving to the complete result set
888
+ *
889
+ * @example
890
+ * ```typescript
891
+ * const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
892
+ * console.log(result.rows);
893
+ * ```
894
+ */
895
+ async execute(sql, args, queryOptions) {
896
+ if (!this.isOpen) {
897
+ throw new TypeError("The database connection is not open");
898
+ }
899
+ await this.execLock.acquire();
900
+ try {
901
+ return await this.session.execute(sql, args || [], this.defaultSafeIntegerMode, queryOptions);
902
+ } finally {
903
+ this.execLock.release();
904
+ }
905
+ }
906
+ /**
907
+ * Execute a SQL statement and return all results.
908
+ *
909
+ * @param sql - The SQL statement to execute
910
+ * @returns Promise resolving to the complete result set
911
+ *
912
+ * @example
913
+ * ```typescript
914
+ * const result = await client.exec("SELECT * FROM users");
915
+ * console.log(result.rows);
916
+ * ```
917
+ */
918
+ async exec(sql, queryOptions) {
919
+ if (!this.isOpen) {
920
+ throw new TypeError("The database connection is not open");
921
+ }
922
+ await this.execLock.acquire();
923
+ try {
924
+ return await this.session.sequence(sql, queryOptions);
925
+ } finally {
926
+ this.execLock.release();
927
+ }
928
+ }
929
+ /**
930
+ * Execute multiple SQL statements in a batch.
931
+ *
932
+ * @param statements - Array of SQL statements to execute
933
+ * @param mode - Optional transaction mode (currently unused)
934
+ * @returns Promise resolving to batch execution results
935
+ *
936
+ * @example
937
+ * ```typescript
938
+ * await client.batch([
939
+ * "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
940
+ * "INSERT INTO users (name) VALUES ('Alice')",
941
+ * "INSERT INTO users (name) VALUES ('Bob')"
942
+ * ]);
943
+ * ```
944
+ */
945
+ async batch(statements, mode, queryOptions) {
946
+ if (!this.isOpen) {
947
+ throw new TypeError("The database connection is not open");
948
+ }
949
+ await this.execLock.acquire();
950
+ try {
951
+ return await this.session.batch(statements, queryOptions);
952
+ } finally {
953
+ this.execLock.release();
954
+ }
955
+ }
956
+ /**
957
+ * Execute a pragma.
958
+ *
959
+ * @param pragma - The pragma to execute
960
+ * @returns Promise resolving to the result of the pragma
961
+ */
962
+ async pragma(pragma, queryOptions) {
963
+ if (!this.isOpen) {
964
+ throw new TypeError("The database connection is not open");
965
+ }
966
+ await this.execLock.acquire();
967
+ try {
968
+ const sql = `PRAGMA ${pragma}`;
969
+ return await this.session.execute(sql, [], false, queryOptions);
970
+ } finally {
971
+ this.execLock.release();
972
+ }
973
+ }
974
+ /**
975
+ * Sets the default safe integers mode for all statements from this connection.
976
+ *
977
+ * @param toggle - Whether to use safe integers by default.
978
+ */
979
+ defaultSafeIntegers(toggle) {
980
+ this.defaultSafeIntegerMode = toggle === false ? false : true;
981
+ }
982
+ /**
983
+ * Returns a function that executes the given function in a transaction.
984
+ *
985
+ * @param fn - The function to wrap in a transaction
986
+ * @returns A function that will execute fn within a transaction
987
+ *
988
+ * @example
989
+ * ```typescript
990
+ * const insert = await client.prepare("INSERT INTO users (name) VALUES (?)");
991
+ * const insertMany = client.transaction((users) => {
992
+ * for (const user of users) {
993
+ * insert.run([user]);
994
+ * }
995
+ * });
996
+ *
997
+ * await insertMany(['Alice', 'Bob', 'Charlie']);
998
+ * ```
999
+ */
1000
+ transaction(fn) {
1001
+ if (typeof fn !== "function") {
1002
+ throw new TypeError("Expected first argument to be a function");
1003
+ }
1004
+ const db = this;
1005
+ const wrapTxn = (mode) => {
1006
+ return async (...bindParameters) => {
1007
+ await db.exec("BEGIN " + mode);
1008
+ db._inTransaction = true;
1009
+ try {
1010
+ const result = await fn(...bindParameters);
1011
+ await db.exec("COMMIT");
1012
+ db._inTransaction = false;
1013
+ return result;
1014
+ } catch (err) {
1015
+ await db.exec("ROLLBACK");
1016
+ db._inTransaction = false;
1017
+ throw err;
1018
+ }
1019
+ };
1020
+ };
1021
+ const properties = {
1022
+ default: { value: wrapTxn("") },
1023
+ deferred: { value: wrapTxn("DEFERRED") },
1024
+ immediate: { value: wrapTxn("IMMEDIATE") },
1025
+ exclusive: { value: wrapTxn("EXCLUSIVE") },
1026
+ database: { value: this, enumerable: true }
1027
+ };
1028
+ Object.defineProperties(properties.default.value, properties);
1029
+ Object.defineProperties(properties.deferred.value, properties);
1030
+ Object.defineProperties(properties.immediate.value, properties);
1031
+ Object.defineProperties(properties.exclusive.value, properties);
1032
+ return properties.default.value;
1033
+ }
1034
+ /**
1035
+ * Close the connection.
1036
+ *
1037
+ * This sends a close request to the server to properly clean up the stream.
1038
+ */
1039
+ async close() {
1040
+ this.isOpen = false;
1041
+ await this.session.close();
1042
+ }
1043
+ async reconnect() {
1044
+ try {
1045
+ if (this.isOpen) {
1046
+ await this.close();
1047
+ }
1048
+ } finally {
1049
+ this.session = new Session(this.config);
1050
+ this.isOpen = true;
1051
+ }
1052
+ }
1053
+ };
1054
+ function connect(config) {
1055
+ return new Connection(config);
1056
+ }
1057
+
1058
+ exports.Connection = Connection;
1059
+ exports.DatabaseError = DatabaseError;
1060
+ exports.ENCRYPTION_KEY_HEADER = ENCRYPTION_KEY_HEADER;
1061
+ exports.Session = Session;
1062
+ exports.Statement = Statement;
1063
+ exports.TimeoutError = TimeoutError;
1064
+ exports.connect = connect;