@tursodatabase/database 0.1.5-pre.2 → 0.1.5-pre.5

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/promise.js CHANGED
@@ -1,373 +1,8 @@
1
- import { Database as NativeDB } from "#entry-point";
2
- import { bindParams } from "./bind.js";
3
- import { SqliteError } from "./sqlite-error.js";
4
- // Step result constants
5
- const STEP_ROW = 1;
6
- const STEP_DONE = 2;
7
- const STEP_IO = 3;
8
- const convertibleErrorTypes = { TypeError };
9
- const CONVERTIBLE_ERROR_PREFIX = "[TURSO_CONVERT_TYPE]";
10
- function convertError(err) {
11
- if ((err.code ?? "").startsWith(CONVERTIBLE_ERROR_PREFIX)) {
12
- return createErrorByName(err.code.substring(CONVERTIBLE_ERROR_PREFIX.length), err.message);
13
- }
14
- return new SqliteError(err.message, err.code, err.rawCode);
15
- }
16
- function createErrorByName(name, message) {
17
- const ErrorConstructor = convertibleErrorTypes[name];
18
- if (!ErrorConstructor) {
19
- throw new Error(`unknown error type ${name} from Turso`);
20
- }
21
- return new ErrorConstructor(message);
22
- }
23
- /**
24
- * Database represents a connection that can prepare and execute SQL statements.
25
- */
26
- class Database {
27
- db;
28
- memory;
29
- open;
30
- _inTransaction = false;
31
- /**
32
- * Creates a new database connection. If the database file pointed to by `path` does not exists, it will be created.
33
- *
34
- * @constructor
35
- * @param {string} path - Path to the database file.
36
- * @param {Object} opts - Options for database behavior.
37
- * @param {boolean} [opts.readonly=false] - Open the database in read-only mode.
38
- * @param {boolean} [opts.fileMustExist=false] - If true, throws if database file does not exist.
39
- * @param {number} [opts.timeout=0] - Timeout duration in milliseconds for database operations. Defaults to 0 (no timeout).
40
- */
1
+ import { DatabasePromise, SqliteError } from "@tursodatabase/database-common";
2
+ import { Database as NativeDB } from "#index";
3
+ class Database extends DatabasePromise {
41
4
  constructor(path, opts = {}) {
42
- opts.readonly = opts.readonly === undefined ? false : opts.readonly;
43
- opts.fileMustExist =
44
- opts.fileMustExist === undefined ? false : opts.fileMustExist;
45
- opts.timeout = opts.timeout === undefined ? 0 : opts.timeout;
46
- const db = new NativeDB(path);
47
- this.initialize(db, opts.path, opts.readonly);
48
- }
49
- static create() {
50
- return Object.create(this.prototype);
51
- }
52
- initialize(db, name, readonly) {
53
- this.db = db;
54
- this.memory = db.memory;
55
- Object.defineProperties(this, {
56
- inTransaction: {
57
- get: () => this._inTransaction,
58
- },
59
- name: {
60
- get() {
61
- return name;
62
- },
63
- },
64
- readonly: {
65
- get() {
66
- return readonly;
67
- },
68
- },
69
- open: {
70
- get() {
71
- return this.db.open;
72
- },
73
- },
74
- });
75
- }
76
- /**
77
- * Prepares a SQL statement for execution.
78
- *
79
- * @param {string} sql - The SQL statement string to prepare.
80
- */
81
- prepare(sql) {
82
- if (!this.open) {
83
- throw new TypeError("The database connection is not open");
84
- }
85
- if (!sql) {
86
- throw new RangeError("The supplied SQL string contains no statements");
87
- }
88
- try {
89
- return new Statement(this.db.prepare(sql), this);
90
- }
91
- catch (err) {
92
- throw convertError(err);
93
- }
94
- }
95
- /**
96
- * Returns a function that executes the given function in a transaction.
97
- *
98
- * @param {function} fn - The function to wrap in a transaction.
99
- */
100
- transaction(fn) {
101
- if (typeof fn !== "function")
102
- throw new TypeError("Expected first argument to be a function");
103
- const db = this;
104
- const wrapTxn = (mode) => {
105
- return (...bindParameters) => {
106
- db.exec("BEGIN " + mode);
107
- db._inTransaction = true;
108
- try {
109
- const result = fn(...bindParameters);
110
- db.exec("COMMIT");
111
- db._inTransaction = false;
112
- return result;
113
- }
114
- catch (err) {
115
- db.exec("ROLLBACK");
116
- db._inTransaction = false;
117
- throw err;
118
- }
119
- };
120
- };
121
- const properties = {
122
- default: { value: wrapTxn("") },
123
- deferred: { value: wrapTxn("DEFERRED") },
124
- immediate: { value: wrapTxn("IMMEDIATE") },
125
- exclusive: { value: wrapTxn("EXCLUSIVE") },
126
- database: { value: this, enumerable: true },
127
- };
128
- Object.defineProperties(properties.default.value, properties);
129
- Object.defineProperties(properties.deferred.value, properties);
130
- Object.defineProperties(properties.immediate.value, properties);
131
- Object.defineProperties(properties.exclusive.value, properties);
132
- return properties.default.value;
133
- }
134
- pragma(source, options) {
135
- if (options == null)
136
- options = {};
137
- if (typeof source !== "string")
138
- throw new TypeError("Expected first argument to be a string");
139
- if (typeof options !== "object")
140
- throw new TypeError("Expected second argument to be an options object");
141
- const pragma = `PRAGMA ${source}`;
142
- const stmt = this.prepare(pragma);
143
- const results = stmt.all();
144
- return results;
145
- }
146
- backup(filename, options) {
147
- throw new Error("not implemented");
148
- }
149
- serialize(options) {
150
- throw new Error("not implemented");
151
- }
152
- function(name, options, fn) {
153
- throw new Error("not implemented");
154
- }
155
- aggregate(name, options) {
156
- throw new Error("not implemented");
157
- }
158
- table(name, factory) {
159
- throw new Error("not implemented");
160
- }
161
- loadExtension(path) {
162
- throw new Error("not implemented");
163
- }
164
- maxWriteReplicationIndex() {
165
- throw new Error("not implemented");
166
- }
167
- /**
168
- * Executes a SQL statement.
169
- *
170
- * @param {string} sql - The SQL statement string to execute.
171
- */
172
- exec(sql) {
173
- if (!this.open) {
174
- throw new TypeError("The database connection is not open");
175
- }
176
- try {
177
- this.db.batch(sql);
178
- }
179
- catch (err) {
180
- throw convertError(err);
181
- }
182
- }
183
- /**
184
- * Interrupts the database connection.
185
- */
186
- interrupt() {
187
- throw new Error("not implemented");
188
- }
189
- /**
190
- * Sets the default safe integers mode for all statements from this database.
191
- *
192
- * @param {boolean} [toggle] - Whether to use safe integers by default.
193
- */
194
- defaultSafeIntegers(toggle) {
195
- this.db.defaultSafeIntegers(toggle);
196
- }
197
- /**
198
- * Closes the database connection.
199
- */
200
- close() {
201
- this.db.close();
202
- }
203
- }
204
- /**
205
- * Statement represents a prepared SQL statement that can be executed.
206
- */
207
- class Statement {
208
- stmt;
209
- db;
210
- constructor(stmt, database) {
211
- this.stmt = stmt;
212
- this.db = database;
213
- }
214
- /**
215
- * Toggle raw mode.
216
- *
217
- * @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
218
- */
219
- raw(raw) {
220
- this.stmt.raw(raw);
221
- return this;
222
- }
223
- /**
224
- * Toggle pluck mode.
225
- *
226
- * @param pluckMode Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
227
- */
228
- pluck(pluckMode) {
229
- this.stmt.pluck(pluckMode);
230
- return this;
231
- }
232
- /**
233
- * Sets safe integers mode for this statement.
234
- *
235
- * @param {boolean} [toggle] - Whether to use safe integers.
236
- */
237
- safeIntegers(toggle) {
238
- this.stmt.safeIntegers(toggle);
239
- return this;
240
- }
241
- /**
242
- * Get column information for the statement.
243
- *
244
- * @returns {Array} An array of column objects with name, column, table, database, and type properties.
245
- */
246
- columns() {
247
- return this.stmt.columns();
248
- }
249
- get source() {
250
- throw new Error("not implemented");
251
- }
252
- get reader() {
253
- throw new Error("not implemented");
254
- }
255
- get database() {
256
- return this.db;
257
- }
258
- /**
259
- * Executes the SQL statement and returns an info object.
260
- */
261
- async run(...bindParameters) {
262
- const totalChangesBefore = this.db.db.totalChanges();
263
- this.stmt.reset();
264
- bindParams(this.stmt, bindParameters);
265
- while (true) {
266
- const stepResult = this.stmt.step();
267
- if (stepResult === STEP_IO) {
268
- await this.db.db.ioLoopAsync();
269
- continue;
270
- }
271
- if (stepResult === STEP_DONE) {
272
- break;
273
- }
274
- if (stepResult === STEP_ROW) {
275
- // For run(), we don't need the row data, just continue
276
- continue;
277
- }
278
- }
279
- const lastInsertRowid = this.db.db.lastInsertRowid();
280
- const changes = this.db.db.totalChanges() === totalChangesBefore ? 0 : this.db.db.changes();
281
- return { changes, lastInsertRowid };
282
- }
283
- /**
284
- * Executes the SQL statement and returns the first row.
285
- *
286
- * @param bindParameters - The bind parameters for executing the statement.
287
- */
288
- async get(...bindParameters) {
289
- this.stmt.reset();
290
- bindParams(this.stmt, bindParameters);
291
- while (true) {
292
- const stepResult = this.stmt.step();
293
- if (stepResult === STEP_IO) {
294
- await this.db.db.ioLoopAsync();
295
- continue;
296
- }
297
- if (stepResult === STEP_DONE) {
298
- return undefined;
299
- }
300
- if (stepResult === STEP_ROW) {
301
- return this.stmt.row();
302
- }
303
- }
304
- }
305
- /**
306
- * Executes the SQL statement and returns an iterator to the resulting rows.
307
- *
308
- * @param bindParameters - The bind parameters for executing the statement.
309
- */
310
- async *iterate(...bindParameters) {
311
- this.stmt.reset();
312
- bindParams(this.stmt, bindParameters);
313
- while (true) {
314
- const stepResult = this.stmt.step();
315
- if (stepResult === STEP_IO) {
316
- await this.db.db.ioLoopAsync();
317
- continue;
318
- }
319
- if (stepResult === STEP_DONE) {
320
- break;
321
- }
322
- if (stepResult === STEP_ROW) {
323
- yield this.stmt.row();
324
- }
325
- }
326
- }
327
- /**
328
- * Executes the SQL statement and returns an array of the resulting rows.
329
- *
330
- * @param bindParameters - The bind parameters for executing the statement.
331
- */
332
- async all(...bindParameters) {
333
- this.stmt.reset();
334
- bindParams(this.stmt, bindParameters);
335
- const rows = [];
336
- while (true) {
337
- const stepResult = this.stmt.step();
338
- if (stepResult === STEP_IO) {
339
- await this.db.db.ioLoopAsync();
340
- continue;
341
- }
342
- if (stepResult === STEP_DONE) {
343
- break;
344
- }
345
- if (stepResult === STEP_ROW) {
346
- rows.push(this.stmt.row());
347
- }
348
- }
349
- return rows;
350
- }
351
- /**
352
- * Interrupts the statement.
353
- */
354
- interrupt() {
355
- throw new Error("not implemented");
356
- }
357
- /**
358
- * Binds the given parameters to the statement _permanently_
359
- *
360
- * @param bindParameters - The bind parameters for binding the statement.
361
- * @returns this - Statement with binded parameters
362
- */
363
- bind(...bindParameters) {
364
- try {
365
- bindParams(this.stmt, bindParameters);
366
- return this;
367
- }
368
- catch (err) {
369
- throw convertError(err);
370
- }
5
+ super(new NativeDB(path, { tracing: opts.tracing }), opts);
371
6
  }
372
7
  }
373
8
  /**
@@ -380,4 +15,4 @@ class Statement {
380
15
  async function connect(path, opts = {}) {
381
16
  return new Database(path, opts);
382
17
  }
383
- export { Database, SqliteError, connect };
18
+ export { connect, Database, SqliteError };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=promise.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"promise.test.d.ts","sourceRoot":"","sources":["../promise.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,95 @@
1
+ import { unlinkSync } from "node:fs";
2
+ import { expect, test } from 'vitest';
3
+ import { connect } from './promise.js';
4
+ test('in-memory db', async () => {
5
+ const db = await connect(":memory:");
6
+ await db.exec("CREATE TABLE t(x)");
7
+ await db.exec("INSERT INTO t VALUES (1), (2), (3)");
8
+ const stmt = db.prepare("SELECT * FROM t WHERE x % 2 = ?");
9
+ const rows = await stmt.all([1]);
10
+ expect(rows).toEqual([{ x: 1 }, { x: 3 }]);
11
+ });
12
+ test('on-disk db', async () => {
13
+ const path = `test-${(Math.random() * 10000) | 0}.db`;
14
+ try {
15
+ const db1 = await connect(path);
16
+ await db1.exec("CREATE TABLE t(x)");
17
+ await db1.exec("INSERT INTO t VALUES (1), (2), (3)");
18
+ const stmt1 = db1.prepare("SELECT * FROM t WHERE x % 2 = ?");
19
+ expect(stmt1.columns()).toEqual([{ name: "x", column: null, database: null, table: null, type: null }]);
20
+ const rows1 = await stmt1.all([1]);
21
+ expect(rows1).toEqual([{ x: 1 }, { x: 3 }]);
22
+ db1.close();
23
+ const db2 = await connect(path);
24
+ const stmt2 = db2.prepare("SELECT * FROM t WHERE x % 2 = ?");
25
+ expect(stmt2.columns()).toEqual([{ name: "x", column: null, database: null, table: null, type: null }]);
26
+ const rows2 = await stmt2.all([1]);
27
+ expect(rows2).toEqual([{ x: 1 }, { x: 3 }]);
28
+ db2.close();
29
+ }
30
+ finally {
31
+ unlinkSync(path);
32
+ unlinkSync(`${path}-wal`);
33
+ }
34
+ });
35
+ test('attach', async () => {
36
+ const path1 = `test-${(Math.random() * 10000) | 0}.db`;
37
+ const path2 = `test-${(Math.random() * 10000) | 0}.db`;
38
+ try {
39
+ const db1 = await connect(path1);
40
+ await db1.exec("CREATE TABLE t(x)");
41
+ await db1.exec("INSERT INTO t VALUES (1), (2), (3)");
42
+ const db2 = await connect(path2);
43
+ await db2.exec("CREATE TABLE q(x)");
44
+ await db2.exec("INSERT INTO q VALUES (4), (5), (6)");
45
+ await db1.exec(`ATTACH '${path2}' as secondary`);
46
+ const stmt = db1.prepare("SELECT * FROM t UNION ALL SELECT * FROM secondary.q");
47
+ expect(stmt.columns()).toEqual([{ name: "x", column: null, database: null, table: null, type: null }]);
48
+ const rows = await stmt.all([1]);
49
+ expect(rows).toEqual([{ x: 1 }, { x: 2 }, { x: 3 }, { x: 4 }, { x: 5 }, { x: 6 }]);
50
+ }
51
+ finally {
52
+ unlinkSync(path1);
53
+ unlinkSync(`${path1}-wal`);
54
+ unlinkSync(path2);
55
+ unlinkSync(`${path2}-wal`);
56
+ }
57
+ });
58
+ test('blobs', async () => {
59
+ const db = await connect(":memory:");
60
+ const rows = await db.prepare("SELECT x'1020' as x").all();
61
+ expect(rows).toEqual([{ x: Buffer.from([16, 32]) }]);
62
+ });
63
+ test('example-1', async () => {
64
+ const db = await connect(':memory:');
65
+ await db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');
66
+ const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
67
+ await insert.run('Alice', 'alice@example.com');
68
+ await insert.run('Bob', 'bob@example.com');
69
+ const users = await db.prepare('SELECT * FROM users').all();
70
+ expect(users).toEqual([
71
+ { id: 1, name: 'Alice', email: 'alice@example.com' },
72
+ { id: 2, name: 'Bob', email: 'bob@example.com' }
73
+ ]);
74
+ });
75
+ test('example-2', async () => {
76
+ const db = await connect(':memory:');
77
+ await db.exec('CREATE TABLE users (name, email)');
78
+ // Using transactions for atomic operations
79
+ const transaction = db.transaction(async (users) => {
80
+ const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
81
+ for (const user of users) {
82
+ await insert.run(user.name, user.email);
83
+ }
84
+ });
85
+ // Execute transaction
86
+ await transaction([
87
+ { name: 'Alice', email: 'alice@example.com' },
88
+ { name: 'Bob', email: 'bob@example.com' }
89
+ ]);
90
+ const rows = await db.prepare('SELECT * FROM users').all();
91
+ expect(rows).toEqual([
92
+ { name: 'Alice', email: 'alice@example.com' },
93
+ { name: 'Bob', email: 'bob@example.com' }
94
+ ]);
95
+ });