Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion deps/defines.gypi
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
'SQLITE_ENABLE_UPDATE_DELETE_LIMIT',
'SQLITE_LIKE_DOESNT_MATCH_BLOBS',
'SQLITE_OMIT_DEPRECATED',
'SQLITE_OMIT_PROGRESS_CALLBACK',
'SQLITE_OMIT_SHARED_CACHE',
'SQLITE_OMIT_TCL_VARIABLE',
'SQLITE_SOUNDEX',
Expand Down
1 change: 0 additions & 1 deletion deps/download.sh
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ SQLITE_ENABLE_STMT_SCANSTATUS
SQLITE_ENABLE_UPDATE_DELETE_LIMIT
SQLITE_LIKE_DOESNT_MATCH_BLOBS
SQLITE_OMIT_DEPRECATED
SQLITE_OMIT_PROGRESS_CALLBACK
SQLITE_OMIT_SHARED_CACHE
SQLITE_OMIT_TCL_VARIABLE
SQLITE_SOUNDEX
Expand Down
22 changes: 22 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- [Database#loadExtension()](#loadextensionpath-entrypoint---this)
- [Database#exec()](#execstring---this)
- [Database#close()](#close---this)
- [Database#progressHandler()](#progresshandlerinterval-callback---this)
- [Database#persistWal()](#persistwaltogglestate---this)
- [Properties](#properties)

Expand Down Expand Up @@ -395,6 +396,27 @@ process.on('SIGINT', () => process.exit(128 + 2));
process.on('SIGTERM', () => process.exit(128 + 15));
```

### .progressHandler([*interval*, *callback*]) -> *this*

Registers a synchronous callback on this connection. SQLite calls it approximately every `interval` virtual machine instructions during SQL execution, including scans that have yet to return a row. SQLite can also call it while preparing a complex statement. The interval must be a positive 32-bit signed integer.

Return `true` to interrupt the operation with a `SqliteError` whose `code` is `SQLITE_INTERRUPT`. Return `false` or `undefined` to continue. Throwing from the callback aborts the operation and propagates the original exception. Keep the callback short and avoid modifying the connection or running SQL on it. Interrupting a write inside an explicit transaction can cause SQLite to roll back the transaction.

Each call replaces the connection's previous handler. Call `db.progressHandler()` to clear it. This example checks a deadline even when the query produces no rows.

```js
const deadline = performance.now() + 2000;
db.progressHandler(10000, () => performance.now() >= deadline);
try {
const rows = db.prepare('SELECT id FROM events WHERE archived = 1').all();
console.log(rows.length);
} finally {
db.progressHandler();
}
```

See [SQLite's progress callback documentation](https://sqlite.org/c3ref/progress_handler.html).

### .persistWal([*toggleState*]) -> *this*

Toggles whether the connection keeps the [write-ahead log](https://www.sqlite.org/wal.html) when it is the last connection to close the database (see [`SQLITE_FCNTL_PERSIST_WAL`](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal)). The last connection still checkpoints the WAL into the database, but leaves the `-wal` and `-shm` files in place instead of deleting them, so the next connection continues the same WAL. It is off by default. Invoking it without an argument turns it on.
Expand Down
1 change: 0 additions & 1 deletion docs/compilation.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ SQLITE_ENABLE_STMT_SCANSTATUS
SQLITE_ENABLE_UPDATE_DELETE_LIMIT
SQLITE_LIKE_DOESNT_MATCH_BLOBS
SQLITE_OMIT_DEPRECATED
SQLITE_OMIT_PROGRESS_CALLBACK
SQLITE_OMIT_SHARED_CACHE
SQLITE_OMIT_TCL_VARIABLE
SQLITE_SOUNDEX
Expand Down
1 change: 1 addition & 0 deletions lib/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ Database.prototype.exec = wrappers.exec;
Database.prototype.close = wrappers.close;
Database.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
Database.prototype.unsafeMode = wrappers.unsafeMode;
Database.prototype.progressHandler = wrappers.progressHandler;
Database.prototype.persistWal = wrappers.persistWal;
Database.prototype.loadExtension = wrappers.loadExtension;
Database.prototype[util.inspect] = require('./methods/inspect');
Expand Down
2 changes: 2 additions & 0 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ declare namespace BetterSqlite3 {
backup(destinationFile: string, options?: Database.BackupOptions): Promise<Database.BackupMetadata>;
table(name: string, options: VirtualTableOptions): this;
unsafeMode(unsafe?: boolean): this;
progressHandler(interval: number, callback: () => boolean | void): this;
progressHandler(): this;
persistWal(persist?: boolean): this;
serialize(options?: Database.SerializeOptions): Buffer;
}
Expand Down
5 changes: 5 additions & 0 deletions lib/methods/wrappers.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ exports.unsafeMode = function unsafeMode(...args) {
return this;
};

exports.progressHandler = function progressHandler(...args) {
this[cppdb].progressHandler(...args);
return this;
};

exports.persistWal = function persistWal(...args) {
this[cppdb].persistWal(...args);
return this;
Expand Down
50 changes: 50 additions & 0 deletions src/objects/database.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Database::~Database() {
void Database::CloseHandles() {
if (open) {
open = false;
sqlite3_progress_handler(db_handle, 0, NULL, NULL);
for (Statement* stmt : stmts) stmt->CloseHandles();
for (Backup* backup : backups) backup->CloseHandles();
stmts.clear();
Expand Down Expand Up @@ -125,6 +126,7 @@ void Database::FreeSerialization(char* data, void* _) {

INIT(Database::Init) {
v8::Local<v8::FunctionTemplate> t = NewConstructorTemplate(isolate, data, JS_new, "Database");
t->InstanceTemplate()->SetInternalFieldCount(PROGRESS_HANDLER_FIELD + 1);
SetPrototypeMethod(isolate, data, t, "prepare", JS_prepare);
SetPrototypeMethod(isolate, data, t, "exec", JS_exec);
SetPrototypeMethod(isolate, data, t, "backup", JS_backup);
Expand All @@ -136,6 +138,7 @@ INIT(Database::Init) {
SetPrototypeMethod(isolate, data, t, "close", JS_close);
SetPrototypeMethod(isolate, data, t, "defaultSafeIntegers", JS_defaultSafeIntegers);
SetPrototypeMethod(isolate, data, t, "unsafeMode", JS_unsafeMode);
SetPrototypeMethod(isolate, data, t, "progressHandler", JS_progressHandler);
SetPrototypeMethod(isolate, data, t, "persistWal", JS_persistWal);
SetPrototypeGetter(isolate, data, t, "open", JS_open);
SetPrototypeGetter(isolate, data, t, "inTransaction", JS_inTransaction);
Expand Down Expand Up @@ -203,10 +206,14 @@ NODE_METHOD(Database::JS_prepare) {
(void)pragmaMode;
UseAddon;
UseIsolate;
Database* db = Unwrap<Database>(info.This());
const bool was_preparing = db->preparing;
db->preparing = true;
v8::Local<v8::Function> c = addon->Statement.Get(isolate);
addon->privileged_info = &info;
v8::MaybeLocal<v8::Object> maybeStatement = c->NewInstance(OnlyContext, 0, NULL);
addon->privileged_info = NULL;
db->preparing = was_preparing;
if (!maybeStatement.IsEmpty()) info.GetReturnValue().Set(maybeStatement.ToLocalChecked());
}

Expand Down Expand Up @@ -392,6 +399,7 @@ NODE_METHOD(Database::JS_close) {
REQUIRE_DATABASE_NO_ITERATORS(db);
db->addon->dbs.erase(db);
db->CloseHandles();
info.This()->SetInternalField(PROGRESS_HANDLER_FIELD, v8::Undefined(OnlyIsolate));
}
}

Expand All @@ -408,6 +416,48 @@ NODE_METHOD(Database::JS_unsafeMode) {
sqlite3_db_config(db->db_handle, SQLITE_DBCONFIG_DEFENSIVE, static_cast<int>(!db->unsafe_mode), NULL);
}

NODE_METHOD(Database::JS_progressHandler) {
Database* db = Unwrap<Database>(info.This());
REQUIRE_DATABASE_OPEN(db);
REQUIRE_DATABASE_NOT_BUSY(db);
if (info.Length() == 0) {
sqlite3_progress_handler(db->db_handle, 0, NULL, NULL);
info.This()->SetInternalField(PROGRESS_HANDLER_FIELD, v8::Undefined(OnlyIsolate));
return;
}
if (info.Length() != 2) return ThrowTypeError("Expected an instruction interval and a progress callback");
REQUIRE_ARGUMENT_INT32(first, int interval);
REQUIRE_ARGUMENT_FUNCTION(second, v8::Local<v8::Function> fn);
if (interval <= 0) return ThrowRangeError("Expected a positive instruction interval");
info.This()->SetInternalField(PROGRESS_HANDLER_FIELD, fn);
sqlite3_progress_handler(db->db_handle, interval, OnProgress, db);
}

int Database::OnProgress(void* context) {
Database* db = static_cast<Database*>(context);
// Only invoke JS during SQL preparation and execution. SQLite may also
// run internal statements in other APIs, such as sqlite3_serialize().
if (!db->busy && !db->preparing) return 0;
if (db->was_js_error) return 1;
EasyIsolate;
v8::HandleScope scope(isolate);
v8::Local<v8::Function> fn = db->handle(isolate)->GetInternalField(PROGRESS_HANDLER_FIELD).As<v8::Function>();
v8::Local<v8::Value> result;
const bool was_busy = db->busy;
db->busy = true;
bool returned = fn->Call(OnlyContext, v8::Undefined(isolate), 0, NULL).ToLocal(&result);
db->busy = was_busy;
if (!returned) {
db->was_js_error = true;
return 1;
}
if (result->IsTrue()) return 1;
if (result->IsFalse() || result->IsUndefined()) return 0;
ThrowTypeError("Expected the progress callback to return a boolean or undefined");
db->was_js_error = true;
return 1;
}

NODE_METHOD(Database::JS_persistWal) {
Database* db = Unwrap<Database>(info.This());
REQUIRE_DATABASE_OPEN(db);
Expand Down
6 changes: 6 additions & 0 deletions src/objects/database.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ class Database : public node::ObjectWrap {
static NODE_METHOD(JS_close);
static NODE_METHOD(JS_defaultSafeIntegers);
static NODE_METHOD(JS_unsafeMode);
static NODE_METHOD(JS_progressHandler);
static int OnProgress(void* context);
// Field 0 belongs to node::ObjectWrap. Keep the callback on its JS owner so
// a callback that captures the connection can be garbage collected with it.
static constexpr int PROGRESS_HANDLER_FIELD = 1;
static NODE_METHOD(JS_persistWal);
static NODE_GETTER(JS_open);
static NODE_GETTER(JS_inTransaction);
Expand All @@ -98,6 +103,7 @@ class Database : public node::ObjectWrap {
const bool has_logger;
unsigned short iterators;
Addon* const addon;
bool preparing = false;
const v8::Global<v8::Value> logger;
std::set<Statement*, CompareStatement> stmts;
std::set<Backup*, CompareBackup> backups;
Expand Down
2 changes: 2 additions & 0 deletions src/objects/statement.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ NODE_METHOD(Statement::JS_new) {
sqlite3_stmt* handle;
const char* tail;

// Preparation can invoke user callbacks. The constructor has consumed its arguments.
addon->privileged_info = NULL;
if (sqlite3_prepare_v3(db->GetHandle(), *utf8, utf8.length() + 1, flags, &handle, &tail) != SQLITE_OK) {
return db->ThrowDatabaseError();
}
Expand Down
105 changes: 105 additions & 0 deletions test/54.progress-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
'use strict';
const Database = require('../.');

describe('Database#progressHandler()', function () {
const scan = 'SELECT x FROM data WHERE x + 1 < 0';
beforeEach(function () {
this.db = new Database(':memory:');
this.db.exec(`
CREATE TABLE data(x INTEGER);
WITH RECURSIVE seq(x) AS (VALUES (1) UNION ALL SELECT x + 1 FROM seq WHERE x < 5000)
INSERT INTO data SELECT x FROM seq;
`);
});
afterEach(function () {
this.db.close();
});

it('interrupts a scan before its first row and can reuse the statement', function () {
const stmt = this.db.prepare(scan);
let calls = 0;
expect(this.db.progressHandler(100, () => ++calls === 3)).to.equal(this.db);
expect(() => stmt.get()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_INTERRUPT');
expect(calls).to.equal(3);
expect(this.db.progressHandler()).to.equal(this.db);
expect(stmt.get()).to.equal(undefined);
expect(calls).to.equal(3);
});

it('leaves an explicit read transaction for the caller to end', function () {
const stmt = this.db.prepare(scan);
this.db.exec('BEGIN');
this.db.progressHandler(100, () => true);
expect(() => stmt.all()).to.throw(Database.SqliteError).with.property('code', 'SQLITE_INTERRUPT');
this.db.progressHandler();
expect(this.db.inTransaction).to.equal(true);
this.db.exec('ROLLBACK');
expect(stmt.all()).to.deep.equal([]);
});

it('continues on false or undefined and replaces the handler per connection', function () {
let calls = 0;
this.db.progressHandler(100, () => { ++calls; });
this.db.prepare(scan).all();
expect(calls).to.be.greaterThan(1);
const originalCalls = calls;
this.db.progressHandler(1, () => false);
this.db.exec(scan);
expect(calls).to.equal(originalCalls);
this.db.progressHandler(1, () => true);
const other = new Database(':memory:');
try {
expect(other.prepare('SELECT 42').pluck().get()).to.equal(42);
} finally {
other.close();
}
expect(() => this.db.exec(scan)).to.throw(Database.SqliteError).with.property('code', 'SQLITE_INTERRUPT');
});

it('propagates the callback exception through a batched iterator and unlocks it', function () {
const stmt = this.db.prepare(scan);
const iterator = stmt.iterate();
const error = new Error('deadline reached');
this.db.progressHandler(100, () => { throw error; });
expect(() => iterator.nextBatch(16)).to.throw(error);
expect(stmt.busy).to.equal(false);
this.db.progressHandler();
expect(stmt.all()).to.deep.equal([]);
});

it('can abort preparation and leaves the connection usable', function () {
const sql = Array(200).fill('SELECT 1').join(' UNION ALL ');
const failure = new Error('cancel prepare');
this.db.progressHandler(1, () => {
expect(() => this.db.progressHandler()).to.throw(TypeError, 'busy');
expect(() => this.db.prepare('SELECT 1')).to.throw(TypeError, 'busy');
throw failure;
});
expect(() => this.db.prepare(sql)).to.throw(failure);
this.db.progressHandler();
expect(this.db.prepare('SELECT 1').pluck().get()).to.equal(1);
});

it('validates registration without replacing a working handler', function () {
let calls = 0;
this.db.progressHandler(100, () => { ++calls; });
for (const args of [[1], [1, null], [1, true], [0.1, () => false], [2 ** 31, () => false]]) {
expect(() => this.db.progressHandler(...args)).to.throw(TypeError);
}
for (const n of [0, -1]) {
expect(() => this.db.progressHandler(n, () => false)).to.throw(RangeError);
}
this.db.exec(scan);
expect(calls).to.be.greaterThan(0);
this.db.close();
expect(() => this.db.progressHandler()).to.throw(TypeError, 'not open');
});

it('rejects asynchronous callbacks when SQLite invokes them', function () {
const stmt = this.db.prepare(scan);
this.db.progressHandler(100, async () => false);
expect(() => stmt.get()).to.throw(TypeError, 'boolean or undefined');
this.db.progressHandler();
expect(stmt.get()).to.equal(undefined);
});
});
Loading