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