@tursodatabase/serverless 1.2.0-pre.1 → 1.2.0

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 DELETED
@@ -1,1146 +0,0 @@
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.isSafeInteger(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/args.ts
551
- function normalizeArgs(args) {
552
- if (args === void 0) return [];
553
- if (Array.isArray(args)) return args;
554
- if (args !== null && typeof args === "object" && args.constructor === Object) {
555
- return args;
556
- }
557
- return [args];
558
- }
559
- function isQueryOptions(value) {
560
- return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "queryTimeout");
561
- }
562
- function splitBindParameters(bindParameters) {
563
- if (bindParameters.length === 0) {
564
- return { params: void 0, queryOptions: void 0 };
565
- }
566
- if (isQueryOptions(bindParameters[bindParameters.length - 1])) {
567
- if (bindParameters.length === 1) {
568
- return { params: void 0, queryOptions: bindParameters[0] };
569
- }
570
- return {
571
- params: bindParameters.length === 2 ? bindParameters[0] : bindParameters.slice(0, -1),
572
- queryOptions: bindParameters[bindParameters.length - 1]
573
- };
574
- }
575
- return {
576
- params: bindParameters.length === 1 ? bindParameters[0] : bindParameters,
577
- queryOptions: void 0
578
- };
579
- }
580
-
581
- // src/statement.ts
582
- var Statement = class _Statement {
583
- constructor(sessionConfig, sql, columns) {
584
- this.presentationMode = "expanded";
585
- this.safeIntegerMode = false;
586
- this.session = new Session(sessionConfig);
587
- this.sql = sql;
588
- this.columnMetadata = columns || [];
589
- }
590
- /**
591
- * Create a Statement that shares an existing session and serializes execution
592
- * through the given lock. Used by Connection.prepare() so prepared statements
593
- * participate in the connection's transaction scope.
594
- */
595
- static fromSession(session, sql, columns, execLock) {
596
- const stmt = Object.create(_Statement.prototype);
597
- stmt.session = session;
598
- stmt.sql = sql;
599
- stmt.columnMetadata = columns || [];
600
- stmt.presentationMode = "expanded";
601
- stmt.safeIntegerMode = false;
602
- stmt.execLock = execLock;
603
- return stmt;
604
- }
605
- /**
606
- * Whether the prepared statement returns data.
607
- *
608
- * This is `true` for SELECT queries and statements with RETURNING clause,
609
- * and `false` for INSERT, UPDATE, DELETE statements without RETURNING.
610
- *
611
- * @example
612
- * ```typescript
613
- * const stmt = await conn.prepare(sql);
614
- * if (stmt.reader) {
615
- * return stmt.all(args); // SELECT-like query
616
- * } else {
617
- * return stmt.run(args); // INSERT/UPDATE/DELETE
618
- * }
619
- * ```
620
- */
621
- get reader() {
622
- return this.columnMetadata.length > 0;
623
- }
624
- /**
625
- * Enable raw mode to return arrays instead of objects.
626
- *
627
- * @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
628
- * @returns This statement instance for chaining
629
- *
630
- * @example
631
- * ```typescript
632
- * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
633
- * const row = await stmt.raw().get([1]);
634
- * console.log(row); // [1, "Alice", "alice@example.org"]
635
- * ```
636
- */
637
- raw(raw) {
638
- this.presentationMode = raw === false ? "expanded" : "raw";
639
- return this;
640
- }
641
- /**
642
- * Enable pluck mode to return only the first column value from each row.
643
- *
644
- * @param pluck Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
645
- * @returns This statement instance for chaining
646
- *
647
- * @example
648
- * ```typescript
649
- * const stmt = client.prepare("SELECT id FROM users");
650
- * const ids = await stmt.pluck().all();
651
- * console.log(ids); // [1, 2, 3, ...]
652
- * ```
653
- */
654
- pluck(pluck) {
655
- this.presentationMode = pluck === false ? "expanded" : "pluck";
656
- return this;
657
- }
658
- /**
659
- * Sets safe integers mode for this statement.
660
- *
661
- * @param toggle Whether to use safe integers. If you don't pass the parameter, safe integers mode is enabled.
662
- * @returns This statement instance for chaining
663
- */
664
- safeIntegers(toggle) {
665
- this.safeIntegerMode = toggle === false ? false : true;
666
- return this;
667
- }
668
- /**
669
- * Get column information for this statement.
670
- *
671
- * @returns Array of column metadata objects matching the native bindings format
672
- *
673
- * @example
674
- * ```typescript
675
- * const stmt = await client.prepare("SELECT id, name, email FROM users");
676
- * const columns = stmt.columns();
677
- * console.log(columns); // [{ name: 'id', type: 'INTEGER', column: null, database: null, table: null }, ...]
678
- * ```
679
- */
680
- columns() {
681
- return this.columnMetadata.map((col) => ({
682
- name: col.name,
683
- type: col.decltype
684
- }));
685
- }
686
- async withLock(fn) {
687
- if (!this.execLock) {
688
- return await fn();
689
- }
690
- await this.execLock.acquire();
691
- try {
692
- return await fn();
693
- } finally {
694
- this.execLock.release();
695
- }
696
- }
697
- /**
698
- * Executes the prepared statement.
699
- *
700
- * @param args - Optional array of parameter values or object with named parameters
701
- * @returns Promise resolving to the result of the statement
702
- *
703
- * @example
704
- * ```typescript
705
- * const stmt = client.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
706
- * const result = await stmt.run(['John Doe', 'john.doe@example.com']);
707
- * console.log(`Inserted user with ID ${result.lastInsertRowid}`);
708
- * ```
709
- */
710
- async run(args, queryOptions) {
711
- return await this.withLock(async () => {
712
- const normalizedArgs = normalizeArgs(args);
713
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
714
- return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
715
- });
716
- }
717
- /**
718
- * Execute the statement and return the first row.
719
- *
720
- * @param args - Optional array of parameter values or object with named parameters
721
- * @returns Promise resolving to the first row or undefined if no results
722
- *
723
- * @example
724
- * ```typescript
725
- * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
726
- * const user = await stmt.get([123]);
727
- * if (user) {
728
- * console.log(user.name);
729
- * }
730
- * ```
731
- */
732
- async get(args, queryOptions) {
733
- return await this.withLock(async () => {
734
- const normalizedArgs = normalizeArgs(args);
735
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
736
- const row = result.rows[0];
737
- if (!row) {
738
- return void 0;
739
- }
740
- if (this.presentationMode === "pluck") {
741
- return row[0];
742
- }
743
- if (this.presentationMode === "raw") {
744
- return [...row];
745
- }
746
- const obj = {};
747
- result.columns.forEach((col, i) => {
748
- obj[col] = row[i];
749
- });
750
- return obj;
751
- });
752
- }
753
- /**
754
- * Execute the statement and return all rows.
755
- *
756
- * @param args - Optional array of parameter values or object with named parameters
757
- * @returns Promise resolving to an array of all result rows
758
- *
759
- * @example
760
- * ```typescript
761
- * const stmt = client.prepare("SELECT * FROM users WHERE active = ?");
762
- * const activeUsers = await stmt.all([true]);
763
- * console.log(`Found ${activeUsers.length} active users`);
764
- * ```
765
- */
766
- async all(args, queryOptions) {
767
- return await this.withLock(async () => {
768
- const normalizedArgs = normalizeArgs(args);
769
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
770
- if (this.presentationMode === "pluck") {
771
- return result.rows.map((row) => row[0]);
772
- }
773
- if (this.presentationMode === "raw") {
774
- return result.rows.map((row) => [...row]);
775
- }
776
- return result.rows.map((row) => {
777
- const obj = {};
778
- result.columns.forEach((col, i) => {
779
- obj[col] = row[i];
780
- });
781
- return obj;
782
- });
783
- });
784
- }
785
- /**
786
- * Execute the statement and return an async iterator for streaming results.
787
- *
788
- * This method provides memory-efficient processing of large result sets
789
- * by streaming rows one at a time instead of loading everything into memory.
790
- *
791
- * @param args - Optional array of parameter values or object with named parameters
792
- * @returns AsyncGenerator that yields individual rows
793
- *
794
- * @example
795
- * ```typescript
796
- * const stmt = client.prepare("SELECT * FROM large_table WHERE category = ?");
797
- * for await (const row of stmt.iterate(['electronics'])) {
798
- * // Process each row individually
799
- * console.log(row.id, row.name);
800
- * }
801
- * ```
802
- */
803
- async *iterate(args, queryOptions) {
804
- if (this.execLock) {
805
- const rows = await this.all(args, queryOptions);
806
- for (const row of rows) {
807
- yield row;
808
- }
809
- return;
810
- }
811
- const normalizedArgs = normalizeArgs(args);
812
- const { entries } = await this.session.executeRaw(this.sql, normalizedArgs, queryOptions);
813
- let columns = [];
814
- for await (const entry of entries) {
815
- switch (entry.type) {
816
- case "step_begin":
817
- if (entry.cols) {
818
- columns = entry.cols.map((col) => col.name);
819
- }
820
- break;
821
- case "row":
822
- if (entry.row) {
823
- const decodedRow = entry.row.map((value) => decodeValue(value, this.safeIntegerMode));
824
- if (this.presentationMode === "pluck") {
825
- yield decodedRow[0];
826
- } else if (this.presentationMode === "raw") {
827
- yield decodedRow;
828
- } else {
829
- const obj = {};
830
- columns.forEach((col, i) => {
831
- obj[col] = decodedRow[i];
832
- });
833
- yield obj;
834
- }
835
- }
836
- break;
837
- case "step_error":
838
- case "error":
839
- throw new DatabaseError(entry.error?.message || "SQL execution failed");
840
- }
841
- }
842
- }
843
- };
844
-
845
- // src/connection.ts
846
- var Connection = class {
847
- constructor(config) {
848
- this.isOpen = true;
849
- this.defaultSafeIntegerMode = false;
850
- this._inTransaction = false;
851
- this.execLock = new AsyncLock();
852
- if (!config.url) {
853
- throw new Error("invalid config: url is required");
854
- }
855
- this.config = config;
856
- this.session = new Session(config);
857
- Object.defineProperty(this, "inTransaction", {
858
- get: () => this._inTransaction,
859
- enumerable: true
860
- });
861
- }
862
- /**
863
- * Whether the database is currently in a transaction.
864
- */
865
- get inTransaction() {
866
- return this._inTransaction;
867
- }
868
- /**
869
- * Prepare a SQL statement for execution.
870
- *
871
- * Prepared statements created from a Connection use the same underlying session so transaction boundaries are preserved.
872
- * This method fetches column metadata using the describe functionality.
873
- *
874
- * @param sql - The SQL statement to prepare
875
- * @returns A Promise that resolves to a Statement object with column metadata
876
- *
877
- * @example
878
- * ```typescript
879
- * const stmt = await client.prepare("SELECT * FROM users WHERE id = ?");
880
- * const columns = stmt.columns();
881
- * const user = await stmt.get([123]);
882
- * ```
883
- */
884
- async prepare(sql) {
885
- if (!this.isOpen) {
886
- throw new TypeError("The database connection is not open");
887
- }
888
- await this.execLock.acquire();
889
- let description;
890
- try {
891
- description = await this.session.describe(sql);
892
- } finally {
893
- this.execLock.release();
894
- }
895
- const stmt = Statement.fromSession(this.session, sql, description.cols, this.execLock);
896
- if (this.defaultSafeIntegerMode) {
897
- stmt.safeIntegers(true);
898
- }
899
- return stmt;
900
- }
901
- /**
902
- * Like `prepare(sql).run(args)` but in a single round trip — skips `describe`
903
- * since run() does not need column metadata.
904
- */
905
- async run(sql, ...bindParameters) {
906
- if (!this.isOpen) throw new TypeError("The database connection is not open");
907
- const { params, queryOptions } = splitBindParameters(bindParameters);
908
- await this.execLock.acquire();
909
- try {
910
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
911
- return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
912
- } finally {
913
- this.execLock.release();
914
- }
915
- }
916
- /**
917
- * Like `prepare(sql).get(args)` but in a single round trip.
918
- */
919
- async get(sql, ...bindParameters) {
920
- if (!this.isOpen) throw new TypeError("The database connection is not open");
921
- const { params, queryOptions } = splitBindParameters(bindParameters);
922
- await this.execLock.acquire();
923
- try {
924
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
925
- const row = result.rows[0];
926
- if (!row) return void 0;
927
- const obj = {};
928
- result.columns.forEach((col, i) => {
929
- obj[col] = row[i];
930
- });
931
- return obj;
932
- } finally {
933
- this.execLock.release();
934
- }
935
- }
936
- /**
937
- * Like `prepare(sql).all(args)` but in a single round trip.
938
- */
939
- async all(sql, ...bindParameters) {
940
- if (!this.isOpen) throw new TypeError("The database connection is not open");
941
- const { params, queryOptions } = splitBindParameters(bindParameters);
942
- await this.execLock.acquire();
943
- try {
944
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
945
- return result.rows.map((row) => {
946
- const obj = {};
947
- result.columns.forEach((col, i) => {
948
- obj[col] = row[i];
949
- });
950
- return obj;
951
- });
952
- } finally {
953
- this.execLock.release();
954
- }
955
- }
956
- /**
957
- * Like `prepare(sql).iterate(args)` but in a single round trip. Buffers the
958
- * result set — the connection lock cannot be held across `yield` points
959
- * without risking deadlock on nested calls.
960
- */
961
- async *iterate(sql, ...bindParameters) {
962
- for (const row of await this.all(sql, ...bindParameters)) yield row;
963
- }
964
- /**
965
- * Execute a SQL statement and return all results.
966
- *
967
- * @param sql - The SQL statement to execute
968
- * @param args - Optional array of parameter values
969
- * @returns Promise resolving to the complete result set
970
- *
971
- * @example
972
- * ```typescript
973
- * const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
974
- * console.log(result.rows);
975
- * ```
976
- */
977
- async execute(sql, args, queryOptions) {
978
- if (!this.isOpen) {
979
- throw new TypeError("The database connection is not open");
980
- }
981
- await this.execLock.acquire();
982
- try {
983
- return await this.session.execute(sql, args || [], this.defaultSafeIntegerMode, queryOptions);
984
- } finally {
985
- this.execLock.release();
986
- }
987
- }
988
- /**
989
- * Execute a SQL statement and return all results.
990
- *
991
- * @param sql - The SQL statement to execute
992
- * @returns Promise resolving to the complete result set
993
- *
994
- * @example
995
- * ```typescript
996
- * const result = await client.exec("SELECT * FROM users");
997
- * console.log(result.rows);
998
- * ```
999
- */
1000
- async exec(sql, queryOptions) {
1001
- if (!this.isOpen) {
1002
- throw new TypeError("The database connection is not open");
1003
- }
1004
- await this.execLock.acquire();
1005
- try {
1006
- return await this.session.sequence(sql, queryOptions);
1007
- } finally {
1008
- this.execLock.release();
1009
- }
1010
- }
1011
- /**
1012
- * Execute multiple SQL statements in a batch.
1013
- *
1014
- * @param statements - Array of SQL statements to execute
1015
- * @param mode - Optional transaction mode (currently unused)
1016
- * @returns Promise resolving to batch execution results
1017
- *
1018
- * @example
1019
- * ```typescript
1020
- * await client.batch([
1021
- * "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
1022
- * "INSERT INTO users (name) VALUES ('Alice')",
1023
- * "INSERT INTO users (name) VALUES ('Bob')"
1024
- * ]);
1025
- * ```
1026
- */
1027
- async batch(statements, mode, queryOptions) {
1028
- if (!this.isOpen) {
1029
- throw new TypeError("The database connection is not open");
1030
- }
1031
- await this.execLock.acquire();
1032
- try {
1033
- return await this.session.batch(statements, queryOptions);
1034
- } finally {
1035
- this.execLock.release();
1036
- }
1037
- }
1038
- /**
1039
- * Execute a pragma.
1040
- *
1041
- * @param pragma - The pragma to execute
1042
- * @returns Promise resolving to the result of the pragma
1043
- */
1044
- async pragma(pragma, queryOptions) {
1045
- if (!this.isOpen) {
1046
- throw new TypeError("The database connection is not open");
1047
- }
1048
- await this.execLock.acquire();
1049
- try {
1050
- const sql = `PRAGMA ${pragma}`;
1051
- return await this.session.execute(sql, [], false, queryOptions);
1052
- } finally {
1053
- this.execLock.release();
1054
- }
1055
- }
1056
- /**
1057
- * Sets the default safe integers mode for all statements from this connection.
1058
- *
1059
- * @param toggle - Whether to use safe integers by default.
1060
- */
1061
- defaultSafeIntegers(toggle) {
1062
- this.defaultSafeIntegerMode = toggle === false ? false : true;
1063
- }
1064
- /**
1065
- * Returns a function that executes the given function in a transaction.
1066
- *
1067
- * @param fn - The function to wrap in a transaction
1068
- * @returns A function that will execute fn within a transaction
1069
- *
1070
- * @example
1071
- * ```typescript
1072
- * const insert = await client.prepare("INSERT INTO users (name) VALUES (?)");
1073
- * const insertMany = client.transaction((users) => {
1074
- * for (const user of users) {
1075
- * insert.run([user]);
1076
- * }
1077
- * });
1078
- *
1079
- * await insertMany(['Alice', 'Bob', 'Charlie']);
1080
- * ```
1081
- */
1082
- transaction(fn) {
1083
- if (typeof fn !== "function") {
1084
- throw new TypeError("Expected first argument to be a function");
1085
- }
1086
- const db = this;
1087
- const wrapTxn = (mode) => {
1088
- return async (...bindParameters) => {
1089
- await db.exec("BEGIN " + mode);
1090
- db._inTransaction = true;
1091
- try {
1092
- const result = await fn(...bindParameters);
1093
- await db.exec("COMMIT");
1094
- db._inTransaction = false;
1095
- return result;
1096
- } catch (err) {
1097
- await db.exec("ROLLBACK");
1098
- db._inTransaction = false;
1099
- throw err;
1100
- }
1101
- };
1102
- };
1103
- const properties = {
1104
- default: { value: wrapTxn("") },
1105
- deferred: { value: wrapTxn("DEFERRED") },
1106
- immediate: { value: wrapTxn("IMMEDIATE") },
1107
- exclusive: { value: wrapTxn("EXCLUSIVE") },
1108
- database: { value: this, enumerable: true }
1109
- };
1110
- Object.defineProperties(properties.default.value, properties);
1111
- Object.defineProperties(properties.deferred.value, properties);
1112
- Object.defineProperties(properties.immediate.value, properties);
1113
- Object.defineProperties(properties.exclusive.value, properties);
1114
- return properties.default.value;
1115
- }
1116
- /**
1117
- * Close the connection.
1118
- *
1119
- * This sends a close request to the server to properly clean up the stream.
1120
- */
1121
- async close() {
1122
- this.isOpen = false;
1123
- await this.session.close();
1124
- }
1125
- async reconnect() {
1126
- try {
1127
- if (this.isOpen) {
1128
- await this.close();
1129
- }
1130
- } finally {
1131
- this.session = new Session(this.config);
1132
- this.isOpen = true;
1133
- }
1134
- }
1135
- };
1136
- function connect(config) {
1137
- return new Connection(config);
1138
- }
1139
-
1140
- exports.Connection = Connection;
1141
- exports.DatabaseError = DatabaseError;
1142
- exports.ENCRYPTION_KEY_HEADER = ENCRYPTION_KEY_HEADER;
1143
- exports.Session = Session;
1144
- exports.Statement = Statement;
1145
- exports.TimeoutError = TimeoutError;
1146
- exports.connect = connect;