NitroSQLite
Guides

Sync and async

Pick the query form that fits your workload and understand connection ordering.

Use db.execute() for a small query that needs an immediate result, and await db.executeAsync() for work that may take longer. A synchronous call blocks its JavaScript caller until SQLite finishes. An asynchronous call returns a promise and lets JavaScript continue while the database work runs in the background.

executeRaw, executeBatch, and loadFile also have matching Async methods. A prepared statement has execute() and executeAsync() for repeated SQL.

import { open } from 'react-native-nitro-sqlite'

const db = open({ name: 'app.sqlite' })
db.execute('CREATE TABLE IF NOT EXISTS notes (body TEXT NOT NULL)')

const smallResult = db.execute('SELECT 1 AS value')
const largerResult = await db.executeAsync('SELECT * FROM notes')

console.log(smallResult.results, largerResult.results)

Use synchronous calls when immediate results are useful and the work is small. Prefer async calls for queries that may scan many rows, batches, or file imports. Performance guidance covers other ways to keep work bounded.

executeAsync() resolves once with the complete result in row order. Returning many rows still costs JavaScript work, so paginate large results.

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:

import {
  NitroSQLiteError,
  NitroSQLiteExceptionType,
} 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 NitroSQLiteError) ||
    error.type !== NitroSQLiteExceptionType.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. 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

Calls on one open() connection run one at a time in submission order. Await a write before a read that depends on it so you can handle write errors. Batches, transactions, and prepared statement executions wait for preceding work and reserve the connection until complete. A synchronous operation, close(), or delete() throws a busy error if work is pending or active. Await async work before calling a synchronous method on that connection:

await db.executeAsync('INSERT INTO notes (body) VALUES (?)', ['Queued write'])
const total = db
  .execute<{ total: number }>('SELECT COUNT(*) AS total FROM notes')
  .rows.item(0)?.total
console.log(total)

Inside db.transaction(), use the callback's tx methods. Calling and awaiting another async operation on the same db leaves it waiting for the callback to finish. See transactions for that restriction and multiple connections for work that can run independently.

See prepared statements for statement cleanup.

Global helpers and native access

The NitroSQLite export also has execute, executeAsync, executeRaw, executeRawAsync, prepare, executeBatch, executeBatchAsync, and transaction helpers that take a database name. NitroSQLite.open(options) is the same helper as the named open() export.

Global queries join the default connection's JavaScript queue when the name was opened through open(). This includes NitroSQLite.executeRaw(dbName, query, params) and NitroSQLite.executeRawAsync(dbName, query, params). A synchronous query throws while that connection is busy; an asynchronous query waits for an active transaction to finish. Global helpers do not address independent connections; use the object returned by open() for those.

Without a default managed connection, global execute, executeAsync, executeRaw, and executeRawAsync call the native methods directly and still need an open native database handle. Global prepare, batches, and transactions need a default connection opened through open().

NitroSQLite.native exposes the underlying NitroSQLiteNative hybrid object. Its methods take a database name and return raw results without the connection helper's rows container. They also throw native errors without converting them to NitroSQLiteError. Its executeAsync() accepts an optional onRows callback that receives leading rows in batches, in order; the resolved results then holds only the rows after the last batch. The promise can resolve before the last batches reach the callback, so wait until the number of rows in the result's batchedRowCount has arrived before you use the rows. The managed API sends those batches to one handler set with setRowBatchHandler() instead of passing a callback per query, so don't replace that handler while you also use the managed API. That handler receives a query's next batch only after it has returned for the previous one, so frames can render between batches of a large result even when SQLite reads rows faster than JavaScript converts them.

import { NitroSQLite } from 'react-native-nitro-sqlite'

NitroSQLite.native.open('raw.sqlite')
try {
  const result = NitroSQLite.native.execute('raw.sqlite', 'SELECT 1 AS value')
  console.log(result.results[0]?.value)
} finally {
  NitroSQLite.native.close('raw.sqlite')
}

Native calls bypass the JavaScript queue. If you use them alongside an open() connection, coordinate access yourself. A native statement can run inside an active connection transaction without joining its callback's sequence. The raw result is a plain JavaScript object with rowsAffected, insertId, results, and metadata; ordinary garbage collection reclaims it. NitroSQLite.native itself is a Nitro hybrid object with a dispose() member. Do not dispose that shared instance during normal database cleanup; dispose() is not a database close() call.

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.

Call raw methods through NitroSQLite.native. Keep the shared threadSafe setting enabled when work can run across multiple database connections.

On this page