From 1aec56b507a51ba94766d40c1f11a2706dd0d54e Mon Sep 17 00:00:00 2001 From: Matt Wonlaw Date: Fri, 20 Nov 2026 12:48:19 -0500 Subject: [PATCH] chore: add progress callback --- deps/defines.gypi | 1 - deps/download.sh | 1 - docs/api.md | 22 ++++++++ docs/compilation.md | 1 - lib/database.js | 1 + lib/index.d.ts | 2 + lib/methods/wrappers.js | 5 ++ src/objects/database.cpp | 50 +++++++++++++++++ src/objects/database.hpp | 6 +++ src/objects/statement.cpp | 2 + test/54.progress-handler.js | 105 ++++++++++++++++++++++++++++++++++++ 11 files changed, 193 insertions(+), 3 deletions(-) create mode 100644 test/54.progress-handler.js diff --git a/deps/defines.gypi b/deps/defines.gypi index 3e74349..e5a3218 100644 --- a/deps/defines.gypi +++ b/deps/defines.gypi @@ -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', diff --git a/deps/download.sh b/deps/download.sh index fa03e22..c690579 100755 --- a/deps/download.sh +++ b/deps/download.sh @@ -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 diff --git a/docs/api.md b/docs/api.md index e76d9a6..cdca07f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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) @@ -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. diff --git a/docs/compilation.md b/docs/compilation.md index 6ff6c55..99d137a 100644 --- a/docs/compilation.md +++ b/docs/compilation.md @@ -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 diff --git a/lib/database.js b/lib/database.js index 150fff8..caa2f4a 100644 --- a/lib/database.js +++ b/lib/database.js @@ -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'); diff --git a/lib/index.d.ts b/lib/index.d.ts index 5240e7d..18feb40 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -116,6 +116,8 @@ declare namespace BetterSqlite3 { backup(destinationFile: string, options?: Database.BackupOptions): Promise; 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; } diff --git a/lib/methods/wrappers.js b/lib/methods/wrappers.js index 49bd235..df511ba 100644 --- a/lib/methods/wrappers.js +++ b/lib/methods/wrappers.js @@ -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; diff --git a/src/objects/database.cpp b/src/objects/database.cpp index 4910f50..6ffb697 100644 --- a/src/objects/database.cpp +++ b/src/objects/database.cpp @@ -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(); @@ -125,6 +126,7 @@ void Database::FreeSerialization(char* data, void* _) { INIT(Database::Init) { v8::Local 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); @@ -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); @@ -203,10 +206,14 @@ NODE_METHOD(Database::JS_prepare) { (void)pragmaMode; UseAddon; UseIsolate; + Database* db = Unwrap(info.This()); + const bool was_preparing = db->preparing; + db->preparing = true; v8::Local c = addon->Statement.Get(isolate); addon->privileged_info = &info; v8::MaybeLocal maybeStatement = c->NewInstance(OnlyContext, 0, NULL); addon->privileged_info = NULL; + db->preparing = was_preparing; if (!maybeStatement.IsEmpty()) info.GetReturnValue().Set(maybeStatement.ToLocalChecked()); } @@ -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)); } } @@ -408,6 +416,48 @@ NODE_METHOD(Database::JS_unsafeMode) { sqlite3_db_config(db->db_handle, SQLITE_DBCONFIG_DEFENSIVE, static_cast(!db->unsafe_mode), NULL); } +NODE_METHOD(Database::JS_progressHandler) { + Database* db = Unwrap(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 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(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 fn = db->handle(isolate)->GetInternalField(PROGRESS_HANDLER_FIELD).As(); + v8::Local 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(info.This()); REQUIRE_DATABASE_OPEN(db); diff --git a/src/objects/database.hpp b/src/objects/database.hpp index 7f59722..632b4cd 100644 --- a/src/objects/database.hpp +++ b/src/objects/database.hpp @@ -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); @@ -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 logger; std::set stmts; std::set backups; diff --git a/src/objects/statement.cpp b/src/objects/statement.cpp index 23aaa94..aecb282 100644 --- a/src/objects/statement.cpp +++ b/src/objects/statement.cpp @@ -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(); } diff --git a/test/54.progress-handler.js b/test/54.progress-handler.js new file mode 100644 index 0000000..182d930 --- /dev/null +++ b/test/54.progress-handler.js @@ -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); + }); +});