Skip to content

Commit 076a2ba

Browse files
DaveyEkechrispadercodex
authored
feat: add executeRaw to return rows as arrays (#447)
* feat: add executeRaw to return rows as arrays * fix(mock): refresh raw columns after schema changes Co-authored-by: Codex <noreply@openai.com> * fix: route global raw queries through the managed queue Co-authored-by: Codex <noreply@openai.com> --------- Co-authored-by: Christoph Pader <chris@margelo.com> Co-authored-by: Codex <noreply@openai.com>
1 parent 1311185 commit 076a2ba

41 files changed

Lines changed: 1151 additions & 69 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/content/docs/guides/node-test-mock.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ test('stores a note', () => {
3838
})
3939
```
4040

41-
The mock returns query rows through both `results` and `rows`, and supports [atomic batches](/docs/guides/batch-operations). Bound `undefined` becomes SQL NULL. A query that fails throws from `execute()` or rejects from `executeAsync()`.
41+
The mock returns query rows through both `results` and `rows`, supports [rows as arrays](/docs/guides/parameters-and-results#rows-as-arrays) through `executeRaw()` and `executeRawAsync()`, and supports [atomic batches](/docs/guides/batch-operations). Bound `undefined` becomes SQL NULL. A query that fails throws from `execute()` or rejects from `executeAsync()`.
4242

4343
## Share a database between connections
4444

‎docs/content/docs/guides/parameters-and-results.mdx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,21 @@ for (const person of result.rows._array) {
3131

3232
SQLite INTEGER and REAL result values both arrive as JavaScript numbers. BLOB values arrive as `ArrayBuffer`; NULL values arrive as `null`, even if the parameter was `undefined`. A bound boolean is stored through SQLite's integer binding, so read it as a number and convert it in application code if needed. JavaScript numbers cannot represent every 64-bit SQLite integer exactly; choose a storage representation appropriate for identifiers that exceed the safe integer range.
3333

34+
## Rows as arrays
35+
36+
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.
37+
38+
```ts
39+
const { columnNames, rows } = db.executeRaw(
40+
'SELECT users.id, users.name, pets.id, pets.name FROM users LEFT JOIN pets ON pets.owner_id = users.id',
41+
)
42+
43+
// columnNames: ['id', 'name', 'id', 'name']
44+
// rows: [[1, 'Ada', 7, 'Rex'], [2, 'Grace', null, null]]
45+
```
46+
47+
The result has `columnNames`, `rows`, `rowsAffected`, and `insertId`. It has no `rows._array` container and no `metadata`. `columnNames` is filled even when the query returns no rows. Transactions and prepared statements have the same two methods. The exact shape is in [`NitroSQLiteRawQueryResult`](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteRawQueryResult).
48+
3449
## Column metadata
3550

3651
For a query with result columns, `metadata` maps column names to `{ name, type, index }`. `index` is the zero-based result column position. The [`ColumnType` values](/api/react-native-nitro-sqlite/enumerations/ColumnType) are `BOOLEAN = 0`, `NUMBER = 1`, `INT64 = 2`, `TEXT = 3`, `ARRAY_BUFFER = 4`, and `NULL_VALUE = 5`. The package exports `ColumnType` as a TypeScript type, not a runtime enum object. In the current native implementation, `metadata.type` is unreliable for detecting a column's declared SQL type. Use your schema for that decision. An expression without a declared type maps to `NULL_VALUE`, which does not mean the result itself is null. The exact shape is in [`NitroSQLiteQueryColumnMetadata`](/api/react-native-nitro-sqlite/type-aliases/NitroSQLiteQueryColumnMetadata).

‎docs/content/docs/guides/prepared-statements.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ title: Prepared statements
33
description: Reuse a compiled SQL statement with different bound values.
44
---
55

6-
Call `db.prepare(query)` to reuse SQL with different parameter values. It returns a statement with `execute(params)`, `executeAsync(params)`, `isFinalized`, and `finalize()`. 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.
6+
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.
77

88
```ts
99
import { open } from 'react-native-nitro-sqlite'

‎docs/content/docs/guides/sync-and-async.mdx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Pick the query form that fits your workload and understand connecti
55

66
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.
77

8-
`executeBatch` and `loadFile` also have matching `Async` methods. A [prepared statement](/docs/guides/prepared-statements) has `execute()` and `executeAsync()` for repeated SQL.
8+
`executeRaw`, `executeBatch`, and `loadFile` also have matching `Async` methods. A [prepared statement](/docs/guides/prepared-statements) has `execute()` and `executeAsync()` for repeated SQL.
99

1010
```ts
1111
import { open } from 'react-native-nitro-sqlite'
@@ -45,7 +45,11 @@ See [prepared statements](/docs/guides/prepared-statements#connection-ordering-a
4545

4646
## Global helpers and native access
4747

48-
The [`NitroSQLite` export](/api/react-native-nitro-sqlite/variables/NitroSQLite) also has `execute`, `executeAsync`, `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()`. They do not address independent connections; use the object returned by `open()` for those. Without a default managed connection, global `execute` and `executeAsync` 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()`.
48+
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).
49+
50+
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.
51+
52+
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()`.
4953

5054
`NitroSQLite.native` exposes the underlying [`NitroSQLiteNative` hybrid object](/api/react-native-nitro-sqlite/hybrid-objects/NitroSQLiteNative). 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.
5155

‎docs/content/docs/guides/transactions.mdx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Throw from the callback when an application check fails. Use `tx` for those chec
2929

3030
## Commit and rollback behavior
3131

32-
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.commit`, or `tx.rollback` after finalization throw.
32+
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.
3333

3434
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.
3535

@@ -39,7 +39,7 @@ If rollback also fails, the rejection preserves the original message and appends
3939

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

42-
The connection queue is occupied for the whole callback. Use `tx.execute` or `tx.executeAsync` for every statement on this database during that callback, including statements in helpers.
42+
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.
4343

4444
> [!TIP]
4545
> Pass `tx` to any helper that runs statements during the transaction.
@@ -57,7 +57,7 @@ await db.transaction(async (tx) => {
5757

5858
## Await pending statements
5959

60-
Await every `tx.executeAsync()` before the callback returns or before manually finalizing. While an async statement is pending, `tx.execute()`, `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.
60+
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.
6161

6262
`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`; the global [`NitroSQLite.transaction`](/api/react-native-nitro-sqlite/variables/NitroSQLite) helper also accepts `isExclusive` to use `BEGIN EXCLUSIVE TRANSACTION`. See [transaction modes](/docs/concepts/transactions#transaction-modes) for the SQLite differences.
6363

‎docs/scripts/check-api.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const requiredExports = {
2222
'NitroSQLiteNative',
2323
'NitroSQLiteQueryResult',
2424
'NitroSQLiteQueryColumnMetadata',
25+
'NitroSQLiteRawQueryResult',
2526
'TypeOrmNitroSQLiteConnection',
2627
'typeORMDriver',
2728
],
@@ -66,6 +67,8 @@ const requiredMembers = {
6667
'transaction',
6768
'execute',
6869
'executeAsync',
70+
'executeRaw',
71+
'executeRawAsync',
6972
'executeBatch',
7073
'executeBatchAsync',
7174
'close',

‎example/tests/unit/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { beforeEach, describe } from '../TestApi'
22
import { setupTestDb } from './common'
33
import registerLoadFileUnitTests from './specs/operations/loadFile.spec'
44
import registerExecuteUnitTests from './specs/operations/execute.spec'
5+
import registerExecuteRawUnitTests from './specs/operations/executeRaw.spec'
56
import registerTransactionUnitTests from './specs/operations/transaction.spec'
67
import registerExecuteBatchUnitTests from './specs/operations/executeBatch.spec'
78
import registerPreparedStatementUnitTests from './specs/operations/preparedStatement.spec'
@@ -15,6 +16,7 @@ export function registerUnitTests() {
1516
beforeEach(setupTestDb)
1617

1718
describe('operations/execute.spec.ts', registerExecuteUnitTests)
19+
describe('operations/executeRaw.spec.ts', registerExecuteRawUnitTests)
1820
describe('operations/transaction.spec.ts', registerTransactionUnitTests)
1921
describe('operations/executeBatch.spec.ts', registerExecuteBatchUnitTests)
2022
describe('operations/loadFile.spec.ts', registerLoadFileUnitTests)
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import {
2+
expect,
3+
isNitroSQLiteError,
4+
TEST_ERROR_CODES,
5+
} from '@tests/unit/common'
6+
import { describe, it } from '@tests/TestApi'
7+
import { testDb } from '@tests/db'
8+
9+
const valuesQuery =
10+
'SELECT 1 AS duplicate, 2 AS duplicate, 3.5 AS "café", NULL AS nullable, zeroblob(2) AS payload'
11+
12+
const joinQuery = `
13+
SELECT owners.id, owners.name, pets.id, pets.name
14+
FROM owners LEFT JOIN pets ON pets.owner_id = owners.id
15+
ORDER BY owners.id
16+
`
17+
18+
function createJoinTables() {
19+
testDb.execute('CREATE TABLE owners (id INTEGER PRIMARY KEY, name TEXT)')
20+
testDb.execute(
21+
'CREATE TABLE pets (id INTEGER PRIMARY KEY, name TEXT, owner_id INTEGER)',
22+
)
23+
testDb.execute("INSERT INTO owners VALUES (1, 'Dave'), (2, 'Ritesh')")
24+
testDb.execute("INSERT INTO pets VALUES (7, 'Rex', 1)")
25+
}
26+
27+
function expectValuesRow(row: unknown[] | undefined) {
28+
expect(row?.slice(0, 4)).toEqual([1, 2, 3.5, null])
29+
expect(Array.from(new Uint8Array(row?.[4] as ArrayBuffer))).toEqual([0, 0])
30+
}
31+
32+
export default function registerExecuteRawUnitTests() {
33+
describe('executeRaw', () => {
34+
it('returns every value type and keeps repeated column names', async () => {
35+
const result = testDb.executeRaw(valuesQuery)
36+
expect(result.columnNames).toEqual([
37+
'duplicate',
38+
'duplicate',
39+
'café',
40+
'nullable',
41+
'payload',
42+
])
43+
expect(result.rows).toHaveLength(1)
44+
expectValuesRow(result.rows[0])
45+
46+
const asyncResult = await testDb.executeRawAsync(valuesQuery)
47+
expect(asyncResult.columnNames).toEqual(result.columnNames)
48+
expectValuesRow(asyncResult.rows[0])
49+
})
50+
51+
it('keeps both sides of a join with matching column names', async () => {
52+
createJoinTables()
53+
const expected = [
54+
[1, 'Dave', 7, 'Rex'],
55+
[2, 'Ritesh', null, null],
56+
]
57+
58+
const result = testDb.executeRaw(joinQuery)
59+
expect(result.columnNames).toEqual(['id', 'name', 'id', 'name'])
60+
expect(result.rows).toEqual(expected)
61+
expect((await testDb.executeRawAsync(joinQuery)).rows).toEqual(expected)
62+
})
63+
64+
it('binds parameters and reports changes for writes', async () => {
65+
const inserted = testDb.executeRaw(
66+
'INSERT INTO User (id, name, age, networth) VALUES (?, ?, ?, ?)',
67+
[1, 'Ada', 36, 1.5],
68+
)
69+
expect(inserted.rowsAffected).toBe(1)
70+
expect(inserted.insertId).toBe(1)
71+
expect(inserted.columnNames).toEqual([])
72+
expect(inserted.rows).toEqual([])
73+
74+
const selected = await testDb.executeRawAsync(
75+
'SELECT name, age FROM User WHERE id = ?',
76+
[1],
77+
)
78+
expect(selected.rows).toEqual([['Ada', 36]])
79+
})
80+
81+
it('returns column names for an empty result', () => {
82+
const result = testDb.executeRaw('SELECT id, name FROM User WHERE 0')
83+
expect(result.columnNames).toEqual(['id', 'name'])
84+
expect(result.rows).toEqual([])
85+
})
86+
87+
it('returns large results in order', async () => {
88+
const query = `
89+
WITH RECURSIVE counter(value) AS (
90+
SELECT 1 UNION ALL SELECT value + 1 FROM counter WHERE value < 10000
91+
)
92+
SELECT value, 'row-' || value FROM counter
93+
`
94+
for (const result of [
95+
testDb.executeRaw(query),
96+
await testDb.executeRawAsync(query),
97+
]) {
98+
expect(result.rows).toHaveLength(10_000)
99+
expect(result.rows[0]).toEqual([1, 'row-1'])
100+
expect(result.rows[9_999]).toEqual([10_000, 'row-10000'])
101+
}
102+
})
103+
104+
it('runs inside a transaction', async () => {
105+
createJoinTables()
106+
await testDb.transaction(async (tx) => {
107+
tx.executeRaw("INSERT INTO pets VALUES (8, 'Tom', 2)")
108+
expect((await tx.executeRawAsync(joinQuery)).rows).toEqual([
109+
[1, 'Dave', 7, 'Rex'],
110+
[2, 'Ritesh', 8, 'Tom'],
111+
])
112+
})
113+
})
114+
115+
it('runs prepared statements and switches between raw and object rows', async () => {
116+
createJoinTables()
117+
const statement = testDb.prepare(`${joinQuery} LIMIT ?`)
118+
try {
119+
expect(statement.executeRaw([1]).rows).toEqual([[1, 'Dave', 7, 'Rex']])
120+
expect(statement.execute([1]).results).toEqual([{ id: 7, name: 'Rex' }])
121+
const asyncResult = await statement.executeRawAsync([2])
122+
expect(asyncResult.columnNames).toEqual(['id', 'name', 'id', 'name'])
123+
expect(asyncResult.rows).toHaveLength(2)
124+
} finally {
125+
statement.finalize()
126+
}
127+
})
128+
129+
it('throws NitroSQLiteError for invalid SQL', async () => {
130+
try {
131+
testDb.executeRaw('SELECT * FROM missing_table')
132+
throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR)
133+
} catch (error) {
134+
expect(isNitroSQLiteError(error)).toBe(true)
135+
}
136+
137+
try {
138+
await testDb.executeRawAsync('SELECT * FROM missing_table')
139+
throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION)
140+
} catch (error) {
141+
expect(isNitroSQLiteError(error)).toBe(true)
142+
}
143+
})
144+
})
145+
}

0 commit comments

Comments
 (0)