-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathpromise.js
More file actions
439 lines (396 loc) · 10.8 KB
/
promise.js
File metadata and controls
439 lines (396 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
"use strict";
const { Database: NativeDb, connect: nativeConnect } = require("./index.js");
const SqliteError = require("./sqlite-error.js");
const { Authorization, Action } = require("./auth");
/**
* @import {Options as NativeOptions, Statement as NativeStatement} from './index.js'
*/
/**
* better-sqlite3-compatible types for db.transaction()
* @typedef {(...params: any[]) => unknown} VariableArgFunction
*/
/**
* @template {VariableArgFunction} F
* @typedef {F extends (...args: infer A) => unknown ? A : never} ArgumentTypes
*/
function convertError(err) {
// Handle errors from Rust with JSON-encoded message
if (typeof err.message === 'string') {
try {
const data = JSON.parse(err.message);
if (data && data.libsqlError) {
if (data.code === "SQLITE_AUTH") {
// For SQLITE_AUTH, preserve the JSON string for the test
return new SqliteError(err.message, data.code, data.rawCode);
} else if (data.code === "SQLITE_NOTOPEN") {
// Convert SQLITE_NOTOPEN to TypeError with expected message
return new TypeError("The database connection is not open");
} else {
// For all other errors, use the plain message string
return new SqliteError(data.message, data.code, data.rawCode);
}
}
} catch (_) {
// Not JSON, ignore
}
}
return err;
}
function isQueryOptions(value) {
return value != null
&& typeof value === "object"
&& !Array.isArray(value)
&& Object.prototype.hasOwnProperty.call(value, "queryTimeout");
}
function splitBindParameters(bindParameters) {
if (bindParameters.length === 0) {
return { params: undefined, queryOptions: undefined };
}
if (bindParameters.length > 1 && isQueryOptions(bindParameters[bindParameters.length - 1])) {
return {
params: bindParameters.length === 2 ? bindParameters[0] : bindParameters.slice(0, -1),
queryOptions: bindParameters[bindParameters.length - 1],
};
}
return { params: bindParameters.length === 1 ? bindParameters[0] : bindParameters, queryOptions: undefined };
}
/**
* Creates a new database connection.
*
* @param {string} path - Path to the database file.
* @param {NativeOptions} opts - Options.
*/
const connect = async (path, opts) => {
const db = await nativeConnect(path, opts);
return new Database(db);
};
/**
* Database represents a connection that can prepare and execute SQL statements.
*/
class Database {
/**
* Creates a new database connection. If the database file pointed to by `path` does not exists, it will be created.
*
* @constructor
* @param {NativeDb} db - Database object
*/
constructor(db) {
this.db = db;
this.memory = this.db.memory
/** @type boolean */
this.inTransaction;
Object.defineProperties(this, {
inTransaction: {
get() {
return db.inTransaction();
}
},
});
}
sync() {
try {
return this.db.sync();
} catch (err) {
throw convertError(err);
}
}
syncUntil(replicationIndex) {
throw new Error("not implemented");
}
/**
* Prepares a SQL statement for execution.
*
* @param {string} sql - The SQL statement string to prepare.
*/
async prepare(sql) {
try {
const stmt = await this.db.prepare(sql);
return new Statement(stmt);
} catch (err) {
throw convertError(err);
}
}
/**
* Returns a function that executes the given function in a transaction.
*
* @template {VariableArgFunction} F
* @param {F} fn - The function to wrap in a transaction.
* @returns {{
* (...bindParameters: ArgumentTypes<F>): Promise<ReturnType<F>>;
* default(...bindParameters: ArgumentTypes<F>): Promise<ReturnType<F>>;
* deferred(...bindParameters: ArgumentTypes<F>): Promise<ReturnType<F>>;
* immediate(...bindParameters: ArgumentTypes<F>): Promise<ReturnType<F>>;
* exclusive(...bindParameters: ArgumentTypes<F>): Promise<ReturnType<F>>;
* }}
*/
transaction(fn) {
if (typeof fn !== "function")
throw new TypeError("Expected first argument to be a function");
const db = this;
const wrapTxn = (mode) => {
return async (...bindParameters) => {
await db.exec("BEGIN " + mode);
try {
const result = await fn(...bindParameters);
await db.exec("COMMIT");
return result;
} catch (err) {
await db.exec("ROLLBACK");
throw err;
}
};
};
const properties = {
default: { value: wrapTxn("") },
deferred: { value: wrapTxn("DEFERRED") },
immediate: { value: wrapTxn("IMMEDIATE") },
exclusive: { value: wrapTxn("EXCLUSIVE") },
database: { value: this, enumerable: true },
};
Object.defineProperties(properties.default.value, properties);
Object.defineProperties(properties.deferred.value, properties);
Object.defineProperties(properties.immediate.value, properties);
Object.defineProperties(properties.exclusive.value, properties);
return properties.default.value;
}
/**
* Execute a pragma statement
* @param {string} source - The pragma statement to execute, without the `PRAGMA` prefix.
* @param {object} [options] - Options object.
* @param {boolean} [options.simple] - If true, return a single value for single-column results.
*/
async pragma(source, options) {
if (options == null) options = {};
if (typeof source !== 'string') throw new TypeError('Expected first argument to be a string');
if (typeof options !== 'object') throw new TypeError('Expected second argument to be an options object');
const simple = options['simple'];
const stmt = await this.prepare(`PRAGMA ${source}`, this, true);
return simple ? stmt.pluck().get() : stmt.all();
}
backup(filename, options) {
throw new Error("not implemented");
}
serialize(options) {
throw new Error("not implemented");
}
function(name, options, fn) {
throw new Error("not implemented");
}
aggregate(name, options) {
throw new Error("not implemented");
}
table(name, factory) {
throw new Error("not implemented");
}
/**
* Loads an extension into the database
* @param {Parameters<NativeDb['loadExtension']>} args - Arguments to pass to the underlying loadExtension method
*/
loadExtension(...args) {
try {
this.db.loadExtension(...args);
} catch (err) {
throw convertError(err);
}
}
maxWriteReplicationIndex() {
try {
return this.db.maxWriteReplicationIndex();
} catch (err) {
throw convertError(err);
}
}
/**
* Executes a SQL statement.
*
* @param {string} sql - The SQL statement string to execute.
*/
async exec(sql, queryOptions) {
try {
await this.db.exec(sql, queryOptions);
} catch (err) {
throw convertError(err);
}
}
/**
* Interrupts the database connection.
*/
interrupt() {
this.db.interrupt();
}
/**
* Closes the database connection.
*/
close() {
this.db.close();
}
authorizer(config) {
try {
this.db.authorizer(config);
} catch (err) {
throw convertError(err);
}
return this;
}
/**
* Toggle 64-bit integer support.
* @param {boolean} [toggle] - Whether to use safe integers by default.
*/
defaultSafeIntegers(toggle) {
this.db.defaultSafeIntegers(toggle);
return this;
}
unsafeMode(...args) {
throw new Error("not implemented");
}
}
/**
* Statement represents a prepared SQL statement that can be executed.
*/
class Statement {
/**
* @param {NativeStatement} stmt
*/
constructor(stmt) {
this.stmt = stmt;
}
/**
* Toggle raw mode.
*
* @param {boolean} [raw] - Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
*/
raw(raw) {
this.stmt.raw(raw);
return this;
}
/**
* Toggle pluck mode.
*
* @param {boolean} [pluckMode] - Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
*/
pluck(pluckMode) {
this.stmt.pluck(pluckMode);
return this;
}
/**
* Toggle query timing.
*
* @param {boolean} [timingMode] - Enable or disable query timing. If you don't pass the parameter, query timing is enabled.
*/
timing(timingMode) {
this.stmt.timing(timingMode);
return this;
}
get reader() {
return this.stmt.columns().length > 0;
}
/**
* Executes the SQL statement and returns an info object.
*/
async run(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
return await this.stmt.run(params, queryOptions);
} catch (err) {
throw convertError(err);
}
}
/**
* Executes the SQL statement and returns the first row.
*
* @param bindParameters - The bind parameters for executing the statement.
*/
async get(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
return await this.stmt.get(params, queryOptions);
} catch (err) {
throw convertError(err);
}
}
/**
* Executes the SQL statement and returns an iterator to the resulting rows.
*
* @param bindParameters - The bind parameters for executing the statement.
*/
async iterate(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
const it = await this.stmt.iterate(params, queryOptions);
return wrappedIter(it);
} catch (err) {
throw convertError(err);
}
}
/**
* Executes the SQL statement and returns an array of the resulting rows.
*
* @param bindParameters - The bind parameters for executing the statement.
*/
async all(...bindParameters) {
try {
const result = [];
const iterator = await this.iterate(...bindParameters);
try {
let next;
while (!(next = await iterator.next()).done) {
result.push(next.value);
}
return result;
} finally {
if (typeof iterator.return === "function") {
await iterator.return();
}
}
} catch (err) {
throw convertError(err);
}
}
/**
* Interrupts the statement.
*/
interrupt() {
this.stmt.interrupt();
return this;
}
/**
* Returns the columns in the result set returned by this prepared statement.
*/
columns() {
return this.stmt.columns();
}
/**
* Toggle 64-bit integer support.
*/
safeIntegers(toggle) {
this.stmt.safeIntegers(toggle);
return this;
}
}
function wrappedIter(it) {
return {
next() {
return it.next();
},
return(value) {
if (typeof it.close === "function") {
it.close();
}
return {
done: true,
value,
};
},
[Symbol.asyncIterator]() {
return this;
}
};
}
module.exports = {
Action,
Authorization,
Database,
SqliteError,
Statement,
connect,
};