@tursodatabase/serverless 1.2.0-pre.2 → 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,1272 +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/args.ts
241
- function normalizeArgs(args) {
242
- if (args === void 0) return [];
243
- if (Array.isArray(args)) return args;
244
- if (args !== null && typeof args === "object" && args.constructor === Object) {
245
- return args;
246
- }
247
- return [args];
248
- }
249
- function isQueryOptions(value) {
250
- return value != null && typeof value === "object" && !Array.isArray(value) && Object.prototype.hasOwnProperty.call(value, "queryTimeout");
251
- }
252
- function splitBindParameters(bindParameters) {
253
- if (bindParameters.length === 0) {
254
- return { params: void 0, queryOptions: void 0 };
255
- }
256
- if (isQueryOptions(bindParameters[bindParameters.length - 1])) {
257
- if (bindParameters.length === 1) {
258
- return { params: void 0, queryOptions: bindParameters[0] };
259
- }
260
- return {
261
- params: bindParameters.length === 2 ? bindParameters[0] : bindParameters.slice(0, -1),
262
- queryOptions: bindParameters[bindParameters.length - 1]
263
- };
264
- }
265
- return {
266
- params: bindParameters.length === 1 ? bindParameters[0] : bindParameters,
267
- queryOptions: void 0
268
- };
269
- }
270
- function encodeSqlArgs(args = []) {
271
- let positionalArgs = [];
272
- let namedArgs = [];
273
- if (Array.isArray(args)) {
274
- positionalArgs = args.map(encodeValue);
275
- } else {
276
- const keys = Object.keys(args);
277
- const isNumericKeys = keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
278
- if (isNumericKeys) {
279
- const sortedKeys = keys.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
280
- const maxIndex = parseInt(sortedKeys[sortedKeys.length - 1], 10);
281
- positionalArgs = new Array(maxIndex);
282
- for (const key of sortedKeys) {
283
- const index = parseInt(key, 10) - 1;
284
- positionalArgs[index] = encodeValue(args[key]);
285
- }
286
- for (let i = 0; i < positionalArgs.length; i++) {
287
- if (positionalArgs[i] === void 0) {
288
- positionalArgs[i] = { type: "null" };
289
- }
290
- }
291
- } else {
292
- namedArgs = Object.entries(args).map(([name, value]) => ({
293
- name,
294
- value: encodeValue(value)
295
- }));
296
- }
297
- }
298
- return { args: positionalArgs, namedArgs };
299
- }
300
-
301
- // src/session.ts
302
- function normalizeUrl(url) {
303
- return url.replace(/^libsql:\/\//, "https://");
304
- }
305
- function isValidIdentifier(str) {
306
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(str);
307
- }
308
- var Session = class {
309
- constructor(config) {
310
- this.baton = null;
311
- this.config = config;
312
- this.baseUrl = normalizeUrl(config.url);
313
- }
314
- createAbortSignal(queryOptions) {
315
- const timeout = queryOptions?.queryTimeout ?? this.config.defaultQueryTimeout;
316
- if (timeout != null && timeout > 0) {
317
- return AbortSignal.timeout(timeout);
318
- }
319
- return void 0;
320
- }
321
- /**
322
- * Describe a SQL statement to get its column metadata.
323
- *
324
- * @param sql - The SQL statement to describe
325
- * @returns Promise resolving to the statement description
326
- */
327
- async describe(sql, queryOptions) {
328
- const request = {
329
- baton: this.baton,
330
- requests: [{
331
- type: "describe",
332
- sql
333
- }]
334
- };
335
- let response;
336
- try {
337
- response = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
338
- } catch (e) {
339
- this.baton = null;
340
- throw e;
341
- }
342
- this.baton = response.baton;
343
- if (response.base_url) {
344
- this.baseUrl = response.base_url;
345
- }
346
- if (response.results && response.results[0]) {
347
- const result = response.results[0];
348
- if (result.type === "error") {
349
- throw new DatabaseError(result.error?.message || "Describe execution failed", result.error?.code);
350
- }
351
- if (result.response?.type === "describe" && result.response.result) {
352
- return result.response.result;
353
- }
354
- }
355
- throw new DatabaseError("Unexpected describe response");
356
- }
357
- /**
358
- * Execute a SQL statement and return all results.
359
- *
360
- * @param sql - The SQL statement to execute
361
- * @param args - Optional array of parameter values or object with named parameters
362
- * @param safeIntegers - Whether to return integers as BigInt
363
- * @returns Promise resolving to the complete result set
364
- */
365
- async execute(sql, args = [], safeIntegers = false, queryOptions) {
366
- const { response, entries } = await this.executeRaw(sql, args, queryOptions);
367
- const result = await this.processCursorEntries(entries, safeIntegers);
368
- return result;
369
- }
370
- /**
371
- * Execute a SQL statement and return the raw response and entries.
372
- *
373
- * @param sql - The SQL statement to execute
374
- * @param args - Optional array of parameter values or object with named parameters
375
- * @returns Promise resolving to the raw response and cursor entries
376
- */
377
- async executeRaw(sql, args = [], queryOptions) {
378
- const encodedArgs = encodeSqlArgs(args);
379
- const request = {
380
- baton: this.baton,
381
- batch: {
382
- steps: [{
383
- stmt: {
384
- sql,
385
- args: encodedArgs.args,
386
- named_args: encodedArgs.namedArgs,
387
- want_rows: true
388
- }
389
- }]
390
- }
391
- };
392
- let result;
393
- try {
394
- result = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
395
- } catch (e) {
396
- this.baton = null;
397
- throw e;
398
- }
399
- const { response, entries } = result;
400
- this.baton = response.baton;
401
- if (response.base_url) {
402
- this.baseUrl = response.base_url;
403
- }
404
- return { response, entries };
405
- }
406
- /**
407
- * Process cursor entries into a structured result.
408
- *
409
- * @param entries - Async generator of cursor entries
410
- * @returns Promise resolving to the processed result
411
- */
412
- async processCursorEntries(entries, safeIntegers = false) {
413
- let columns = [];
414
- let columnTypes = [];
415
- let rows = [];
416
- let rowsAffected = 0;
417
- let lastInsertRowid;
418
- for await (const entry of entries) {
419
- switch (entry.type) {
420
- case "step_begin":
421
- if (entry.cols) {
422
- columns = entry.cols.map((col) => col.name);
423
- columnTypes = entry.cols.map((col) => col.decltype || "");
424
- }
425
- break;
426
- case "row":
427
- if (entry.row) {
428
- const decodedRow = entry.row.map((value) => decodeValue(value, safeIntegers));
429
- const rowObject = this.createRowObject(decodedRow, columns);
430
- rows.push(rowObject);
431
- }
432
- break;
433
- case "step_end":
434
- if (entry.affected_row_count !== void 0) {
435
- rowsAffected = entry.affected_row_count;
436
- }
437
- if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
438
- lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
439
- }
440
- break;
441
- case "step_error":
442
- case "error":
443
- throw new DatabaseError(entry.error?.message || "SQL execution failed", entry.error?.code);
444
- }
445
- }
446
- return {
447
- columns,
448
- columnTypes,
449
- rows,
450
- rowsAffected,
451
- lastInsertRowid
452
- };
453
- }
454
- /**
455
- * Create a row object with both array and named property access.
456
- *
457
- * @param values - Array of column values
458
- * @param columns - Array of column names
459
- * @returns Row object with dual access patterns
460
- */
461
- createRowObject(values, columns) {
462
- const row = [...values];
463
- columns.forEach((column, index) => {
464
- if (column && isValidIdentifier(column)) {
465
- Object.defineProperty(row, column, {
466
- value: values[index],
467
- enumerable: false,
468
- writable: false,
469
- configurable: true
470
- });
471
- }
472
- });
473
- return row;
474
- }
475
- /**
476
- * Execute multiple SQL statements in a batch.
477
- *
478
- * When `mode` is set, the batch is sent as a single Hrana request that
479
- * also carries `BEGIN <mode>` / `COMMIT` / `ROLLBACK` steps using the
480
- * server-side condition chain, giving atomic execution in one round-trip.
481
- * When `mode` is omitted, the user statements are sent as-is and run
482
- * under autocommit (or whatever transaction is already active on this
483
- * stream).
484
- *
485
- * @param statements - Array of SQL statements to execute.
486
- * @param mode - Optional locking mode; when set, the batch executes
487
- * atomically. Accepts the same values as `Database.transaction(...)`
488
- * variants: `"deferred"`, `"immediate"`, `"exclusive"`, `"concurrent"`.
489
- * @returns Promise resolving to batch execution results.
490
- */
491
- async batch(statements, mode, queryOptions) {
492
- const userSteps = statements.map((statement) => {
493
- if (typeof statement === "string") {
494
- return {
495
- stmt: { sql: statement, args: [], named_args: [], want_rows: false }
496
- };
497
- }
498
- const encodedArgs = encodeSqlArgs(statement.args ?? []);
499
- return {
500
- stmt: {
501
- sql: statement.sql,
502
- args: encodedArgs.args,
503
- named_args: encodedArgs.namedArgs,
504
- want_rows: false
505
- }
506
- };
507
- });
508
- let steps;
509
- let firstUserStepIdx = 0;
510
- let lastUserStepIdx = userSteps.length - 1;
511
- let beginIdx = -1;
512
- let commitIdx = -1;
513
- let rollbackIdx = -1;
514
- if (mode === void 0) {
515
- steps = userSteps;
516
- } else {
517
- beginIdx = 0;
518
- firstUserStepIdx = 1;
519
- lastUserStepIdx = userSteps.length;
520
- commitIdx = lastUserStepIdx + 1;
521
- rollbackIdx = commitIdx + 1;
522
- steps = [
523
- { stmt: { sql: `BEGIN ${mode.toUpperCase()}`, args: [], named_args: [], want_rows: false } },
524
- ...userSteps.map((step, i) => ({
525
- ...step,
526
- condition: { type: "ok", step: i === 0 ? beginIdx : firstUserStepIdx + i - 1 }
527
- })),
528
- {
529
- stmt: { sql: "COMMIT", args: [], named_args: [], want_rows: false },
530
- condition: { type: "ok", step: lastUserStepIdx }
531
- },
532
- {
533
- stmt: { sql: "ROLLBACK", args: [], named_args: [], want_rows: false },
534
- condition: {
535
- type: "and",
536
- conds: [
537
- { type: "ok", step: beginIdx },
538
- { type: "not", cond: { type: "ok", step: commitIdx } }
539
- ]
540
- }
541
- }
542
- ];
543
- }
544
- const request = {
545
- baton: this.baton,
546
- batch: { steps }
547
- };
548
- let batchResult;
549
- try {
550
- batchResult = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
551
- } catch (e) {
552
- this.baton = null;
553
- throw e;
554
- }
555
- const { response, entries } = batchResult;
556
- this.baton = response.baton;
557
- if (response.base_url) {
558
- this.baseUrl = response.base_url;
559
- }
560
- let totalRowsAffected = 0;
561
- let lastInsertRowid;
562
- let deferredError = null;
563
- let currentStep;
564
- const isUserStep = (step) => {
565
- if (mode === void 0) {
566
- return true;
567
- }
568
- return step !== void 0 && step >= firstUserStepIdx && step <= lastUserStepIdx;
569
- };
570
- for await (const entry of entries) {
571
- switch (entry.type) {
572
- case "step_begin":
573
- currentStep = entry.step;
574
- break;
575
- case "step_end":
576
- if (isUserStep(currentStep)) {
577
- if (entry.affected_row_count !== void 0) {
578
- totalRowsAffected += entry.affected_row_count;
579
- }
580
- if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
581
- lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
582
- }
583
- }
584
- currentStep = void 0;
585
- break;
586
- case "step_error":
587
- if (mode === void 0) {
588
- throw new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
589
- }
590
- if (deferredError === null && entry.step !== rollbackIdx) {
591
- deferredError = new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
592
- }
593
- currentStep = void 0;
594
- break;
595
- case "error":
596
- throw new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
597
- }
598
- }
599
- if (deferredError !== null) {
600
- throw deferredError;
601
- }
602
- return {
603
- rowsAffected: totalRowsAffected,
604
- lastInsertRowid
605
- };
606
- }
607
- /**
608
- * Execute a sequence of SQL statements separated by semicolons.
609
- *
610
- * @param sql - SQL string containing multiple statements separated by semicolons
611
- * @returns Promise resolving when all statements are executed
612
- */
613
- async sequence(sql, queryOptions) {
614
- const request = {
615
- baton: this.baton,
616
- requests: [{
617
- type: "sequence",
618
- sql
619
- }]
620
- };
621
- let seqResponse;
622
- try {
623
- seqResponse = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
624
- } catch (e) {
625
- this.baton = null;
626
- throw e;
627
- }
628
- this.baton = seqResponse.baton;
629
- if (seqResponse.base_url) {
630
- this.baseUrl = seqResponse.base_url;
631
- }
632
- if (seqResponse.results && seqResponse.results[0]) {
633
- const result = seqResponse.results[0];
634
- if (result.type === "error") {
635
- throw new DatabaseError(result.error?.message || "Sequence execution failed", result.error?.code);
636
- }
637
- }
638
- }
639
- /**
640
- * Close the session.
641
- *
642
- * This sends a close request to the server to properly clean up the stream
643
- * before resetting the local state.
644
- */
645
- async close() {
646
- if (this.baton) {
647
- try {
648
- const request = {
649
- baton: this.baton,
650
- requests: [{
651
- type: "close"
652
- }]
653
- };
654
- await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
655
- } catch {
656
- }
657
- }
658
- this.baton = null;
659
- this.baseUrl = "";
660
- }
661
- };
662
-
663
- // src/statement.ts
664
- var Statement = class _Statement {
665
- constructor(sessionConfig, sql, columns) {
666
- this.presentationMode = "expanded";
667
- this.safeIntegerMode = false;
668
- this.session = new Session(sessionConfig);
669
- this.sql = sql;
670
- this.columnMetadata = columns || [];
671
- }
672
- /**
673
- * Create a Statement that shares an existing session and serializes execution
674
- * through the given lock. Used by Connection.prepare() so prepared statements
675
- * participate in the connection's transaction scope.
676
- */
677
- static fromSession(session, sql, columns, execLock) {
678
- const stmt = Object.create(_Statement.prototype);
679
- stmt.session = session;
680
- stmt.sql = sql;
681
- stmt.columnMetadata = columns || [];
682
- stmt.presentationMode = "expanded";
683
- stmt.safeIntegerMode = false;
684
- stmt.execLock = execLock;
685
- return stmt;
686
- }
687
- /**
688
- * Whether the prepared statement returns data.
689
- *
690
- * This is `true` for SELECT queries and statements with RETURNING clause,
691
- * and `false` for INSERT, UPDATE, DELETE statements without RETURNING.
692
- *
693
- * @example
694
- * ```typescript
695
- * const stmt = await conn.prepare(sql);
696
- * if (stmt.reader) {
697
- * return stmt.all(args); // SELECT-like query
698
- * } else {
699
- * return stmt.run(args); // INSERT/UPDATE/DELETE
700
- * }
701
- * ```
702
- */
703
- get reader() {
704
- return this.columnMetadata.length > 0;
705
- }
706
- /**
707
- * Enable raw mode to return arrays instead of objects.
708
- *
709
- * @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
710
- * @returns This statement instance for chaining
711
- *
712
- * @example
713
- * ```typescript
714
- * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
715
- * const row = await stmt.raw().get([1]);
716
- * console.log(row); // [1, "Alice", "alice@example.org"]
717
- * ```
718
- */
719
- raw(raw) {
720
- this.presentationMode = raw === false ? "expanded" : "raw";
721
- return this;
722
- }
723
- /**
724
- * Enable pluck mode to return only the first column value from each row.
725
- *
726
- * @param pluck Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
727
- * @returns This statement instance for chaining
728
- *
729
- * @example
730
- * ```typescript
731
- * const stmt = client.prepare("SELECT id FROM users");
732
- * const ids = await stmt.pluck().all();
733
- * console.log(ids); // [1, 2, 3, ...]
734
- * ```
735
- */
736
- pluck(pluck) {
737
- this.presentationMode = pluck === false ? "expanded" : "pluck";
738
- return this;
739
- }
740
- /**
741
- * Sets safe integers mode for this statement.
742
- *
743
- * @param toggle Whether to use safe integers. If you don't pass the parameter, safe integers mode is enabled.
744
- * @returns This statement instance for chaining
745
- */
746
- safeIntegers(toggle) {
747
- this.safeIntegerMode = toggle === false ? false : true;
748
- return this;
749
- }
750
- /**
751
- * Get column information for this statement.
752
- *
753
- * @returns Array of column metadata objects matching the native bindings format
754
- *
755
- * @example
756
- * ```typescript
757
- * const stmt = await client.prepare("SELECT id, name, email FROM users");
758
- * const columns = stmt.columns();
759
- * console.log(columns); // [{ name: 'id', type: 'INTEGER', column: null, database: null, table: null }, ...]
760
- * ```
761
- */
762
- columns() {
763
- return this.columnMetadata.map((col) => ({
764
- name: col.name,
765
- type: col.decltype
766
- }));
767
- }
768
- async withLock(fn) {
769
- if (!this.execLock) {
770
- return await fn();
771
- }
772
- await this.execLock.acquire();
773
- try {
774
- return await fn();
775
- } finally {
776
- this.execLock.release();
777
- }
778
- }
779
- /**
780
- * Executes the prepared statement.
781
- *
782
- * @param args - Optional array of parameter values or object with named parameters
783
- * @returns Promise resolving to the result of the statement
784
- *
785
- * @example
786
- * ```typescript
787
- * const stmt = client.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
788
- * const result = await stmt.run(['John Doe', 'john.doe@example.com']);
789
- * console.log(`Inserted user with ID ${result.lastInsertRowid}`);
790
- * ```
791
- */
792
- async run(args, queryOptions) {
793
- return await this.withLock(async () => {
794
- const normalizedArgs = normalizeArgs(args);
795
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
796
- return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
797
- });
798
- }
799
- /**
800
- * Execute the statement and return the first row.
801
- *
802
- * @param args - Optional array of parameter values or object with named parameters
803
- * @returns Promise resolving to the first row or undefined if no results
804
- *
805
- * @example
806
- * ```typescript
807
- * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
808
- * const user = await stmt.get([123]);
809
- * if (user) {
810
- * console.log(user.name);
811
- * }
812
- * ```
813
- */
814
- async get(args, queryOptions) {
815
- return await this.withLock(async () => {
816
- const normalizedArgs = normalizeArgs(args);
817
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
818
- const row = result.rows[0];
819
- if (!row) {
820
- return void 0;
821
- }
822
- if (this.presentationMode === "pluck") {
823
- return row[0];
824
- }
825
- if (this.presentationMode === "raw") {
826
- return [...row];
827
- }
828
- const obj = {};
829
- result.columns.forEach((col, i) => {
830
- obj[col] = row[i];
831
- });
832
- return obj;
833
- });
834
- }
835
- /**
836
- * Execute the statement and return all rows.
837
- *
838
- * @param args - Optional array of parameter values or object with named parameters
839
- * @returns Promise resolving to an array of all result rows
840
- *
841
- * @example
842
- * ```typescript
843
- * const stmt = client.prepare("SELECT * FROM users WHERE active = ?");
844
- * const activeUsers = await stmt.all([true]);
845
- * console.log(`Found ${activeUsers.length} active users`);
846
- * ```
847
- */
848
- async all(args, queryOptions) {
849
- return await this.withLock(async () => {
850
- const normalizedArgs = normalizeArgs(args);
851
- const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
852
- if (this.presentationMode === "pluck") {
853
- return result.rows.map((row) => row[0]);
854
- }
855
- if (this.presentationMode === "raw") {
856
- return result.rows.map((row) => [...row]);
857
- }
858
- return result.rows.map((row) => {
859
- const obj = {};
860
- result.columns.forEach((col, i) => {
861
- obj[col] = row[i];
862
- });
863
- return obj;
864
- });
865
- });
866
- }
867
- /**
868
- * Execute the statement and return an async iterator for streaming results.
869
- *
870
- * This method provides memory-efficient processing of large result sets
871
- * by streaming rows one at a time instead of loading everything into memory.
872
- *
873
- * @param args - Optional array of parameter values or object with named parameters
874
- * @returns AsyncGenerator that yields individual rows
875
- *
876
- * @example
877
- * ```typescript
878
- * const stmt = client.prepare("SELECT * FROM large_table WHERE category = ?");
879
- * for await (const row of stmt.iterate(['electronics'])) {
880
- * // Process each row individually
881
- * console.log(row.id, row.name);
882
- * }
883
- * ```
884
- */
885
- async *iterate(args, queryOptions) {
886
- if (this.execLock) {
887
- const rows = await this.all(args, queryOptions);
888
- for (const row of rows) {
889
- yield row;
890
- }
891
- return;
892
- }
893
- const normalizedArgs = normalizeArgs(args);
894
- const { entries } = await this.session.executeRaw(this.sql, normalizedArgs, queryOptions);
895
- let columns = [];
896
- for await (const entry of entries) {
897
- switch (entry.type) {
898
- case "step_begin":
899
- if (entry.cols) {
900
- columns = entry.cols.map((col) => col.name);
901
- }
902
- break;
903
- case "row":
904
- if (entry.row) {
905
- const decodedRow = entry.row.map((value) => decodeValue(value, this.safeIntegerMode));
906
- if (this.presentationMode === "pluck") {
907
- yield decodedRow[0];
908
- } else if (this.presentationMode === "raw") {
909
- yield decodedRow;
910
- } else {
911
- const obj = {};
912
- columns.forEach((col, i) => {
913
- obj[col] = decodedRow[i];
914
- });
915
- yield obj;
916
- }
917
- }
918
- break;
919
- case "step_error":
920
- case "error":
921
- throw new DatabaseError(entry.error?.message || "SQL execution failed");
922
- }
923
- }
924
- }
925
- };
926
-
927
- // src/connection.ts
928
- var Connection = class {
929
- constructor(config) {
930
- this.isOpen = true;
931
- this.defaultSafeIntegerMode = false;
932
- this._inTransaction = false;
933
- this.execLock = new AsyncLock();
934
- if (!config.url) {
935
- throw new Error("invalid config: url is required");
936
- }
937
- this.config = config;
938
- this.session = new Session(config);
939
- Object.defineProperty(this, "inTransaction", {
940
- get: () => this._inTransaction,
941
- enumerable: true
942
- });
943
- }
944
- /**
945
- * Whether the database is currently in a transaction.
946
- */
947
- get inTransaction() {
948
- return this._inTransaction;
949
- }
950
- /**
951
- * Prepare a SQL statement for execution.
952
- *
953
- * Prepared statements created from a Connection use the same underlying session so transaction boundaries are preserved.
954
- * This method fetches column metadata using the describe functionality.
955
- *
956
- * @param sql - The SQL statement to prepare
957
- * @returns A Promise that resolves to a Statement object with column metadata
958
- *
959
- * @example
960
- * ```typescript
961
- * const stmt = await client.prepare("SELECT * FROM users WHERE id = ?");
962
- * const columns = stmt.columns();
963
- * const user = await stmt.get([123]);
964
- * ```
965
- */
966
- async prepare(sql) {
967
- if (!this.isOpen) {
968
- throw new TypeError("The database connection is not open");
969
- }
970
- await this.execLock.acquire();
971
- let description;
972
- try {
973
- description = await this.session.describe(sql);
974
- } finally {
975
- this.execLock.release();
976
- }
977
- const stmt = Statement.fromSession(this.session, sql, description.cols, this.execLock);
978
- if (this.defaultSafeIntegerMode) {
979
- stmt.safeIntegers(true);
980
- }
981
- return stmt;
982
- }
983
- /**
984
- * Like `prepare(sql).run(args)` but in a single round trip — skips `describe`
985
- * since run() does not need column metadata.
986
- */
987
- async run(sql, ...bindParameters) {
988
- if (!this.isOpen) throw new TypeError("The database connection is not open");
989
- const { params, queryOptions } = splitBindParameters(bindParameters);
990
- await this.execLock.acquire();
991
- try {
992
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
993
- return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
994
- } finally {
995
- this.execLock.release();
996
- }
997
- }
998
- /**
999
- * Like `prepare(sql).get(args)` but in a single round trip.
1000
- */
1001
- async get(sql, ...bindParameters) {
1002
- if (!this.isOpen) throw new TypeError("The database connection is not open");
1003
- const { params, queryOptions } = splitBindParameters(bindParameters);
1004
- await this.execLock.acquire();
1005
- try {
1006
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
1007
- const row = result.rows[0];
1008
- if (!row) return void 0;
1009
- const obj = {};
1010
- result.columns.forEach((col, i) => {
1011
- obj[col] = row[i];
1012
- });
1013
- return obj;
1014
- } finally {
1015
- this.execLock.release();
1016
- }
1017
- }
1018
- /**
1019
- * Like `prepare(sql).all(args)` but in a single round trip.
1020
- */
1021
- async all(sql, ...bindParameters) {
1022
- if (!this.isOpen) throw new TypeError("The database connection is not open");
1023
- const { params, queryOptions } = splitBindParameters(bindParameters);
1024
- await this.execLock.acquire();
1025
- try {
1026
- const result = await this.session.execute(sql, normalizeArgs(params), this.defaultSafeIntegerMode, queryOptions);
1027
- return result.rows.map((row) => {
1028
- const obj = {};
1029
- result.columns.forEach((col, i) => {
1030
- obj[col] = row[i];
1031
- });
1032
- return obj;
1033
- });
1034
- } finally {
1035
- this.execLock.release();
1036
- }
1037
- }
1038
- /**
1039
- * Like `prepare(sql).iterate(args)` but in a single round trip. Buffers the
1040
- * result set — the connection lock cannot be held across `yield` points
1041
- * without risking deadlock on nested calls.
1042
- */
1043
- async *iterate(sql, ...bindParameters) {
1044
- for (const row of await this.all(sql, ...bindParameters)) yield row;
1045
- }
1046
- /**
1047
- * Execute a SQL statement and return all results.
1048
- *
1049
- * @param sql - The SQL statement to execute
1050
- * @param args - Optional array of parameter values
1051
- * @returns Promise resolving to the complete result set
1052
- *
1053
- * @example
1054
- * ```typescript
1055
- * const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
1056
- * console.log(result.rows);
1057
- * ```
1058
- */
1059
- async execute(sql, args, queryOptions) {
1060
- if (!this.isOpen) {
1061
- throw new TypeError("The database connection is not open");
1062
- }
1063
- await this.execLock.acquire();
1064
- try {
1065
- return await this.session.execute(sql, args || [], this.defaultSafeIntegerMode, queryOptions);
1066
- } finally {
1067
- this.execLock.release();
1068
- }
1069
- }
1070
- /**
1071
- * Execute a SQL statement and return all results.
1072
- *
1073
- * @param sql - The SQL statement to execute
1074
- * @returns Promise resolving to the complete result set
1075
- *
1076
- * @example
1077
- * ```typescript
1078
- * const result = await client.exec("SELECT * FROM users");
1079
- * console.log(result.rows);
1080
- * ```
1081
- */
1082
- async exec(sql, queryOptions) {
1083
- if (!this.isOpen) {
1084
- throw new TypeError("The database connection is not open");
1085
- }
1086
- await this.execLock.acquire();
1087
- try {
1088
- return await this.session.sequence(sql, queryOptions);
1089
- } finally {
1090
- this.execLock.release();
1091
- }
1092
- }
1093
- /**
1094
- * Executes a batch of SQL statements over this connection.
1095
- *
1096
- * By default, batch() is not transactional: each statement runs in its
1097
- * own autocommit step, so a failure mid-batch leaves earlier successful
1098
- * statements committed. Pass a `mode` to make the batch atomic — the
1099
- * statements are wrapped in `BEGIN <mode>` / `COMMIT` (with `ROLLBACK`
1100
- * on failure) and dispatched as a single Hrana request, so the whole
1101
- * batch completes in one round-trip. When called from inside a
1102
- * `connection.transaction(...)` callback the `mode` argument is ignored
1103
- * and the surrounding transaction is reused.
1104
- *
1105
- * When `mode` is set, `batch()` owns the surrounding
1106
- * `BEGIN`/`COMMIT`/`ROLLBACK`, so the `statements` array must not
1107
- * contain its own transaction-control SQL (`BEGIN`, `COMMIT`,
1108
- * `ROLLBACK`, `SAVEPOINT`, `RELEASE`). The input is not validated
1109
- * for that — a user-supplied `COMMIT` will close the wrapper
1110
- * transaction mid-batch and leave earlier statements committed,
1111
- * defeating the all-or-nothing contract.
1112
- *
1113
- * @param statements - An array of SQL strings or `{ sql, args }` objects.
1114
- * @param mode - When set, makes the batch atomic. Accepts the same
1115
- * values as `connection.transaction(...)` variants: `"deferred"`,
1116
- * `"immediate"`, `"exclusive"`, `"concurrent"`. Ignored when already
1117
- * inside a transaction.
1118
- * @returns An object with `rowsAffected` (sum of affected rows) and
1119
- * `lastInsertRowid` (rowid of the last successful insert).
1120
- *
1121
- * @example
1122
- * // Plain SQL strings (non-atomic).
1123
- * await db.batch([
1124
- * "INSERT INTO users(name) VALUES ('Alice')",
1125
- * "INSERT INTO users(name) VALUES ('Bob')",
1126
- * ]);
1127
- *
1128
- * @example
1129
- * // Positional and named bind parameters.
1130
- * await db.batch([
1131
- * { sql: "INSERT INTO users(name, email) VALUES (?, ?)", args: ["Carol", "carol@example.net"] },
1132
- * { sql: "INSERT INTO users(name, email) VALUES (:name, :email)", args: { name: "Dave", email: "dave@example.net" } },
1133
- * ]);
1134
- *
1135
- * @example
1136
- * // Atomic via the mode parameter.
1137
- * await db.batch([
1138
- * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] },
1139
- * { sql: "INSERT INTO users(name) VALUES (?)", args: ["Frank"] },
1140
- * ], "immediate");
1141
- *
1142
- * @example
1143
- * // Atomic via the transaction() API for mixed workloads.
1144
- * const txn = db.transaction(async () => {
1145
- * await db.batch([{ sql: "INSERT INTO users(name) VALUES (?)", args: ["Eve"] }]);
1146
- * await db.execute("UPDATE counters SET n = n + 1");
1147
- * });
1148
- * await txn.immediate();
1149
- */
1150
- async batch(statements, mode, queryOptions) {
1151
- if (!this.isOpen) {
1152
- throw new TypeError("The database connection is not open");
1153
- }
1154
- await this.execLock.acquire();
1155
- try {
1156
- const effectiveMode = this._inTransaction ? void 0 : mode;
1157
- return await this.session.batch(statements, effectiveMode, queryOptions);
1158
- } finally {
1159
- this.execLock.release();
1160
- }
1161
- }
1162
- /**
1163
- * Execute a pragma.
1164
- *
1165
- * @param pragma - The pragma to execute
1166
- * @returns Promise resolving to the result of the pragma
1167
- */
1168
- async pragma(pragma, queryOptions) {
1169
- if (!this.isOpen) {
1170
- throw new TypeError("The database connection is not open");
1171
- }
1172
- await this.execLock.acquire();
1173
- try {
1174
- const sql = `PRAGMA ${pragma}`;
1175
- return await this.session.execute(sql, [], false, queryOptions);
1176
- } finally {
1177
- this.execLock.release();
1178
- }
1179
- }
1180
- /**
1181
- * Sets the default safe integers mode for all statements from this connection.
1182
- *
1183
- * @param toggle - Whether to use safe integers by default.
1184
- */
1185
- defaultSafeIntegers(toggle) {
1186
- this.defaultSafeIntegerMode = toggle === false ? false : true;
1187
- }
1188
- /**
1189
- * Returns a function that executes the given function in a transaction.
1190
- *
1191
- * @param fn - The function to wrap in a transaction
1192
- * @returns A function that will execute fn within a transaction
1193
- *
1194
- * @example
1195
- * ```typescript
1196
- * const insert = await client.prepare("INSERT INTO users (name) VALUES (?)");
1197
- * const insertMany = client.transaction((users) => {
1198
- * for (const user of users) {
1199
- * insert.run([user]);
1200
- * }
1201
- * });
1202
- *
1203
- * await insertMany(['Alice', 'Bob', 'Charlie']);
1204
- * ```
1205
- */
1206
- transaction(fn) {
1207
- if (typeof fn !== "function") {
1208
- throw new TypeError("Expected first argument to be a function");
1209
- }
1210
- const db = this;
1211
- const wrapTxn = (mode) => {
1212
- return async (...bindParameters) => {
1213
- await db.exec("BEGIN " + mode);
1214
- db._inTransaction = true;
1215
- try {
1216
- const result = await fn(...bindParameters);
1217
- await db.exec("COMMIT");
1218
- db._inTransaction = false;
1219
- return result;
1220
- } catch (err) {
1221
- await db.exec("ROLLBACK");
1222
- db._inTransaction = false;
1223
- throw err;
1224
- }
1225
- };
1226
- };
1227
- const properties = {
1228
- default: { value: wrapTxn("") },
1229
- deferred: { value: wrapTxn("DEFERRED") },
1230
- concurrent: { value: wrapTxn("CONCURRENT") },
1231
- immediate: { value: wrapTxn("IMMEDIATE") },
1232
- exclusive: { value: wrapTxn("EXCLUSIVE") },
1233
- database: { value: this, enumerable: true }
1234
- };
1235
- Object.defineProperties(properties.default.value, properties);
1236
- Object.defineProperties(properties.deferred.value, properties);
1237
- Object.defineProperties(properties.concurrent.value, properties);
1238
- Object.defineProperties(properties.immediate.value, properties);
1239
- Object.defineProperties(properties.exclusive.value, properties);
1240
- return properties.default.value;
1241
- }
1242
- /**
1243
- * Close the connection.
1244
- *
1245
- * This sends a close request to the server to properly clean up the stream.
1246
- */
1247
- async close() {
1248
- this.isOpen = false;
1249
- await this.session.close();
1250
- }
1251
- async reconnect() {
1252
- try {
1253
- if (this.isOpen) {
1254
- await this.close();
1255
- }
1256
- } finally {
1257
- this.session = new Session(this.config);
1258
- this.isOpen = true;
1259
- }
1260
- }
1261
- };
1262
- function connect(config) {
1263
- return new Connection(config);
1264
- }
1265
-
1266
- exports.Connection = Connection;
1267
- exports.DatabaseError = DatabaseError;
1268
- exports.ENCRYPTION_KEY_HEADER = ENCRYPTION_KEY_HEADER;
1269
- exports.Session = Session;
1270
- exports.Statement = Statement;
1271
- exports.TimeoutError = TimeoutError;
1272
- exports.connect = connect;