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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/content/docs/guides/node-test-mock.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -149,3 +151,8 @@ 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 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.
7 changes: 5 additions & 2 deletions docs/content/docs/guides/parameters-and-results.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
2 changes: 2 additions & 0 deletions docs/content/docs/guides/prepared-statements.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 46 additions & 0 deletions docs/content/docs/guides/sync-and-async.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,49 @@ 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 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.

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

<span id="ordering-on-one-connection" />
Expand Down Expand Up @@ -76,3 +119,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.

13 changes: 11 additions & 2 deletions docs/scripts/check-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ const requiredExports = {
'Connection',
'ConnectionOptions',
'QueryResult',
'ExecuteAsyncOptions',
'ReadCancellationSignal',
'ReadCancellation',
'Transaction',
'BatchQueryCommand',
'SQLiteError',
Expand Down Expand Up @@ -189,8 +192,12 @@ const requiredMembers = {
'executeRaw',
'executeRawAsync',
],
ExecuteAsyncOptions: ['signal'],
ReadCancellation: ['cancel'],
SQLiteExceptionType: ['OperationCancelled'],
SQLiteError: ['type', 'fromError'],
NativeSQLite: [
'createReadCancellation',
'open',
'openConnection',
'close',
Expand Down Expand Up @@ -235,7 +242,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 ?? []

Expand Down Expand Up @@ -441,7 +450,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}`,
Expand Down
5 changes: 5 additions & 0 deletions examples/shared/tests/unit/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading