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
10 changes: 9 additions & 1 deletion .github/ci-paths.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@
".github/actions/**",
".github/ci-paths.json",
"scripts/ci*",
"bun.lock",
"package.json",
"examples/react-native/package.json",
"packages/react-native-nitro-sqlite/package.json",
"patches/react-native-nitro-modules*",
"packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.*",
"packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.*",
"packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.*",
Expand Down Expand Up @@ -138,7 +143,10 @@
"packages/nitro-sqlite/package.json",
"packages/nitro-sqlite/nitro.json",
"packages/nitro-sqlite/platform/cpp/**",
"packages/nitro-sqlite/src/specs/**"
"packages/nitro-sqlite/src/specs/**",
"packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.*",
"packages/react-native-nitro-sqlite/cpp/SQLiteLazyQueryRows.*",
"scripts/check-lazy-cpp.sh"
],
"docs": [
".github/workflows/**",
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,9 @@ jobs:
- name: Test C++ database lifecycle and SQLite symbols
if: steps.select.outputs.cpp_tests == 'true'
run: bash scripts/test-cpp.sh
- name: Compile lazy row conversion for both hosts
if: steps.select.outputs.cpp_tests == 'true'
run: bash scripts/check-lazy-cpp.sh
- name: Check documentation
if: steps.select.outputs.docs == 'true'
run: |
Expand Down
2 changes: 2 additions & 0 deletions docs/content/docs/guides/parameters-and-results.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ Transactions and prepared statements also support raw results. The [Drizzle driv

## Column metadata

SQLite column aliases become keys in the metadata object. Eager and lazy native results preserve aliases such as `__proto__` and `constructor` as own data properties, without invoking inherited setters.

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 [`QueryColumnMetadata`](/api/react-native-nitro-sqlite/type-aliases/QueryColumnMetadata).

```ts
Expand Down
3 changes: 3 additions & 0 deletions docs/content/docs/guides/sync-and-async.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,6 @@ Native calls bypass the JavaScript queue. If you use them alongside an `open()`
Native direct and prepared `execute()` methods return [`NativeQueryResult`](/api/react-native-nitro-sqlite/interfaces/NativeQueryResult). Their `executeAsync()` methods resolve to the same result shape.

Call raw methods through `NitroSQLite.native`. Keep SQLite thread safety enabled when work can run across multiple database connections. Use React Native's [`threadSafe` setting](/docs/configuration#thread-safety) or retain the [NitroUI adapter's native default](/docs/configuration#nitroui-build-settings).

SQLite produces each result row as it advances the statement. `NitroSQLite.native.executeLazy()` and `executeLazyAsync()` read the complete result into native memory and convert rows when you access them. Use `rows.item(index)` for one row or `rows.toArray()` for all rows in result order. Both use the same cached row objects. Native prepared statements offer the same methods. You can read the returned rows after the statement or connection closes.

2 changes: 2 additions & 0 deletions examples/shared/tests/unit/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { setupTestDb } from './common'
import registerLoadFileUnitTests from './specs/operations/loadFile.spec'
import registerExecuteUnitTests from './specs/operations/execute.spec'
import registerChangeListenerUnitTests from './specs/operations/changeListener.spec'
import registerExecuteLazyUnitTests from './specs/operations/executeLazy.spec'
import registerExecuteRawUnitTests from './specs/operations/executeRaw.spec'
import registerQueryResultUnitTests from './specs/operations/queryResults.spec'
import registerTransactionUnitTests from './specs/operations/transaction.spec'
Expand All @@ -31,6 +32,7 @@ export function registerUnitTestsForEnvironment(

describe('operations/execute.spec.ts', registerExecuteUnitTests)
describe('operations/changeListener.spec.ts', registerChangeListenerUnitTests)
describe('operations/executeLazy.spec.ts', registerExecuteLazyUnitTests)
describe('operations/executeRaw.spec.ts', registerExecuteRawUnitTests)
describe('operations/queryResults.spec.ts', registerQueryResultUnitTests)
describe('operations/transaction.spec.ts', registerTransactionUnitTests)
Expand Down
160 changes: 160 additions & 0 deletions examples/shared/tests/unit/specs/operations/executeLazy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { NitroSQLite } from '@example-sqlite/core'
import { expect } from '../../common'
import { it } from '../../../TestApi'
import { TEST_DB_NAME } from '../../../db'

export default function registerExecuteLazyUnitTests() {
it('keeps metadata and row access valid for an empty native result', () => {
const query = 'SELECT 1 AS value WHERE 0'
const eager = NitroSQLite.native.execute(TEST_DB_NAME, query)
const lazy = NitroSQLite.native.executeLazy(TEST_DB_NAME, query)
expect(lazy.metadata).toEqual(eager.metadata)
expect(lazy.rows.length).toBe(0)
expect(lazy.rows.item(0)).toBe(undefined)
expect(lazy.rows.toArray()).toEqual([])
expect(lazy.rows.toArray()).toEqual([])
})

it('caches native async rows by index without invoking inherited setters', async () => {
const key = 'nitroSQLiteLazyTestValue'
let setterCalls = 0
Object.defineProperty(Object.prototype, key, {

Check warning on line 21 in examples/shared/tests/unit/specs/operations/executeLazy.spec.ts

View workflow job for this annotation

GitHub Actions / Fast checks

Object prototype is read only, properties should not be added
configurable: true,
set(this: object, value: unknown) {
if (typeof value === 'number') setterCalls++
Object.defineProperty(this, key, {
value,
enumerable: true,
writable: true,
configurable: true,
})
},
})

try {
const { rows } = await NitroSQLite.native.executeLazyAsync(
TEST_DB_NAME,
`WITH RECURSIVE seq(n) AS (
VALUES (1) UNION ALL SELECT n + 1 FROM seq WHERE n < 600
) SELECT n AS ${key} FROM seq ORDER BY n`,
)
expect(rows.length).toBe(600)
for (const index of [-1, 0.5, 600, NaN, Infinity]) {
expect(rows.item(index)).toBe(undefined)
}
expect(setterCalls).toBe(0)
const { item } = rows
const last = item(599)
expect(last).toEqual({ [key]: 600 })
expect(rows.item(599)).toBe(last)
expect(setterCalls).toBe(0)
const all = rows.toArray()
expect(setterCalls).toBe(0)
expect(all[0]).toEqual({ [key]: 1 })
expect(all[599]).toBe(last)
expect(rows.toArray()[599]).toBe(last)
expect(setterCalls).toBe(0)
} finally {
Reflect.deleteProperty(Object.prototype, key)
}
})

it('ignores inherited caches and setters on its row accessors', () => {
const keys = ['cache', 'item', 'toArray', 'length']
const inherited = { cache: { 0: { value: 'inherited' } } }
let setterCalls = 0
try {
for (const key of keys) {
// eslint-disable-next-line no-extend-native -- Exercise inherited cache values and swallowed assignments.
Object.defineProperty(Object.prototype, key, {
configurable: true,
get() {
return key === 'cache' ? inherited.cache : undefined
},
set() {
setterCalls++
},
})
}
const { rows } = NitroSQLite.native.executeLazy(
TEST_DB_NAME,
'SELECT 42 AS value UNION ALL SELECT 7',
)
const first = rows.item(0)
const all = rows.toArray()
expect(first).toEqual({ value: 42 })
expect(rows.item(0)).toBe(first)
expect(all[0]).toBe(first)
expect(rows.item(1)).toBe(all[1])
expect(rows.length).toBe(2)
expect(rows.toArray()).toEqual(all)
expect(setterCalls).toBe(0)
} finally {
for (const key of keys) Reflect.deleteProperty(Object.prototype, key)
}
})

it('keeps inherited columns as own properties without invoking setters', () => {
const key = 'nitroSQLiteLazyReentrantValue'
const query = `SELECT 1 AS ${key}, x'00ff' AS "__proto__" UNION ALL SELECT 2, x'01'`
let setterCalls = 0
// eslint-disable-next-line no-extend-native -- Match eager conversion of inherited column names.
Object.defineProperty(Object.prototype, key, {
configurable: true,
set() {
setterCalls++
throw new Error('inherited setter must not run')
},
})
try {
const eager = NitroSQLite.native.execute(TEST_DB_NAME, query)
const { rows } = NitroSQLite.native.executeLazy(TEST_DB_NAME, query)
const first = rows.item(0)
expect(rows.toArray()).toEqual(eager.results)
expect(rows.item(0)).toBe(first)
expect(Object.getPrototypeOf(first)).toBe(Object.prototype)
expect(Object.prototype.hasOwnProperty.call(first, '__proto__')).toBe(
true,
)
expect(Object.prototype.hasOwnProperty.call(first, key)).toBe(true)
expect(setterCalls).toBe(0)
} finally {
Reflect.deleteProperty(Object.prototype, key)
}
})

it('matches native eager values and metadata, including duplicate aliases and BLOBs', async () => {
const query = `
SELECT id, 'old' AS label, ? AS label, 1.5 AS "café", NULL AS nullable,
x'00ff' AS payload, zeroblob(0) AS empty
FROM User ORDER BY id
`
NitroSQLite.native.execute(
TEST_DB_NAME,
"INSERT INTO User (id, name, age, networth) VALUES (1, 'Ada', 37, 1)",
)
const params = ['a\0b']
const eager = NitroSQLite.native.execute(TEST_DB_NAME, query, params)
const lazy = NitroSQLite.native.executeLazy(TEST_DB_NAME, query, params)
expect(lazy.metadata).toEqual(eager.metadata)
expect(lazy.rowsAffected).toBe(eager.rowsAffected)
expect(lazy.insertId).toBe(eager.insertId)
expect(lazy.rows.toArray()).toEqual(eager.results)
const row = lazy.rows.item(0)
expect(row?.label).toBe('a\0b')
expect(Array.from(new Uint8Array(row?.payload as ArrayBuffer))).toEqual([
0, 255,
])
expect((row?.empty as ArrayBuffer).byteLength).toBe(0)
expect(lazy.rows.item(0)?.payload).toBe(row?.payload)
})

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])
const second = await statement.executeLazyAsync([2])
statement.finalize()
expect(first.rows.item(0)).toEqual({ x: 1 })
expect(second.rows.item(0)).toEqual({ x: 2 })
})
}
5 changes: 4 additions & 1 deletion packages/nitro-sqlite-core/cpp/NativeQueryResult.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,17 @@ namespace {
if (!metadata) {
return jsi::Value::undefined();
}
jsi::Object obj(runtime);
const auto prototype = jsi::Object(runtime).getPrototype(runtime);
// Column aliases must become own data properties, including inherited setter names.
auto obj = jsi::Object::create(runtime, jsi::Value::null());
for (const auto& [columnName, column] : *metadata) {
jsi::Object columnObj(runtime);
columnObj.setProperty(runtime, keys.name, JSIConverter<std::string>::toJSI(runtime, column.name));
columnObj.setProperty(runtime, keys.type, JSIConverter<ColumnType>::toJSI(runtime, column.type));
columnObj.setProperty(runtime, keys.index, JSIConverter<double>::toJSI(runtime, column.index));
obj.setProperty(runtime, getColumnName(runtime, keys, columnName), std::move(columnObj));
}
obj.setPrototype(runtime, prototype);
return obj;
}

Expand Down
Loading
Loading