-
Notifications
You must be signed in to change notification settings - Fork 25
/
promise.js
407 lines (366 loc) · 10.5 KB
/
promise.js
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
"use strict";
const { load, currentTarget } = require("@neon-rs/load");
const { familySync, GLIBC } = require("detect-libc");
// Static requires for bundlers.
if (0) {
require("./.targets");
}
const SqliteError = require("./sqlite-error");
function convertError(err) {
if (err.libsqlError) {
return new SqliteError(err.message, err.code, err.rawCode);
}
return err;
}
function requireNative() {
if (process.env.LIBSQL_JS_DEV) {
return load(__dirname)
}
let target = currentTarget();
// Workaround for Bun, which reports a musl target, but really wants glibc...
if (familySync() == GLIBC) {
switch (target) {
case "linux-x64-musl":
target = "linux-x64-gnu";
break;
case "linux-arm64-musl":
target = "linux-arm64-gnu";
break;
}
}
return require(`@libsql/${target}`);
}
const {
databaseOpen,
databaseOpenWithSync,
databaseInTransaction,
databaseInterrupt,
databaseClose,
databaseSyncAsync,
databaseSyncUntilAsync,
databaseExecAsync,
databasePrepareAsync,
databaseMaxWriteReplicationIndex,
databaseDefaultSafeIntegers,
statementRaw,
statementIsReader,
statementGet,
statementRun,
statementRowsAsync,
statementColumns,
statementSafeIntegers,
rowsNext,
} = requireNative();
/**
* 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 {string} path - Path to the database file.
*/
constructor(path, opts) {
const encryptionCipher = opts?.encryptionCipher ?? "aes256cbc";
if (opts && opts.syncUrl) {
var authToken = "";
if (opts.syncAuth) {
console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead.");
authToken = opts.syncAuth;
} else if (opts.authToken) {
authToken = opts.authToken;
}
const encryptionKey = opts?.encryptionKey ?? "";
const syncPeriod = opts?.syncPeriod ?? 0.0;
const offline = opts?.offline ?? false;
this.db = databaseOpenWithSync(path, opts.syncUrl, authToken, encryptionCipher, encryptionKey, syncPeriod, offline);
} else {
const authToken = opts?.authToken ?? "";
const encryptionKey = opts?.encryptionKey ?? "";
this.db = databaseOpen(path, authToken, encryptionCipher, encryptionKey);
}
// TODO: Use a libSQL API for this?
this.memory = path === ":memory:";
this.readonly = false;
this.name = "";
this.open = true;
const db = this.db;
Object.defineProperties(this, {
inTransaction: {
get() {
return databaseInTransaction(db);
}
},
});
}
sync() {
return databaseSyncAsync.call(this.db);
}
syncUntil(replicationIndex) {
return databaseSyncUntilAsync.call(this.db, replicationIndex);
}
/**
* Prepares a SQL statement for execution.
*
* @param {string} sql - The SQL statement string to prepare.
*/
prepare(sql) {
return databasePrepareAsync.call(this.db, sql).then((stmt) => {
return new Statement(stmt);
}).catch((err) => {
throw convertError(err);
});
}
/**
* Returns a function that executes the given function in a transaction.
*
* @param {function} fn - The function to wrap in a transaction.
*/
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 = 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;
}
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'];
return this.prepare(`PRAGMA ${source}`, this, true).then(async (stmt) => {
return simple ? await stmt.pluck().get() : await stmt.all();
});
}
backup(filename, options) {
throw new Error("not implemented");
}
serialize(options) {
throw new Error("not implemented");
}
function(name, options, fn) {
// Apply defaults
if (options == null) options = {};
if (typeof options === "function") {
fn = options;
options = {};
}
// Validate arguments
if (typeof name !== "string")
throw new TypeError("Expected first argument to be a string");
if (typeof fn !== "function")
throw new TypeError("Expected last argument to be a function");
if (typeof options !== "object")
throw new TypeError("Expected second argument to be an options object");
if (!name)
throw new TypeError(
"User-defined function name cannot be an empty string"
);
throw new Error("not implemented");
}
aggregate(name, options) {
// Validate arguments
if (typeof name !== "string")
throw new TypeError("Expected first argument to be a string");
if (typeof options !== "object" || options === null)
throw new TypeError("Expected second argument to be an options object");
if (!name)
throw new TypeError(
"User-defined function name cannot be an empty string"
);
throw new Error("not implemented");
}
table(name, factory) {
// Validate arguments
if (typeof name !== "string")
throw new TypeError("Expected first argument to be a string");
if (!name)
throw new TypeError(
"Virtual table module name cannot be an empty string"
);
throw new Error("not implemented");
}
loadExtension(...args) {
throw new Error("not implemented");
}
maxWriteReplicationIndex() {
return databaseMaxWriteReplicationIndex.call(this.db)
}
/**
* Executes a SQL statement.
*
* @param {string} sql - The SQL statement string to execute.
*/
exec(sql) {
return databaseExecAsync.call(this.db, sql).catch((err) => {
throw convertError(err);
});
}
/**
* Interrupts the database connection.
*/
interrupt() {
databaseInterrupt.call(this.db);
}
/**
* Closes the database connection.
*/
close() {
databaseClose.call(this.db);
}
/**
* Toggle 64-bit integer support.
*/
defaultSafeIntegers(toggle) {
databaseDefaultSafeIntegers.call(this.db, toggle ?? true);
return this;
}
unsafeMode(...args) {
throw new Error("not implemented");
}
}
/**
* Statement represents a prepared SQL statement that can be executed.
*/
class Statement {
constructor(stmt) {
this.stmt = stmt;
}
/**
* Toggle raw mode.
*
* @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
*/
raw(raw) {
statementRaw.call(this.stmt, raw ?? true);
return this;
}
get reader() {
return statementIsReader.call(this.stmt);
}
/**
* Executes the SQL statement and returns an info object.
*/
run(...bindParameters) {
try {
if (bindParameters.length == 1 && typeof bindParameters[0] === "object") {
return statementRun.call(this.stmt, bindParameters[0]);
} else {
return statementRun.call(this.stmt, bindParameters.flat());
}
} catch (err) {
throw convertError(err);
}
}
/**
* Executes the SQL statement and returns the first row.
*
* @param bindParameters - The bind parameters for executing the statement.
*/
get(...bindParameters) {
try {
if (bindParameters.length == 1 && typeof bindParameters[0] === "object") {
return statementGet.call(this.stmt, bindParameters[0]);
} else {
return statementGet.call(this.stmt, bindParameters.flat());
}
} catch (e) {
throw convertError(e);
}
}
/**
* Executes the SQL statement and returns an iterator to the resulting rows.
*
* @param bindParameters - The bind parameters for executing the statement.
*/
async iterate(...bindParameters) {
var rows = undefined;
if (bindParameters.length == 1 && typeof bindParameters[0] === "object") {
rows = await statementRowsAsync.call(this.stmt, bindParameters[0]);
} else {
rows = await statementRowsAsync.call(this.stmt, bindParameters.flat());
}
const iter = {
nextRows: Array(100),
nextRowIndex: 100,
next() {
try {
if (this.nextRowIndex === 100) {
this.nextRows.fill(null);
rowsNext.call(rows, this.nextRows);
this.nextRowIndex = 0;
}
const row = this.nextRows[this.nextRowIndex];
this.nextRows[this.nextRowIndex] = null;
if (!row) {
return { done: true };
}
this.nextRowIndex++;
return { value: row, done: false };
} catch (e) {
throw convertError(e);
}
},
[Symbol.iterator]() {
return this;
},
};
return iter;
}
/**
* 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 it = await this.iterate(...bindParameters);
for (const row of it) {
result.push(row);
}
return result;
} catch (e) {
throw convertError(e);
}
}
/**
* Returns the columns in the result set returned by this prepared statement.
*/
columns() {
return statementColumns.call(this.stmt);
}
/**
* Toggle 64-bit integer support.
*/
safeIntegers(toggle) {
statementSafeIntegers.call(this.stmt, toggle ?? true);
return this;
}
}
module.exports = Database;
module.exports.SqliteError = SqliteError;