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
2 changes: 2 additions & 0 deletions docs/content/docs/guides/node-test-mock.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ test('opens a temporary database', () => {
})
```

The mock also supports the [lazy row API](/docs/guides/parameters-and-results#convert-rows-on-demand). It reads rows into JavaScript during execution and exposes them through `rows.item()` and `rows.toArray()`.

## Share a database between connections

Connections with the same `name` and `location` open the same temporary file. A default connection reserves its name until you close it. Set `connection: 'independent'` to open another handle, and `readOnly: true` to prevent writes. Read-only opens fail if the file does not exist.
Expand Down
28 changes: 28 additions & 0 deletions docs/content/docs/guides/parameters-and-results.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,34 @@ SQLite INTEGER and REAL result values both arrive as JavaScript numbers. BLOB va

SQLite uses the alias in `AS` as the result column name. Each column in a native NitroSQLite result is an own enumerable property of the row object. An alias such as `__proto__` holds the column value, and the row still inherits from `Object.prototype`.

## Convert rows on demand

SQLite produces rows one at a time as it advances a statement. NitroSQLite can read those rows into native memory, finish the statement, and then convert each row to a JavaScript object when you need it. This is useful when a query returns many rows and a screen reads only a small subset.

```ts
const { rows } = await db.executeLazyAsync<{ id: number; name: string }>(
'SELECT id, name FROM people WHERE age >= ? ORDER BY id',

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex: Please say that lazy rows only offer length, item() and toArray(): no index access, no iteration, and no _array, and that JSON.stringify(result) doesn't include the rows. The eager example just above uses rows._array, so readers will try the same here.

[18],
)

console.log(rows.length)
const firstPerson = rows.item(0)
```

`rows.length` counts the rows without converting them. `rows.item(index)` converts and caches a row on first access. It returns `undefined` for an invalid index. Use `rows.toArray()` to convert all remaining rows and get a new array in query order. Each element is the same object you get from `rows.item(index)`. The result also carries `rowsAffected`, `insertId`, and column `metadata`.

Lazy `rows` only exposes `length`, `item()` and `toArray()`. It has no numeric index access or `_array`, and it cannot be iterated with `for...of` or spread. `JSON.stringify(result)` includes `rows.length` but omits row values. Convert the rows explicitly when serializing them:

```ts
const result = db.executeLazy('SELECT id, name FROM people')
const json = JSON.stringify({ ...result, rows: result.rows.toArray() })
```

SQLite steps through the entire result before `executeLazy()` returns or `executeLazyAsync()` resolves. Unconverted rows occupy native memory while you hold the rows object or either accessor. Conversion releases each native row. Converting every row also releases the outer positional storage. Each cached row occupies JavaScript memory and keeps any BLOB buffers it references. If you drop a partially read result, garbage collection determines when its remaining native storage is released. You can read the rows after closing the connection or finalizing a prepared statement. Use SQL filters or pagination when you need to bound the number of rows SQLite reads and stores.

Both lazy methods accept the same positional values as the eager methods. They are available on managed connections, transaction handles, prepared statements, and the name-based `NitroSQLite` helpers. For the exact managed result type, see [`LazyQueryResult`](/api/react-native-nitro-sqlite/type-aliases/LazyQueryResult).


## Rows as arrays

A row object holds one value per column name, so when two result columns share a name, the later value replaces the earlier one. This happens in joins such as `SELECT users.id, pets.id ...`. `db.executeRaw()` and `db.executeRawAsync()` take the same arguments as `execute()` and `executeAsync()` but return each row as an array of values in column order, so every column is kept.
Expand Down
10 changes: 6 additions & 4 deletions docs/content/docs/guides/prepared-statements.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Prepared statements
description: Reuse a compiled SQL statement with different bound values.
---

Call `db.prepare(query)` to reuse SQL with different parameter values. It returns a statement with `execute(params)`, `executeAsync(params)`, `isFinalized`, and `finalize()`, plus `executeRaw(params)` and `executeRawAsync(params)` for [rows as arrays](/docs/guides/parameters-and-results#rows-as-arrays). Preparation is synchronous and throws if the connection has work pending or running. For a query that runs only once, use `db.execute()` or `db.executeAsync()`. See [parameters and prepared statements](/docs/concepts/queries-and-indexes#parameters-and-prepared-statements) for the SQLite concept.
Call `db.prepare(query)` to reuse SQL with different parameter values. It returns a statement with `execute(params)`, `executeAsync(params)`, `isFinalized`, and `finalize()`, plus `executeRaw(params)` and `executeRawAsync(params)` for [rows as arrays](/docs/guides/parameters-and-results#rows-as-arrays). Use `executeLazy(params)` or `executeLazyAsync(params)` for [on-demand row conversion](/docs/guides/parameters-and-results#convert-rows-on-demand). Preparation is synchronous and throws if the connection has work pending or running. For a query that runs only once, use `db.execute()` or `db.executeAsync()`. See [parameters and prepared statements](/docs/concepts/queries-and-indexes#parameters-and-prepared-statements) for the SQLite concept.

Examples use `react-native-nitro-sqlite` for React Native. In NitroUI, import from `nitro-sqlite` with the same APIs. See [supported platforms](/docs/supported-platforms).

Expand All @@ -30,7 +30,7 @@ Pass a positional array for the SQL's `?` placeholders on each execution. The [p

## Read rows and run asynchronously

Both execution methods return the same [query result](/docs/guides/parameters-and-results) as the connection's `execute` methods. Give a row type when you want typed access to `rows._array` or `rows.item()`; the type does not validate SQLite values at runtime.
`execute()` and `executeAsync()` return the same [query result](/docs/guides/parameters-and-results) as the connection's `execute` methods. Give a row type when you want typed access to `rows._array` or `rows.item()`; the type does not validate SQLite values at runtime.

```ts
const findNote = db.prepare('SELECT id, body FROM notes WHERE id = ?')
Expand All @@ -48,11 +48,13 @@ 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.

The lazy methods finish reading SQLite before returning the completed result. `executeLazyAsync()` resolves before JavaScript row conversion, which happens synchronously through `rows.item()` or `rows.toArray()`. Rows remain readable after statement reuse or finalization.

## 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.
On a managed connection, `executeAsync()`, `executeRawAsync()` and `executeLazyAsync()` run in submission order with the connection's other async calls. Each call waits for earlier work, and later work starts only after it completes. While async work is pending, synchronous `prepare()`, `execute()`, `executeRaw()`, `executeLazy()`, `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.

Do not await a prepared statement's `executeAsync()` from inside `db.transaction()` on the same connection. It waits behind the transaction, while the transaction waits for your callback. Use the callback's `tx.execute()` or `tx.executeAsync()` instead. See [transactions](/docs/guides/transactions) and [connection ordering](/docs/guides/sync-and-async#connection-ordering).
Do not await a prepared statement's async execution methods from inside `db.transaction()` on the same connection. Those calls wait behind the transaction, while the transaction waits for your callback. Use the callback's `tx.execute()` or `tx.executeAsync()` instead. See [transactions](/docs/guides/transactions) and [connection ordering](/docs/guides/sync-and-async#connection-ordering).

## Choose the right query form

Expand Down
6 changes: 3 additions & 3 deletions docs/content/docs/guides/sync-and-async.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: Pick the query form that fits your workload and understand connecti

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](/docs/guides/prepared-statements) has `execute()` and `executeAsync()` for repeated SQL.
`executeLazy`, `executeRaw`, `executeBatch`, and `loadFile` also have matching `Async` methods. A [prepared statement](/docs/guides/prepared-statements) has `execute()` and `executeAsync()` for repeated SQL.

Examples use `react-native-nitro-sqlite` for React Native. In NitroUI, import from `nitro-sqlite` with the same APIs. See [supported platforms](/docs/supported-platforms).

Expand Down Expand Up @@ -51,11 +51,11 @@ See [prepared statements](/docs/guides/prepared-statements#connection-ordering-a

## Global helpers and native access

The [`NitroSQLite` export](/api/react-native-nitro-sqlite/variables/NitroSQLite) 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](/api/react-native-nitro-sqlite/functions/open).
The [`NitroSQLite` export](/api/react-native-nitro-sqlite/variables/NitroSQLite) also has `execute`, `executeAsync`, `executeLazy`, `executeLazyAsync`, `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](/api/react-native-nitro-sqlite/functions/open).

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()`.
Without a default managed connection, global `execute`, `executeAsync`, `executeLazy`, `executeLazyAsync`, `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 [`NativeSQLite` hybrid object](/api/react-native-nitro-sqlite/hybrid-objects/NativeSQLite). 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 `SQLiteError`. 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.

Expand Down
10 changes: 6 additions & 4 deletions docs/content/docs/guides/transactions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Throw from the callback when an application check fails. Use `tx` for those chec

## Commit and rollback behavior

When the callback resolves, the wrapper commits unless you already called `tx.commit()` or `tx.rollback()`. When it rejects or throws, the wrapper rolls back unless the transaction has already been finalized. An explicit `tx.rollback()` does not itself reject the callback: it ends the transaction, and the callback can still resolve. Calls to `tx.execute`, `tx.executeAsync`, `tx.executeRaw`, `tx.executeRawAsync`, `tx.commit`, or `tx.rollback` after finalization throw.
When the callback resolves, the wrapper commits unless you already called `tx.commit()` or `tx.rollback()`. When it rejects or throws, the wrapper rolls back unless the transaction has already been finalized. An explicit `tx.rollback()` does not itself reject the callback: it ends the transaction, and the callback can still resolve. Calls to `tx.execute`, `tx.executeAsync`, `tx.executeRaw`, `tx.executeRawAsync`, `tx.executeLazy`, `tx.executeLazyAsync`, `tx.commit`, or `tx.rollback` after finalization throw.

A failed COMMIT can leave SQLite's transaction active, for example when a deferred foreign-key constraint fails. NitroSQLite marks a commit complete only after SQLite accepts it. A failed manual or automatic commit triggers rollback and rejects with the commit error. This also happens if the callback catches a failed `tx.commit()` and returns without explicitly rolling back. After the failure, only `tx.rollback()` is allowed on that transaction handle.

Expand All @@ -39,12 +39,12 @@ If rollback also fails, the rejection preserves the original message and appends

<span id="check-application-rules" />

The connection queue is occupied for the whole callback. Use the `tx` methods (`execute`, `executeAsync`, `executeRaw`, or `executeRawAsync`) for every statement on this database during that callback, including statements in helpers.
The connection queue is occupied for the whole callback. Use the `tx` methods (`execute`, `executeAsync`, `executeRaw`, `executeRawAsync`, `executeLazy`, or `executeLazyAsync`) for every statement on this database during that callback, including statements in helpers.

> [!TIP]
> Pass `tx` to any helper that runs statements during the transaction.

Awaiting `db.executeAsync()`, `db.executeBatchAsync()`, or another `db.transaction()` for the same database inside the callback deadlocks: those calls wait for the current transaction to leave the queue. A synchronous connection call fails with a busy error instead.
Awaiting `db.executeAsync()`, `db.executeRawAsync()`, `db.executeLazyAsync()`, `db.executeBatchAsync()`, or another `db.transaction()` for the same database inside the callback deadlocks: those calls wait for the current transaction to leave the queue. A synchronous connection call fails with a busy error instead.

```ts
await db.transaction(async (tx) => {
Expand All @@ -55,9 +55,11 @@ await db.transaction(async (tx) => {
})
```

Use `tx.executeLazy()` and `tx.executeLazyAsync()` when you need [on-demand row conversion](/docs/guides/parameters-and-results#convert-rows-on-demand). They finish reading SQLite within the transaction. The completed rows remain readable after commit or rollback.

## Await pending statements

Await every `tx.executeAsync()` and `tx.executeRawAsync()` before the callback returns or before manually finalizing. While an async statement is pending, `tx.execute()`, `tx.executeRaw()`, `tx.commit()`, and `tx.rollback()` throw instead of running out of order. If the callback throws, the wrapper waits for pending async statements before rolling back. A thrown error after an explicit commit or rollback cannot undo that completed transaction.
Await every `tx.executeAsync()`, `tx.executeRawAsync()` and `tx.executeLazyAsync()` before the callback returns or before manually finalizing. While an async statement is pending, `tx.execute()`, `tx.executeRaw()`, `tx.executeLazy()`, `tx.commit()`, and `tx.rollback()` throw instead of running out of order. If the callback throws, the wrapper waits for pending async statements before rolling back. A thrown error after an explicit commit or rollback cannot undo that completed transaction.

`tx.commit()` and `tx.rollback()` are synchronous. Their declared return type exposes the native query result fields. The JavaScript helper also adds `rows` at runtime, but that field is not in their declared type. Use them to finalize the transaction, not to retrieve rows. The transaction starts with `BEGIN TRANSACTION`, which runs synchronously like `COMMIT` because a deferred `BEGIN` takes no lock. The global [`NitroSQLite.transaction`](/api/react-native-nitro-sqlite/variables/NitroSQLite) helper also accepts `isExclusive` to use `BEGIN EXCLUSIVE TRANSACTION`, which runs on the connection's background thread because it can wait for another connection's lock. See [transaction modes](/docs/concepts/transactions#transaction-modes) for the SQLite differences.

Expand Down
7 changes: 7 additions & 0 deletions docs/releases/lazy-queries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Lazy queries let you convert completed result rows to JavaScript when you read them. Use `executeLazy()` or `executeLazyAsync()` on connections, transactions and prepared statements. `rows.item(index)` caches each row, and `rows.toArray()` converts the full result.

Lazy rows expose `length`, `item()` and `toArray()`. They have no `_array`, numeric index access or iterator. Convert them with `toArray()` before serializing row values as JSON. SQLite reads the entire result before returning it, so use SQL filters or pagination to bound native storage.

## Type compatibility

`NitroSQLiteConnection`, `Transaction` and `PreparedStatement` require `executeLazy` and `executeLazyAsync`. Custom implementations and test doubles must provide these methods when upgrading. Existing eager query methods keep their result shape.
Loading
Loading