From fe6f59b957a45281f1330d1b157dc11eb4a6a9b9 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:47:37 +0100 Subject: [PATCH 1/6] feat: expose cancellation for async SQLite reads #400 Accept an AbortSignal for managed and prepared reads, preserve native FIFO ordering, and expose an OperationCancelled error when cancellation wins. Co-authored-by: Codex --- docs/content/docs/guides/node-test-mock.mdx | 2 + .../docs/guides/prepared-statements.mdx | 2 + docs/content/docs/guides/sync-and-async.mdx | 42 ++++ examples/shared/tests/unit/register.ts | 5 + .../specs/operations/readCancellation.spec.ts | 165 +++++++++++++ .../cpp/hybridObjects/HybridNitroSQLite.cpp | 27 +- .../cpp/hybridObjects/HybridNitroSQLite.hpp | 8 +- .../hybridObjects/HybridPreparedStatement.cpp | 51 +++- .../hybridObjects/HybridPreparedStatement.hpp | 14 +- .../hybridObjects/HybridReadCancellation.hpp | 29 +++ .../SQLiteConnectionOperation.hpp | 39 ++- .../nitro-sqlite-core/src/DatabaseQueue.ts | 18 +- packages/nitro-sqlite-core/src/SQLiteError.ts | 17 +- packages/nitro-sqlite-core/src/index.ts | 5 +- packages/nitro-sqlite-core/src/mock.ts | 80 +++++- .../src/operations/execute.ts | 47 +++- .../src/operations/prepare.ts | 43 +++- .../src/operations/readCancellation.ts | 31 +++ .../src/operations/session.ts | 24 +- .../src/readCancellationError.ts | 7 + .../src/specs/NitroSQLite.nitro.ts | 10 +- .../src/specs/PreparedStatement.nitro.ts | 15 +- .../src/specs/ReadCancellation.nitro.ts | 8 + packages/nitro-sqlite-core/src/types.ts | 37 ++- .../platform/src/__mocks__/nitro.ts | 1 + .../platform/src/__tests__/mock.test.ts | 20 ++ .../platform/src/__tests__/prepare.test.ts | 30 +++ .../src/__tests__/readCancellation.test.ts | 232 ++++++++++++++++++ 28 files changed, 928 insertions(+), 81 deletions(-) create mode 100644 examples/shared/tests/unit/specs/operations/readCancellation.spec.ts create mode 100644 packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp create mode 100644 packages/nitro-sqlite-core/src/operations/readCancellation.ts create mode 100644 packages/nitro-sqlite-core/src/readCancellationError.ts create mode 100644 packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts create mode 100644 packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index 400fee174..f34392446 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -5,6 +5,8 @@ description: Test shared SQLite connections, statements, and transactions in Nod Both host packages export a Node mock. Use `react-native-nitro-sqlite/mock` for React Native or `nitro-sqlite/mock` for NitroUI. Neither entry point initializes the native runtime. See [supported platforms](/docs/supported-platforms) for native host requirements. Install `better-sqlite3` as a development dependency in your test project. The mock creates databases in a temporary directory and supports queries, atomic batches, prepared statements, and callback transactions. Separate connections share committed data and can keep consistent read snapshots under [WAL](/docs/guides/multiple-connections). +Mock async reads accept an `AbortSignal` and can be cancelled before execution. The mock runs SQLite on the Node.js thread, so an abort cannot interrupt a statement that is already running there. Use a device test for in-flight cancellation. + ## Set up Jest The examples below use the React Native package. For NitroUI, replace `react-native-nitro-sqlite` with `nitro-sqlite` in the mock mapping, imports, and `/mock` paths. Keep your test runner's TypeScript transform enabled for the NitroUI package's source entry points. diff --git a/docs/content/docs/guides/prepared-statements.mdx b/docs/content/docs/guides/prepared-statements.mdx index 4b321cf87..478e1b8b6 100644 --- a/docs/content/docs/guides/prepared-statements.mdx +++ b/docs/content/docs/guides/prepared-statements.mdx @@ -48,6 +48,8 @@ try { `execute()` blocks its JavaScript caller until SQLite finishes. `executeAsync()` runs native database work on a background thread and resolves with the result. Await each execution when a later one depends on its write. The statement can be reused after an execution error, provided the error has not made the database unusable. +Pass `{ signal }` as the second argument to `executeAsync(params, options)` or `executeRawAsync(params, options)` to [cancel one read](/docs/guides/sync-and-async#cancel-an-async-read). The statement stays prepared after cancellation. Await the rejected execution before reusing or finalizing it. + ## Connection ordering and cleanup On a managed connection, `executeAsync()` runs in submission order with the connection's other async calls. It waits for earlier work, and later work starts only after it completes. While async work is pending, synchronous `prepare()`, `execute()`, `finalize()`, and `close()` on that connection throw a busy error. Await the last execution before finalizing, then finalize before closing the connection. `isFinalized` reports whether the statement has been finalized; executing it afterward throws. diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index 3b19228b5..b0849a89a 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -29,6 +29,45 @@ SQLite stores binary data as BLOBs. Query results return those values as `ArrayB SQLite produces results one row at a time. For larger synchronous queries that return named rows, Nitro SQLite copies the values into compact native blocks before creating the JavaScript rows. The synchronous call still blocks until the JavaScript result is ready. +## Cancel an async read + +SQLite can interrupt a statement while it runs. Interrupting a write can roll back its entire transaction. Nitro SQLite checks that an execution with a signal is a read and that the connection is outside a transaction before it lets the execution run. + +Pass an `AbortSignal` to cancel work the caller no longer needs, such as a search query for an older input: + +```ts +import { + SQLiteError, + SQLiteExceptionType, +} from 'react-native-nitro-sqlite/errors' + +const controller = new AbortController() +const results = db.executeAsync( + 'SELECT * FROM notes WHERE body LIKE ?', + ['%SQLite%'], + { signal: controller.signal }, +) + +// When the search changes or the screen closes: +controller.abort() + +try { + const result = await results + console.log(result.results) +} catch (error) { + if ( + !(error instanceof SQLiteError) || + error.type !== SQLiteExceptionType.OperationCancelled + ) { + throw error + } +} +``` + +An aborted read leaves whichever queue is holding it. If SQLite is already running the read, it stops when it next checks for progress. Work such as a long-running function or a wait for a database lock may delay that check. If native execution has already finished, the result still wins. Wait for the promise to settle before closing the managed connection. + +The options argument also works with `executeRawAsync()`, both global async query helpers, and [prepared statement executions](/docs/guides/prepared-statements). Queries with a signal support `SELECT`, `VALUES`, and read-only common table expressions. Run PRAGMAs, writes, and transaction commands without a signal. Transaction callback methods, batches, and imports have no cancellation option. + ## Connection ordering @@ -76,3 +115,6 @@ Native calls bypass the JavaScript queue. If you use them alongside an `open()` Native direct and prepared `execute()` methods return [`NativeQueryResult`](/api/react-native-nitro-sqlite/interfaces/NativeQueryResult). Their `executeAsync()` methods resolve to the same result shape. Call raw methods through `NitroSQLite.native`. Keep SQLite thread safety enabled when work can run across multiple database connections. Use React Native's [`threadSafe` setting](/docs/configuration#thread-safety) or retain the [NitroUI adapter's native default](/docs/configuration#nitroui-build-settings). + +For direct native calls, create a single-use token with `NitroSQLite.native.createReadCancellation()`. Pass it as the last argument to a native async query or prepared statement execution, and call `cancel()` on that token to cancel the read. Callers using a row callback may have already received partial rows when a read is cancelled. + diff --git a/examples/shared/tests/unit/register.ts b/examples/shared/tests/unit/register.ts index a9ec16e11..cce2c7b5a 100644 --- a/examples/shared/tests/unit/register.ts +++ b/examples/shared/tests/unit/register.ts @@ -13,6 +13,7 @@ import registerQueryResultUnitTests from './specs/operations/queryResults.spec' import registerTransactionUnitTests from './specs/operations/transaction.spec' import registerExecuteBatchUnitTests from './specs/operations/executeBatch.spec' import registerPreparedStatementUnitTests from './specs/operations/preparedStatement.spec' +import registerReadCancellationUnitTests from './specs/operations/readCancellation.spec' import registerTypeORMUnitTestsSpecs from './specs/typeorm.spec' import registerDatabaseQueueUnitTests from './specs/DatabaseQueue.spec' import registerSqliteVecUnitTestsSpecs from './specs/sqlite-vec.spec' @@ -41,6 +42,10 @@ export function registerUnitTestsForEnvironment( 'operations/preparedStatement.spec.ts', registerPreparedStatementUnitTests, ) + describe( + 'operations/readCancellation.spec.ts', + registerReadCancellationUnitTests, + ) describe('DatabaseQueue.spec.ts', registerDatabaseQueueUnitTests) describe('Connections.spec.ts', registerConnectionUnitTests) describe('benchmarkDatabase.spec.ts', registerBenchmarkDatabaseUnitTests) diff --git a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts new file mode 100644 index 000000000..cc2f2fa85 --- /dev/null +++ b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts @@ -0,0 +1,165 @@ +import { + NitroSQLite, + SQLiteError, + SQLiteExceptionType, + open, +} from 'react-native-nitro-sqlite' +import { expect, it } from '@tests/TestApi' +import { TEST_DB_NAME, testDb } from '@tests/db' + +const slowRead = ` + WITH RECURSIVE numbers(value) AS ( + VALUES(1) UNION ALL SELECT value + 1 FROM numbers WHERE value < 100000000 + ) + SELECT value FROM numbers WHERE value <= 300 +` + +async function failureOf(promise: Promise): Promise { + try { + await promise + } catch (error) { + return SQLiteError.fromError(error) + } + throw new Error('Expected the read to reject') +} + +export default function registerReadCancellationUnitTests() { + it('cancels reads in the native FIFO and interrupts only the active operation', async () => { + const native = NitroSQLite.native + const activeToken = native.createReadCancellation() + const independent = open({ + name: TEST_DB_NAME, + connection: 'independent', + readOnly: true, + }) + const prepared = testDb.prepare('SELECT ? AS value') + let notifyFirstBatch: () => void = () => {} + const firstBatch = new Promise((resolve) => { + notifyFirstBatch = resolve + }) + const active = failureOf( + native.executeAsync( + TEST_DB_NAME, + slowRead, + undefined, + notifyFirstBatch, + undefined, + activeToken, + ), + ) + + let next: Promise | undefined + try { + await Promise.race([ + firstBatch, + active.then((error) => Promise.reject(error)), + ]) + const controller = new AbortController() + const queued = failureOf( + prepared.executeRawAsync([2], { signal: controller.signal }), + ) + const following = prepared.executeAsync([3]) + next = following + controller.abort() + expect((await queued).type).toBe( + SQLiteExceptionType.OperationCancelled, + ) + expect((await independent.executeRawAsync('SELECT 9')).rows).toEqual([ + [9], + ]) + + activeToken.cancel() + expect((await active).type).toBe( + SQLiteExceptionType.OperationCancelled, + ) + expect((await following).rows.item(0)).toEqual({ value: 3 }) + const afterCompletion = native.createReadCancellation() + await native.executeRawAsync( + TEST_DB_NAME, + 'SELECT 4', + undefined, + afterCompletion, + ) + const afterAbort = testDb.executeRawAsync('SELECT 5') + afterCompletion.cancel() + expect((await afterAbort).rows).toEqual([[5]]) + } finally { + activeToken.cancel() + await Promise.allSettled([active, next]) + prepared.finalize() + independent.close() + } + }) + + it('resets a prepared statement after aborting an expensive execution', async () => { + const prepared = testDb.prepare(` + WITH RECURSIVE numbers(value) AS ( + VALUES(1) UNION ALL SELECT value + 1 FROM numbers WHERE value < ? + ) + SELECT sum(value) AS total FROM numbers + `) + const controller = new AbortController() + const pending = failureOf( + prepared.executeAsync([100000000], { signal: controller.signal }), + ) + // This query returns no rows until its entire input has been read. + const abort = setTimeout(() => controller.abort(), 25) + try { + expect((await pending).type).toBe( + SQLiteExceptionType.OperationCancelled, + ) + expect((await prepared.executeRawAsync([4])).rows).toEqual([[10]]) + } finally { + clearTimeout(abort) + prepared.finalize() + } + }) + + it('rejects writes and connection changes without disturbing transaction state', async () => { + const options = { signal: new AbortController().signal } + const write = + "INSERT INTO User VALUES (1, 'Alice', NULL, NULL) RETURNING id" + const preparedWrite = testDb.prepare(write) + const preparedControl = testDb.prepare('BEGIN') + try { + for (const operation of [ + () => testDb.executeAsync(write, undefined, options), + () => preparedWrite.executeRawAsync(undefined, options), + () => preparedControl.executeAsync(undefined, options), + () => + testDb.executeRawAsync('PRAGMA user_version=99', undefined, options), + ]) { + expect((await failureOf(operation())).type).toBe( + SQLiteExceptionType.SqlExecutionError, + ) + } + expect(testDb.executeRaw('PRAGMA user_version').rows).toEqual([[0]]) + expect(testDb.executeRaw('SELECT count(*) FROM User').rows).toEqual([[0]]) + + testDb.execute('BEGIN') + try { + testDb.execute(write) + expect( + (await failureOf(testDb.executeAsync('SELECT 1', undefined, options))) + .message, + ).toContain('outside a transaction') + testDb.execute('COMMIT') + } catch (error) { + testDb.execute('ROLLBACK') + throw error + } + expect( + ( + await testDb.executeRawAsync( + 'SELECT name FROM User', + undefined, + options, + ) + ).rows, + ).toEqual([['Alice']]) + } finally { + preparedControl.finalize() + preparedWrite.finalize() + } + }) +} diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index 7b7a048eb..077c8ae52 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -7,6 +7,7 @@ #include "../SQLiteMacros.hpp" #include "../SQLiteOperations.hpp" #include "HybridPreparedStatement.hpp" +#include "HybridReadCancellation.hpp" #include "SQLiteConnectionOperation.hpp" #include "SQLiteRowBatchSender.hpp" #include @@ -205,12 +206,17 @@ NativeQueryResult HybridNitroSQLite::execute(const std::string& dbName, const st requireTransaction.value_or(false)); }; +std::shared_ptr HybridNitroSQLite::createReadCancellation() { + return std::make_shared(); +} + Promise HybridNitroSQLite::executeAsync(const std::string& dbName, const std::string& query, const std::optional& params, const std::optional>& onRows, const std::optional& rowBatchId, - const std::optional& requireTransaction) { + const std::optional& requireTransaction, const std::optional>& cancellation) { auto copiedParams = copyArrayBufferParamsForBackground(params); + const auto token = getReadCancellation(cancellation); SQLiteConnectionPtr connection; try { connection = _connections.get(dbName); @@ -232,18 +238,20 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db batchDelivery.emplace(*_rowBatchHandler, *rowBatchId, std::chrono::steady_clock::now()); } + const auto cancellationSender = token ? std::make_shared>() : nullptr; return enqueueConnectionOperation( connection, [connection, query, copiedParams = std::move(copiedParams), batchDelivery = std::move(batchDelivery), - requireTransaction]() mutable -> NativeQueryResult { + requireTransaction, token, cancellationSender]() mutable -> NativeQueryResult { std::shared_ptr sender; SQLiteRowBatchHandler rowBatches; if (const auto* direct = std::get_if(&batchDelivery)) { rowBatches = [direct](SQLiteQueryResults rows) { (*direct)(std::move(rows)); }; } else if (auto* paced = std::get_if(&batchDelivery)) { - rowBatches = [paced, &sender](SQLiteQueryResults rows) { + rowBatches = [paced, &sender, &cancellationSender](SQLiteQueryResults rows) { if (!sender) { sender = std::make_shared(std::move(paced->handler), paced->id, paced->submittedAt); + if (cancellationSender) *cancellationSender = sender; } sender->send(std::move(rows)); }; @@ -251,14 +259,14 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db try { return sqliteExecute(connection, query, copiedParams, SQLiteExecutionMode::Asynchronous, rowBatches, - requireTransaction.value_or(false)); + requireTransaction.value_or(false), token.get()); } catch (...) { if (sender) { sender->cancel(); } throw; } - }); + }, token, [cancellationSender] { if (cancellationSender && *cancellationSender) (*cancellationSender)->cancel(); }); }; void HybridNitroSQLite::setRowBatchHandler(const Callback& handler) { @@ -293,8 +301,9 @@ NativeRawQueryResult HybridNitroSQLite::executeRaw(const std::string& dbName, co Promise HybridNitroSQLite::executeRawAsync(const std::string& dbName, const std::string& query, const std::optional& params, - const std::optional& requireTransaction) { + const std::optional& requireTransaction, const std::optional>& cancellation) { auto copiedParams = copyArrayBufferParamsForBackground(params); + const auto token = getReadCancellation(cancellation); SQLiteConnectionPtr connection; try { connection = _connections.get(dbName); @@ -303,9 +312,9 @@ Promise HybridNitroSQLite::executeRawAsync(const std::stri } return enqueueConnectionOperation( - connection, [connection, query, copiedParams = std::move(copiedParams), requireTransaction]() -> NativeRawQueryResult { - return sqliteExecuteRaw(connection, query, copiedParams, requireTransaction.value_or(false)); - }); + connection, [connection, query, copiedParams = std::move(copiedParams), requireTransaction, token]() -> NativeRawQueryResult { + return sqliteExecuteRaw(connection, query, copiedParams, requireTransaction.value_or(false), token.get()); + }, token); } std::shared_ptr HybridNitroSQLite::prepare(const std::string& dbName, const std::string& query) { diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp index 7e8ae7a72..d33d71929 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -74,15 +74,19 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { NativeQueryResult execute(const std::string& dbName, const std::string& query, const std::optional& params, const std::optional& requireTransaction) override; + /** Create a single-use cancellation token for one native async read. */ + std::shared_ptr createReadCancellation() override; + /** Require a live SQLite transaction when @p requireTransaction is true; checked under the execution lock. * Execute one SQL statement on a background thread. Leading row batches go to @p onRows, or else to * the handler from setRowBatchHandler, tagged with @p rowBatchId. + * @param cancellation Single-use token for a read outside a transaction. * @return A promise of the native query result. */ Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional& params, const std::optional>& onRows, - const std::optional& rowBatchId, const std::optional& requireTransaction) override; + const std::optional& rowBatchId, const std::optional& requireTransaction, const std::optional>& cancellation) override; /** Set the handler that receives row batches for executeAsync calls made with a row batch ID. */ void setRowBatchHandler(const Callback& handler) override; @@ -100,7 +104,7 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { * Execute one SQL statement on a background thread, returning rows as arrays of column values. */ Promise executeRawAsync(const std::string& dbName, const std::string& query, const std::optional& params, - const std::optional& requireTransaction) override; + const std::optional& requireTransaction, const std::optional>& cancellation) override; /** Prepare one SQL statement for repeated execution on an open connection. */ std::shared_ptr prepare(const std::string& dbName, const std::string& query) override; diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp index 8f55a510e..350f1c2b6 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -1,4 +1,6 @@ #include "HybridPreparedStatement.hpp" +#include "../SQLiteLogs.hpp" +#include "HybridReadCancellation.hpp" #include "SQLiteConnectionOperation.hpp" #include @@ -25,6 +27,26 @@ namespace { return copiedParams; } + std::shared_ptr retainStatement(const std::shared_ptr& statement, + const std::shared_ptr& token) { + if (!token) { + return statement; + } + return std::shared_ptr(statement.get(), [retained = statement, token](SQLitePreparedStatement*) mutable { + if (!token->isCancelled()) { + return; + } + // Finalization takes the connection mutex. Let the worker release the reference + // when a cancelled job is removed on the JavaScript thread. + const auto connection = retained->connection(); + try { + connection->enqueueAsync([retained = std::move(retained)] {}); + } catch (const std::exception& error) { + LOGE("Could not defer release of cancelled SQLite statement: %s", error.what()); + } + }); + } + } // namespace HybridPreparedStatement::HybridPreparedStatement(std::shared_ptr statement) : _statement(std::move(statement)) {} @@ -33,23 +55,32 @@ NativeQueryResult HybridPreparedStatement::execute(const std::optionalexecute(params, SQLiteExecutionMode::Synchronous); } -Promise HybridPreparedStatement::executeAsync(const std::optional& params) { - auto copiedParams = copyArrayBufferParamsForBackground(params); - const auto statement = _statement; - return enqueueConnectionOperation(statement->connection(), [statement, copiedParams = std::move(copiedParams)]() { - return statement->execute(copiedParams, SQLiteExecutionMode::Asynchronous); - }); +Promise HybridPreparedStatement::executeAsync( + const std::optional& params, + const std::optional>& cancellation) { + const auto token = getReadCancellation(cancellation); + const auto copiedParams = copyArrayBufferParamsForBackground(params); + const auto statement = retainStatement(_statement, token); + + // The connection's worker keeps executions in call order, so JavaScript can submit several without + // waiting for each result. + return enqueueConnectionOperation( + statement->connection(), [statement, copiedParams, token]() { return statement->execute(copiedParams, SQLiteExecutionMode::Asynchronous, token.get()); }, token); } NativeRawQueryResult HybridPreparedStatement::executeRaw(const std::optional& params) { return _statement->executeRaw(params); } -Promise HybridPreparedStatement::executeRawAsync(const std::optional& params) { - auto copiedParams = copyArrayBufferParamsForBackground(params); - const auto statement = _statement; +Promise HybridPreparedStatement::executeRawAsync( + const std::optional& params, + const std::optional>& cancellation) { + const auto token = getReadCancellation(cancellation); + const auto copiedParams = copyArrayBufferParamsForBackground(params); + const auto statement = retainStatement(_statement, token); + return enqueueConnectionOperation( - statement->connection(), [statement, copiedParams = std::move(copiedParams)]() { return statement->executeRaw(copiedParams); }); + statement->connection(), [statement, copiedParams, token]() { return statement->executeRaw(copiedParams, token.get()); }, token); } void HybridPreparedStatement::finalize() { diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp index e50043f50..cdf967288 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp @@ -15,12 +15,18 @@ class HybridPreparedStatement : public HybridPreparedStatementSpec { /** Execute with new bindings on the calling thread. */ NativeQueryResult execute(const std::optional& params) override; - /** Execute with new bindings on the connection's worker, in call order. */ - Promise executeAsync(const std::optional& params) override; + /** Execute with new bindings on the connection's worker, in call order. + * @param cancellation Single-use token for a read outside a transaction. + */ + Promise + executeAsync(const std::optional& params, + const std::optional>& cancellation) override; /** Execute with new bindings on the calling thread, returning rows as arrays of column values. */ NativeRawQueryResult executeRaw(const std::optional& params) override; - /** Execute with new bindings on the connection's worker, returning rows as arrays of column values. */ - Promise executeRawAsync(const std::optional& params) override; + /** Execute like executeAsync(), returning rows as arrays of column values. */ + Promise + executeRawAsync(const std::optional& params, + const std::optional>& cancellation) override; /** Release the native statement. */ void finalize() override; /** Check whether the native statement has been released. */ diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp new file mode 100644 index 000000000..0b103899f --- /dev/null +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include "../SQLiteOperationCancellation.hpp" +#include "HybridReadCancellationSpec.hpp" + +namespace margelo::nitro::nitrosqlite { + +/** The native token created by NitroSQLite for one asynchronous read. */ +class HybridReadCancellation final : public HybridReadCancellationSpec { +public: + HybridReadCancellation() : HybridObject(TAG) {} + + /** Request cancellation without accessing the connection's SQLite handle. */ + void cancel() override { + state->cancel(); + } + + const std::shared_ptr state = std::make_shared(); +}; + +inline std::shared_ptr +getReadCancellation(const std::optional>& cancellation) { + if (!cancellation) { + return nullptr; + } + return std::static_pointer_cast(*cancellation)->state; +} + +} // namespace margelo::nitro::nitrosqlite diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp index 9ff384f1b..c3758d0ad 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp @@ -1,6 +1,7 @@ #pragma once #include "../SQLiteDatabaseConnections.hpp" +#include "../SQLiteOperationCancellation.hpp" #include #include #include @@ -10,18 +11,34 @@ namespace margelo::nitro::nitrosqlite { /** Run @p operation on the connection's FIFO worker and settle the returned promise with its result. - * Calls on one connection run in submission order, one at a time. + * Calls on one connection run in submission order, one at a time. A cancellation token + * can remove a pending call or win against its result before the worker commits completion. */ template -Promise enqueueConnectionOperation(const SQLiteConnectionPtr& connection, Operation&& operation) { +Promise enqueueConnectionOperation(const SQLiteConnectionPtr& connection, Operation&& operation, + const std::shared_ptr& cancellation = nullptr, + std::function onRejected = {}) { auto promise = Promise::pending(); + const auto reject = [promise, onRejected = std::move(onRejected)](const std::exception_ptr& error) { + if (onRejected) { + onRejected(); + } + promise.reject(error); + }; try { - connection->enqueueAsync([promise, operation = std::forward(operation)]() mutable { + auto run = [promise, reject, cancellation, operation = std::forward(operation)]() mutable { std::optional result; + std::exception_ptr error; try { result.emplace(operation()); } catch (...) { - promise.reject(std::current_exception()); + error = std::current_exception(); + } + if (cancellation && !cancellation->finish()) { + error = std::make_exception_ptr(SQLiteException::Cancelled()); + } + if (error) { + reject(error); return; } // Resolving may dispatch to JavaScript and throw after the native promise @@ -30,14 +47,22 @@ Promise enqueueConnectionOperation(const SQLiteConnectionPtr& connection promise.resolve(std::move(*result)); } catch (...) { if (promise.isPending()) { - promise.reject(std::current_exception()); + reject(std::current_exception()); return; } throw; } - }); + }; + if (cancellation) { + connection->enqueueAsync(std::move(run), cancellation, + [reject] { reject(std::make_exception_ptr(SQLiteException::Cancelled())); }); + } else { + connection->enqueueAsync(std::move(run)); + } } catch (...) { - promise.reject(std::current_exception()); + if (promise.isPending()) { + reject(std::current_exception()); + } } return promise; } diff --git a/packages/nitro-sqlite-core/src/DatabaseQueue.ts b/packages/nitro-sqlite-core/src/DatabaseQueue.ts index 2d6678576..f4499a3af 100644 --- a/packages/nitro-sqlite-core/src/DatabaseQueue.ts +++ b/packages/nitro-sqlite-core/src/DatabaseQueue.ts @@ -1,4 +1,5 @@ import SQLiteError from './SQLiteError' +import { readCancellationError } from './readCancellationError' export interface QueuedOperation { kind: 'statement' | 'exclusive' | 'notification' @@ -72,15 +73,17 @@ export function getDatabaseQueue(dbName: DatabaseQueueKey) { export function queueOperationAsync( dbName: DatabaseQueueKey, callback: () => Promise, + signal?: AbortSignal, ): Promise { - return enqueueOperation(dbName, 'exclusive', callback) + return enqueueOperation(dbName, 'exclusive', callback, signal) } export function queueStatementAsync( dbName: DatabaseQueueKey, callback: () => Promise, + signal?: AbortSignal, ): Promise { - return enqueueOperation(dbName, 'statement', callback) + return enqueueOperation(dbName, 'statement', callback, signal) } /** Deliver a change batch in queue order once earlier work has finished. @@ -95,7 +98,9 @@ function enqueueOperation( dbName: DatabaseQueueKey, kind: 'statement' | 'exclusive', callback: () => Promise, + signal?: AbortSignal, ): Promise { + if (signal?.aborted) return Promise.reject(readCancellationError()) let databaseQueue: DatabaseQueue try { databaseQueue = getDatabaseQueue(dbName) @@ -117,6 +122,7 @@ function enqueueOperation( // Chains the operation directly instead of awaiting it in an async function, // which saves a promise and several microtask turns per queued query. const start = () => { + signal?.removeEventListener('abort', cancelQueuedOperation) let operation: Promise try { operation = Promise.resolve(callback()) @@ -142,6 +148,14 @@ function enqueueOperation( start, } + const cancelQueuedOperation = () => { + const index = databaseQueue.queue.indexOf(operation) + if (index === -1) return + databaseQueue.queue.splice(index, 1) + reject(readCancellationError()) + startNextOperations(databaseQueue) + } + signal?.addEventListener('abort', cancelQueuedOperation, { once: true }) databaseQueue.queue.push(operation) startNextOperations(databaseQueue) }) diff --git a/packages/nitro-sqlite-core/src/SQLiteError.ts b/packages/nitro-sqlite-core/src/SQLiteError.ts index 31ce4fbd9..830fa3de3 100644 --- a/packages/nitro-sqlite-core/src/SQLiteError.ts +++ b/packages/nitro-sqlite-core/src/SQLiteError.ts @@ -2,7 +2,7 @@ const SQLITE_ERROR_NAME = 'SQLiteError' as const const NATIVE_EXCEPTION_PREFIX = '[NativeNitroSQLiteException][' /** - * Native error categories exposed by {@linkcode SQLiteError.type}. + * Error categories exposed by {@linkcode SQLiteError.type}. * Compare against these constants when handling a specific failure. The values * are categories, not SQLite's numeric result codes. Import them from * `react-native-nitro-sqlite/errors` to avoid initializing the native module. @@ -27,6 +27,8 @@ export const SQLiteExceptionType = { CouldNotLoadFile: 'CouldNotLoadFile', /** An empty batch was submitted. */ NoBatchCommandsProvided: 'NoBatchCommandsProvided', + /** The caller cancelled an asynchronous read. */ + OperationCancelled: 'OperationCancelled', } as const /** @@ -41,16 +43,19 @@ export type SQLiteExceptionType = /** Error thrown by managed NitroSQLite operations. Native errors are wrapped with this class. */ export default class SQLiteError extends Error { /** - * Recognized native category from {@linkcode SQLiteExceptionType}, or - * `undefined` for JavaScript failures and unrecognized native categories. + * Category from {@linkcode SQLiteExceptionType}, or `undefined` when + * the failure has no recognized category. */ readonly type: SQLiteExceptionType | undefined - /** Create an error with a message and optional cause. */ - constructor(message: string, options?: ErrorOptions) { + /** Create an error with a message and optional cause or explicit category. */ + constructor( + message: string, + options?: ErrorOptions & { type?: SQLiteExceptionType }, + ) { super(message, options) this.name = SQLITE_ERROR_NAME - this.type = getNativeExceptionType(message) + this.type = options?.type ?? getNativeExceptionType(message) // Maintains proper prototype chain for instanceof checks Object.setPrototypeOf(this, SQLiteError.prototype) diff --git a/packages/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index deac167a8..d5260f953 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -33,12 +33,13 @@ export { open } from './operations/session' export { SQLiteError, SQLiteExceptionType, - NitroSQLiteError, - NitroSQLiteExceptionType, + SQLiteError, + SQLiteExceptionType, } from './errors' export type { DatabaseQueueKey } from './DatabaseQueue' export type { NitroSQLite as NativeSQLite } from './specs/NitroSQLite.nitro' export type { PreparedStatement as NativePreparedStatement } from './specs/PreparedStatement.nitro' +export type { ReadCancellation } from './specs/ReadCancellation.nitro' export type { NativeQueryResult, NativeQueryResultBinding, diff --git a/packages/nitro-sqlite-core/src/mock.ts b/packages/nitro-sqlite-core/src/mock.ts index 8897ec8d5..c4ab6aaf5 100644 --- a/packages/nitro-sqlite-core/src/mock.ts +++ b/packages/nitro-sqlite-core/src/mock.ts @@ -26,6 +26,7 @@ import { executeRawQuery, } from './mock/query' import { runTransaction } from './mock/transaction' +import { readCancellationError } from './readCancellationError' export type { MockConnection } from './mock/MockConnection' @@ -72,9 +73,42 @@ export function open(options: ConnectionOptions): MockConnection { const runAsync = async ( callback: () => Result, exclusive = false, + signal?: AbortSignal, ) => { const enqueue = exclusive ? queueOperationAsync : queueStatementAsync - return enqueue(queueKey, () => Promise.resolve().then(callback)) + return enqueue( + queueKey, + () => + Promise.resolve().then(() => { + if (signal?.aborted) throw readCancellationError() + return callback() + }), + signal, + ) + } + const checkRead = (query: string, statement?: Statement) => { + if (database.inTransaction) { + throw new NitroSQLiteError( + 'Cancellable reads require a connection outside a transaction', + ) + } + // better-sqlite3 does not expose SQLite's authorizer. Check the first keyword + // before preparation because some PRAGMAs take effect during prepare(). + const readPrefix = + /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:SELECT|VALUES|WITH|EXPLAIN)\b/i + if (!readPrefix.test(query)) { + throw new NitroSQLiteError( + 'Cancellation is only supported for read-only queries', + ) + } + const prepared = + statement ?? database.prepare>(query) + if (!prepared.readonly) { + throw new NitroSQLiteError( + 'Cancellation is only supported for read-only queries', + ) + } + return prepared } const close = () => { runSync(() => database.close()) @@ -114,12 +148,26 @@ export function open(options: ConnectionOptions): MockConnection { }, execute: (query, params) => runSync(() => executeQuery(database, query, params)), - executeAsync: (query, params) => - runAsync(() => executeQuery(database, query, params)), + executeAsync: (query, params, queryOptions) => + runAsync( + () => + queryOptions?.signal === undefined + ? executeQuery(database, query, params) + : executePrepared(database, checkRead(query), params), + false, + queryOptions?.signal, + ), executeRaw: (query, params) => runSync(() => executeRawQuery(database, query, params)), - executeRawAsync: (query, params) => - runAsync(() => executeRawQuery(database, query, params)), + executeRawAsync: (query, params, queryOptions) => + runAsync( + () => + queryOptions?.signal === undefined + ? executeRawQuery(database, query, params) + : executePreparedRaw(database, checkRead(query), params), + false, + queryOptions?.signal, + ), executeBatch: (commands) => runSync(() => executeBatch(database, commands)), executeBatchAsync: (commands) => runAsync(() => executeBatch(database, commands), true), @@ -142,9 +190,27 @@ export function open(options: ConnectionOptions): MockConnection { return statement === undefined }, execute: (params) => runSync(() => execute(params)), - executeAsync: (params) => runAsync(() => execute(params), true), + executeAsync: (params, queryOptions) => + runAsync( + () => { + if (queryOptions?.signal !== undefined && statement !== undefined) + checkRead(query, statement) + return execute(params) + }, + true, + queryOptions?.signal, + ), executeRaw: (params) => runSync(() => executeRaw(params)), - executeRawAsync: (params) => runAsync(() => executeRaw(params), true), + executeRawAsync: (params, queryOptions) => + runAsync( + () => { + if (queryOptions?.signal !== undefined && statement !== undefined) + checkRead(query, statement) + return executeRaw(params) + }, + true, + queryOptions?.signal, + ), finalize: () => runSync(() => { // better-sqlite3 releases statement resources when the object is collected. diff --git a/packages/nitro-sqlite-core/src/operations/execute.ts b/packages/nitro-sqlite-core/src/operations/execute.ts index b9b0d927d..7018d4f05 100644 --- a/packages/nitro-sqlite-core/src/operations/execute.ts +++ b/packages/nitro-sqlite-core/src/operations/execute.ts @@ -1,5 +1,10 @@ import { HybridNitroSQLite } from '../nitro' -import type { QueryResult, QueryResultRow, SQLiteQueryParams } from '../types' +import type { + ExecuteAsyncOptions, + QueryResult, + QueryResultRow, + SQLiteQueryParams, +} from '../types' import SQLiteError from '../SQLiteError' import { callNativeAsync, rejectWithSQLiteError } from '../nativePromise' import type { @@ -13,6 +18,8 @@ import { startOperationSync, } from '../DatabaseQueue' import type { DatabaseQueueKey } from '../DatabaseQueue' +import { runWithReadCancellation } from './readCancellation' +import type { ReadCancellation } from '../specs/ReadCancellation.nitro' /** Execute one SQL statement synchronously by database name. * Uses the managed queue when the database has an open managed connection. @@ -65,18 +72,21 @@ export function executeNative( * @param dbName Name of an open native database. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param options Optional cancellation signal for reads. * @returns A promise of the query result with typed rows. */ export function executeAsync( dbName: string, query: string, params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ): Promise> { + const signal = options?.signal if (!isDatabaseOpen(dbName)) { - return executeAsyncNative(dbName, query, params) + return executeAsyncNative(dbName, query, params, signal) } - return executeAsyncManaged(dbName, query, params) + return executeAsyncManaged(dbName, query, params, dbName, signal) } export function executeAsyncManaged( @@ -84,9 +94,12 @@ export function executeAsyncManaged( query: string, params?: SQLiteQueryParams, queueKey: DatabaseQueueKey = dbName, + signal?: AbortSignal, ): Promise> { - return queueStatementAsync(queueKey, () => - executeAsyncNative(dbName, query, params), + return queueStatementAsync( + queueKey, + () => executeAsyncNative(dbName, query, params, signal), + signal, ) } @@ -171,6 +184,7 @@ function nextRowBatchId(): number { }) } lastRowBatchId++ + leadingRowBatches.set(lastRowBatchId, undefined) return lastRowBatchId } @@ -304,6 +318,7 @@ export function executeRawNative( * @param dbName Name of an open database. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param options Optional cancellation signal for reads. * @returns A promise of rows and column names in SQL column order, with affected row count and insert ID. * @throws SQLiteError as a rejected promise if the query fails. */ @@ -311,22 +326,27 @@ export function executeRawAsync( dbName: string, query: string, params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ): Promise { + const signal = options?.signal if (!isDatabaseOpen(dbName)) { - return executeRawAsyncNative(dbName, query, params) + return executeRawAsyncNative(dbName, query, params, signal) } - return executeRawAsyncManaged(dbName, query, params) + return executeRawAsyncManaged(dbName, query, params, dbName, signal) } export function executeRawAsyncManaged( dbName: string, query: string, - params?: SQLiteQueryParams, - queueKey: DatabaseQueueKey = dbName, + params: SQLiteQueryParams | undefined, + queueKey: DatabaseQueueKey, + signal?: AbortSignal, ): Promise { - return queueStatementAsync(queueKey, () => - executeRawAsyncNative(dbName, query, params), + return queueStatementAsync( + queueKey, + () => executeRawAsyncNative(dbName, query, params, signal), + signal, ) } @@ -336,6 +356,11 @@ export function executeRawAsyncNative( params?: SQLiteQueryParams, requireTransaction?: boolean, ): Promise { + if (signal !== undefined) { + return runWithReadCancellation(signal, (cancellation) => + HybridNitroSQLite.executeRawAsync(dbName, query, params, cancellation), + ) + } return callNativeAsync(() => requireTransaction ? HybridNitroSQLite.executeRawAsync(dbName, query, params, true) diff --git a/packages/nitro-sqlite-core/src/operations/prepare.ts b/packages/nitro-sqlite-core/src/operations/prepare.ts index 17bac34fa..59202da46 100644 --- a/packages/nitro-sqlite-core/src/operations/prepare.ts +++ b/packages/nitro-sqlite-core/src/operations/prepare.ts @@ -1,6 +1,7 @@ import { HybridNitroSQLite } from '../nitro' import SQLiteError from '../SQLiteError' import type { + ExecuteAsyncOptions, PreparedStatement, QueryResult, QueryResultRow, @@ -11,6 +12,7 @@ import { buildJSQueryResult } from './execute' import { rejectWithSQLiteError } from '../nativePromise' import { queueStatementAsync, startOperationSync } from '../DatabaseQueue' import type { DatabaseQueueKey } from '../DatabaseQueue' +import { runWithReadCancellation } from './readCancellation' /** * Prepare one SQL statement on an open managed connection for repeated execution. @@ -51,12 +53,23 @@ export function prepare( // queue as statements and several can be submitted without waiting for each result. executeAsync: ( params?: SQLiteQueryParams, - ): Promise> => - queueStatementAsync(queueKey, () => - nativeStatement - .executeAsync(params) - .then((result) => buildJSQueryResult(result)), - ).catch(rejectWithSQLiteError), + options?: ExecuteAsyncOptions, + ): Promise> => { + const signal = options?.signal + return queueStatementAsync( + queueKey, + () => { + const pending = + signal === undefined + ? nativeStatement.executeAsync(params) + : runWithReadCancellation(signal, (cancellation) => + nativeStatement.executeAsync(params, cancellation), + ) + return pending.then((result) => buildJSQueryResult(result)) + }, + signal, + ).catch(rejectWithSQLiteError) + }, executeRaw: (params?: SQLiteQueryParams): NativeRawQueryResult => { try { return startOperationSync(queueKey, () => @@ -68,10 +81,20 @@ export function prepare( }, executeRawAsync: ( params?: SQLiteQueryParams, - ): Promise => - queueStatementAsync(queueKey, () => - nativeStatement.executeRawAsync(params), - ).catch(rejectWithSQLiteError), + options?: ExecuteAsyncOptions, + ): Promise => { + const signal = options?.signal + return queueStatementAsync( + queueKey, + () => + signal === undefined + ? nativeStatement.executeRawAsync(params) + : runWithReadCancellation(signal, (cancellation) => + nativeStatement.executeRawAsync(params, cancellation), + ), + signal, + ).catch(rejectWithSQLiteError) + }, finalize: () => { try { startOperationSync(queueKey, () => nativeStatement.finalize()) diff --git a/packages/nitro-sqlite-core/src/operations/readCancellation.ts b/packages/nitro-sqlite-core/src/operations/readCancellation.ts new file mode 100644 index 000000000..a7a657640 --- /dev/null +++ b/packages/nitro-sqlite-core/src/operations/readCancellation.ts @@ -0,0 +1,31 @@ +import { HybridNitroSQLite } from '../nitro' +import { callNativeAsync } from '../nativePromise' +import SQLiteError from '../SQLiteError' +import { readCancellationError } from '../readCancellationError' +import type { ReadCancellation } from '../specs/ReadCancellation.nitro' + +export function runWithReadCancellation( + signal: AbortSignal, + run: (cancellation: ReadCancellation) => Promise, +): Promise { + if (signal.aborted) return Promise.reject(readCancellationError()) + if (typeof HybridNitroSQLite.createReadCancellation !== 'function') { + return Promise.reject( + new SQLiteError( + 'Read cancellation requires a newer Nitro SQLite native build.', + ), + ) + } + return callNativeAsync(() => { + const cancellation = HybridNitroSQLite.createReadCancellation() + const onAbort = () => cancellation.cancel() + signal.addEventListener('abort', onAbort, { once: true }) + try { + const result = run(cancellation) + return result.finally(() => signal.removeEventListener('abort', onAbort)) + } catch (error) { + signal.removeEventListener('abort', onAbort) + throw error + } + }) +} diff --git a/packages/nitro-sqlite-core/src/operations/session.ts b/packages/nitro-sqlite-core/src/operations/session.ts index f44266456..9f4a831a8 100644 --- a/packages/nitro-sqlite-core/src/operations/session.ts +++ b/packages/nitro-sqlite-core/src/operations/session.ts @@ -2,6 +2,7 @@ import { HybridNitroSQLite } from '../nitro' import { transaction } from './transaction' import type { BatchQueryCommand, + ExecuteAsyncOptions, Connection, ConnectionOptions, Transaction, @@ -166,17 +167,34 @@ export function open(options: ConnectionOptions): Connection { executeAsync: ( query: string, params?: SQLiteQueryParams, + queryOptions?: ExecuteAsyncOptions, ): Promise> => runAsyncOperation(() => - executeAsyncManaged(connectionId, query, params, queueKey), + executeAsyncManaged( + connectionId, + query, + params, + queueKey, + queryOptions?.signal, + ), ), executeRaw: (query: string, params?: SQLiteQueryParams) => runOperation(() => executeRawManaged(connectionId, query, params, queueKey), ), - executeRawAsync: (query: string, params?: SQLiteQueryParams) => + executeRawAsync: ( + query: string, + params?: SQLiteQueryParams, + queryOptions?: ExecuteAsyncOptions, + ) => runAsyncOperation(() => - executeRawAsyncManaged(connectionId, query, params, queueKey), + executeRawAsyncManaged( + connectionId, + query, + params, + queueKey, + queryOptions?.signal, + ), ), prepare: (query: string) => runOperation(() => prepare(connectionId, query, queueKey)), diff --git a/packages/nitro-sqlite-core/src/readCancellationError.ts b/packages/nitro-sqlite-core/src/readCancellationError.ts new file mode 100644 index 000000000..55edaaa81 --- /dev/null +++ b/packages/nitro-sqlite-core/src/readCancellationError.ts @@ -0,0 +1,7 @@ +import SQLiteError, { SQLiteExceptionType } from './SQLiteError' + +export function readCancellationError(): SQLiteError { + return new SQLiteError('SQLite read was cancelled', { + type: SQLiteExceptionType.OperationCancelled, + }) +} diff --git a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index 3d0913748..4a0a734e2 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -10,8 +10,9 @@ import type { NativeQueryResultBinding, NativeQueryRows, NativeRawQueryResult, -} from './NativeQueryResult' +} from './NativeQueryResultBinding' import type { PreparedStatement } from './PreparedStatement.nitro' +import type { ReadCancellation } from './ReadCancellation.nitro' export * from '#nitro/NitroSQLite' @@ -127,6 +128,8 @@ export declare class NitroSQLite extends HybridObject { params?: SQLiteQueryParams, requireTransaction?: boolean, ): NativeQueryResultBinding + /** Create a token for one native async read. Pass it to exactly one execution. */ + createReadCancellation(): ReadCancellation /** Execute one SQL statement on a background thread. * @param dbName Name of an open database. * @param query SQL statement with optional positional placeholders. @@ -142,6 +145,8 @@ export declare class NitroSQLite extends HybridObject { * The check runs under the connection lock, including for queued background calls. * Omit for normal execution, including manual BEGIN, COMMIT, and ROLLBACK. * @throws If the connection is closed or a required transaction has ended. + * @param cancellation Single-use token for a read outside a transaction. Cancellation rejects + * with `OperationCancelled` and discards row batches that have yet to be posted. * @returns A promise of the native query result. */ executeAsync( @@ -151,6 +156,7 @@ export declare class NitroSQLite extends HybridObject { onRows?: (rows: NativeQueryRows) => void, rowBatchId?: number, requireTransaction?: boolean, + cancellation?: ReadCancellation, ): Promise /** Set the function that receives row batches for `executeAsync` calls made with a `rowBatchId`. * The managed API sets it on its first async query and relies on it, so replacing it leaves managed @@ -201,6 +207,7 @@ export declare class NitroSQLite extends HybridObject { * The check runs under the connection lock, including for queued background calls. * Omit for normal execution, including manual BEGIN, COMMIT, and ROLLBACK. * @throws If the connection is closed or a required transaction has ended. + * @param cancellation Single-use token for a read outside a transaction. * @returns A promise of the native raw query result. */ executeRawAsync( @@ -208,6 +215,7 @@ export declare class NitroSQLite extends HybridObject { query: string, params?: SQLiteQueryParams, requireTransaction?: boolean, + cancellation?: ReadCancellation, ): Promise /** Prepare one SQL statement on an open native connection for repeated execution. * Finalize the returned statement before closing its connection. diff --git a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts index 99ceb8f69..712fc22f6 100644 --- a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts @@ -1,9 +1,10 @@ import { Android, iOS, type HybridObject } from 'nitro-core' import type { SQLiteQueryParams } from '../types' +import type { ReadCancellation } from './ReadCancellation.nitro' import type { NativeQueryResultBinding, NativeRawQueryResult, -} from './NativeQueryResult' +} from './NativeQueryResultBinding' export * from '#nitro/PreparedStatement' @@ -36,9 +37,13 @@ export declare class PreparedStatement extends HybridObject { * Executions run in call order with the connection's other async calls. * Rejects after finalization or connection closure. * @param params Values bound to positional placeholders. + * @param cancellation Single-use token for a read outside a transaction. * @returns A promise of the native query result. */ - executeAsync(params?: SQLiteQueryParams): Promise + executeAsync( + params?: SQLiteQueryParams, + cancellation?: ReadCancellation, + ): Promise /** Execute on the calling thread like `execute`, returning rows as arrays of column values. * @param params Values bound to positional placeholders. * @returns Column names, rows as value arrays, affected row count, and insert ID. @@ -46,9 +51,13 @@ export declare class PreparedStatement extends HybridObject { executeRaw(params?: SQLiteQueryParams): NativeRawQueryResult /** Execute on a background thread like `executeAsync`, returning rows as arrays of column values. * @param params Values bound to positional placeholders. + * @param cancellation Single-use token for a read outside a transaction. * @returns A promise of the native raw query result. */ - executeRawAsync(params?: SQLiteQueryParams): Promise + executeRawAsync( + params?: SQLiteQueryParams, + cancellation?: ReadCancellation, + ): Promise /** Release the native statement. Repeated calls are safe. */ finalize(): void } diff --git a/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts b/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts new file mode 100644 index 000000000..b1f1520c6 --- /dev/null +++ b/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts @@ -0,0 +1,8 @@ +import type { HybridObject } from 'nitro-core' + +/** Single-use cancellation token created by `NitroSQLite.native.createReadCancellation()`. */ +export interface ReadCancellation + extends HybridObject<{ ios: 'c++'; android: 'c++' }> { + /** Cancel the associated read. Calling this again or after native completion has no effect. */ + cancel(): void +} diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 727ab73d3..e23efd569 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -179,6 +179,15 @@ export type SQLiteValue = */ export type SQLiteQueryParams = SQLiteValue[] +/** Options for asynchronous reads on a connection or prepared statement. */ +export interface ExecuteAsyncOptions { + /** Cancels this execution. When supplied, only read queries outside an explicit + * transaction are allowed. Cancellation rejects with a `SQLiteError` of + * type `OperationCancelled`. An abort after native completion has no effect. + */ + signal?: AbortSignal +} + /** A row keyed by result column names. */ export type QueryResultRow = Record @@ -217,10 +226,12 @@ export type ExecuteQuery = ( /** Queue one SQL statement and resolve with its typed rows. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param options Optional cancellation signal for reads. */ export type ExecuteAsyncQuery = ( query: string, params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ) => Promise> /** Execute one SQL statement synchronously and return rows as arrays of column values. @@ -236,10 +247,12 @@ export type ExecuteRawQuery = ( /** Queue one SQL statement and resolve with rows as arrays of column values. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param options Optional cancellation signal for reads. */ export type ExecuteRawAsyncQuery = ( query: string, params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ) => Promise /** @@ -277,11 +290,13 @@ export type ExecutePreparedStatement = < * Queue a prepared statement execution and resolve with typed rows. Calls on the * same managed connection run in queue order. * @param params Values bound to the statement's positional placeholders. + * @param options Optional cancellation signal for reads. */ export type ExecutePreparedStatementAsync = < Row extends QueryResultRow = QueryResultRow, >( params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ) => Promise> /** @@ -296,9 +311,11 @@ export type ExecuteRawPreparedStatement = ( /** * Queue a prepared statement execution and resolve with rows as arrays of column values. * @param params Values bound to the statement's positional placeholders. + * @param options Optional cancellation signal for reads. */ export type ExecuteRawPreparedStatementAsync = ( params?: SQLiteQueryParams, + options?: ExecuteAsyncOptions, ) => Promise /** Handle valid only while its transaction callback and SQLite transaction are active. @@ -320,12 +337,24 @@ export interface Transaction { rollback(): NativeQueryResult /** Execute within this transaction on the calling thread. */ execute: ExecuteQuery - /** Execute within this transaction on a background thread. */ - executeAsync: ExecuteAsyncQuery + /** Execute within this transaction on a background thread. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + */ + executeAsync: ( + query: string, + params?: SQLiteQueryParams, + ) => Promise> /** Execute within this transaction on the calling thread, returning rows as arrays of column values. */ executeRaw: ExecuteRawQuery - /** Execute within this transaction on a background thread, returning rows as arrays of column values. */ - executeRawAsync: ExecuteRawAsyncQuery + /** Execute within this transaction on a background thread, returning rows as arrays of column values. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + */ + executeRawAsync: ( + query: string, + params?: SQLiteQueryParams, + ) => Promise } /** One command in a batch. A nested `params` array repeats the query for each parameter set. */ diff --git a/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts b/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts index 84d412bb0..e725dca75 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts @@ -7,6 +7,7 @@ export const HybridNitroSQLite = { attach: jest.fn(), detach: jest.fn(), execute: jest.fn(), + createReadCancellation: jest.fn(), executeAsync: jest.fn(), setRowBatchHandler: jest.fn(), setChangeHandler: jest.fn(), diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts index d37107cca..02efec61a 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts @@ -4,6 +4,26 @@ import type { Transaction } from '../types' afterEach(resetAllDatabases) describe('Node SQLite mock', () => { + it('cancels a read before execution and avoids side effects from unsupported SQL', async () => { + const database = open({ name: 'cancel-read' }) + const query = 'SELECT ? AS value' + const prepared = database.prepare(query) + const controller = new AbortController() + const pending = prepared.executeAsync([1], { signal: controller.signal }) + controller.abort() + await expect(pending).rejects.toMatchObject({ type: 'OperationCancelled' }) + + const options = { signal: new AbortController().signal } + await expect( + database.executeRawAsync('PRAGMA user_version=99', undefined, options), + ).rejects.toThrow('read-only') + expect(database.executeRaw('PRAGMA user_version').rows).toEqual([[0]]) + await expect(prepared.executeRawAsync([2], options)).resolves.toMatchObject( + { rows: [[2]] }, + ) + prepared.finalize() + }) + it('runs queries and returns Nitro-shaped rows', async () => { const database = open({ name: 'users' }) database.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/prepare.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/prepare.test.ts index 7a87e1c2a..9caef5d0a 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/prepare.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/prepare.test.ts @@ -42,6 +42,36 @@ function mockStatement(): PreparedStatement { } } +it('passes separate cancellation tokens to object and raw prepared reads', async () => { + const native = mockStatement() + jest.mocked(HybridNitroSQLite.prepare).mockReturnValue(native) + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockImplementation(() => ({ + name: 'NitroSQLiteReadCancellation', + toString: () => 'NitroSQLiteReadCancellation', + equals: () => false, + dispose: jest.fn(), + cancel: jest.fn(), + })) + const statement = prepare(dbName, query) + const signal = new AbortController().signal + + await expect(statement.executeAsync([8], { signal })).resolves.toMatchObject({ + results: [{ value: 8 }], + }) + await expect( + statement.executeRawAsync([10], { signal }), + ).resolves.toMatchObject({ + rows: [[10]], + }) + const [first, second] = jest.mocked(HybridNitroSQLite.createReadCancellation) + .mock.results + expect(first?.value).not.toBe(second?.value) + expect(native.executeAsync).toHaveBeenCalledWith([8], first?.value) + expect(native.executeRawAsync).toHaveBeenCalledWith([10], second?.value) +}) + it('reuses a statement, returns rows, and exposes finalization', async () => { closeDatabaseQueue(dbName) const db = open({ name: dbName }) diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts new file mode 100644 index 000000000..8f00261fb --- /dev/null +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts @@ -0,0 +1,232 @@ +jest.mock('../nitro') + +import { NitroSQLite } from '../index' +import { HybridNitroSQLite } from '../nitro' +import { SQLiteExceptionType } from '../errors' +import type { ReadCancellation } from '../specs/ReadCancellation.nitro' +import { deferred, nativeRawResult, nativeResult } from './testUtils' + +const dbName = 'read-cancellation' +const query = 'SELECT 1 AS value' +const cancelled = { type: SQLiteExceptionType.OperationCancelled } +let deliverRowBatch: + | Parameters[0] + | undefined +jest + .mocked(HybridNitroSQLite.setRowBatchHandler) + .mockImplementation((handler) => { + deliverRowBatch = handler + }) + +function mockCancellation(): ReadCancellation { + return { + name: 'ReadCancellation', + toString: () => 'ReadCancellation', + equals: () => false, + dispose: jest.fn(), + cancel: jest.fn(), + } +} + +beforeEach(() => { + jest.clearAllMocks() + jest.mocked(HybridNitroSQLite.execute).mockReturnValue(nativeResult()) + jest.mocked(HybridNitroSQLite.executeAsync).mockResolvedValue(nativeResult()) + jest + .mocked(HybridNitroSQLite.executeRawAsync) + .mockResolvedValue(nativeRawResult(['value'], [[1]])) + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockImplementation(mockCancellation) +}) + +it('rejects a pre-aborted read before native work, with or without a managed connection', async () => { + const controller = new AbortController() + controller.abort() + const options = { signal: controller.signal } + + await expect( + NitroSQLite.executeAsync(dbName, query, undefined, options), + ).rejects.toMatchObject(cancelled) + const db = NitroSQLite.open({ name: dbName }) + await expect( + db.executeRawAsync(query, undefined, options), + ).rejects.toMatchObject(cancelled) + expect(HybridNitroSQLite.createReadCancellation).not.toHaveBeenCalled() + expect(HybridNitroSQLite.executeAsync).not.toHaveBeenCalled() + expect(HybridNitroSQLite.executeRawAsync).not.toHaveBeenCalled() + db.close() +}) + +it('removes a JS-queued read and rejects while the transaction is still open', async () => { + const db = NitroSQLite.open({ name: dbName }) + const started = deferred() + const release = deferred() + const transaction = db.transaction(async () => { + started.resolve() + await release.promise + }) + await started.promise + + const controller = new AbortController() + const pending = NitroSQLite.executeAsync(dbName, query, undefined, { + signal: controller.signal, + }) + controller.abort() + try { + await expect(pending).rejects.toMatchObject(cancelled) + expect(HybridNitroSQLite.createReadCancellation).not.toHaveBeenCalled() + expect(HybridNitroSQLite.executeAsync).not.toHaveBeenCalled() + } finally { + release.resolve() + await transaction + } + await expect(db.executeAsync(query)).resolves.toMatchObject({ + rows: { length: 0 }, + }) + db.close() +}) + +it('does not submit a read aborted by the preceding admission in the same drain', async () => { + const db = NitroSQLite.open({ name: dbName }) + const started = deferred() + const release = deferred() + const transaction = db.transaction(async () => { + started.resolve() + await release.promise + }) + await started.promise + + const controller = new AbortController() + jest + .mocked(HybridNitroSQLite.executeAsync) + .mockImplementationOnce(async () => { + controller.abort() + return nativeResult() + }) + const first = db.executeAsync(query) + const second = db.executeAsync(query, undefined, { + signal: controller.signal, + }) + release.resolve() + await expect(second).rejects.toMatchObject(cancelled) + await Promise.all([transaction, first]) + expect(HybridNitroSQLite.createReadCancellation).not.toHaveBeenCalled() + expect(HybridNitroSQLite.executeAsync).toHaveBeenCalledTimes(1) + db.close() +}) + +it('passes the abort to the exact native token and detaches once the read rejects', async () => { + const db = NitroSQLite.open({ name: dbName }) + const controller = new AbortController() + const result = deferred>() + const token = mockCancellation() + const removeListener = jest.spyOn(controller.signal, 'removeEventListener') + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockReturnValueOnce(token) + jest + .mocked(HybridNitroSQLite.executeRawAsync) + .mockReturnValueOnce(result.promise) + + const pending = db.executeRawAsync(query, undefined, { + signal: controller.signal, + }) + controller.abort() + expect(HybridNitroSQLite.executeRawAsync).toHaveBeenCalledWith( + dbName, + query, + undefined, + token, + ) + expect(token.cancel).toHaveBeenCalledTimes(1) + result.reject( + new Error( + '[NativeNitroSQLiteException][OperationCancelled] SQLite read was cancelled', + ), + ) + await expect(pending).rejects.toMatchObject(cancelled) + expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function)) + await expect(db.executeRawAsync(query)).resolves.toMatchObject({ + rows: [[1]], + }) + db.close() +}) + +it('removes a completed read listener before a late abort', async () => { + const controller = new AbortController() + const token = mockCancellation() + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockReturnValueOnce(token) + await NitroSQLite.executeRawAsync(dbName, query, undefined, { + signal: controller.signal, + }) + controller.abort() + expect(token.cancel).not.toHaveBeenCalled() +}) + +it('discards row batches delivered after a cancelled query rejects', async () => { + const controller = new AbortController() + const nativeResultPending = deferred>() + const token = mockCancellation() + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockReturnValueOnce(token) + jest + .mocked(HybridNitroSQLite.executeAsync) + .mockReturnValueOnce(nativeResultPending.promise) + const pending = NitroSQLite.executeAsync(dbName, query, undefined, { + signal: controller.signal, + }) + const rowBatchId = jest.mocked(HybridNitroSQLite.executeAsync).mock + .lastCall?.[4] + expect(rowBatchId).toEqual(expect.any(Number)) + if (rowBatchId === undefined || deliverRowBatch === undefined) + throw new Error('Expected a row batch handler') + deliverRowBatch(rowBatchId, [{ value: 1 }]) + controller.abort() + nativeResultPending.reject( + '[NativeNitroSQLiteException][OperationCancelled] SQLite read was cancelled', + ) + await expect(pending).rejects.toMatchObject(cancelled) + deliverRowBatch(rowBatchId, [{ value: 2 }]) + await expect(NitroSQLite.executeAsync(dbName, query)).resolves.toMatchObject({ + results: [], + }) +}) + +it('releases the listener when the bridge throws while submitting', async () => { + const controller = new AbortController() + const token = mockCancellation() + jest + .mocked(HybridNitroSQLite.createReadCancellation) + .mockReturnValueOnce(token) + jest.mocked(HybridNitroSQLite.executeRawAsync).mockImplementationOnce(() => { + throw new Error('native call failed') + }) + await expect( + NitroSQLite.executeRawAsync(dbName, query, undefined, { + signal: controller.signal, + }), + ).rejects.toThrow('native call failed') + controller.abort() + expect(token.cancel).not.toHaveBeenCalled() +}) + +it('does not silently drop a signal on an older native build', async () => { + const factory = HybridNitroSQLite.createReadCancellation + Object.defineProperty(HybridNitroSQLite, 'createReadCancellation', { + value: undefined, + }) + try { + const signal = new AbortController().signal + await expect( + NitroSQLite.executeAsync(dbName, query, undefined, { signal }), + ).rejects.toThrow('newer Nitro SQLite native build') + } finally { + Object.defineProperty(HybridNitroSQLite, 'createReadCancellation', { + value: factory, + }) + } +}) From 9283ef41153e564836ceec99d35905e6e32f9d42 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:53:50 +0100 Subject: [PATCH 2/6] docs: describe how SQLite stops an active read Co-authored-by: Codex --- docs/content/docs/guides/sync-and-async.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index b0849a89a..7f0ecebc4 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -64,7 +64,7 @@ try { } ``` -An aborted read leaves whichever queue is holding it. If SQLite is already running the read, it stops when it next checks for progress. Work such as a long-running function or a wait for a database lock may delay that check. If native execution has already finished, the result still wins. Wait for the promise to settle before closing the managed connection. +An aborted read leaves whichever queue is holding it. If SQLite is already running the read, it stops when it next checks for interruption. Work such as a long-running function or a wait for a database lock may delay that check. If native execution has already finished, the result still wins. Wait for the promise to settle before closing the managed connection. The options argument also works with `executeRawAsync()`, both global async query helpers, and [prepared statement executions](/docs/guides/prepared-statements). Queries with a signal support `SELECT`, `VALUES`, and read-only common table expressions. Run PRAGMAs, writes, and transaction commands without a signal. Transaction callback methods, batches, and imports have no cancellation option. From ef85d38068729fed092f42bcec3161752eff80db Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:05:07 +0100 Subject: [PATCH 3/6] fix: preserve cancellation causes and validate mock reads Keep AbortSignal reasons across queue and native cancellation. Reject unsafe EXPLAIN preparation in the mock, check native token implementations, and document transaction and error contracts with regressions. Co-authored-by: Codex --- docs/content/docs/guides/node-test-mock.mdx | 3 + .../docs/guides/parameters-and-results.mdx | 7 +- docs/content/docs/guides/sync-and-async.mdx | 6 +- docs/scripts/check-api.mjs | 28 +++--- .../specs/operations/readCancellation.spec.ts | 57 +++++++++++- .../hybridObjects/HybridReadCancellation.hpp | 6 +- .../nitro-sqlite-core/src/DatabaseQueue.ts | 5 +- packages/nitro-sqlite-core/src/SQLiteError.ts | 2 +- packages/nitro-sqlite-core/src/mock.ts | 89 +++++++++++++------ packages/nitro-sqlite-core/src/mock/query.ts | 3 +- .../src/operations/readCancellation.ts | 14 ++- .../src/readCancellationError.ts | 4 +- packages/nitro-sqlite-core/src/types.ts | 6 +- .../platform/src/__tests__/mock.test.ts | 65 +++++++++++++- .../src/__tests__/readCancellation.test.ts | 37 ++++++-- 15 files changed, 273 insertions(+), 59 deletions(-) diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index f34392446..555c0347d 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -151,3 +151,6 @@ The mock ignores `encryptionKey` and writes plaintext databases. Test SEE encryp The generated [mock API reference](/api/react-native-nitro-sqlite/mock) documents `open()`, `NitroSQLite.open()`, `MockConnection`, and `resetAllDatabases()`. Connection methods use the same parameter and result types as the native API. The mock exports `open`, `NitroSQLite.open`, `resetAllDatabases`, and the `MockConnection` type. It does not replace every native package export. It does not implement attachments, SQL file imports, or direct `NitroSQLite.native` methods. Its SQL runs synchronously on Node's thread; async methods schedule that work and return promises. It uses the SQLite version bundled with `better-sqlite3`, which can differ from the library's native SQLite build. Use device tests for native integration, thread behavior, lock contention, and performance. + + +Async reads accept the same `AbortSignal` option as native reads. The mock can cancel before execution and retains `signal.reason` as the cancellation error's cause. It rejects writes, PRAGMAs, transaction commands, and `load_extension()` calls with `SqlExecutionError` when a signal is supplied, including through `EXPLAIN` or a prepared statement. An explicit transaction also prevents a cancellable read. The mock cannot interrupt SQL once it starts on Node's thread. Native authorizer behavior for extension-defined functions and virtual tables still needs device coverage. diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 62430329b..812cb90cd 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -103,10 +103,13 @@ try { [`SQLiteError`](/api/react-native-nitro-sqlite/classes/SQLiteError) extends `Error`. `SQLiteError.fromError(error)` returns an existing instance unchanged, copies an `Error`'s message, cause, and stack, or uses a string as its message. For other values, it sets the message to `'Unknown error occurred'` and keeps the original value as `cause`. -When a native `NitroSQLiteException` reaches a managed helper, `error.type` holds a [`SQLiteExceptionType`](/api/react-native-nitro-sqlite/type-aliases/SQLiteExceptionType) such as `SqlExecutionError`. It is `undefined` for JavaScript errors, including connection queue errors, and unrecognized native categories. These categories are not SQLite's numeric error codes. The native categories are `UnknownError`, `DatabaseCannotBeOpened`, `EncryptionNotEnabled`, `DatabaseCannotBeDecrypted`, `DatabaseNotOpen`, `UnableToAttachToDatabase`, `SqlExecutionError`, `CouldNotLoadFile`, and `NoBatchCommandsProvided`. See [encrypt a database](/docs/guides/encryption#handle-open-failures) for the encryption errors. The current native `DatabaseNotOpen` helper emits `UnableToAttachToDatabase`, and a missing database file emits `SqlExecutionError`. Calls through `NitroSQLite.native` throw raw native errors. +When a native `SQLiteException` reaches a managed helper, `error.type` holds a [`SQLiteExceptionType`](/api/react-native-nitro-sqlite/type-aliases/SQLiteExceptionType) such as `SqlExecutionError`. It is `undefined` for JavaScript errors, including connection queue errors, and unrecognized native categories. These categories are not SQLite's numeric error codes. The native categories are `UnknownError`, `DatabaseCannotBeOpened`, `EncryptionNotEnabled`, `DatabaseCannotBeDecrypted`, `DatabaseNotOpen`, `UnableToAttachToDatabase`, `SqlExecutionError`, `CouldNotLoadFile`, `NoBatchCommandsProvided`, and `OperationCancelled`. See [encrypt a database](/docs/guides/encryption#handle-open-failures) for the encryption errors. The current native `DatabaseNotOpen` helper emits `UnableToAttachToDatabase`, and a missing database file emits `SqlExecutionError`. Calls through `NitroSQLite.native` throw raw native errors. -The [`SQLiteExceptionType` constants](/api/react-native-nitro-sqlite/variables/SQLiteExceptionType) expose these categories as runtime strings. The object and the TypeScript union share the same name, so existing type-only imports still work. Both the constants and `SQLiteError` are available from each package's root and `/errors` entry point. The `/errors` entry points do not initialize the native module, so shared classifiers and Node tests can use them without a native runtime. `error.name` is `SQLiteError`. Use `error instanceof SQLiteError` to identify a managed failure and `error.type` to distinguish its category. The deprecated `NitroSQLiteError` export refers to the same constructor, so existing `instanceof NitroSQLiteError` checks also work. +The [`SQLiteExceptionType` constants](/api/react-native-nitro-sqlite/variables/SQLiteExceptionType) expose these categories as runtime strings. The object and the TypeScript union share the same name, so existing type-only imports still work. Both the constants and `SQLiteError` are available from each package's root and `/errors` entry point. The `/errors` entry points do not initialize the native module, so shared classifiers and Node tests can use them without a native runtime. `error.name` is `SQLiteError`. Use `error instanceof SQLiteError` to identify a managed failure and `error.type` to distinguish its category. The deprecated `SQLiteError` export refers to the same constructor, so existing `instanceof SQLiteError` checks also work. `DatabaseCannotBeOpened` covers several causes, including invalid paths, an already-open default connection, and filesystem failures. It does not by itself establish that the device is low on storage. For exact types, see [`QueryResult`](/api/react-native-nitro-sqlite/type-aliases/QueryResult), [`NativeQueryResult`](/api/react-native-nitro-sqlite/interfaces/NativeQueryResult), and [`QueryResultRows`](/api/react-native-nitro-sqlite/type-aliases/QueryResultRows). The row generic narrows `rows._array` and `rows.item()`, but not the raw `results` array. Query results are plain JavaScript objects; see [native access](/docs/guides/sync-and-async#global-helpers-and-native-access) for results returned without the connection helper. + + +When an `AbortSignal` cancels a read, the managed API rejects with `OperationCancelled` and uses `signal.reason` as `error.cause`. A signal supplied to a write, PRAGMA, or read inside an explicit transaction rejects with `SqlExecutionError`. See [cancel an async read](/docs/guides/sync-and-async#cancel-an-async-read) for the completion race and transaction restrictions. diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index 7f0ecebc4..aa9a62574 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -66,7 +66,11 @@ try { An aborted read leaves whichever queue is holding it. If SQLite is already running the read, it stops when it next checks for interruption. Work such as a long-running function or a wait for a database lock may delay that check. If native execution has already finished, the result still wins. Wait for the promise to settle before closing the managed connection. -The options argument also works with `executeRawAsync()`, both global async query helpers, and [prepared statement executions](/docs/guides/prepared-statements). Queries with a signal support `SELECT`, `VALUES`, and read-only common table expressions. Run PRAGMAs, writes, and transaction commands without a signal. Transaction callback methods, batches, and imports have no cancellation option. +Cancellation rejects with `OperationCancelled` and preserves `signal.reason` as `error.cause`. This includes reads cancelled before submission or while queued. A timeout reason remains available to distinguish a deadline from a user abort. A result or SQL error committed before cancellation still wins. + +A read with a signal rejects with `SqlExecutionError` if the connection already has an explicit transaction, including one opened through `execute('BEGIN')`. That rejection leaves the transaction open and its changes intact. Commit or roll back the transaction before submitting the cancellable read. Managed connection calls queued behind a callback transaction wait for it to finish first. + +The options argument also works with `executeRawAsync()`, both global async query helpers, and [prepared statement executions](/docs/guides/prepared-statements). Queries with a signal support `SELECT`, `VALUES`, and read-only common table expressions. Read-only `EXPLAIN` queries are also supported. PRAGMAs, writes, transaction commands, and `load_extension()` reject with `SqlExecutionError` when a signal is supplied. This restriction also applies to previously prepared statements. Run those operations without a signal. Transaction callback methods, batches, and imports have no cancellation option. ## Connection ordering diff --git a/docs/scripts/check-api.mjs b/docs/scripts/check-api.mjs index 97a1c684f..f81e51e78 100644 --- a/docs/scripts/check-api.mjs +++ b/docs/scripts/check-api.mjs @@ -18,14 +18,14 @@ const api = JSON.parse( const deprecatedExports = [ 'NitroSQLiteConnection', 'NitroSQLiteConnectionOptions', - 'NitroSQLiteQueryResultRows', + 'NativeQueryResultRows', 'NitroSQLiteQueryColumnMetadata', - 'NitroSQLiteQueryResult', - 'NitroSQLiteQueryRows', - 'NitroSQLitePreparedStatement', + 'NativeQueryResult', + 'NativeQueryRows', + 'PreparedStatement', 'NitroSQLiteNative', - 'NitroSQLiteError', - 'NitroSQLiteExceptionType', + 'SQLiteError', + 'SQLiteExceptionType', ] const drizzleExports = [ @@ -77,6 +77,8 @@ const requiredExports = { 'Connection', 'ConnectionOptions', 'QueryResult', + 'ExecuteAsyncOptions', + 'ReadCancellation', 'Transaction', 'BatchQueryCommand', 'SQLiteError', @@ -87,8 +89,8 @@ const requiredExports = { 'NativeQueryResultBinding', 'NativeQueryRows', 'NativeRawQueryResult', - 'NitroSQLiteRawQueryResult', - 'NitroSQLiteRawQueryRows', + 'NativeRawQueryResult', + 'NativeRawQueryRows', 'QueryResultRows', 'QueryColumnMetadata', 'TypeOrmConnection', @@ -189,8 +191,12 @@ const requiredMembers = { 'executeRaw', 'executeRawAsync', ], + ExecuteAsyncOptions: ['signal'], + ReadCancellation: ['cancel'], + SQLiteExceptionType: ['OperationCancelled'], SQLiteError: ['type', 'fromError'], NativeSQLite: [ + 'createReadCancellation', 'open', 'openConnection', 'close', @@ -235,7 +241,9 @@ for (const [packageName, symbols] of Object.entries(requiredMembers)) { ) for (const [name, members] of Object.entries(symbols)) { const symbol = packageReflection.children.find( - (child) => child.name === name, + (child) => + child.name === name && + (child.type?.declaration?.children ?? child.children), ) const actual = symbol?.type?.declaration?.children ?? symbol?.children ?? [] @@ -441,7 +449,7 @@ assert.ok( corePackageHome.indexOf('## Classes'), 'Hybrid Objects must appear before other API groups', ) -for (const name of ['NativeSQLite']) { +for (const name of ['NativeSQLite', 'ReadCancellation']) { assert.ok( pagePaths.has(`react-native-nitro-sqlite/hybrid-objects/${name}.mdx`), `Missing Hybrid Object page: ${name}`, diff --git a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts index cc2f2fa85..baf803914 100644 --- a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts +++ b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts @@ -58,7 +58,9 @@ export default function registerReadCancellationUnitTests() { const queued = failureOf( prepared.executeRawAsync([2], { signal: controller.signal }), ) - const following = prepared.executeAsync([3]) + const following = prepared.executeAsync([3], { + signal: new AbortController().signal, + }) next = following controller.abort() expect((await queued).type).toBe( @@ -108,13 +110,64 @@ export default function registerReadCancellationUnitTests() { expect((await pending).type).toBe( SQLiteExceptionType.OperationCancelled, ) - expect((await prepared.executeRawAsync([4])).rows).toEqual([[10]]) + expect( + ( + await prepared.executeRawAsync([4], { + signal: new AbortController().signal, + }) + ).rows, + ).toEqual([[10]]) } finally { clearTimeout(abort) prepared.finalize() } }) + it('can close during native cancellation and reopen for another cancellable read', async () => { + const native = NitroSQLite.native + const name = 'read-cancellation-close.sqlite' + native.open(name) + let isOpen = true + const token = native.createReadCancellation() + let notifyStarted: () => void = () => {} + const started = new Promise((resolve) => { + notifyStarted = resolve + }) + const active = failureOf( + native.executeAsync( + name, + slowRead, + undefined, + notifyStarted, + undefined, + token, + ), + ) + try { + await Promise.race([ + started, + active.then((error) => Promise.reject(error)), + ]) + token.cancel() + native.close(name) + isOpen = false + expect((await active).type).toBe( + NitroSQLiteExceptionType.OperationCancelled, + ) + token.cancel() + native.open(name) + isOpen = true + const next = native.createReadCancellation() + expect( + (await native.executeRawAsync(name, 'SELECT 42', undefined, next)).rows, + ).toEqual([[42]]) + } finally { + token.cancel() + await active + if (isOpen) native.close(name) + } + }) + it('rejects writes and connection changes without disturbing transaction state', async () => { const options = { signal: new AbortController().signal } const write = diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp index 0b103899f..00d457720 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp @@ -23,7 +23,11 @@ getReadCancellation(const std::optional(*cancellation)->state; + const auto nativeCancellation = std::dynamic_pointer_cast(*cancellation); + if (!nativeCancellation) { + throw SQLiteException::SqlExecution("Expected a read cancellation token created by NitroSQLite"); + } + return nativeCancellation->state; } } // namespace margelo::nitro::nitrosqlite diff --git a/packages/nitro-sqlite-core/src/DatabaseQueue.ts b/packages/nitro-sqlite-core/src/DatabaseQueue.ts index f4499a3af..ae9c8a3e7 100644 --- a/packages/nitro-sqlite-core/src/DatabaseQueue.ts +++ b/packages/nitro-sqlite-core/src/DatabaseQueue.ts @@ -100,7 +100,8 @@ function enqueueOperation( callback: () => Promise, signal?: AbortSignal, ): Promise { - if (signal?.aborted) return Promise.reject(readCancellationError()) + if (signal?.aborted) + return Promise.reject(readCancellationError(signal?.reason)) let databaseQueue: DatabaseQueue try { databaseQueue = getDatabaseQueue(dbName) @@ -152,7 +153,7 @@ function enqueueOperation( const index = databaseQueue.queue.indexOf(operation) if (index === -1) return databaseQueue.queue.splice(index, 1) - reject(readCancellationError()) + reject(readCancellationError(signal?.reason)) startNextOperations(databaseQueue) } signal?.addEventListener('abort', cancelQueuedOperation, { once: true }) diff --git a/packages/nitro-sqlite-core/src/SQLiteError.ts b/packages/nitro-sqlite-core/src/SQLiteError.ts index 830fa3de3..93c1a8d25 100644 --- a/packages/nitro-sqlite-core/src/SQLiteError.ts +++ b/packages/nitro-sqlite-core/src/SQLiteError.ts @@ -27,7 +27,7 @@ export const SQLiteExceptionType = { CouldNotLoadFile: 'CouldNotLoadFile', /** An empty batch was submitted. */ NoBatchCommandsProvided: 'NoBatchCommandsProvided', - /** The caller cancelled an asynchronous read. */ + /** The caller cancelled an asynchronous read. Managed AbortSignal calls preserve signal.reason as the error's cause. */ OperationCancelled: 'OperationCancelled', } as const diff --git a/packages/nitro-sqlite-core/src/mock.ts b/packages/nitro-sqlite-core/src/mock.ts index c4ab6aaf5..d5aba58fc 100644 --- a/packages/nitro-sqlite-core/src/mock.ts +++ b/packages/nitro-sqlite-core/src/mock.ts @@ -15,8 +15,12 @@ import { queueStatementAsync, startOperationSync, } from './DatabaseQueue' -import SQLiteError from './SQLiteError' -import type { ConnectionOptions, PreparedStatement } from './types' +import SQLiteError, { SQLiteExceptionType } from './SQLiteError' +import type { + ConnectionOptions, + PreparedStatement, + SQLiteQueryParams, +} from './types' import type { MockConnection } from './mock/MockConnection' import { executeBatch, @@ -24,6 +28,7 @@ import { executePreparedRaw, executeQuery, executeRawQuery, + getBindings, } from './mock/query' import { runTransaction } from './mock/transaction' import { readCancellationError } from './readCancellationError' @@ -80,35 +85,67 @@ export function open(options: ConnectionOptions): MockConnection { queueKey, () => Promise.resolve().then(() => { - if (signal?.aborted) throw readCancellationError() + if (signal?.aborted) throw readCancellationError(signal.reason) return callback() }), signal, ) } - const checkRead = (query: string, statement?: Statement) => { + const checkRead = ( + query: string, + params?: SQLiteQueryParams, + statement?: Statement, + ) => { + const rejectRead = (message: string): never => { + throw new SQLiteError(message, { + type: SQLiteExceptionType.SqlExecutionError, + }) + } if (database.inTransaction) { - throw new NitroSQLiteError( - 'Cancellable reads require a connection outside a transaction', - ) + rejectRead('Cancellable reads require a connection outside a transaction') } - // better-sqlite3 does not expose SQLite's authorizer. Check the first keyword - // before preparation because some PRAGMAs take effect during prepare(). - const readPrefix = - /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:SELECT|VALUES|WITH|EXPLAIN)\b/i - if (!readPrefix.test(query)) { - throw new NitroSQLiteError( - 'Cancellation is only supported for read-only queries', - ) + // EXPLAIN still prepares its underlying SQL, including PRAGMA side effects. + const trivia = String.raw`(?:\s|--[^\n]*(?:\n|$)|/\*[\s\S]*?\*/)` + const prefix = new RegExp( + `^(?:${trivia}|;)*(?:EXPLAIN${trivia}+(?:QUERY${trivia}+PLAN${trivia}+)?)?`, + 'i', + ) + const readSql = query.replace(prefix, '') + if (!/^(?:SELECT|VALUES|WITH)\b/i.test(readSql)) { + rejectRead('Cancellation is only supported for read-only queries') } - const prepared = - statement ?? database.prepare>(query) - if (!prepared.readonly) { - throw new NitroSQLiteError( - 'Cancellation is only supported for read-only queries', - ) + try { + const prepared = + statement ?? database.prepare>(query) + if (!prepared.readonly) { + rejectRead('Cancellation is only supported for read-only queries') + } + // Inspect SQLite's compiled functions so views and quoted function names + // receive the same load_extension restriction as the native authorizer. + const instructions = database + .prepare< + unknown[], + { opcode: string; p4: string | null } + >(`EXPLAIN ${readSql}`) + .all(...getBindings(readSql, params)) + if ( + instructions.some( + ({ opcode, p4 }) => + (opcode === 'Function' || opcode === 'PureFunc') && + p4?.toLowerCase().startsWith('load_extension('), + ) + ) { + rejectRead('Cancellation does not support load_extension') + } + return prepared + } catch (error) { + const failure = SQLiteError.fromError(error) + if (failure.type !== undefined) throw failure + throw new SQLiteError(failure.message, { + type: SQLiteExceptionType.SqlExecutionError, + cause: error, + }) } - return prepared } const close = () => { runSync(() => database.close()) @@ -153,7 +190,7 @@ export function open(options: ConnectionOptions): MockConnection { () => queryOptions?.signal === undefined ? executeQuery(database, query, params) - : executePrepared(database, checkRead(query), params), + : executePrepared(database, checkRead(query, params), params), false, queryOptions?.signal, ), @@ -164,7 +201,7 @@ export function open(options: ConnectionOptions): MockConnection { () => queryOptions?.signal === undefined ? executeRawQuery(database, query, params) - : executePreparedRaw(database, checkRead(query), params), + : executePreparedRaw(database, checkRead(query, params), params), false, queryOptions?.signal, ), @@ -194,7 +231,7 @@ export function open(options: ConnectionOptions): MockConnection { runAsync( () => { if (queryOptions?.signal !== undefined && statement !== undefined) - checkRead(query, statement) + checkRead(query, params, statement) return execute(params) }, true, @@ -205,7 +242,7 @@ export function open(options: ConnectionOptions): MockConnection { runAsync( () => { if (queryOptions?.signal !== undefined && statement !== undefined) - checkRead(query, statement) + checkRead(query, params, statement) return executeRaw(params) }, true, diff --git a/packages/nitro-sqlite-core/src/mock/query.ts b/packages/nitro-sqlite-core/src/mock/query.ts index 0e596161b..9d28a23cc 100644 --- a/packages/nitro-sqlite-core/src/mock/query.ts +++ b/packages/nitro-sqlite-core/src/mock/query.ts @@ -133,7 +133,8 @@ export function executeBatch( return { rowsAffected } } -function getBindings(query: string, params?: SQLiteQueryParams) { +/** @internal Normalize positional bindings for execution or EXPLAIN validation. */ +export function getBindings(query: string, params?: SQLiteQueryParams) { const { names, positionalCount } = extractParameters(query) if (names.length === 0) { const values = params?.map(toBoundValue) ?? [] diff --git a/packages/nitro-sqlite-core/src/operations/readCancellation.ts b/packages/nitro-sqlite-core/src/operations/readCancellation.ts index a7a657640..3fa5d7dc7 100644 --- a/packages/nitro-sqlite-core/src/operations/readCancellation.ts +++ b/packages/nitro-sqlite-core/src/operations/readCancellation.ts @@ -1,6 +1,6 @@ import { HybridNitroSQLite } from '../nitro' import { callNativeAsync } from '../nativePromise' -import SQLiteError from '../SQLiteError' +import SQLiteError, { SQLiteExceptionType } from '../SQLiteError' import { readCancellationError } from '../readCancellationError' import type { ReadCancellation } from '../specs/ReadCancellation.nitro' @@ -8,7 +8,8 @@ export function runWithReadCancellation( signal: AbortSignal, run: (cancellation: ReadCancellation) => Promise, ): Promise { - if (signal.aborted) return Promise.reject(readCancellationError()) + if (signal.aborted) + return Promise.reject(readCancellationError(signal.reason)) if (typeof HybridNitroSQLite.createReadCancellation !== 'function') { return Promise.reject( new SQLiteError( @@ -27,5 +28,14 @@ export function runWithReadCancellation( signal.removeEventListener('abort', onAbort) throw error } + }).catch((error: unknown) => { + if ( + signal.aborted && + error instanceof SQLiteError && + error.type === SQLiteExceptionType.OperationCancelled + ) { + throw readCancellationError(signal.reason) + } + throw error }) } diff --git a/packages/nitro-sqlite-core/src/readCancellationError.ts b/packages/nitro-sqlite-core/src/readCancellationError.ts index 55edaaa81..776c9dd17 100644 --- a/packages/nitro-sqlite-core/src/readCancellationError.ts +++ b/packages/nitro-sqlite-core/src/readCancellationError.ts @@ -1,7 +1,9 @@ import SQLiteError, { SQLiteExceptionType } from './SQLiteError' -export function readCancellationError(): SQLiteError { +/** @internal Create the cancellation error, preserving an AbortSignal's reason as its cause. */ +export function readCancellationError(reason?: unknown): SQLiteError { return new SQLiteError('SQLite read was cancelled', { type: SQLiteExceptionType.OperationCancelled, + cause: reason, }) } diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index e23efd569..4aa21c1ed 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -183,7 +183,11 @@ export type SQLiteQueryParams = SQLiteValue[] export interface ExecuteAsyncOptions { /** Cancels this execution. When supplied, only read queries outside an explicit * transaction are allowed. Cancellation rejects with a `SQLiteError` of - * type `OperationCancelled`. An abort after native completion has no effect. + * type `OperationCancelled`, with `signal.reason` as its `cause`. A signal + * supplied to writes, PRAGMAs, transaction commands, or `load_extension()` + * rejects with `SqlExecutionError`. A read inside an explicit transaction + * also rejects with `SqlExecutionError` and leaves that transaction intact. + * An abort after native completion has no effect. */ signal?: AbortSignal } diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts index 02efec61a..0f2339c4b 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts @@ -10,8 +10,12 @@ describe('Node SQLite mock', () => { const prepared = database.prepare(query) const controller = new AbortController() const pending = prepared.executeAsync([1], { signal: controller.signal }) - controller.abort() - await expect(pending).rejects.toMatchObject({ type: 'OperationCancelled' }) + const reason = new Error('obsolete query') + controller.abort(reason) + await expect(pending).rejects.toMatchObject({ + type: 'OperationCancelled', + cause: reason, + }) const options = { signal: new AbortController().signal } await expect( @@ -24,6 +28,63 @@ describe('Node SQLite mock', () => { prepared.finalize() }) + it('matches read restrictions before prepare-time effects and preserves SQL error categories', async () => { + const database = open({ name: 'read-policy' }) + database.execute('CREATE TABLE notes(value)') + database.execute( + "CREATE VIEW extension_call AS SELECT load_extension('missing')", + ) + const options = { signal: new AbortController().signal } + database.execute('PRAGMA cache_size=2000') + for (const sql of [ + '(SELECT 1)', + 'PRAGMA user_version', + 'PRAGMA cache_size=17', + 'EXPLAIN /* comment */ PRAGMA cache_size=17', + 'EXPLAIN QUERY PLAN PRAGMA cache_size=17', + 'EXPLAIN INSERT INTO notes VALUES(1)', + 'WITH value AS (SELECT 1) INSERT INTO notes SELECT * FROM value', + 'BEGIN', + "SELECT load_extension('missing')", + 'SELECT * FROM extension_call', + 'EXPLAIN SELECT * FROM extension_call', + ]) { + await expect( + database.executeRawAsync(sql, undefined, options), + ).rejects.toMatchObject({ type: 'SqlExecutionError' }) + } + expect(database.executeRaw('PRAGMA cache_size').rows).toEqual([[2000]]) + expect(database.executeRaw('SELECT count(*) FROM notes').rows).toEqual([ + [0], + ]) + for (const sql of [ + '; -- comment\n SELECT 1', + 'VALUES(1)', + 'WITH value AS (SELECT 1) SELECT * FROM value', + 'EXPLAIN /* comment */ SELECT 1', + 'EXPLAIN QUERY PLAN SELECT 1', + "SELECT 'load_extension(1)'", + ]) { + await expect( + database.executeRawAsync(sql, undefined, options), + ).resolves.toHaveProperty('rows') + } + const preparedControl = database.prepare('PRAGMA cache_size=17') + database.execute('PRAGMA cache_size=2000') + await expect( + preparedControl.executeAsync(undefined, options), + ).rejects.toMatchObject({ type: 'SqlExecutionError' }) + expect(database.executeRaw('PRAGMA cache_size').rows).toEqual([[2000]]) + preparedControl.finalize() + database.execute('BEGIN') + database.execute('INSERT INTO notes VALUES(2)') + await expect( + database.executeAsync('SELECT 1', undefined, options), + ).rejects.toMatchObject({ type: 'SqlExecutionError' }) + database.execute('COMMIT') + expect(database.executeRaw('SELECT value FROM notes').rows).toEqual([[2]]) + }) + it('runs queries and returns Nitro-shaped rows', async () => { const database = open({ name: 'users' }) database.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts index 8f00261fb..313adca0b 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts @@ -42,16 +42,17 @@ beforeEach(() => { it('rejects a pre-aborted read before native work, with or without a managed connection', async () => { const controller = new AbortController() - controller.abort() + const reason = new Error('search replaced') + controller.abort(reason) const options = { signal: controller.signal } await expect( NitroSQLite.executeAsync(dbName, query, undefined, options), - ).rejects.toMatchObject(cancelled) + ).rejects.toMatchObject({ ...cancelled, cause: reason }) const db = NitroSQLite.open({ name: dbName }) await expect( db.executeRawAsync(query, undefined, options), - ).rejects.toMatchObject(cancelled) + ).rejects.toMatchObject({ ...cancelled, cause: reason }) expect(HybridNitroSQLite.createReadCancellation).not.toHaveBeenCalled() expect(HybridNitroSQLite.executeAsync).not.toHaveBeenCalled() expect(HybridNitroSQLite.executeRawAsync).not.toHaveBeenCalled() @@ -72,9 +73,10 @@ it('removes a JS-queued read and rejects while the transaction is still open', a const pending = NitroSQLite.executeAsync(dbName, query, undefined, { signal: controller.signal, }) - controller.abort() + const reason = { requestId: 7 } + controller.abort(reason) try { - await expect(pending).rejects.toMatchObject(cancelled) + await expect(pending).rejects.toMatchObject({ ...cancelled, cause: reason }) expect(HybridNitroSQLite.createReadCancellation).not.toHaveBeenCalled() expect(HybridNitroSQLite.executeAsync).not.toHaveBeenCalled() } finally { @@ -132,7 +134,9 @@ it('passes the abort to the exact native token and detaches once the read reject const pending = db.executeRawAsync(query, undefined, { signal: controller.signal, }) - controller.abort() + const reason = new Error('deadline exceeded') + reason.name = 'TimeoutError' + controller.abort(reason) expect(HybridNitroSQLite.executeRawAsync).toHaveBeenCalledWith( dbName, query, @@ -145,7 +149,7 @@ it('passes the abort to the exact native token and detaches once the read reject '[NativeNitroSQLiteException][OperationCancelled] SQLite read was cancelled', ), ) - await expect(pending).rejects.toMatchObject(cancelled) + await expect(pending).rejects.toMatchObject({ ...cancelled, cause: reason }) expect(removeListener).toHaveBeenCalledWith('abort', expect.any(Function)) await expect(db.executeRawAsync(query)).resolves.toMatchObject({ rows: [[1]], @@ -230,3 +234,22 @@ it('does not silently drop a signal on an older native build', async () => { }) } }) + +it('preserves a native failure if completion beats an abort', async () => { + const controller = new AbortController() + const result = deferred>() + jest + .mocked(HybridNitroSQLite.executeRawAsync) + .mockReturnValueOnce(result.promise) + const pending = NitroSQLite.executeRawAsync(dbName, query, undefined, { + signal: controller.signal, + }) + controller.abort(new Error('late abort')) + result.reject( + new Error('[NativeNitroSQLiteException][SqlExecutionError] invalid SQL'), + ) + await expect(pending).rejects.toMatchObject({ + type: 'SqlExecutionError', + cause: undefined, + }) +}) From 956dfaa1161d337b0a2f18a3f01d3fd87600824e Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:39:00 +0100 Subject: [PATCH 4/6] test: document and verify cancellation authorizer boundaries Co-authored-by: Codex --- docs/content/docs/guides/node-test-mock.mdx | 4 +++- .../specs/operations/readCancellation.spec.ts | 21 +++++++++++++++++++ packages/nitro-sqlite-core/src/mock.ts | 4 ++-- .../platform/src/__tests__/mock.test.ts | 1 + .../tests/cpp/readCancellation.test.cpp | 9 +++++--- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index 555c0347d..4f25cb976 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -153,4 +153,6 @@ The generated [mock API reference](/api/react-native-nitro-sqlite/mock) document The mock exports `open`, `NitroSQLite.open`, `resetAllDatabases`, and the `MockConnection` type. It does not replace every native package export. It does not implement attachments, SQL file imports, or direct `NitroSQLite.native` methods. Its SQL runs synchronously on Node's thread; async methods schedule that work and return promises. It uses the SQLite version bundled with `better-sqlite3`, which can differ from the library's native SQLite build. Use device tests for native integration, thread behavior, lock contention, and performance. -Async reads accept the same `AbortSignal` option as native reads. The mock can cancel before execution and retains `signal.reason` as the cancellation error's cause. It rejects writes, PRAGMAs, transaction commands, and `load_extension()` calls with `SqlExecutionError` when a signal is supplied, including through `EXPLAIN` or a prepared statement. An explicit transaction also prevents a cancellable read. The mock cannot interrupt SQL once it starts on Node's thread. Native authorizer behavior for extension-defined functions and virtual tables still needs device coverage. +Async reads accept the same `AbortSignal` option as native reads. The mock can cancel before execution and retains `signal.reason` as the cancellation error's cause. It rejects writes, PRAGMAs, transaction commands, and compiled `load_extension()` calls with `SqlExecutionError` when a signal is supplied, including through `EXPLAIN` or a prepared statement. An explicit transaction also prevents a cancellable read. The mock cannot interrupt SQL once it starts on Node's thread. + +SQLite's native authorizer checks operations while preparing SQL. The mock's backend does not expose that hook, so its function check inspects compiled instructions. An unused expression can disappear from those instructions: `SELECT 1 FROM (SELECT load_extension(NULL))` succeeds in the mock but is rejected by a native cancellable read. A completely unused CTE such as `WITH unused AS (SELECT load_extension(NULL)) SELECT 1` is accepted by both because SQLite does not resolve its body. Use device tests for preparation-time authorization, extension-defined functions, and virtual tables; passing mock tests does not establish that parity. diff --git a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts index baf803914..e1d6b0e5d 100644 --- a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts +++ b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts @@ -24,6 +24,27 @@ async function failureOf(promise: Promise): Promise { } export default function registerReadCancellationUnitTests() { + it('authorizes resolved expressions before SQLite optimizes the query', async () => { + const options = { signal: new AbortController().signal } + for (const sql of [ + 'SELECT 1 FROM (SELECT load_extension(NULL))', + 'EXPLAIN SELECT 1 FROM (SELECT load_extension(NULL))', + ]) { + expect( + (await failureOf(testDb.executeRawAsync(sql, undefined, options))).type, + ).toBe(NitroSQLiteExceptionType.SqlExecutionError) + } + expect( + ( + await testDb.executeRawAsync( + 'WITH unused AS (SELECT load_extension(NULL)) SELECT 1', + undefined, + options, + ) + ).rows, + ).toEqual([[1]]) + }) + it('cancels reads in the native FIFO and interrupts only the active operation', async () => { const native = NitroSQLite.native const activeToken = native.createReadCancellation() diff --git a/packages/nitro-sqlite-core/src/mock.ts b/packages/nitro-sqlite-core/src/mock.ts index d5aba58fc..393c903a0 100644 --- a/packages/nitro-sqlite-core/src/mock.ts +++ b/packages/nitro-sqlite-core/src/mock.ts @@ -120,8 +120,8 @@ export function open(options: ConnectionOptions): MockConnection { if (!prepared.readonly) { rejectRead('Cancellation is only supported for read-only queries') } - // Inspect SQLite's compiled functions so views and quoted function names - // receive the same load_extension restriction as the native authorizer. + // This backend has no authorizer hook. Compiled functions cover views and + // quoted names, but omit expressions SQLite removed during optimization. const instructions = database .prepare< unknown[], diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts index 0f2339c4b..e1407f310 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/mock.test.ts @@ -61,6 +61,7 @@ describe('Node SQLite mock', () => { '; -- comment\n SELECT 1', 'VALUES(1)', 'WITH value AS (SELECT 1) SELECT * FROM value', + 'WITH unused AS (SELECT load_extension(NULL)) SELECT 1', 'EXPLAIN /* comment */ SELECT 1', 'EXPLAIN QUERY PLAN SELECT 1', "SELECT 'load_extension(1)'", diff --git a/packages/react-native-nitro-sqlite/tests/cpp/readCancellation.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/readCancellation.test.cpp index ce815b83f..5c027a1e0 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/readCancellation.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/readCancellation.test.cpp @@ -73,7 +73,8 @@ void testReadPolicy(SQLiteConnection& connection) { for (const char* sql : {"PRAGMA user_version=9", "PRAGMA cache_size=17", "PRAGMA user_version", "BEGIN", "SAVEPOINT x", "ATTACH ':memory:' AS other", "INSERT INTO notes VALUES(2)", "EXPLAIN INSERT INTO notes VALUES(2)", - "EXPLAIN PRAGMA cache_size=17", "SELECT load_extension('missing')"}) { + "EXPLAIN PRAGMA cache_size=17", "SELECT load_extension('missing')", "SELECT 1 FROM (SELECT load_extension(NULL))", + "EXPLAIN SELECT 1 FROM (SELECT load_extension(NULL))"}) { auto prepared = prepare(database, sql); bool allowed = false; SQLiteOperationCancellation cancellation; @@ -86,13 +87,15 @@ void testReadPolicy(SQLiteConnection& connection) { SQLiteOperationCancellation cancellation; SQLiteReadCancellationScope scope(connection, &cancellation); for (const char* sql : {"PRAGMA cache_size=17", "EXPLAIN PRAGMA cache_size=17", "PRAGMA user_version=9", "BEGIN", - "INSERT INTO notes VALUES(2)", "SELECT load_extension('missing')"}) { + "INSERT INTO notes VALUES(2)", "SELECT load_extension('missing')", + "SELECT 1 FROM (SELECT load_extension(NULL))", "EXPLAIN SELECT 1 FROM (SELECT load_extension(NULL))"}) { sqlite3_stmt* statement = nullptr; const int status = sqlite3_prepare_v2(database, sql, -1, &statement, nullptr); sqlite3_finalize(statement); expect(status != SQLITE_OK, "unsafe SQL must be rejected during preparation"); } - for (const char* sql : {"; -- comment\n SELECT 1", "VALUES(1)", "WITH t AS (SELECT 1) SELECT * FROM t", "EXPLAIN SELECT 1"}) { + for (const char* sql : {"; -- comment\n SELECT 1", "VALUES(1)", "WITH t AS (SELECT 1) SELECT * FROM t", "EXPLAIN SELECT 1", + "WITH unused AS (SELECT load_extension(NULL)) SELECT 1"}) { auto statement = prepare(database, sql); scope.checkStatement(statement.get()); expect(sqlite3_step(statement.get()) == SQLITE_ROW, "supported read syntax remains allowed"); From 20c1e26be993f5e87b5df7acd2c2da105df09a97 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 13:03:15 +0100 Subject: [PATCH 5/6] fix: complete cancellation bindings for Nitro v1 Co-authored-by: Codex --- docs/scripts/check-api.mjs | 16 ++-- .../cpp/hybridObjects/HybridNitroSQLite.cpp | 30 ++++--- .../cpp/hybridObjects/HybridNitroSQLite.hpp | 6 +- .../hybridObjects/HybridPreparedStatement.cpp | 16 ++-- .../hybridObjects/HybridPreparedStatement.hpp | 10 +-- .../hybridObjects/HybridReadCancellation.hpp | 4 +- .../SQLiteConnectionOperation.hpp | 11 ++- packages/nitro-sqlite-core/src/index.ts | 4 +- .../src/operations/execute.ts | 85 ++++++++++++++----- .../src/specs/NitroSQLite.nitro.ts | 2 +- .../src/specs/PreparedStatement.nitro.ts | 2 +- .../src/specs/ReadCancellation.nitro.ts | 21 ++++- .../android/RNNitroSQLite+autolinking.cmake | 2 + .../generated/android/RNNitroSQLiteOnLoad.cpp | 2 + .../c++/HybridNitroSQLiteSpecClass.cpp | 4 +- .../c++/HybridPreparedStatementSpecClass.cpp | 2 + .../c++/HybridReadCancellationSpecClass.cpp | 22 +++++ .../apple/RNNitroSQLiteAutolinking.cpp | 2 + .../apple/c++/HybridNitroSQLiteSpecClass.cpp | 4 +- .../c++/HybridPreparedStatementSpecClass.cpp | 2 + .../c++/HybridReadCancellationSpecClass.cpp | 22 +++++ .../nitrogen/generated/hybrid-classes.json | 16 ++++ .../shared/c++/HybridReadCancellationSpec.cpp | 14 +++ .../RNNitroSQLite/HybridNitroSQLiteSpec.hpp | 9 +- .../HybridPreparedStatementSpec.hpp | 7 +- .../HybridReadCancellationSpec.hpp | 59 +++++++++++++ .../shared/javascript/ReadCancellation.cjs | 19 +++++ .../shared/javascript/ReadCancellation.d.cts | 9 ++ .../src/__tests__/readCancellation.test.ts | 3 +- 29 files changed, 324 insertions(+), 81 deletions(-) create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridReadCancellationSpecClass.cpp create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridReadCancellationSpecClass.cpp create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridReadCancellationSpec.cpp create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridReadCancellationSpec.hpp create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.cjs create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.d.cts diff --git a/docs/scripts/check-api.mjs b/docs/scripts/check-api.mjs index f81e51e78..0af54a939 100644 --- a/docs/scripts/check-api.mjs +++ b/docs/scripts/check-api.mjs @@ -18,14 +18,14 @@ const api = JSON.parse( const deprecatedExports = [ 'NitroSQLiteConnection', 'NitroSQLiteConnectionOptions', - 'NativeQueryResultRows', + 'NitroSQLiteQueryResultRows', 'NitroSQLiteQueryColumnMetadata', - 'NativeQueryResult', - 'NativeQueryRows', - 'PreparedStatement', + 'NitroSQLiteQueryResult', + 'NitroSQLiteQueryRows', + 'NitroSQLitePreparedStatement', 'NitroSQLiteNative', - 'SQLiteError', - 'SQLiteExceptionType', + 'NitroSQLiteError', + 'NitroSQLiteExceptionType', ] const drizzleExports = [ @@ -89,8 +89,8 @@ const requiredExports = { 'NativeQueryResultBinding', 'NativeQueryRows', 'NativeRawQueryResult', - 'NativeRawQueryResult', - 'NativeRawQueryRows', + 'NitroSQLiteRawQueryResult', + 'NitroSQLiteRawQueryRows', 'QueryResultRows', 'QueryColumnMetadata', 'TypeOrmConnection', diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index 077c8ae52..c0e6ebcde 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -214,7 +214,8 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db const std::optional& params, const std::optional>& onRows, const std::optional& rowBatchId, - const std::optional& requireTransaction, const std::optional>& cancellation) { + const std::optional& requireTransaction, + const std::optional>& cancellation) { auto copiedParams = copyArrayBufferParamsForBackground(params); const auto token = getReadCancellation(cancellation); SQLiteConnectionPtr connection; @@ -241,8 +242,8 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db const auto cancellationSender = token ? std::make_shared>() : nullptr; return enqueueConnectionOperation( connection, - [connection, query, copiedParams = std::move(copiedParams), batchDelivery = std::move(batchDelivery), - requireTransaction, token, cancellationSender]() mutable -> NativeQueryResult { + [connection, query, copiedParams = std::move(copiedParams), batchDelivery = std::move(batchDelivery), requireTransaction, token, + cancellationSender]() mutable -> NativeQueryResult { std::shared_ptr sender; SQLiteRowBatchHandler rowBatches; if (const auto* direct = std::get_if(&batchDelivery)) { @@ -251,7 +252,8 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db rowBatches = [paced, &sender, &cancellationSender](SQLiteQueryResults rows) { if (!sender) { sender = std::make_shared(std::move(paced->handler), paced->id, paced->submittedAt); - if (cancellationSender) *cancellationSender = sender; + if (cancellationSender) + *cancellationSender = sender; } sender->send(std::move(rows)); }; @@ -266,7 +268,12 @@ Promise HybridNitroSQLite::executeAsync(const std::string& db } throw; } - }, token, [cancellationSender] { if (cancellationSender && *cancellationSender) (*cancellationSender)->cancel(); }); + }, + token, + [cancellationSender] { + if (cancellationSender && *cancellationSender) + (*cancellationSender)->cancel(); + }); }; void HybridNitroSQLite::setRowBatchHandler(const Callback& handler) { @@ -299,9 +306,10 @@ NativeRawQueryResult HybridNitroSQLite::executeRaw(const std::string& dbName, co return sqliteExecuteRaw(_connections.get(dbName), query, params, requireTransaction.value_or(false)); } -Promise HybridNitroSQLite::executeRawAsync(const std::string& dbName, const std::string& query, - const std::optional& params, - const std::optional& requireTransaction, const std::optional>& cancellation) { +Promise +HybridNitroSQLite::executeRawAsync(const std::string& dbName, const std::string& query, const std::optional& params, + const std::optional& requireTransaction, + const std::optional>& cancellation) { auto copiedParams = copyArrayBufferParamsForBackground(params); const auto token = getReadCancellation(cancellation); SQLiteConnectionPtr connection; @@ -312,9 +320,11 @@ Promise HybridNitroSQLite::executeRawAsync(const std::stri } return enqueueConnectionOperation( - connection, [connection, query, copiedParams = std::move(copiedParams), requireTransaction, token]() -> NativeRawQueryResult { + connection, + [connection, query, copiedParams = std::move(copiedParams), requireTransaction, token]() -> NativeRawQueryResult { return sqliteExecuteRaw(connection, query, copiedParams, requireTransaction.value_or(false), token.get()); - }, token); + }, + token); } std::shared_ptr HybridNitroSQLite::prepare(const std::string& dbName, const std::string& query) { diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp index d33d71929..0d8470904 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -86,7 +86,8 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional& params, const std::optional>& onRows, - const std::optional& rowBatchId, const std::optional& requireTransaction, const std::optional>& cancellation) override; + const std::optional& rowBatchId, const std::optional& requireTransaction, + const std::optional>& cancellation) override; /** Set the handler that receives row batches for executeAsync calls made with a row batch ID. */ void setRowBatchHandler(const Callback& handler) override; @@ -104,7 +105,8 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { * Execute one SQL statement on a background thread, returning rows as arrays of column values. */ Promise executeRawAsync(const std::string& dbName, const std::string& query, const std::optional& params, - const std::optional& requireTransaction, const std::optional>& cancellation) override; + const std::optional& requireTransaction, + const std::optional>& cancellation) override; /** Prepare one SQL statement for repeated execution on an open connection. */ std::shared_ptr prepare(const std::string& dbName, const std::string& query) override; diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp index 350f1c2b6..42b79e036 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -55,9 +55,9 @@ NativeQueryResult HybridPreparedStatement::execute(const std::optionalexecute(params, SQLiteExecutionMode::Synchronous); } -Promise HybridPreparedStatement::executeAsync( - const std::optional& params, - const std::optional>& cancellation) { +Promise +HybridPreparedStatement::executeAsync(const std::optional& params, + const std::optional>& cancellation) { const auto token = getReadCancellation(cancellation); const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = retainStatement(_statement, token); @@ -65,16 +65,18 @@ Promise HybridPreparedStatement::executeAsync( // The connection's worker keeps executions in call order, so JavaScript can submit several without // waiting for each result. return enqueueConnectionOperation( - statement->connection(), [statement, copiedParams, token]() { return statement->execute(copiedParams, SQLiteExecutionMode::Asynchronous, token.get()); }, token); + statement->connection(), + [statement, copiedParams, token]() { return statement->execute(copiedParams, SQLiteExecutionMode::Asynchronous, token.get()); }, + token); } NativeRawQueryResult HybridPreparedStatement::executeRaw(const std::optional& params) { return _statement->executeRaw(params); } -Promise HybridPreparedStatement::executeRawAsync( - const std::optional& params, - const std::optional>& cancellation) { +Promise +HybridPreparedStatement::executeRawAsync(const std::optional& params, + const std::optional>& cancellation) { const auto token = getReadCancellation(cancellation); const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = retainStatement(_statement, token); diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp index cdf967288..5787ffa49 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp @@ -18,15 +18,13 @@ class HybridPreparedStatement : public HybridPreparedStatementSpec { /** Execute with new bindings on the connection's worker, in call order. * @param cancellation Single-use token for a read outside a transaction. */ - Promise - executeAsync(const std::optional& params, - const std::optional>& cancellation) override; + Promise executeAsync(const std::optional& params, + const std::optional>& cancellation) override; /** Execute with new bindings on the calling thread, returning rows as arrays of column values. */ NativeRawQueryResult executeRaw(const std::optional& params) override; /** Execute like executeAsync(), returning rows as arrays of column values. */ - Promise - executeRawAsync(const std::optional& params, - const std::optional>& cancellation) override; + Promise executeRawAsync(const std::optional& params, + const std::optional>& cancellation) override; /** Release the native statement. */ void finalize() override; /** Check whether the native statement has been released. */ diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp index 00d457720..12c58e0ca 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridReadCancellation.hpp @@ -1,15 +1,13 @@ #pragma once #include "../SQLiteOperationCancellation.hpp" -#include "HybridReadCancellationSpec.hpp" +#include namespace margelo::nitro::nitrosqlite { /** The native token created by NitroSQLite for one asynchronous read. */ class HybridReadCancellation final : public HybridReadCancellationSpec { public: - HybridReadCancellation() : HybridObject(TAG) {} - /** Request cancellation without accessing the connection's SQLite handle. */ void cancel() override { state->cancel(); diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp index c3758d0ad..2771e8e9f 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/SQLiteConnectionOperation.hpp @@ -16,14 +16,14 @@ namespace margelo::nitro::nitrosqlite { */ template Promise enqueueConnectionOperation(const SQLiteConnectionPtr& connection, Operation&& operation, - const std::shared_ptr& cancellation = nullptr, - std::function onRejected = {}) { + const std::shared_ptr& cancellation = nullptr, + std::function onRejected = {}) { auto promise = Promise::pending(); - const auto reject = [promise, onRejected = std::move(onRejected)](const std::exception_ptr& error) { + const auto reject = [promise, onRejected = std::move(onRejected)](std::exception_ptr error) { if (onRejected) { onRejected(); } - promise.reject(error); + promise.reject(std::move(error)); }; try { auto run = [promise, reject, cancellation, operation = std::forward(operation)]() mutable { @@ -54,8 +54,7 @@ Promise enqueueConnectionOperation(const SQLiteConnectionPtr& connection } }; if (cancellation) { - connection->enqueueAsync(std::move(run), cancellation, - [reject] { reject(std::make_exception_ptr(SQLiteException::Cancelled())); }); + connection->enqueueAsync(std::move(run), cancellation, [reject] { reject(std::make_exception_ptr(SQLiteException::Cancelled())); }); } else { connection->enqueueAsync(std::move(run)); } diff --git a/packages/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index d5260f953..027bf4c5f 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -33,8 +33,8 @@ export { open } from './operations/session' export { SQLiteError, SQLiteExceptionType, - SQLiteError, - SQLiteExceptionType, + NitroSQLiteError, + NitroSQLiteExceptionType, } from './errors' export type { DatabaseQueueKey } from './DatabaseQueue' export type { NitroSQLite as NativeSQLite } from './specs/NitroSQLite.nitro' diff --git a/packages/nitro-sqlite-core/src/operations/execute.ts b/packages/nitro-sqlite-core/src/operations/execute.ts index 7018d4f05..d1af802b0 100644 --- a/packages/nitro-sqlite-core/src/operations/execute.ts +++ b/packages/nitro-sqlite-core/src/operations/execute.ts @@ -83,7 +83,7 @@ export function executeAsync( ): Promise> { const signal = options?.signal if (!isDatabaseOpen(dbName)) { - return executeAsyncNative(dbName, query, params, signal) + return executeAsyncNative(dbName, query, params, undefined, signal) } return executeAsyncManaged(dbName, query, params, dbName, signal) @@ -98,7 +98,7 @@ export function executeAsyncManaged( ): Promise> { return queueStatementAsync( queueKey, - () => executeAsyncNative(dbName, query, params, signal), + () => executeAsyncNative(dbName, query, params, undefined, signal), signal, ) } @@ -108,10 +108,32 @@ export function executeAsyncNative( query: string, params?: SQLiteQueryParams, requireTransaction?: boolean, + signal?: AbortSignal, +): Promise> { + if (signal !== undefined) { + return runWithReadCancellation(signal, (cancellation) => + executeAsyncWithRows( + dbName, + query, + params, + requireTransaction, + cancellation, + ), + ) + } + return executeAsyncWithRows(dbName, query, params, requireTransaction) +} + +function executeAsyncWithRows( + dbName: string, + query: string, + params?: SQLiteQueryParams, + requireTransaction?: boolean, + cancellation?: ReadCancellation, ): Promise> { // Not `async`: every extra promise layer is a measurable part of a short query's cost. // Large results arrive in batches, so rows are converted while SQLite reads the rest. - if (!hasRowBatchHandler) { + if (!hasRowBatchHandler && cancellation === undefined) { return executeAsyncWithRowCallback( dbName, query, @@ -124,22 +146,33 @@ export function executeAsyncNative( pendingRowBatches.set(rowBatchId, batches) let nativeResult: Promise try { - nativeResult = requireTransaction - ? HybridNitroSQLite.executeAsync( - dbName, - query, - params, - undefined, - rowBatchId, - true, - ) - : HybridNitroSQLite.executeAsync( - dbName, - query, - params, - undefined, - rowBatchId, - ) + nativeResult = + cancellation !== undefined + ? HybridNitroSQLite.executeAsync( + dbName, + query, + params, + undefined, + rowBatchId, + requireTransaction, + cancellation, + ) + : requireTransaction + ? HybridNitroSQLite.executeAsync( + dbName, + query, + params, + undefined, + rowBatchId, + true, + ) + : HybridNitroSQLite.executeAsync( + dbName, + query, + params, + undefined, + rowBatchId, + ) } catch (error) { pendingRowBatches.delete(rowBatchId) return Promise.reject(SQLiteError.fromError(error)) @@ -184,7 +217,6 @@ function nextRowBatchId(): number { }) } lastRowBatchId++ - leadingRowBatches.set(lastRowBatchId, undefined) return lastRowBatchId } @@ -330,7 +362,7 @@ export function executeRawAsync( ): Promise { const signal = options?.signal if (!isDatabaseOpen(dbName)) { - return executeRawAsyncNative(dbName, query, params, signal) + return executeRawAsyncNative(dbName, query, params, undefined, signal) } return executeRawAsyncManaged(dbName, query, params, dbName, signal) @@ -345,7 +377,7 @@ export function executeRawAsyncManaged( ): Promise { return queueStatementAsync( queueKey, - () => executeRawAsyncNative(dbName, query, params, signal), + () => executeRawAsyncNative(dbName, query, params, undefined, signal), signal, ) } @@ -355,10 +387,17 @@ export function executeRawAsyncNative( query: string, params?: SQLiteQueryParams, requireTransaction?: boolean, + signal?: AbortSignal, ): Promise { if (signal !== undefined) { return runWithReadCancellation(signal, (cancellation) => - HybridNitroSQLite.executeRawAsync(dbName, query, params, cancellation), + HybridNitroSQLite.executeRawAsync( + dbName, + query, + params, + requireTransaction, + cancellation, + ), ) } return callNativeAsync(() => diff --git a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index 4a0a734e2..461cf8619 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -10,7 +10,7 @@ import type { NativeQueryResultBinding, NativeQueryRows, NativeRawQueryResult, -} from './NativeQueryResultBinding' +} from './NativeQueryResult' import type { PreparedStatement } from './PreparedStatement.nitro' import type { ReadCancellation } from './ReadCancellation.nitro' diff --git a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts index 712fc22f6..36f362157 100644 --- a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts @@ -4,7 +4,7 @@ import type { ReadCancellation } from './ReadCancellation.nitro' import type { NativeQueryResultBinding, NativeRawQueryResult, -} from './NativeQueryResultBinding' +} from './NativeQueryResult' export * from '#nitro/PreparedStatement' diff --git a/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts b/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts index b1f1520c6..e2cfcd0eb 100644 --- a/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/ReadCancellation.nitro.ts @@ -1,8 +1,23 @@ -import type { HybridObject } from 'nitro-core' +import { Android, iOS, type HybridObject } from 'nitro-core' + +export * from '#nitro/ReadCancellation' /** Single-use cancellation token created by `NitroSQLite.native.createReadCancellation()`. */ -export interface ReadCancellation - extends HybridObject<{ ios: 'c++'; android: 'c++' }> { +@iOS({ + language: 'c++', + implementation: { + className: 'HybridReadCancellation', + include: '"hybridObjects/HybridReadCancellation.hpp"', + }, +}) +@Android({ + language: 'c++', + implementation: { + className: 'HybridReadCancellation', + include: '"hybridObjects/HybridReadCancellation.hpp"', + }, +}) +export declare class ReadCancellation extends HybridObject { /** Cancel the associated read. Calling this again or after native completion has no effect. */ cancel(): void } diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake index eac5b3282..552f7c191 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake @@ -15,6 +15,7 @@ target_sources(RNNitroSQLite PRIVATE "${CMAKE_CURRENT_LIST_DIR}/RNNitroSQLiteOnLoad.cpp" "${CMAKE_CURRENT_LIST_DIR}/../android/c++/HybridNitroSQLiteSpecClass.cpp" "${CMAKE_CURRENT_LIST_DIR}/../android/c++/HybridPreparedStatementSpecClass.cpp" + "${CMAKE_CURRENT_LIST_DIR}/../android/c++/HybridReadCancellationSpecClass.cpp" "${CMAKE_CURRENT_LIST_DIR}/../android/c++/JHybridPlatformContextSpec.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/BatchQueryCommand.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/BatchQueryResult.cpp" @@ -22,6 +23,7 @@ target_sources(RNNitroSQLite PRIVATE "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/FileLoadResult.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridNitroSQLiteSpec.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridPreparedStatementSpec.cpp" + "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridReadCancellationSpec.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NativeRawQueryResult.cpp" ) diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLiteOnLoad.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLiteOnLoad.cpp index 5dc623166..c95e0dd2f 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLiteOnLoad.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLiteOnLoad.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace margelo::nitro::rnnitrosqlite { void registerAllNatives() { @@ -18,5 +19,6 @@ namespace margelo::nitro::rnnitrosqlite { HybridClassRegistry::registerHybridClass("rnnitrosqlite.NitroSQLite", HybridNitroSQLiteSpec::Class::get()); HybridClassRegistry::registerHybridClass("rnnitrosqlite.PlatformContext", JHybridPlatformContextSpec::Class::get()); HybridClassRegistry::registerHybridClass("rnnitrosqlite.PreparedStatement", HybridPreparedStatementSpec::Class::get()); + HybridClassRegistry::registerHybridClass("rnnitrosqlite.ReadCancellation", HybridReadCancellationSpec::Class::get()); } } diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp index 943d77455..202e766da 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp @@ -13,13 +13,14 @@ #include #include #include +#include +#include #include #include "SQLiteQueryResults.hpp" #include #include #include #include -#include #include #include #include @@ -51,6 +52,7 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridMethod("attach", &HybridNitroSQLiteSpec::attach); clazz.registerHybridMethod("detach", &HybridNitroSQLiteSpec::detach); clazz.registerHybridMethod("execute", &HybridNitroSQLiteSpec::execute); + clazz.registerHybridMethod("createReadCancellation", &HybridNitroSQLiteSpec::createReadCancellation); clazz.registerHybridMethod("executeAsync", &HybridNitroSQLiteSpec::executeAsync); clazz.registerHybridMethod("setRowBatchHandler", &HybridNitroSQLiteSpec::setRowBatchHandler); clazz.registerHybridMethod("setChangeHandler", &HybridNitroSQLiteSpec::setChangeHandler); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp index 26c229a67..b4f937b1b 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridReadCancellationSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridReadCancellationSpecClass.cpp new file mode 100644 index 000000000..bd6957000 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridReadCancellationSpecClass.cpp @@ -0,0 +1,22 @@ +/// +/// HybridReadCancellationSpecClass.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include + + +namespace margelo::nitro::rnnitrosqlite { + + + + const std::shared_ptr& HybridReadCancellationSpec::Class::get() { + static const auto hybridClass = HybridClass::create([](HybridClass& clazz) { + clazz.registerHybridMethod("cancel", &HybridReadCancellationSpec::cancel); + }); + return hybridClass; + } + +} // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/RNNitroSQLiteAutolinking.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/RNNitroSQLiteAutolinking.cpp index 1ec737015..f8d43543e 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/RNNitroSQLiteAutolinking.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/RNNitroSQLiteAutolinking.cpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace margelo::nitro::rnnitrosqlite { void registerHybridClasses() { @@ -20,5 +21,6 @@ namespace margelo::nitro::rnnitrosqlite { HybridClassRegistry::registerHybridClass("rnnitrosqlite.NitroSQLite", HybridNitroSQLiteSpec::Class::get()); HybridClassRegistry::registerHybridClass("rnnitrosqlite.PlatformContext", HybridPlatformContextSpec::Class::get()); HybridClassRegistry::registerHybridClass("rnnitrosqlite.PreparedStatement", HybridPreparedStatementSpec::Class::get()); + HybridClassRegistry::registerHybridClass("rnnitrosqlite.ReadCancellation", HybridReadCancellationSpec::Class::get()); } } // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp index 943d77455..202e766da 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp @@ -13,13 +13,14 @@ #include #include #include +#include +#include #include #include "SQLiteQueryResults.hpp" #include #include #include #include -#include #include #include #include @@ -51,6 +52,7 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridMethod("attach", &HybridNitroSQLiteSpec::attach); clazz.registerHybridMethod("detach", &HybridNitroSQLiteSpec::detach); clazz.registerHybridMethod("execute", &HybridNitroSQLiteSpec::execute); + clazz.registerHybridMethod("createReadCancellation", &HybridNitroSQLiteSpec::createReadCancellation); clazz.registerHybridMethod("executeAsync", &HybridNitroSQLiteSpec::executeAsync); clazz.registerHybridMethod("setRowBatchHandler", &HybridNitroSQLiteSpec::setRowBatchHandler); clazz.registerHybridMethod("setChangeHandler", &HybridNitroSQLiteSpec::setChangeHandler); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp index 26c229a67..b4f937b1b 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp @@ -14,6 +14,8 @@ #include #include #include +#include +#include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridReadCancellationSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridReadCancellationSpecClass.cpp new file mode 100644 index 000000000..bd6957000 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridReadCancellationSpecClass.cpp @@ -0,0 +1,22 @@ +/// +/// HybridReadCancellationSpecClass.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include + + +namespace margelo::nitro::rnnitrosqlite { + + + + const std::shared_ptr& HybridReadCancellationSpec::Class::get() { + static const auto hybridClass = HybridClass::create([](HybridClass& clazz) { + clazz.registerHybridMethod("cancel", &HybridReadCancellationSpec::cancel); + }); + return hybridClass; + } + +} // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/hybrid-classes.json b/packages/react-native-nitro-sqlite/nitrogen/generated/hybrid-classes.json index 3fd5b5b64..aa3766142 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/hybrid-classes.json +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/hybrid-classes.json @@ -47,6 +47,22 @@ }, "language": "c++" } + }, + "ReadCancellation": { + "android": { + "implementation": { + "className": "HybridReadCancellation", + "include": "\"hybridObjects/HybridReadCancellation.hpp\"" + }, + "language": "c++" + }, + "apple": { + "implementation": { + "className": "HybridReadCancellation", + "include": "\"hybridObjects/HybridReadCancellation.hpp\"" + }, + "language": "c++" + } } } } diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridReadCancellationSpec.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridReadCancellationSpec.cpp new file mode 100644 index 000000000..8e0b1081d --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridReadCancellationSpec.cpp @@ -0,0 +1,14 @@ +/// +/// HybridReadCancellationSpec.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include + +namespace margelo::nitro::rnnitrosqlite { + + HybridReadCancellationSpec::~HybridReadCancellationSpec() = default; + +} // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp index e583eeb41..42a447a6c 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp @@ -16,13 +16,15 @@ #include #include #include +#include +// Forward declaration of `HybridReadCancellationSpec` to properly resolve imports. +namespace margelo::nitro::rnnitrosqlite { class HybridReadCancellationSpec; } #include #include "SQLiteQueryResults.hpp" #include #include #include #include -#include // Forward declaration of `HybridPreparedStatementSpec` to properly resolve imports. namespace margelo::nitro::rnnitrosqlite { class HybridPreparedStatementSpec; } #include @@ -74,11 +76,12 @@ namespace margelo::nitro::rnnitrosqlite { virtual void attach(const std::string& mainDbName, const std::string& dbNameToAttach, const std::string& alias, const std::optional& location) = 0; virtual void detach(const std::string& mainDbName, const std::string& alias) = 0; virtual margelo::nitro::rnnitrosqlite::NativeQueryResult execute(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; - virtual Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional>& onRows, const std::optional& rowBatchId, const std::optional& requireTransaction) = 0; + virtual std::shared_ptr createReadCancellation() = 0; + virtual Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional>& onRows, const std::optional& rowBatchId, const std::optional& requireTransaction, const std::optional>& cancellation) = 0; virtual void setRowBatchHandler(const Callback& handler) = 0; virtual void setChangeHandler(const std::string& dbName, const std::optional& /* changes */)>>& handler) = 0; virtual NativeRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; - virtual Promise executeRawAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; + virtual Promise executeRawAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction, const std::optional>& cancellation) = 0; virtual std::shared_ptr prepare(const std::string& dbName, const std::string& query) = 0; virtual BatchQueryResult executeBatch(const std::string& dbName, const std::vector& commands) = 0; virtual Promise executeBatchAsync(const std::string& dbName, const std::vector& commands) = 0; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp index aa6819b49..326529075 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp @@ -17,6 +17,9 @@ #include #include #include +#include +// Forward declaration of `HybridReadCancellationSpec` to properly resolve imports. +namespace margelo::nitro::rnnitrosqlite { class HybridReadCancellationSpec; } #include namespace margelo::nitro::rnnitrosqlite { @@ -57,9 +60,9 @@ namespace margelo::nitro::rnnitrosqlite { public: // Methods virtual margelo::nitro::rnnitrosqlite::NativeQueryResult execute(const std::optional>>>& params) = 0; - virtual Promise executeAsync(const std::optional>>>& params) = 0; + virtual Promise executeAsync(const std::optional>>>& params, const std::optional>& cancellation) = 0; virtual NativeRawQueryResult executeRaw(const std::optional>>>& params) = 0; - virtual Promise executeRawAsync(const std::optional>>>& params) = 0; + virtual Promise executeRawAsync(const std::optional>>>& params, const std::optional>& cancellation) = 0; virtual void finalize() = 0; protected: diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridReadCancellationSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridReadCancellationSpec.hpp new file mode 100644 index 000000000..bedefb811 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridReadCancellationSpec.hpp @@ -0,0 +1,59 @@ +/// +/// HybridReadCancellationSpec.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include + +namespace margelo::nitro::rnnitrosqlite { + + using namespace margelo::nitro; + + /** + * An abstract base class for `ReadCancellation` + * Inherit this class to create instances of `HybridReadCancellationSpec` in C++. + * @example + * ```cpp + * class HybridReadCancellation : public HybridReadCancellationSpec { + * public: + * HybridReadCancellation(...) { ... } + * // ... + * }; + * ``` + */ + class HybridReadCancellationSpec : public virtual HybridObject { + public: + struct Class { + using Base = HybridObject::Class; + static constexpr const char* name = "ReadCancellation"; + static const std::shared_ptr& get(); + }; + + public: + // Constructor + HybridReadCancellationSpec() = default; + + // Destructor + ~HybridReadCancellationSpec() override; + + public: + // Properties + + + public: + // Methods + virtual void cancel() = 0; + + protected: + // Hybrid Setup + const std::shared_ptr& getHybridClass() override { + return Class::get(); + } + }; + +} // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.cjs b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.cjs new file mode 100644 index 000000000..52032add8 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.cjs @@ -0,0 +1,19 @@ +/// +/// ReadCancellation.cjs +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +const { NitroModules } = require('react-native-nitro-modules') + +let hybridClass + +module.exports = { + get ReadCancellation() { + if (hybridClass === undefined) { + hybridClass = NitroModules.getHybridClass('rnnitrosqlite.ReadCancellation') + } + return hybridClass + }, +} diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.d.cts b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.d.cts new file mode 100644 index 000000000..db7f628c8 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/javascript/ReadCancellation.d.cts @@ -0,0 +1,9 @@ +/// +/// ReadCancellation.d.cts +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +// The spec's `export declare class ReadCancellation` types this runtime export. +export {} diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts index 313adca0b..4a509c139 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/readCancellation.test.ts @@ -20,8 +20,6 @@ jest function mockCancellation(): ReadCancellation { return { - name: 'ReadCancellation', - toString: () => 'ReadCancellation', equals: () => false, dispose: jest.fn(), cancel: jest.fn(), @@ -141,6 +139,7 @@ it('passes the abort to the exact native token and detaches once the read reject dbName, query, undefined, + undefined, token, ) expect(token.cancel).toHaveBeenCalledTimes(1) From a98c5463e263be9acb1d8b7fcef9532f0869581f Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 13:16:14 +0100 Subject: [PATCH 6/6] fix: keep cancellation types portable across hosts Co-authored-by: Codex --- docs/scripts/check-api.mjs | 1 + .../specs/operations/readCancellation.spec.ts | 37 ++++++++++--------- .../nitro-sqlite-core/src/DatabaseQueue.ts | 7 ++-- packages/nitro-sqlite-core/src/mock.ts | 3 +- .../src/operations/execute.ts | 9 +++-- .../src/operations/readCancellation.ts | 3 +- packages/nitro-sqlite-core/src/types.ts | 28 +++++++++++++- 7 files changed, 61 insertions(+), 27 deletions(-) diff --git a/docs/scripts/check-api.mjs b/docs/scripts/check-api.mjs index 0af54a939..f3cfb5423 100644 --- a/docs/scripts/check-api.mjs +++ b/docs/scripts/check-api.mjs @@ -78,6 +78,7 @@ const requiredExports = { 'ConnectionOptions', 'QueryResult', 'ExecuteAsyncOptions', + 'ReadCancellationSignal', 'ReadCancellation', 'Transaction', 'BatchQueryCommand', diff --git a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts index e1d6b0e5d..3ef8d91a6 100644 --- a/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts +++ b/examples/shared/tests/unit/specs/operations/readCancellation.spec.ts @@ -3,9 +3,9 @@ import { SQLiteError, SQLiteExceptionType, open, -} from 'react-native-nitro-sqlite' -import { expect, it } from '@tests/TestApi' -import { TEST_DB_NAME, testDb } from '@tests/db' +} from '@example-sqlite/core' +import { expect, it } from '../../../TestApi' +import { TEST_DB_NAME, testDb } from '../../../db' const slowRead = ` WITH RECURSIVE numbers(value) AS ( @@ -32,7 +32,7 @@ export default function registerReadCancellationUnitTests() { ]) { expect( (await failureOf(testDb.executeRawAsync(sql, undefined, options))).type, - ).toBe(NitroSQLiteExceptionType.SqlExecutionError) + ).toBe(SQLiteExceptionType.SqlExecutionError) } expect( ( @@ -65,6 +65,7 @@ export default function registerReadCancellationUnitTests() { undefined, notifyFirstBatch, undefined, + undefined, activeToken, ), ) @@ -84,23 +85,20 @@ export default function registerReadCancellationUnitTests() { }) next = following controller.abort() - expect((await queued).type).toBe( - SQLiteExceptionType.OperationCancelled, - ) + expect((await queued).type).toBe(SQLiteExceptionType.OperationCancelled) expect((await independent.executeRawAsync('SELECT 9')).rows).toEqual([ [9], ]) activeToken.cancel() - expect((await active).type).toBe( - SQLiteExceptionType.OperationCancelled, - ) + expect((await active).type).toBe(SQLiteExceptionType.OperationCancelled) expect((await following).rows.item(0)).toEqual({ value: 3 }) const afterCompletion = native.createReadCancellation() await native.executeRawAsync( TEST_DB_NAME, 'SELECT 4', undefined, + undefined, afterCompletion, ) const afterAbort = testDb.executeRawAsync('SELECT 5') @@ -128,9 +126,7 @@ export default function registerReadCancellationUnitTests() { // This query returns no rows until its entire input has been read. const abort = setTimeout(() => controller.abort(), 25) try { - expect((await pending).type).toBe( - SQLiteExceptionType.OperationCancelled, - ) + expect((await pending).type).toBe(SQLiteExceptionType.OperationCancelled) expect( ( await prepared.executeRawAsync([4], { @@ -161,6 +157,7 @@ export default function registerReadCancellationUnitTests() { undefined, notifyStarted, undefined, + undefined, token, ), ) @@ -172,15 +169,21 @@ export default function registerReadCancellationUnitTests() { token.cancel() native.close(name) isOpen = false - expect((await active).type).toBe( - NitroSQLiteExceptionType.OperationCancelled, - ) + expect((await active).type).toBe(SQLiteExceptionType.OperationCancelled) token.cancel() native.open(name) isOpen = true const next = native.createReadCancellation() expect( - (await native.executeRawAsync(name, 'SELECT 42', undefined, next)).rows, + ( + await native.executeRawAsync( + name, + 'SELECT 42', + undefined, + undefined, + next, + ) + ).rows, ).toEqual([[42]]) } finally { token.cancel() diff --git a/packages/nitro-sqlite-core/src/DatabaseQueue.ts b/packages/nitro-sqlite-core/src/DatabaseQueue.ts index ae9c8a3e7..0ae98a86a 100644 --- a/packages/nitro-sqlite-core/src/DatabaseQueue.ts +++ b/packages/nitro-sqlite-core/src/DatabaseQueue.ts @@ -1,3 +1,4 @@ +import type { ReadCancellationSignal } from './types' import SQLiteError from './SQLiteError' import { readCancellationError } from './readCancellationError' @@ -73,7 +74,7 @@ export function getDatabaseQueue(dbName: DatabaseQueueKey) { export function queueOperationAsync( dbName: DatabaseQueueKey, callback: () => Promise, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise { return enqueueOperation(dbName, 'exclusive', callback, signal) } @@ -81,7 +82,7 @@ export function queueOperationAsync( export function queueStatementAsync( dbName: DatabaseQueueKey, callback: () => Promise, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise { return enqueueOperation(dbName, 'statement', callback, signal) } @@ -98,7 +99,7 @@ function enqueueOperation( dbName: DatabaseQueueKey, kind: 'statement' | 'exclusive', callback: () => Promise, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise { if (signal?.aborted) return Promise.reject(readCancellationError(signal?.reason)) diff --git a/packages/nitro-sqlite-core/src/mock.ts b/packages/nitro-sqlite-core/src/mock.ts index 393c903a0..41402649e 100644 --- a/packages/nitro-sqlite-core/src/mock.ts +++ b/packages/nitro-sqlite-core/src/mock.ts @@ -1,3 +1,4 @@ +import type { ReadCancellationSignal } from './types' /** * Adapted from the Onyx SQLite mock originally authored by Hubert Sosinski. * https://github.com/Expensify/react-native-onyx/blob/main/tests/unit/mocks/sqliteMock.ts @@ -78,7 +79,7 @@ export function open(options: ConnectionOptions): MockConnection { const runAsync = async ( callback: () => Result, exclusive = false, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ) => { const enqueue = exclusive ? queueOperationAsync : queueStatementAsync return enqueue( diff --git a/packages/nitro-sqlite-core/src/operations/execute.ts b/packages/nitro-sqlite-core/src/operations/execute.ts index d1af802b0..baa75785f 100644 --- a/packages/nitro-sqlite-core/src/operations/execute.ts +++ b/packages/nitro-sqlite-core/src/operations/execute.ts @@ -1,3 +1,4 @@ +import type { ReadCancellationSignal } from '../types' import { HybridNitroSQLite } from '../nitro' import type { ExecuteAsyncOptions, @@ -94,7 +95,7 @@ export function executeAsyncManaged( query: string, params?: SQLiteQueryParams, queueKey: DatabaseQueueKey = dbName, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise> { return queueStatementAsync( queueKey, @@ -108,7 +109,7 @@ export function executeAsyncNative( query: string, params?: SQLiteQueryParams, requireTransaction?: boolean, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise> { if (signal !== undefined) { return runWithReadCancellation(signal, (cancellation) => @@ -373,7 +374,7 @@ export function executeRawAsyncManaged( query: string, params: SQLiteQueryParams | undefined, queueKey: DatabaseQueueKey, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise { return queueStatementAsync( queueKey, @@ -387,7 +388,7 @@ export function executeRawAsyncNative( query: string, params?: SQLiteQueryParams, requireTransaction?: boolean, - signal?: AbortSignal, + signal?: ReadCancellationSignal, ): Promise { if (signal !== undefined) { return runWithReadCancellation(signal, (cancellation) => diff --git a/packages/nitro-sqlite-core/src/operations/readCancellation.ts b/packages/nitro-sqlite-core/src/operations/readCancellation.ts index 3fa5d7dc7..9b08b3437 100644 --- a/packages/nitro-sqlite-core/src/operations/readCancellation.ts +++ b/packages/nitro-sqlite-core/src/operations/readCancellation.ts @@ -1,3 +1,4 @@ +import type { ReadCancellationSignal } from '../types' import { HybridNitroSQLite } from '../nitro' import { callNativeAsync } from '../nativePromise' import SQLiteError, { SQLiteExceptionType } from '../SQLiteError' @@ -5,7 +6,7 @@ import { readCancellationError } from '../readCancellationError' import type { ReadCancellation } from '../specs/ReadCancellation.nitro' export function runWithReadCancellation( - signal: AbortSignal, + signal: ReadCancellationSignal, run: (cancellation: ReadCancellation) => Promise, ): Promise { if (signal.aborted) diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 4aa21c1ed..f43f385b6 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -179,6 +179,32 @@ export type SQLiteValue = */ export type SQLiteQueryParams = SQLiteValue[] +/** The part of a standard `AbortSignal` used to cancel a read. + * Browser, React Native, and Node `AbortController.signal` values satisfy this interface. + * Standalone consumers do not need DOM or Node global type declarations. + */ +export interface ReadCancellationSignal { + /** Whether cancellation was requested before or during this read. */ + readonly aborted: boolean + /** Original cancellation reason, preserved as the rejected SQLiteError's cause. */ + readonly reason?: unknown + /** Subscribe to cancellation for the lifetime of this read. + * @param type The abort event. + * @param listener Callback invoked when cancellation is requested. + * @param options Use `once` to remove the listener after its first call. + */ + addEventListener( + type: 'abort', + listener: () => void, + options?: { once?: boolean }, + ): void + /** Unsubscribe when the read settles. + * @param type The abort event. + * @param listener Previously registered callback. + */ + removeEventListener(type: 'abort', listener: () => void): void +} + /** Options for asynchronous reads on a connection or prepared statement. */ export interface ExecuteAsyncOptions { /** Cancels this execution. When supplied, only read queries outside an explicit @@ -189,7 +215,7 @@ export interface ExecuteAsyncOptions { * also rejects with `SqlExecutionError` and leaves that transaction intact. * An abort after native completion has no effect. */ - signal?: AbortSignal + signal?: ReadCancellationSignal } /** A row keyed by result column names. */