-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathcompat.js
More file actions
433 lines (391 loc) · 11 KB
/
compat.js
File metadata and controls
433 lines (391 loc) · 11 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
"use strict";
const { Database: NativeDb, databasePrepareSync, databaseSyncSync, databaseExecSync, statementRunSync, statementGetSync, statementIterateSync, iteratorNextSync } = require("./index.js");
const SqliteError = require("./sqlite-error.js");
const Authorization = require("./auth");
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 };
}
const symbolDispose = typeof Symbol.dispose === "symbol" ? Symbol.dispose : null;
const hasWeakRef = typeof WeakRef === "function";
/**
* 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) {
this.db = new NativeDb(path, opts);
this.memory = this.db.memory
this._closed = false;
this._statements = hasWeakRef ? new Set() : null;
const db = this.db;
Object.defineProperties(this, {
inTransaction: {
get() {
return db.inTransaction();
}
},
});
}
sync() {
try {
const result = databaseSyncSync(this.db);
return {
frames_synced: result.frames_synced,
replication_index: result.replication_index
};
} 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.
*/
prepare(sql) {
try {
const stmt = databasePrepareSync(this.db, sql);
const wrappedStmt = new Statement(stmt, this);
if (this._statements != null) {
const statementRef = new WeakRef(wrappedStmt);
wrappedStmt._statementRef = statementRef;
this._statements.add(statementRef);
}
return wrappedStmt;
} 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 (...bindParameters) => {
db.exec("BEGIN " + mode);
try {
const result = fn(...bindParameters);
db.exec("COMMIT");
return result;
} catch (err) {
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'];
const stmt = 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");
}
authorizer(rules) {
try {
this.db.authorizer(rules);
} catch (err) {
throw convertError(err);
}
}
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.
*/
exec(sql, queryOptions) {
try {
databaseExecSync(this.db, sql, queryOptions);
} catch (err) {
throw convertError(err);
}
}
/**
* Interrupts the database connection.
*/
interrupt() {
this.db.interrupt();
}
/**
* Closes the database connection.
*/
close() {
if (this._closed) {
return;
}
this._closed = true;
if (this._statements != null) {
for (const statementRef of Array.from(this._statements)) {
const statement = statementRef.deref();
if (statement == null) {
this._statements.delete(statementRef);
continue;
}
statement.close();
}
this._statements.clear();
}
this.db.close();
}
authorizer(hook) {
this.db.authorizer(hook);
return this;
}
/**
* Toggle 64-bit integer support.
*/
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 {
constructor(stmt, database) {
this.stmt = stmt;
this.database = database;
this._statementRef = null;
this._closed = false;
}
close() {
if (this._closed) {
return this;
}
this._closed = true;
if (this.database != null && this.database._statements != null && this._statementRef != null) {
this.database._statements.delete(this._statementRef);
}
if (this.database != null) {
this.database = null;
}
if (this.stmt != null) {
this.stmt.close();
this.stmt = null;
}
return this;
}
_getNativeStatement() {
if (this._closed || this.stmt == null) {
throw new TypeError("The database connection is not open");
}
return this.stmt;
}
/**
* Toggle raw mode.
*
* @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
*/
raw(raw) {
this._getNativeStatement().raw(raw);
return this;
}
/**
* Toggle pluck mode.
*
* @param pluckMode Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
*/
pluck(pluckMode) {
this._getNativeStatement().pluck(pluckMode);
return this;
}
/**
* Toggle query timing.
*
* @param timing Enable or disable query timing. If you don't pass the parameter, query timing is enabled.
*/
timing(timingMode) {
this._getNativeStatement().timing(timingMode);
return this;
}
get reader() {
return this._getNativeStatement().columns().length > 0;
}
/**
* Executes the SQL statement and returns an info object.
*/
run(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
return statementRunSync(this._getNativeStatement(), 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.
*/
get(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
return statementGetSync(this._getNativeStatement(), 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.
*/
iterate(...bindParameters) {
try {
const { params, queryOptions } = splitBindParameters(bindParameters);
const it = statementIterateSync(this._getNativeStatement(), params, queryOptions);
return {
next: () => iteratorNextSync(it),
[Symbol.iterator]() {
return {
next: () => iteratorNextSync(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.
*/
all(...bindParameters) {
try {
const result = [];
const iterator = this.iterate(...bindParameters);
let next;
while (!(next = iterator.next()).done) {
result.push(next.value);
}
return result;
} catch (err) {
throw convertError(err);
}
}
/**
* Interrupts the statement.
*/
interrupt() {
this._getNativeStatement().interrupt();
return this;
}
/**
* Returns the columns in the result set returned by this prepared statement.
*/
columns() {
return this._getNativeStatement().columns();
}
/**
* Toggle 64-bit integer support.
*/
safeIntegers(toggle) {
this._getNativeStatement().safeIntegers(toggle);
return this;
}
}
if (symbolDispose != null) {
Database.prototype[symbolDispose] = Database.prototype.close;
Statement.prototype[symbolDispose] = Statement.prototype.close;
}
module.exports = Database;
module.exports.SqliteError = SqliteError;
module.exports.Authorization = Authorization;