diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index 400fee17..a85a6f7c 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -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. diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 83b19a89..263902eb 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -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', + [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. diff --git a/docs/content/docs/guides/prepared-statements.mdx b/docs/content/docs/guides/prepared-statements.mdx index 4b321cf8..8018ad28 100644 --- a/docs/content/docs/guides/prepared-statements.mdx +++ b/docs/content/docs/guides/prepared-statements.mdx @@ -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). @@ -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 = ?') @@ -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 diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index 2df9e78f..6dacb728 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -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). @@ -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. diff --git a/docs/content/docs/guides/transactions.mdx b/docs/content/docs/guides/transactions.mdx index b7c1a6d4..44f507fe 100644 --- a/docs/content/docs/guides/transactions.mdx +++ b/docs/content/docs/guides/transactions.mdx @@ -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. @@ -39,12 +39,12 @@ If rollback also fails, the rejection preserves the original message and appends -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) => { @@ -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. diff --git a/docs/releases/lazy-queries.md b/docs/releases/lazy-queries.md new file mode 100644 index 00000000..6b4147c9 --- /dev/null +++ b/docs/releases/lazy-queries.md @@ -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. diff --git a/docs/scripts/check-api.mjs b/docs/scripts/check-api.mjs index 97a1c684..5967cdc2 100644 --- a/docs/scripts/check-api.mjs +++ b/docs/scripts/check-api.mjs @@ -77,6 +77,9 @@ const requiredExports = { 'Connection', 'ConnectionOptions', 'QueryResult', + 'LazyQueryResult', + 'LazyQueryRows', + 'NativeLazyQueryResult', 'Transaction', 'BatchQueryCommand', 'SQLiteError', @@ -162,6 +165,8 @@ const requiredMembers = { 'executeAsync', 'executeRaw', 'executeRawAsync', + 'executeLazy', + 'executeLazyAsync', 'executeBatch', 'executeBatchAsync', ], @@ -175,6 +180,8 @@ const requiredMembers = { 'executeAsync', 'executeRaw', 'executeRawAsync', + 'executeLazy', + 'executeLazyAsync', 'executeBatch', 'executeBatchAsync', 'loadFile', @@ -188,7 +195,19 @@ const requiredMembers = { 'executeAsync', 'executeRaw', 'executeRawAsync', + 'executeLazy', + 'executeLazyAsync', ], + PreparedStatement: ['executeLazy', 'executeLazyAsync', 'finalize'], + NativePreparedStatement: ['executeLazy', 'executeLazyAsync', 'finalize'], + NitroSQLitePreparedStatement: [ + 'executeLazy', + 'executeLazyAsync', + 'finalize', + ], + LazyQueryRows: ['length', 'item', 'toArray'], + LazyQueryResult: ['rows'], + NativeLazyQueryResult: ['rows'], SQLiteError: ['type', 'fromError'], NativeSQLite: [ 'open', @@ -201,6 +220,8 @@ const requiredMembers = { 'executeAsync', 'executeRaw', 'executeRawAsync', + 'executeLazy', + 'executeLazyAsync', 'executeBatch', 'executeBatchAsync', 'loadFile', @@ -237,7 +258,17 @@ for (const [packageName, symbols] of Object.entries(requiredMembers)) { const symbol = packageReflection.children.find( (child) => child.name === name, ) - const actual = symbol?.type?.declaration?.children ?? symbol?.children ?? [] + const target = + symbol?.target === undefined + ? symbol + : packageReflection.children.find((child) => child.id === symbol.target) + const actual = + target?.type?.declaration?.children ?? + target?.children ?? + target?.type?.types?.flatMap( + (type) => type.declaration?.children ?? [], + ) ?? + [] for (const member of members) { assert.ok( diff --git a/examples/shared/benchmarks/readCases.ts b/examples/shared/benchmarks/readCases.ts index 60f643a4..10464fa3 100644 --- a/examples/shared/benchmarks/readCases.ts +++ b/examples/shared/benchmarks/readCases.ts @@ -10,6 +10,7 @@ import { const NARROW_ROWS = 10000 const WIDE_ROWS = 300000 const FRACTIONAL_ROWS = 100000 +const LAZY_COMPARISON_ROWS = 100000 const POINT_READS = 1000 const CHUNK_SIZE = 1000 const NARROW_SCHEMA = @@ -102,6 +103,16 @@ export const readCases: BenchmarkCase[] = [ label: '10k narrow rows · raw arrays read + access', setup: setupNarrowRawRead, }, + // Unread native rows survive until GC. Memory peaks can include earlier runs, + // especially for first/partial access, because this comparison does not force GC. + ...(['first', 'partial', 'full'] as const).flatMap((access) => + (['eager', 'lazy'] as const).map((mode) => ({ + id: `read-${mode}-${access}`, + label: `100k rows · ${mode} async · ${access} read`, + measuredRuns: 10, + setup: () => setupRowConversionComparison(mode, access), + })), + ), ] export function resetLargeDbSchema(db: Connection): void { @@ -245,6 +256,65 @@ async function setupNarrowRawRead(): Promise { } } +async function setupRowConversionComparison( + mode: 'eager' | 'lazy', + access: 'first' | 'partial' | 'full', +): Promise { + const db = createBenchmarkDatabase(`bench_${mode}_${access}`, NARROW_SCHEMA) + try { + await seedNarrowRows(db, LAZY_COMPARISON_ROWS) + const query = 'SELECT id, name, value FROM Bench ORDER BY id' + const consumed = { first: 1, partial: 64, full: LAZY_COMPARISON_ROWS }[ + access + ] + const expected = narrowChecksum(consumed) + let rowCount = 0 + let checksum = 0 + const add = (row: NarrowRow | undefined, index: number) => { + assertBenchmark(row?.id === index, 'Unexpected row order') + checksum += row.id + row.value + row.name.length + } + + return { + database: db, + run: async () => { + checksum = 0 + const started = performance.now() + const { rows } = + mode === 'lazy' + ? await db.executeLazyAsync(query) + : await db.executeAsync(query) + const first = rows.item(0) + const firstRowMs = performance.now() - started + rowCount = rows.length + if (access === 'full') { + const all = '_array' in rows ? rows._array : rows.toArray() + assertBenchmark( + all.length === consumed, + 'Wrong materialized row count', + ) + for (let i = 0; i < all.length; i++) add(all[i], i) + } else { + add(first, 0) + for (let i = 1; i < consumed; i++) add(rows.item(i), i) + } + return { firstRowMs } + }, + verify: () => { + assertBenchmark( + rowCount === LAZY_COMPARISON_ROWS, + 'Wrong query row count', + ) + assertBenchmark(checksum === expected, 'Wrong row conversion checksum') + }, + dispose: () => disposeBenchmarkDatabase(db), + } + } catch (error) { + disposeBenchmarkDatabase(db) + throw error + } +} + async function setupWideRead(asynchronous: boolean): Promise { const db = open({ name: asynchronous ? 'benchmark_wide_async' : 'benchmark_wide', @@ -356,17 +426,20 @@ async function setupFractionalRead(): Promise { } } -async function seedNarrowRows(db: Connection): Promise { +async function seedNarrowRows( + db: Connection, + rowCount = NARROW_ROWS, +): Promise { const params: SQLiteQueryParams[] = Array.from( - { length: NARROW_ROWS }, + { length: rowCount }, (_, i) => [i, `name_${i}`, i], ) await db.executeBatchAsync([{ query: NARROW_INSERT, params }]) } -function narrowChecksum(): number { +function narrowChecksum(rowCount = NARROW_ROWS): number { let sum = 0 - for (let i = 0; i < NARROW_ROWS; i++) sum += i * 2 + `name_${i}`.length + for (let i = 0; i < rowCount; i++) sum += i * 2 + `name_${i}`.length return sum } diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts index fc436ec6..0b2704dd 100644 --- a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -1,7 +1,7 @@ -import { NitroSQLite } from '@example-sqlite/core' +import { NitroSQLite, open } from '@example-sqlite/core' import { expect } from '../../common' import { it } from '../../../TestApi' -import { TEST_DB_NAME } from '../../../db' +import { TEST_DB_NAME, testDb } from '../../../db' export default function registerExecuteLazyUnitTests() { it('keeps metadata and row access valid for an empty native result', () => { @@ -18,6 +18,7 @@ export default function registerExecuteLazyUnitTests() { it('caches native async rows by index without invoking inherited setters', async () => { const key = 'nitroSQLiteLazyTestValue' let setterCalls = 0 + // eslint-disable-next-line no-extend-native -- Exercise inherited column setters. Object.defineProperty(Object.prototype, key, { configurable: true, set(this: object, value: unknown) { @@ -149,6 +150,42 @@ export default function registerExecuteLazyUnitTests() { expect(lazy.rows.item(0)?.payload).toBe(row?.payload) }) + for (const method of ['executeLazy', 'executeLazyAsync'] as const) { + it(`rejects ${method} writes after SQLite rolls back the transaction`, async () => { + let guardError: unknown + let transactionError: unknown + try { + await testDb.transaction(async (tx) => { + tx.execute( + "INSERT INTO User (id, name, age, networth) VALUES (1, 'Ada', 37, 1)", + ) + try { + tx.execute( + "INSERT OR ROLLBACK INTO User (id, name, age, networth) VALUES (1, 'Ada', 37, 1)", + ) + } catch { + // SQLite has rolled back, while the callback still owns the JS transaction. + } + try { + await tx[method]( + "INSERT INTO User (id, name, age, networth) VALUES (2, 'Grace', 40, 2)", + ) + } catch (error) { + guardError = error + } + }) + } catch (error) { + transactionError = error + } + expect( + guardError instanceof Error && + guardError.message.includes('ended the transaction'), + ).toBe(true) + expect(transactionError instanceof Error).toBe(true) + expect(testDb.execute('SELECT * FROM User').rows.length).toBe(0) + }) + } + it('keeps native prepared results after reuse and finalization', async () => { const statement = NitroSQLite.native.prepare(TEST_DB_NAME, 'SELECT ? AS x') const first = statement.executeLazy([1]) @@ -157,4 +194,49 @@ export default function registerExecuteLazyUnitTests() { expect(first.rows.item(0)).toEqual({ x: 1 }) expect(second.rows.item(0)).toEqual({ x: 2 }) }) + + it('supports managed transactions and leaves the eager result adapter intact', async () => { + const result = await testDb.transaction(async (tx) => { + const inserted = tx.executeLazy( + 'INSERT INTO User (id, name) VALUES (?, ?) RETURNING name', + [1, 'Ada'], + ) + expect(inserted.rowsAffected).toBe(1) + expect(inserted.rows.item(0)).toEqual({ name: 'Ada' }) + return tx.executeLazyAsync<{ name: string }>('SELECT name FROM User') + }) + expect(result.rows.item(0)?.name).toBe('Ada') + expect(result.rows.toArray()[0]).toBe(result.rows.item(0)) + + const eager = await testDb.executeAsync('SELECT name FROM User') + expect(eager.results).toBe(eager.results) + expect(eager.rows._array).toBe(eager.results) + expect(eager.rows.item(0)).toBe(eager.rows._array[0]) + expect(result.rows.toArray()).toEqual(eager.results) + }) + + it('keeps managed results after independent connections close', async () => { + const db = open({ name: TEST_DB_NAME, connection: 'independent' }) + const statement = db.prepare('SELECT ? AS value') + let fromStatement + let fromConnection + try { + fromStatement = await statement.executeLazyAsync([42]) + fromConnection = db.executeLazy('SELECT ? AS value', [7]) + expect(db.executeLazy('SELECT 1 WHERE 0').rows.toArray()).toEqual([]) + } finally { + statement.finalize() + db.close() + } + expect(fromStatement.rows.item(0)).toEqual({ value: 42 }) + expect(fromConnection.rows.item(0)).toEqual({ value: 7 }) + }) + + it('runs name-based lazy queries on a managed connection', async () => { + const query = 'SELECT ? AS value' + const sync = NitroSQLite.executeLazy(TEST_DB_NAME, query, [1]) + const async = await NitroSQLite.executeLazyAsync(TEST_DB_NAME, query, [2]) + expect(sync.rows.item(0)).toEqual({ value: 1 }) + expect(async.rows.item(0)).toEqual({ value: 2 }) + }) } diff --git a/packages/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index e01dc6e7..07c050d0 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -7,6 +7,7 @@ import { executeRaw, executeRawAsync, } from './operations/execute' +import { executeLazy, executeLazyAsync } from './operations/executeLazy' import { prepare } from './operations/prepare' import { executeBatch, executeBatchAsync } from './operations/executeBatch' @@ -22,6 +23,8 @@ export const NitroSQLite = { transaction, execute, executeAsync, + executeLazy, + executeLazyAsync, executeRaw, executeRawAsync, prepare, diff --git a/packages/nitro-sqlite-core/src/mock.ts b/packages/nitro-sqlite-core/src/mock.ts index 8897ec8d..92ca25a9 100644 --- a/packages/nitro-sqlite-core/src/mock.ts +++ b/packages/nitro-sqlite-core/src/mock.ts @@ -20,6 +20,7 @@ import type { ConnectionOptions, PreparedStatement } from './types' import type { MockConnection } from './mock/MockConnection' import { executeBatch, + asLazyQueryResult, executePrepared, executePreparedRaw, executeQuery, @@ -116,6 +117,10 @@ export function open(options: ConnectionOptions): MockConnection { runSync(() => executeQuery(database, query, params)), executeAsync: (query, params) => runAsync(() => executeQuery(database, query, params)), + executeLazy: (query, params) => + runSync(() => asLazyQueryResult(executeQuery(database, query, params))), + executeLazyAsync: (query, params) => + runAsync(() => asLazyQueryResult(executeQuery(database, query, params))), executeRaw: (query, params) => runSync(() => executeRawQuery(database, query, params)), executeRawAsync: (query, params) => @@ -143,6 +148,10 @@ export function open(options: ConnectionOptions): MockConnection { }, execute: (params) => runSync(() => execute(params)), executeAsync: (params) => runAsync(() => execute(params), true), + executeLazy: (params) => + runSync(() => asLazyQueryResult(execute(params))), + executeLazyAsync: (params) => + runAsync(() => asLazyQueryResult(execute(params)), true), executeRaw: (params) => runSync(() => executeRaw(params)), executeRawAsync: (params) => runAsync(() => executeRaw(params), true), finalize: () => diff --git a/packages/nitro-sqlite-core/src/mock/MockConnection.ts b/packages/nitro-sqlite-core/src/mock/MockConnection.ts index 03d8be0b..a474395e 100644 --- a/packages/nitro-sqlite-core/src/mock/MockConnection.ts +++ b/packages/nitro-sqlite-core/src/mock/MockConnection.ts @@ -13,6 +13,8 @@ export type MockConnection = Pick< | 'delete' | 'execute' | 'executeAsync' + | 'executeLazy' + | 'executeLazyAsync' | 'executeRaw' | 'executeRawAsync' | 'executeBatch' diff --git a/packages/nitro-sqlite-core/src/mock/query.ts b/packages/nitro-sqlite-core/src/mock/query.ts index 0e596161..c7b1ba9c 100644 --- a/packages/nitro-sqlite-core/src/mock/query.ts +++ b/packages/nitro-sqlite-core/src/mock/query.ts @@ -6,6 +6,7 @@ import type { import type { BatchQueryCommand, ColumnType, + LazyQueryResult, QueryResult, QueryResultRow, SQLiteQueryParams, @@ -111,6 +112,28 @@ export function executeQuery( return executePrepared(database, database.prepare(query), params) } +/** @internal Expose the lazy row API over the Node mock's already decoded rows. */ +export function asLazyQueryResult({ + rowsAffected, + insertId, + metadata, + rows, +}: QueryResult): LazyQueryResult { + return { + rowsAffected, + insertId, + metadata, + rows: { + length: rows.length, + item: (index) => + Number.isInteger(index) && index >= 0 && index < rows.length + ? rows.item(index) + : undefined, + toArray: () => rows._array.slice(), + }, + } +} + /** @internal Execute a batch atomically and count affected rows. */ export function executeBatch( database: Database, diff --git a/packages/nitro-sqlite-core/src/mock/transaction.ts b/packages/nitro-sqlite-core/src/mock/transaction.ts index cd087b50..8c482021 100644 --- a/packages/nitro-sqlite-core/src/mock/transaction.ts +++ b/packages/nitro-sqlite-core/src/mock/transaction.ts @@ -1,7 +1,7 @@ import type BetterSqlite3 from 'better-sqlite3' import SQLiteError from '../SQLiteError' import type { QueryResultRow, SQLiteQueryParams, Transaction } from '../types' -import { executeQuery, executeRawQuery } from './query' +import { asLazyQueryResult, executeQuery, executeRawQuery } from './query' /** @internal Run a callback while the connection's exclusive queue item owns it. */ export async function runTransaction( @@ -24,7 +24,7 @@ export async function runTransaction( assertActive() if (pending.size > 0) { throw new SQLiteError( - 'Await all tx.executeAsync calls before a synchronous transaction operation.', + 'Await all tx.executeAsync, tx.executeRawAsync, and tx.executeLazyAsync calls before a synchronous transaction operation.', ) } } @@ -59,6 +59,19 @@ export async function runTransaction( }), ) }, + executeLazy: (query, params) => { + assertSync() + return asLazyQueryResult(executeQuery(database, query, params)) + }, + executeLazyAsync: async (query, params) => { + assertActive() + return track( + Promise.resolve().then(() => { + assertActive() + return asLazyQueryResult(executeQuery(database, query, params)) + }), + ) + }, executeRaw: (query, params) => { assertSync() return executeRawQuery(database, query, params) diff --git a/packages/nitro-sqlite-core/src/operations/executeLazy.ts b/packages/nitro-sqlite-core/src/operations/executeLazy.ts new file mode 100644 index 00000000..e072f535 --- /dev/null +++ b/packages/nitro-sqlite-core/src/operations/executeLazy.ts @@ -0,0 +1,102 @@ +import { + isDatabaseOpen, + queueStatementAsync, + startOperationSync, +} from '../DatabaseQueue' +import type { DatabaseQueueKey } from '../DatabaseQueue' +import SQLiteError from '../SQLiteError' +import { HybridNitroSQLite } from '../nitro' +import { callNativeAsync } from '../nativePromise' +import type { + LazyQueryResult, + QueryResultRow, + SQLiteQueryParams, +} from '../types' + +/** Execute one SQL statement synchronously with on-demand row conversion. + * Uses the managed queue when the database was opened through `open()`. + * @param dbName Name of an open database. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @returns The completed result with typed rows. + * @throws SQLiteError if the managed connection is busy or the statement fails. + */ +export function executeLazy( + dbName: string, + query: string, + params?: SQLiteQueryParams, +): LazyQueryResult { + return isDatabaseOpen(dbName) + ? executeLazyManaged(dbName, query, params, dbName) + : executeLazyNative(dbName, query, params) +} + +/** Execute one SQL statement on a background thread with on-demand row conversion. + * Uses the managed queue when the database was opened through `open()`. + * @param dbName Name of an open database. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @returns A promise of the completed result with typed rows. + * @throws SQLiteError as a rejected promise if the statement fails. + */ +export function executeLazyAsync( + dbName: string, + query: string, + params?: SQLiteQueryParams, +): Promise> { + return isDatabaseOpen(dbName) + ? executeLazyAsyncManaged(dbName, query, params, dbName) + : executeLazyAsyncNative(dbName, query, params) +} + +export function executeLazyManaged( + dbName: string, + query: string, + params: SQLiteQueryParams | undefined, + queueKey: DatabaseQueueKey, +): LazyQueryResult { + return startOperationSync(queueKey, () => + executeLazyNative(dbName, query, params), + ) +} + +export function executeLazyAsyncManaged( + dbName: string, + query: string, + params: SQLiteQueryParams | undefined, + queueKey: DatabaseQueueKey, +): Promise> { + return queueStatementAsync(queueKey, () => + executeLazyAsyncNative(dbName, query, params), + ) +} + +export function executeLazyNative( + dbName: string, + query: string, + params?: SQLiteQueryParams, + requireTransaction?: boolean, +): LazyQueryResult { + try { + return ( + requireTransaction + ? HybridNitroSQLite.executeLazy(dbName, query, params, true) + : HybridNitroSQLite.executeLazy(dbName, query, params) + ) as LazyQueryResult + } catch (error) { + throw SQLiteError.fromError(error) + } +} + +export function executeLazyAsyncNative( + dbName: string, + query: string, + params?: SQLiteQueryParams, + requireTransaction?: boolean, +): Promise> { + return callNativeAsync(() => + requireTransaction + ? HybridNitroSQLite.executeLazyAsync(dbName, query, params, true) + : HybridNitroSQLite.executeLazyAsync(dbName, query, params), + ) as Promise> +} diff --git a/packages/nitro-sqlite-core/src/operations/prepare.ts b/packages/nitro-sqlite-core/src/operations/prepare.ts index 17bac34f..3fb761c0 100644 --- a/packages/nitro-sqlite-core/src/operations/prepare.ts +++ b/packages/nitro-sqlite-core/src/operations/prepare.ts @@ -2,6 +2,7 @@ import { HybridNitroSQLite } from '../nitro' import SQLiteError from '../SQLiteError' import type { PreparedStatement, + LazyQueryResult, QueryResult, QueryResultRow, SQLiteQueryParams, @@ -57,6 +58,27 @@ export function prepare( .executeAsync(params) .then((result) => buildJSQueryResult(result)), ).catch(rejectWithSQLiteError), + executeLazy: ( + params?: SQLiteQueryParams, + ): LazyQueryResult => { + try { + return startOperationSync(queueKey, () => + nativeStatement.executeLazy(params), + ) as LazyQueryResult + } catch (error) { + throw SQLiteError.fromError(error) + } + }, + executeLazyAsync: ( + params?: SQLiteQueryParams, + ): Promise> => + queueStatementAsync( + queueKey, + () => + nativeStatement.executeLazyAsync(params) as Promise< + LazyQueryResult + >, + ).catch(rejectWithSQLiteError), executeRaw: (params?: SQLiteQueryParams): NativeRawQueryResult => { try { return startOperationSync(queueKey, () => diff --git a/packages/nitro-sqlite-core/src/operations/session.ts b/packages/nitro-sqlite-core/src/operations/session.ts index f4426645..14cdb737 100644 --- a/packages/nitro-sqlite-core/src/operations/session.ts +++ b/packages/nitro-sqlite-core/src/operations/session.ts @@ -8,6 +8,7 @@ import type { SQLiteQueryParams, QueryResultRow, QueryResult, + LazyQueryResult, } from '../types' import { callNativeAsync } from '../nativePromise' import { @@ -16,6 +17,7 @@ import { executeRawAsyncManaged, executeRawManaged, } from './execute' +import { executeLazyAsyncManaged, executeLazyManaged } from './executeLazy' import { executeBatch, executeBatchAsync } from './executeBatch' import { prepare } from './prepare' import { createChangeListeners } from './changeListeners' @@ -170,6 +172,20 @@ export function open(options: ConnectionOptions): Connection { runAsyncOperation(() => executeAsyncManaged(connectionId, query, params, queueKey), ), + executeLazy: ( + query: string, + params?: SQLiteQueryParams, + ): LazyQueryResult => + runOperation(() => + executeLazyManaged(connectionId, query, params, queueKey), + ), + executeLazyAsync: ( + query: string, + params?: SQLiteQueryParams, + ): Promise> => + runAsyncOperation(() => + executeLazyAsyncManaged(connectionId, query, params, queueKey), + ), executeRaw: (query: string, params?: SQLiteQueryParams) => runOperation(() => executeRawManaged(connectionId, query, params, queueKey), diff --git a/packages/nitro-sqlite-core/src/operations/transaction.ts b/packages/nitro-sqlite-core/src/operations/transaction.ts index 041f28ef..6b01f3a5 100644 --- a/packages/nitro-sqlite-core/src/operations/transaction.ts +++ b/packages/nitro-sqlite-core/src/operations/transaction.ts @@ -4,6 +4,7 @@ import type { SQLiteQueryParams, QueryResult, QueryResultRow, + LazyQueryResult, } from '../types' import { executeAsyncNative, @@ -11,6 +12,7 @@ import { executeRawAsyncNative, executeRawNative, } from './execute' +import { executeLazyAsyncNative, executeLazyNative } from './executeLazy' import type { NativeRawQueryResult } from '../specs/NativeQueryResult' import SQLiteError from '../SQLiteError' import type { DatabaseQueueKey } from '../DatabaseQueue' @@ -45,7 +47,7 @@ export const transaction = ( const throwIfAsyncPending = () => { if (pendingAsyncStatements.size > 0) { throw new SQLiteError( - `Cannot run synchronous operation on transaction ${dbName} while async queries are pending. Await all tx.executeAsync calls first.`, + `Cannot run synchronous operation on transaction ${dbName} while async queries are pending. Await all tx.executeAsync, tx.executeRawAsync, and tx.executeLazyAsync calls first.`, ) } } @@ -168,6 +170,20 @@ export const transaction = ( commit, execute: executeOnTransaction, executeAsync: executeAsyncOnTransaction, + executeLazy: ( + query: string, + params?: SQLiteQueryParams, + ): LazyQueryResult => + runOnTransaction(() => + executeLazyNative(dbName, query, params, true), + ), + executeLazyAsync: ( + query: string, + params?: SQLiteQueryParams, + ): Promise> => + runAsyncOnTransaction(() => + executeLazyAsyncNative(dbName, query, params, true), + ), executeRaw: executeRawOnTransaction, executeRawAsync: executeRawAsyncOnTransaction, rollback, diff --git a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts index b4d85b07..84c06728 100644 --- a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts +++ b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts @@ -13,6 +13,7 @@ export interface LazyQueryRows { /** Return the row at a zero-based index, converting and caching it on first access. * An invalid or out-of-range index returns `undefined`. + * @param index Zero-based row index. */ item(index: number): Row | undefined diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 727ab73d..583243f8 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -2,6 +2,10 @@ import type { NativeQueryResult, NativeRawQueryResult, } from './specs/NativeQueryResult' +import type { + LazyQueryRows, + NativeLazyQueryResult, +} from './specs/NativeLazyQueryResult' /** Options for `open()` and `NitroSQLite.open()`. */ export interface ConnectionOptions { @@ -66,6 +70,10 @@ export interface Connection { execute: ExecuteQuery /** Queue one SQL statement and resolve with its result. */ executeAsync: ExecuteAsyncQuery + /** Execute one statement synchronously with on-demand row conversion. Throws while the connection is busy. */ + executeLazy: ExecuteLazyQuery + /** Queue one statement and resolve with rows that convert on demand. */ + executeLazyAsync: ExecuteLazyAsyncQuery /** Execute one SQL statement synchronously, returning rows as arrays of column values. Throws while the connection is busy. */ executeRaw: ExecuteRawQuery /** Queue one SQL statement and resolve with rows as arrays of column values. */ @@ -205,6 +213,15 @@ export type QueryResultRows< item: (idx: number) => Row | undefined } +/** Completed query result with typed on-demand rows. The row type does not validate SQL values at runtime. */ +export type LazyQueryResult = Omit< + NativeLazyQueryResult, + 'rows' +> & { + /** Rows that remain available after the statement and connection close. */ + readonly rows: LazyQueryRows +} + /** Execute one SQL statement synchronously and return its typed rows. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. @@ -223,6 +240,28 @@ export type ExecuteAsyncQuery = ( params?: SQLiteQueryParams, ) => Promise> +/** Execute a statement synchronously and return a result with on-demand row conversion. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @throws SQLiteError if the connection is busy or the statement fails. + */ +export type ExecuteLazyQuery = ( + query: string, + params?: SQLiteQueryParams, +) => LazyQueryResult + +/** Queue a statement and resolve with the completed result, whose rows convert on access. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @throws SQLiteError as a rejected promise if the statement fails. + */ +export type ExecuteLazyAsyncQuery = < + Row extends QueryResultRow = QueryResultRow, +>( + query: string, + params?: SQLiteQueryParams, +) => Promise> + /** Execute one SQL statement synchronously and return rows as arrays of column values. * Repeated column names are kept, in the order of `columnNames`. * @param query SQL statement with optional positional placeholders. @@ -254,6 +293,20 @@ export interface PreparedStatement { execute: ExecutePreparedStatement /** Queue execution on a background thread and resolve with the query result. */ executeAsync: ExecutePreparedStatementAsync + /** Execute on the calling thread with new bindings and convert rows on demand. + * Throws if the statement is finalized, the connection is closed or busy, or execution fails. + * @param params Values bound to the statement's positional placeholders. + */ + executeLazy( + params?: SQLiteQueryParams, + ): LazyQueryResult + /** Queue execution with new bindings and resolve with rows that convert on access. + * Rejects if the statement is finalized, the connection is closed, or execution fails. + * @param params Values bound to the statement's positional placeholders. + */ + executeLazyAsync( + params?: SQLiteQueryParams, + ): Promise> /** Execute on the calling thread like `execute`, returning rows as arrays of column values. */ executeRaw: ExecuteRawPreparedStatement /** Queue execution like `executeAsync` and resolve with rows as arrays of column values. */ @@ -322,6 +375,10 @@ export interface Transaction { execute: ExecuteQuery /** Execute within this transaction on a background thread. */ executeAsync: ExecuteAsyncQuery + /** Execute within this transaction on the calling thread with on-demand row conversion. */ + executeLazy: ExecuteLazyQuery + /** Execute within this transaction on a background thread with on-demand row conversion. */ + executeLazyAsync: ExecuteLazyAsyncQuery /** 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. */ diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/executeLazy.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/executeLazy.test.ts new file mode 100644 index 00000000..4aad0825 --- /dev/null +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/executeLazy.test.ts @@ -0,0 +1,94 @@ +jest.mock('../nitro') + +import SQLiteError from '../SQLiteError' +import { HybridNitroSQLite } from '../nitro' +import { executeLazy, executeLazyAsync } from '../operations/executeLazy' +import { open } from '../operations/session' +import { deferred, nativeLazyResult, nativeResult } from './testUtils' + +const dbName = 'lazy-queries' +const query = 'SELECT ? AS value' + +beforeEach(() => jest.resetAllMocks()) + +it('returns the native rows untouched from the name-based helpers', async () => { + const native = nativeLazyResult(7) + jest.mocked(HybridNitroSQLite.executeLazy).mockReturnValue(native) + jest.mocked(HybridNitroSQLite.executeLazyAsync).mockResolvedValue(native) + + expect(executeLazy(dbName, query, [7])).toBe(native) + expect(await executeLazyAsync(dbName, query, [7])).toBe(native) + expect(HybridNitroSQLite.executeLazy).toHaveBeenCalledWith(dbName, query, [7]) + expect(HybridNitroSQLite.executeLazyAsync).toHaveBeenCalledWith( + dbName, + query, + [7], + ) + expect(native.rows.item).not.toHaveBeenCalled() + expect(native.rows.toArray).not.toHaveBeenCalled() +}) + +it('keeps managed lazy queries queued and returns their unmaterialized results', async () => { + const native = nativeLazyResult(7) + const pendingResult = deferred() + jest.mocked(HybridNitroSQLite.executeLazy).mockReturnValue(native) + jest.mocked(HybridNitroSQLite.executeLazyAsync).mockResolvedValue(native) + jest + .mocked(HybridNitroSQLite.executeLazyAsync) + .mockReturnValueOnce(pendingResult.promise) + const db = open({ name: dbName }) + + try { + const pending = executeLazyAsync(dbName, query, [7]) + expect(() => executeLazy(dbName, query, [7])).toThrow('busy') + pendingResult.resolve(native) + await expect(pending).resolves.toBe(native) + expect(executeLazy(dbName, query, [7])).toBe(native) + expect(db.executeLazy(query, [7])).toBe(native) + await expect(db.executeLazyAsync(query, [7])).resolves.toBe(native) + expect(native.rows.item).not.toHaveBeenCalled() + } finally { + db.close() + } +}) + +it('uses the native transaction connection for lazy queries', async () => { + const native = nativeLazyResult(7) + jest + .mocked(HybridNitroSQLite.execute) + .mockImplementation(() => nativeResult()) + jest.mocked(HybridNitroSQLite.executeLazy).mockReturnValue(native) + jest.mocked(HybridNitroSQLite.executeLazyAsync).mockResolvedValue(native) + const db = open({ name: dbName }) + + try { + await db.transaction(async (tx) => { + expect(tx.executeLazy(query, [7])).toBe(native) + const pending = tx.executeLazyAsync(query, [7]) + expect(() => tx.executeLazy(query, [7])).toThrow( + 'while async queries are pending', + ) + for (const finalize of [tx.commit, tx.rollback]) { + expect(finalize).toThrow('tx.executeLazyAsync') + } + await expect(pending).resolves.toBe(native) + }) + } finally { + db.close() + } +}) + +it('normalizes native errors from lazy queries', async () => { + jest.mocked(HybridNitroSQLite.executeLazy).mockImplementation(() => { + throw new Error('invalid SQL') + }) + jest + .mocked(HybridNitroSQLite.executeLazyAsync) + .mockRejectedValue('invalid SQL') + + expect(() => executeLazy(dbName, query)).toThrow(SQLiteError) + await expect(executeLazyAsync(dbName, query)).rejects.toMatchObject({ + name: 'SQLiteError', + message: 'invalid SQL', + }) +}) 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 d37107cc..6b274738 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 @@ -60,6 +60,31 @@ describe('Node SQLite mock', () => { } }) + it('exposes lazy results through queries, transactions, and prepared statements', async () => { + const database = open({ name: 'lazy' }) + const query = 'SELECT ? AS value UNION ALL SELECT 2' + const first = database.executeLazy<{ value: number }>(query, [1]) + const second = await database.executeLazyAsync(query, [8]) + const third = await database.transaction(async (tx) => + tx.executeLazyAsync(query, [9]), + ) + const statement = database.prepare(query) + const fourth = await statement.executeLazyAsync([10]) + statement.finalize() + database.close() + + expect(first.rows.length).toBe(2) + expect(first.rows.item(0)?.value).toBe(1) + expect(first.rows.item(0.5)).toBeUndefined() + expect(first.rows.item(2)).toBeUndefined() + expect(first.rows.toArray()).toEqual([{ value: 1 }, { value: 2 }]) + expect(first.rows.toArray()[1]).toBe(first.rows.item(1)) + expect(first.rows.toArray()).not.toBe(first.rows.toArray()) + expect(second.rows.item(0)).toEqual({ value: 8 }) + expect(third.rows.item(0)).toEqual({ value: 9 }) + expect(fourth.rows.item(0)).toEqual({ value: 10 }) + }) + it('returns raw rows that keep repeated column names', async () => { const database = open({ name: 'raw' }) database.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') @@ -415,8 +440,10 @@ describe('Node SQLite mock', () => { const database = open({ name: 'pending.sqlite' }) database.execute('CREATE TABLE notes (title TEXT)') await database.transaction(async (tx) => { - const insert = tx.executeAsync('INSERT INTO notes VALUES (?)', ['Draft']) - expect(() => tx.commit()).toThrow('Await all') + const insert = tx.executeLazyAsync('INSERT INTO notes VALUES (?)', [ + 'Draft', + ]) + expect(() => tx.commit()).toThrow('tx.executeLazyAsync') expect(() => tx.rollback()).toThrow('Await all') expect(() => tx.execute('SELECT 1')).toThrow('Await all') await insert 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 770b00cf..42112ec5 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 @@ -9,7 +9,7 @@ import { import type { PreparedStatement } from '../specs/PreparedStatement.nitro' import { prepare } from '../operations/prepare' import { open } from '../operations/session' -import { nativeRawResult, nativeResult } from './testUtils' +import { nativeLazyResult, nativeRawResult, nativeResult } from './testUtils' const dbName = 'prepare-test' const query = 'SELECT ? AS value' @@ -148,6 +148,29 @@ it('runs raw executions through the statement queue', async () => { statement.finalize() }) +it('runs lazy executions through the statement queue without converting rows', async () => { + const native = mockStatement() + const lazy = nativeLazyResult(7) + jest.mocked(native.executeLazy).mockReturnValue(lazy) + jest.mocked(native.executeLazyAsync).mockResolvedValue(lazy) + jest.mocked(HybridNitroSQLite.prepare).mockReturnValue(native) + const statement = prepare(dbName, query) + + expect(statement.executeLazy([7])).toBe(lazy) + const pending = statement.executeLazyAsync([7]) + expect(() => statement.executeLazy()).toThrow('busy') + await expect(pending).resolves.toBe(lazy) + expect(native.executeLazy).toHaveBeenCalledWith([7]) + expect(native.executeLazyAsync).toHaveBeenCalledWith([7]) + expect(lazy.rows.item).not.toHaveBeenCalled() + jest.mocked(native.executeLazyAsync).mockRejectedValueOnce('invalid SQL') + await expect(statement.executeLazyAsync()).rejects.toMatchObject({ + name: 'SQLiteError', + message: 'invalid SQL', + }) + statement.finalize() +}) + it('converts preparation and execution errors', async () => { jest.mocked(HybridNitroSQLite.prepare).mockImplementationOnce(() => { throw new Error('prepare failed') diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/testUtils.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/testUtils.ts index bf8462f0..38eb62e3 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/testUtils.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/testUtils.ts @@ -3,6 +3,7 @@ import type { NativeRawQueryResult, } from '../specs/NativeQueryResult' import type { SQLiteValue } from '../types' +import type { NativeLazyQueryResult } from '../specs/NativeLazyQueryResult' export function nativeResult( results: Record[] = [], @@ -21,6 +22,18 @@ export function nativeRawResult( } as NativeRawQueryResult } +export function nativeLazyResult(value: SQLiteValue): NativeLazyQueryResult { + const row = { value } + return { + rowsAffected: 0, + rows: { + length: 1, + item: jest.fn((index: number) => (index === 0 ? row : undefined)), + toArray: jest.fn(() => [row]), + }, + } +} + export function deferred() { let resolve!: (value: T) => void let reject!: (reason: unknown) => void diff --git a/packages/react-native-nitro-sqlite/platform/src/__tests__/transactionIntegrity.test.ts b/packages/react-native-nitro-sqlite/platform/src/__tests__/transactionIntegrity.test.ts index da654b0b..42ca6df7 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__tests__/transactionIntegrity.test.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__tests__/transactionIntegrity.test.ts @@ -6,7 +6,7 @@ import { closeDatabaseQueue, openDatabaseQueue } from '../DatabaseQueue' import { executeManaged, executeAsyncManaged } from '../operations/execute' import { transaction } from '../operations/transaction' import { open, resetAllDatabases } from '../mock' -import { executeQuery, executeRawQuery } from '../mock/query' +import { asLazyQueryResult, executeQuery, executeRawQuery } from '../mock/query' import type { Transaction } from '../types' import type { NitroSQLiteConnection } from '../index' @@ -20,6 +20,8 @@ const methods = [ 'executeRaw', 'executeAsync', 'executeRawAsync', + 'executeLazy', + 'executeLazyAsync', ] as const for (const owner of ['native', 'mock']) { @@ -85,6 +87,24 @@ for (const owner of ['native', 'mock']) { execute(() => executeRawQuery(database, query, params), required), ), ) + jest + .mocked(HybridNitroSQLite.executeLazy) + .mockImplementation((_name, query, params, required) => + execute( + () => asLazyQueryResult(executeQuery(database, query, params)), + required, + ), + ) + jest + .mocked(HybridNitroSQLite.executeLazyAsync) + .mockImplementation((_name, query, params, required) => + enqueue(() => + execute( + () => asLazyQueryResult(executeQuery(database, query, params)), + required, + ), + ), + ) connection = { execute: (query, params) => executeManaged(name, query, params), executeAsync: (query, params) => @@ -132,7 +152,7 @@ for (const owner of ['native', 'mock']) { }, ) - it.each(['executeAsync', 'executeRawAsync'] as const)( + it.each(['executeAsync', 'executeRawAsync', 'executeLazyAsync'] as const)( 'checks queued %s calls when they execute and releases the queue for retries', async (method) => { let saved: Transaction | undefined