@tursodatabase/database 0.1.4-pre.10

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.
@@ -0,0 +1,383 @@
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
+ */
41
+ 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
+ }
371
+ }
372
+ }
373
+ /**
374
+ * Creates a new database connection asynchronously.
375
+ *
376
+ * @param {string} path - Path to the database file.
377
+ * @param {Object} opts - Options for database behavior.
378
+ * @returns {Promise<Database>} - A promise that resolves to a Database instance.
379
+ */
380
+ async function connect(path, opts = {}) {
381
+ return new Database(path, opts);
382
+ }
383
+ export { Database, SqliteError, connect };
@@ -0,0 +1,12 @@
1
+ export class SqliteError extends Error {
2
+ name;
3
+ code;
4
+ rawCode;
5
+ constructor(message, code, rawCode) {
6
+ super(message);
7
+ this.name = 'SqliteError';
8
+ this.code = code;
9
+ this.rawCode = rawCode;
10
+ Error.captureStackTrace(this, SqliteError);
11
+ }
12
+ }
package/index.d.ts ADDED
@@ -0,0 +1,130 @@
1
+ /* auto-generated by NAPI-RS */
2
+ /* eslint-disable */
3
+ /** A database connection. */
4
+ export declare class Database {
5
+ /**
6
+ * Creates a new database instance.
7
+ *
8
+ * # Arguments
9
+ * * `path` - The path to the database file.
10
+ */
11
+ constructor(path: string)
12
+ /** Returns whether the database is in memory-only mode. */
13
+ get memory(): boolean
14
+ /** Returns whether the database connection is open. */
15
+ get open(): boolean
16
+ /**
17
+ * Executes a batch of SQL statements.
18
+ *
19
+ * # Arguments
20
+ *
21
+ * * `sql` - The SQL statements to execute.
22
+ *
23
+ * # Returns
24
+ */
25
+ batch(sql: string): void
26
+ /**
27
+ * Prepares a statement for execution.
28
+ *
29
+ * # Arguments
30
+ *
31
+ * * `sql` - The SQL statement to prepare.
32
+ *
33
+ * # Returns
34
+ *
35
+ * A `Statement` instance.
36
+ */
37
+ prepare(sql: string): Statement
38
+ /**
39
+ * Returns the rowid of the last row inserted.
40
+ *
41
+ * # Returns
42
+ *
43
+ * The rowid of the last row inserted.
44
+ */
45
+ lastInsertRowid(): number
46
+ /**
47
+ * Returns the number of changes made by the last statement.
48
+ *
49
+ * # Returns
50
+ *
51
+ * The number of changes made by the last statement.
52
+ */
53
+ changes(): number
54
+ /**
55
+ * Returns the total number of changes made by all statements.
56
+ *
57
+ * # Returns
58
+ *
59
+ * The total number of changes made by all statements.
60
+ */
61
+ totalChanges(): number
62
+ /**
63
+ * Closes the database connection.
64
+ *
65
+ * # Returns
66
+ *
67
+ * `Ok(())` if the database is closed successfully.
68
+ */
69
+ close(): void
70
+ /**
71
+ * Sets the default safe integers mode for all statements from this database.
72
+ *
73
+ * # Arguments
74
+ *
75
+ * * `toggle` - Whether to use safe integers by default.
76
+ */
77
+ defaultSafeIntegers(toggle?: boolean | undefined | null): void
78
+ /** Runs the I/O loop synchronously. */
79
+ ioLoopSync(): void
80
+ /** Runs the I/O loop asynchronously, returning a Promise. */
81
+ ioLoopAsync(): Promise<void>
82
+ }
83
+
84
+ /** A prepared statement. */
85
+ export declare class Statement {
86
+ reset(): void
87
+ /** Returns the number of parameters in the statement. */
88
+ parameterCount(): number
89
+ /**
90
+ * Returns the name of a parameter at a specific 1-based index.
91
+ *
92
+ * # Arguments
93
+ *
94
+ * * `index` - The 1-based parameter index.
95
+ */
96
+ parameterName(index: number): string | null
97
+ /**
98
+ * Binds a parameter at a specific 1-based index with explicit type.
99
+ *
100
+ * # Arguments
101
+ *
102
+ * * `index` - The 1-based parameter index.
103
+ * * `value_type` - The type constant (0=null, 1=int, 2=float, 3=text, 4=blob).
104
+ * * `value` - The value to bind.
105
+ */
106
+ bindAt(index: number, value: unknown): void
107
+ /**
108
+ * Step the statement and return result code:
109
+ * 1 = Row available, 2 = Done, 3 = I/O needed
110
+ */
111
+ step(): number
112
+ /** Get the current row data according to the presentation mode */
113
+ row(): unknown
114
+ /** Sets the presentation mode to raw. */
115
+ raw(raw?: boolean | undefined | null): void
116
+ /** Sets the presentation mode to pluck. */
117
+ pluck(pluck?: boolean | undefined | null): void
118
+ /**
119
+ * Sets safe integers mode for this statement.
120
+ *
121
+ * # Arguments
122
+ *
123
+ * * `toggle` - Whether to use safe integers.
124
+ */
125
+ safeIntegers(toggle?: boolean | undefined | null): void
126
+ /** Get column information for the statement */
127
+ columns(): unknown[]
128
+ /** Finalizes the statement. */
129
+ finalize(): void
130
+ }