From cb1cf350bddd0debb3a3fd7fa6ca92cf2d5a1958 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:36:37 +0100 Subject: [PATCH 01/10] feat: convert native SQLite result rows on demand Co-authored-by: Codex --- docs/content/docs/guides/sync-and-async.mdx | 3 + examples/shared/tests/unit/register.ts | 2 + .../unit/specs/operations/executeLazy.spec.ts | 85 +++++++++++ .../cpp/SQLiteLazyQueryRows.cpp | 137 ++++++++++++++++++ .../cpp/SQLiteLazyQueryRows.hpp | 48 ++++++ .../cpp/SQLiteOperations.cpp | 59 ++++++-- .../cpp/SQLiteOperations.hpp | 7 + .../cpp/SQLiteQueryResults.hpp | 18 +++ .../cpp/hybridObjects/HybridNitroSQLite.cpp | 18 +++ .../cpp/hybridObjects/HybridNitroSQLite.hpp | 7 + .../hybridObjects/HybridPreparedStatement.cpp | 17 ++- .../hybridObjects/HybridPreparedStatement.hpp | 4 + packages/nitro-sqlite-core/src/deprecated.ts | 2 +- packages/nitro-sqlite-core/src/index.ts | 9 +- .../src/specs/NativeLazyQueryResult.ts | 41 ++++++ .../src/specs/NitroSQLite.nitro.ts | 25 ++++ .../src/specs/PreparedStatement.nitro.ts | 15 ++ .../platform/src/__mocks__/nitro.ts | 2 + .../platform/src/__tests__/prepare.test.ts | 2 + 19 files changed, 485 insertions(+), 16 deletions(-) create mode 100644 examples/shared/tests/unit/specs/operations/executeLazy.spec.ts create mode 100644 packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp create mode 100644 packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp create mode 100644 packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index 3b19228b5..2df9e78f6 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -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. + diff --git a/examples/shared/tests/unit/register.ts b/examples/shared/tests/unit/register.ts index a9ec16e11..7d32c7908 100644 --- a/examples/shared/tests/unit/register.ts +++ b/examples/shared/tests/unit/register.ts @@ -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' @@ -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) diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts new file mode 100644 index 000000000..368fd5f6e --- /dev/null +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -0,0 +1,85 @@ +import { NitroSQLite } from 'react-native-nitro-sqlite' +import { expect } from '@tests/unit/common' +import { it } from '@tests/TestApi' +import { TEST_DB_NAME } from '@tests/db' + +export default function registerExecuteLazyUnitTests() { + it('converts native async rows only when read and caches them by index', async () => { + const key = 'nitroSQLiteLazyTestValue' + let conversions = 0 + Object.defineProperty(Object.prototype, key, { + configurable: true, + set(this: object, value: unknown) { + if (typeof value === 'number') conversions++ + 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(conversions).toBe(0) + const { item } = rows + const last = item(599) + expect(last).toEqual({ [key]: 600 }) + expect(rows.item(599)).toBe(last) + expect(conversions).toBe(1) + const all = rows.toArray() + expect(conversions).toBe(600) + expect(all[0]).toEqual({ [key]: 1 }) + expect(all[599]).toBe(last) + expect(rows.toArray()[599]).toBe(last) + expect(conversions).toBe(600) + } 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 }) + }) +} diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp new file mode 100644 index 000000000..f679e437a --- /dev/null +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -0,0 +1,137 @@ +#include "SQLiteLazyQueryRows.hpp" +#include +#include +#include + +namespace margelo::nitro::nitrosqlite { + +namespace { + + size_t stringAllocationSize(const std::string& value) { + const auto* start = reinterpret_cast(&value); + const std::less less; + if (!less(value.data(), start) && less(value.data(), start + sizeof(value))) { + return 0; // Short strings are already counted as part of their containing vector. + } + return value.capacity() + 1; + } + + size_t rowAllocationSize(const SQLiteQueryResultRow& row) { + size_t bytes = row.capacity() * sizeof(SQLiteValue); + for (const auto& value : row) { + if (!value) + continue; + if (const auto* text = std::get_if(&*value)) { + bytes += stringAllocationSize(*text); + } else if (const auto* blob = std::get_if>(&*value)) { + bytes += (*blob)->getExternalMemorySize(); + } + } + return bytes; + } + + jsi::Value bindAccessor(jsi::Runtime& runtime, const jsi::Object& owner, const char* name, unsigned int arity, + jsi::HostFunctionType accessor) { + auto function = jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forAscii(runtime, name), arity, std::move(accessor)); + return function.getPropertyAsFunction(runtime, "bind").callWithThis(runtime, function, owner); + } + +} // namespace + +SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, std::vector rows) + : HybridObject("SQLiteLazyQueryRows"), _data{std::move(columnNames), std::move(rows)}, + _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + + _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { + for (const auto& name : _data.columnNames) { + _retainedBytes += stringAllocationSize(name); + } + for (const auto& row : _data.rows) { + _retainedBytes += rowAllocationSize(row); + } +} + +jsi::Object SQLiteLazyQueryRows::toRows(jsi::Runtime& runtime) { + auto owner = toObject(runtime).asObject(runtime); + if (!owner.hasProperty(runtime, "cache")) { + owner.setProperty(runtime, "cache", CommonGlobals::Object::create(runtime, jsi::Value::null())); + } + + // The bound functions keep the owner and its cache on the JS heap. Native code holds + // no strong JS references, so even a cached row that references its result can be collected. + jsi::Object result(runtime); + result.setProperty(runtime, "length", static_cast(_data.rows.size())); + result.setProperty( + runtime, "item", + bindAccessor(runtime, owner, "item", 1, [](jsi::Runtime& rt, const jsi::Value& receiver, const jsi::Value* args, size_t count) { + auto state = receiver.asObject(rt); + return dynamic_cast(*state.getNativeState(rt)).item(rt, state, args, count); + })); + result.setProperty( + runtime, "toArray", + bindAccessor(runtime, owner, "toArray", 0, [](jsi::Runtime& rt, const jsi::Value& receiver, const jsi::Value*, size_t) { + auto state = receiver.asObject(rt); + return dynamic_cast(*state.getNativeState(rt)).toArray(rt, state); + })); + return result; +} + +size_t SQLiteLazyQueryRows::getExternalMemorySize() noexcept { + return _retainedBytes; +} + +jsi::Value SQLiteLazyQueryRows::item(jsi::Runtime& runtime, const jsi::Object& owner, const jsi::Value* args, size_t count) { + if (count == 0 || !args[0].isNumber()) + return jsi::Value::undefined(); + const double index = args[0].getNumber(); + if (!(index >= 0 && index < _data.rows.size() && std::trunc(index) == index)) { + return jsi::Value::undefined(); + } + + return materialize(runtime, owner, owner.getPropertyAsObject(runtime, "cache"), static_cast(index)); +} + +jsi::Array SQLiteLazyQueryRows::toArray(jsi::Runtime& runtime, const jsi::Object& owner) { + const auto cache = owner.getPropertyAsObject(runtime, "cache"); + const auto names = makeQueryColumnNames(runtime, _data.columnNames); + jsi::Array array(runtime, _data.rows.size()); + for (size_t index = 0; index < _data.rows.size(); index++) { + array.setValueAtIndex(runtime, index, materialize(runtime, owner, cache, index, &names)); + } + return array; +} + +jsi::Value SQLiteLazyQueryRows::materialize(jsi::Runtime& runtime, const jsi::Object& owner, const jsi::Object& cache, size_t index, + const std::vector* names) { + const auto key = jsi::PropNameID::forAscii(runtime, std::to_string(index)); + auto cached = cache.getProperty(runtime, key); + if (!cached.isUndefined()) + return cached; + + std::vector itemNames; + if (names == nullptr) { + itemNames = makeQueryColumnNames(runtime, _data.columnNames); + names = &itemNames; + } + auto& slot = _data.rows[index]; + if (slot.empty()) { + throw jsi::JSError(runtime, "Cannot access a SQLite row while it is being converted"); + } + // A column setter on Object.prototype can call back into this accessor. + SQLiteQueryResultRow nativeRow; + nativeRow.swap(slot); + jsi::Value row; + try { + row = convertQueryRow(runtime, *names, nativeRow); + cache.setProperty(runtime, key, jsi::Value(runtime, row)); + } catch (...) { + nativeRow.swap(slot); + throw; + } + // Nitro now accounts for any BLOB buffers on their JS ArrayBuffers. + _retainedBytes -= rowAllocationSize(nativeRow); + SQLiteQueryResultRow{}.swap(nativeRow); + owner.setExternalMemoryPressure(runtime, _retainedBytes); + return row; +} + +} // namespace margelo::nitro::nitrosqlite diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp new file mode 100644 index 000000000..72a2c7e45 --- /dev/null +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include "SQLiteQueryResults.hpp" +#include + +namespace margelo::nitro::nitrosqlite { + +/** Owns the positional rows of a completed query until JavaScript accesses them. */ +class SQLiteLazyQueryRows final : public HybridObject { +public: + SQLiteLazyQueryRows(std::vector columnNames, std::vector rows); + + /** Transfer access to the rows to the JavaScript runtime that issued the query. */ + jsi::Object toRows(jsi::Runtime& runtime); + +private: + size_t getExternalMemorySize() noexcept override; + jsi::Value item(jsi::Runtime& runtime, const jsi::Object& owner, const jsi::Value* args, size_t count); + jsi::Array toArray(jsi::Runtime& runtime, const jsi::Object& owner); + jsi::Value materialize(jsi::Runtime& runtime, const jsi::Object& owner, const jsi::Object& cache, size_t index, + const std::vector* names = nullptr); + + SQLiteNativeQueryResults _data; + size_t _retainedBytes; +}; + +} // namespace margelo::nitro::nitrosqlite + +namespace margelo::nitro { + +template <> +struct JSIConverter> final { + using Rows = std::shared_ptr; + + static jsi::Value toJSI(jsi::Runtime& runtime, const Rows& rows) { + return rows->toRows(runtime); + } + + static Rows fromJSI(jsi::Runtime&, const jsi::Value&) { + throw std::logic_error("SQLite lazy query rows cannot be passed from JavaScript"); + } + + static bool canConvert(jsi::Runtime&, const jsi::Value&) { + return false; + } +}; + +} // namespace margelo::nitro diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index 7ca3e5c2e..f2dfce150 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -1,4 +1,5 @@ #include "SQLiteOperations.hpp" +#include "SQLiteLazyQueryRows.hpp" #include "SQLiteException.hpp" #include "SQLiteStatementGroup.hpp" #include "SQLiteStatementTail.hpp" @@ -234,6 +235,22 @@ namespace { return names; } + std::optional getQueryMetadata(sqlite3_stmt* statement, const std::vector& columnNames) { + std::optional metadata = std::nullopt; + for (int i = 0; i < static_cast(columnNames.size()); i++) { + const std::string& columnName = columnNames[i]; + ColumnType columnDeclaredType = mapSQLiteTypeToColumnType(sqlite3_column_decltype(statement, i)); + auto columnMeta = QueryColumnMetadata(columnName, std::move(columnDeclaredType), i); + + if (!metadata) { + metadata = std::make_optional(); + } + metadata->insert({columnName, std::move(columnMeta)}); + } + + return metadata; + } + NativeQueryResult executeStatement(sqlite3* db, sqlite3_stmt* statement, SQLiteExecutionMode mode, const SQLiteRowBatchHandler& onRows = nullptr) { std::optional rows; @@ -254,23 +271,34 @@ namespace { } const auto& columnNames = rows->columnNames(); - std::optional metadata = std::nullopt; - for (int i = 0; i < static_cast(columnNames.size()); i++) { - const std::string& columnName = columnNames[i]; - ColumnType columnDeclaredType = mapSQLiteTypeToColumnType(sqlite3_column_decltype(statement, i)); - auto columnMeta = QueryColumnMetadata(columnName, std::move(columnDeclaredType), i); - - if (!metadata) { - metadata = std::make_optional(); - } - metadata->insert({columnName, std::move(columnMeta)}); - } + auto metadata = getQueryMetadata(statement, columnNames); return NativeQueryResult(sqlite3_changes(db), static_cast(sqlite3_last_insert_rowid(db)), rows->takeRows(/*isFinalBatch=*/true), rowBatchCount == 0 ? std::nullopt : std::optional(rowBatchCount * kRowBatchSize), std::move(metadata), static_cast(rowBatchCount)); } + NativeLazyQueryResult executeStatementLazy(sqlite3* db, sqlite3_stmt* statement) { + std::optional> columnNames; + std::vector rows; + consumeStatement(db, statement, [&](sqlite3_stmt* currentStatement) { + if (!columnNames) columnNames = readResultColumnNames(db, currentStatement); + SQLiteQueryResultRow row; + row.reserve(columnNames->size()); + for (size_t index = 0; index < columnNames->size(); index++) { + row.push_back(readSQLiteResultColumn(currentStatement, static_cast(index))); + } + rows.push_back(std::move(row)); + }); + if (!columnNames) columnNames = readResultColumnNames(db, statement); + NativeLazyQueryResult result; + result.rowsAffected = sqlite3_changes(db); + result.insertId = static_cast(sqlite3_last_insert_rowid(db)); + result.metadata = getQueryMetadata(statement, *columnNames); + result.rows = std::make_shared(std::move(*columnNames), std::move(rows)); + return result; + } + NativeRawQueryResult executeStatementRaw(sqlite3* db, sqlite3_stmt* statement) { std::optional> columnNames; std::vector rows; @@ -322,6 +350,11 @@ NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std [&](sqlite3* db, sqlite3_stmt* statement) { return executeStatement(db, statement, mode, onRows); }); } +NativeLazyQueryResult sqliteExecuteLazy(const SQLiteConnectionPtr& connection, const std::string& query, + const std::optional& params) { + return executeCached(connection, query, params, false, executeStatementLazy); +} + NativeRawQueryResult sqliteExecuteRaw(const SQLiteConnectionPtr& connection, const std::string& query, const std::optional& params, bool requireTransaction) { return executeCached(connection, query, params, requireTransaction, executeStatementRaw); @@ -420,6 +453,10 @@ NativeQueryResult SQLitePreparedStatement::execute(const std::optional& params) { + return executeBound(params, executeStatementLazy); +} + NativeRawQueryResult SQLitePreparedStatement::executeRaw(const std::optional& params) { return executeBound(params, executeStatementRaw); } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index b1f31a3df..19e7c816c 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -2,6 +2,7 @@ #include "SQLiteDatabaseConnections.hpp" #include "results/NativeQueryResult.hpp" +#include #include "sqlite/sqlite3.h" #include #include @@ -29,6 +30,8 @@ class SQLitePreparedStatement { * Throws after finalization or connection closure. */ NativeQueryResult execute(const std::optional& params, SQLiteExecutionMode mode); + /** Reset and execute with new bindings, retaining the rows for on-demand conversion. */ + NativeLazyQueryResult executeLazy(const std::optional& params); /** Reset and execute with new bindings, returning rows as arrays of column values. */ NativeRawQueryResult executeRaw(const std::optional& params); /** Release the native statement. Repeated calls are safe. */ @@ -73,6 +76,10 @@ NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std const std::optional& params, SQLiteExecutionMode mode, const SQLiteRowBatchHandler& onRows = nullptr, bool requireTransaction = false); +/** Execute one statement, retaining all rows independently of the connection for on-demand conversion. */ +NativeLazyQueryResult sqliteExecuteLazy(const SQLiteConnectionPtr& connection, const std::string& query, + const std::optional& params); + /** Execute one statement, returning rows as arrays of column values. * @param requireTransaction Reject under the execution lock if SQLite has ended the transaction. */ diff --git a/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp b/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp index 54e91445b..4a83ee3fb 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp @@ -107,6 +107,24 @@ class SQLiteQueryResultBuilder final { /** Receives leading result rows in batches while the statement still runs. */ using SQLiteRowBatchHandler = std::function; +inline std::vector makeQueryColumnNames(jsi::Runtime& runtime, const std::vector& columnNames) { + std::vector names; + names.reserve(columnNames.size()); + for (const auto& name : columnNames) { + names.emplace_back(jsi::PropNameID::forUtf8(runtime, reinterpret_cast(name.data()), name.size())); + } + return names; +} + +inline jsi::Object convertQueryRow(jsi::Runtime& runtime, const std::vector& names, const SQLiteQueryResultRow& row) { + jsi::Object object(runtime); + for (size_t columnIndex = 0; columnIndex < names.size(); columnIndex++) { + // Repeated aliases overwrite earlier values, as the former row map did. + object.setProperty(runtime, names[columnIndex], JSIConverter::toJSI(runtime, row[columnIndex])); + } + return object; +} + } // namespace margelo::nitro::nitrosqlite namespace margelo::nitro { diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index 7b7a048eb..39721ce7c 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -265,6 +265,24 @@ void HybridNitroSQLite::setRowBatchHandler(const Callback& params) { + return sqliteExecuteLazy(_connections.get(dbName), query, params); +} + +Promise +HybridNitroSQLite::executeLazyAsync(const std::string& dbName, const std::string& query, const std::optional& params) { + const auto copiedParams = copyArrayBufferParamsForBackground(params); + SQLiteConnectionPtr connection; + try { + connection = _connections.get(dbName); + } catch (...) { + return Promise::rejected(std::current_exception()); + } + return enqueueConnectionOperation( + connection, [connection, query, copiedParams]() { return sqliteExecuteLazy(connection, query, copiedParams); }); +} + void HybridNitroSQLite::setChangeHandler(const std::string& dbName, const std::optional&)>>& handler) { const auto connection = _connections.get(dbName); diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp index 7e8ae7a72..f00cfad3f 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -91,6 +91,13 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { void setChangeHandler(const std::string& dbName, const std::optional&)>>& handler) override; + /** Execute one SQL statement on the calling thread, retaining rows for on-demand conversion. */ + NativeLazyQueryResult executeLazy(const std::string& dbName, const std::string& query, + const std::optional& params) override; + /** Execute one SQL statement on the background worker, retaining rows for on-demand conversion. */ + Promise executeLazyAsync(const std::string& dbName, const std::string& query, + const std::optional& params) override; + /** Require a live SQLite transaction when @p requireTransaction is true; checked under the execution lock. * Execute one SQL statement on the calling thread, returning rows as arrays of column values. */ NativeRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional& params, diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp index 8f55a510e..106bc941b 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -45,8 +45,21 @@ NativeRawQueryResult HybridPreparedStatement::executeRaw(const std::optionalexecuteRaw(params); } -Promise HybridPreparedStatement::executeRawAsync(const std::optional& params) { - auto copiedParams = copyArrayBufferParamsForBackground(params); +NativeLazyQueryResult HybridPreparedStatement::executeLazy(const std::optional& params) { + return _statement->executeLazy(params); +} + +Promise +HybridPreparedStatement::executeLazyAsync(const std::optional& params) { + const auto copiedParams = copyArrayBufferParamsForBackground(params); + const auto statement = _statement; + return enqueueConnectionOperation( + statement->connection(), [statement, copiedParams]() { return statement->executeLazy(copiedParams); }); +} + +Promise +HybridPreparedStatement::executeRawAsync(const std::optional& params) { + const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; return enqueueConnectionOperation( statement->connection(), [statement, copiedParams = std::move(copiedParams)]() { return statement->executeRaw(copiedParams); }); diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp index e50043f50..5b86d197f 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.hpp @@ -17,6 +17,10 @@ class HybridPreparedStatement : public HybridPreparedStatementSpec { NativeQueryResult execute(const std::optional& params) override; /** Execute with new bindings on the connection's worker, in call order. */ Promise executeAsync(const std::optional& params) override; + /** Execute with new bindings on the calling thread, retaining rows for on-demand conversion. */ + NativeLazyQueryResult executeLazy(const std::optional& params) override; + /** Execute with new bindings on the connection's worker, retaining rows for on-demand conversion. */ + Promise executeLazyAsync(const std::optional& params) override; /** Execute with new bindings on the calling thread, returning rows as arrays of column values. */ NativeRawQueryResult executeRaw(const std::optional& params) override; /** Execute with new bindings on the connection's worker, returning rows as arrays of column values. */ diff --git a/packages/nitro-sqlite-core/src/deprecated.ts b/packages/nitro-sqlite-core/src/deprecated.ts index c8a628657..5d723f724 100644 --- a/packages/nitro-sqlite-core/src/deprecated.ts +++ b/packages/nitro-sqlite-core/src/deprecated.ts @@ -16,7 +16,7 @@ export type { /** @deprecated Use {@linkcode NativeRawQueryRows}. */ NativeRawQueryRows as NitroSQLiteRawQueryRows, /** @deprecated Use {@linkcode QueryColumnMetadata}. */ - QueryColumnMetadata as NitroSQLiteQueryColumnMetadata, + QueryColumnMetadata as QueryColumnMetadata, } from './specs/NativeQueryResult' export type { /** @deprecated Use {@linkcode NativePreparedStatement}. */ diff --git a/packages/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index deac167a8..52d93b1e4 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -33,12 +33,17 @@ export { open } from './operations/session' export { SQLiteError, SQLiteExceptionType, - NitroSQLiteError, - NitroSQLiteExceptionType, + SQLiteError, + SQLiteExceptionType, } from './errors' export type { DatabaseQueueKey } from './DatabaseQueue' export type { NitroSQLite as NativeSQLite } from './specs/NitroSQLite.nitro' export type { PreparedStatement as NativePreparedStatement } from './specs/PreparedStatement.nitro' +export type { + LazyQueryRows, + NativeLazyQueryResult, + SQLiteLazyQueryRows, +} from './specs/NativeLazyQueryResult' export type { NativeQueryResult, NativeQueryResultBinding, diff --git a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts new file mode 100644 index 000000000..01c2f021f --- /dev/null +++ b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts @@ -0,0 +1,41 @@ +import type { CustomType } from 'nitro-core' +import type { QueryResultRow } from '../types' +import type { QueryColumnMetadata } from './NativeQueryResult' + +/** Rows of a completed query, converted to JavaScript on demand. */ +export interface LazyQueryRows { + /** Number of rows in the completed result. Reading it does not convert rows. */ + readonly length: number + + /** Return the row at a zero-based index, converting and caching it on first access. + * An invalid or out-of-range index returns `undefined`. + */ + item(index: number): Row | undefined + + /** Return all rows in SQL result order in a new array. + * Each element is the same object that `item` returns for that index. + */ + toArray(): Row[] +} + +/** Native-backed rows passed from SQLite to JavaScript. */ +export type SQLiteLazyQueryRows = CustomType< + LazyQueryRows, + 'std::shared_ptr', + { include: 'SQLiteLazyQueryRows.hpp' } +> + +/** Native result of a completed statement with on-demand conversion. + * The rows can outlive the statement and connection. Unconverted rows occupy + * native memory while the rows object or one of its accessors is reachable. + */ +export interface NativeLazyQueryResult { + /** SQLite's latest row change count. For a read-only query it may reflect an earlier write. */ + readonly rowsAffected: number + /** Last insert row ID for this connection. It may refer to an earlier statement. */ + readonly insertId?: number + /** The backed rows of this result. */ + readonly rows: SQLiteLazyQueryRows + /** Column metadata keyed by result column name, when available. */ + readonly metadata?: Record +} diff --git a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index 3d0913748..f8b993029 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -12,6 +12,7 @@ import type { NativeRawQueryResult, } from './NativeQueryResult' import type { PreparedStatement } from './PreparedStatement.nitro' +import type { NativeLazyQueryResult } from './NativeLazyQueryResult' export * from '#nitro/NitroSQLite' @@ -177,6 +178,30 @@ export declare class NitroSQLite extends HybridObject { dbName: string, handler?: (changes: DatabaseChange[]) => void, ): void + /** Execute one SQL statement synchronously and retain its rows for on-demand conversion. + * @param dbName Name or ID of an open database connection. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @returns The completed result with individually accessible rows. + * @throws If the connection is closed or the statement fails. + */ + executeLazy( + dbName: string, + query: string, + params?: SQLiteQueryParams, + ): NativeLazyQueryResult + /** Execute like `executeLazy` on the connection's background worker. + * The promise resolves after SQLite has read the whole result and rejects on failure. + * @param dbName Name or ID of an open database connection. + * @param query SQL statement with optional positional placeholders. + * @param params Values bound to the placeholders. + * @returns A promise of the completed result with individually accessible rows. + */ + executeLazyAsync( + dbName: string, + query: string, + params?: SQLiteQueryParams, + ): Promise /** Execute one SQL statement synchronously on the calling thread, returning rows as arrays of column values. * @param dbName Name of an open database. * @param query SQL statement with optional positional placeholders. diff --git a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts index 99ceb8f69..0deaf8f09 100644 --- a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts @@ -1,5 +1,6 @@ import { Android, iOS, type HybridObject } from 'nitro-core' import type { SQLiteQueryParams } from '../types' +import type { NativeLazyQueryResult } from './NativeLazyQueryResult' import type { NativeQueryResultBinding, NativeRawQueryResult, @@ -39,6 +40,20 @@ export declare class PreparedStatement extends HybridObject { * @returns A promise of the native query result. */ executeAsync(params?: SQLiteQueryParams): Promise + /** Execute with new bindings on the calling thread and convert rows on demand. + * @param params Values bound to positional placeholders. + * @returns Rows that remain usable after the statement is finalized. + * @throws If the statement is finalized, the connection is closed, or execution fails. + */ + executeLazy(params?: SQLiteQueryParams): NativeLazyQueryResult + /** Execute like `executeLazy` on the connection's background worker. + * Executions run in call order with the connection's other async calls. + * @param params Values bound to positional placeholders. + * @returns A promise that resolves with the completed result and rejects on failure. + */ + executeLazyAsync( + params?: SQLiteQueryParams, + ): Promise /** Execute on the calling thread like `execute`, returning rows as arrays of column values. * @param params Values bound to positional placeholders. * @returns Column names, rows as value arrays, affected row count, and insert ID. diff --git a/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts b/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts index 84d412bb0..ef33d3d16 100644 --- a/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts +++ b/packages/react-native-nitro-sqlite/platform/src/__mocks__/nitro.ts @@ -8,6 +8,8 @@ export const HybridNitroSQLite = { detach: jest.fn(), execute: jest.fn(), executeAsync: jest.fn(), + executeLazy: jest.fn(), + executeLazyAsync: jest.fn(), setRowBatchHandler: jest.fn(), setChangeHandler: jest.fn(), executeRaw: jest.fn(), 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 7a87e1c2a..770b00cf3 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 @@ -34,6 +34,8 @@ function mockStatement(): PreparedStatement { }, execute: jest.fn(() => nativeResult([{ value: 7 }])), executeAsync: jest.fn(async () => nativeResult([{ value: 8 }])), + executeLazy: jest.fn(), + executeLazyAsync: jest.fn(), executeRaw: jest.fn(() => nativeRawResult(['value'], [[9]])), executeRawAsync: jest.fn(async () => nativeRawResult(['value'], [[10]])), finalize: jest.fn(() => { From 717796bb32c810d08870d7317c2f656cbb403c59 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:40:24 +0100 Subject: [PATCH 02/10] fix: create the lazy row cache through public JSI Co-authored-by: Codex --- packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp index f679e437a..c57de31d1 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -1,5 +1,4 @@ #include "SQLiteLazyQueryRows.hpp" -#include #include #include @@ -53,7 +52,9 @@ SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, s jsi::Object SQLiteLazyQueryRows::toRows(jsi::Runtime& runtime) { auto owner = toObject(runtime).asObject(runtime); if (!owner.hasProperty(runtime, "cache")) { - owner.setProperty(runtime, "cache", CommonGlobals::Object::create(runtime, jsi::Value::null())); + auto object = runtime.global().getPropertyAsObject(runtime, "Object"); + auto cache = object.getPropertyAsFunction(runtime, "create").call(runtime, jsi::Value::null()); + owner.setProperty(runtime, "cache", std::move(cache)); } // The bound functions keep the owner and its cache on the JS heap. Native code holds From 480150827c6aeb4840b67fe3865d918d9361ea48 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:43:19 +0100 Subject: [PATCH 03/10] fix: preserve lazy row caches and release converted storage Compile lazy conversion on draft CI against Nitro 0.35.0 and the installed version. Keep row count stable after releasing positional storage. Co-authored-by: Codex --- .github/ci-paths.json | 4 +- .github/workflows/ci.yml | 3 + .../unit/specs/operations/executeLazy.spec.ts | 71 +++++++++++++++++++ .../cpp/SQLiteLazyQueryRows.cpp | 61 ++++++++++------ .../cpp/SQLiteLazyQueryRows.hpp | 2 + .../src/specs/NativeLazyQueryResult.ts | 10 ++- scripts/check-lazy-cpp.sh | 24 +++++++ scripts/ci.test.ts | 10 +++ scripts/ci.ts | 1 + 9 files changed, 164 insertions(+), 22 deletions(-) create mode 100644 scripts/check-lazy-cpp.sh diff --git a/.github/ci-paths.json b/.github/ci-paths.json index ba03fc6a8..4f4cb6f85 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -138,7 +138,9 @@ "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.*", + "scripts/check-lazy-cpp.sh" ], "docs": [ ".github/workflows/**", diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6fb81637..405db891b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: | diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts index 368fd5f6e..8a6ea8b5e 100644 --- a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -48,6 +48,77 @@ export default function registerExecuteLazyUnitTests() { } }) + 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('restores a row after conversion throws and handles nested row conversion', () => { + const key = 'nitroSQLiteLazyReentrantValue' + const { rows } = NitroSQLite.native.executeLazy( + TEST_DB_NAME, + `SELECT 1 AS ${key} UNION ALL SELECT 2`, + ) + let shouldThrow = true + // eslint-disable-next-line no-extend-native -- Exercise conversion failure and nested access to the same result. + Object.defineProperty(Object.prototype, key, { + configurable: true, + set(this: object, value: unknown) { + if (shouldThrow) throw new Error('row conversion failed') + if (value === 1) expect(rows.item(1)).toEqual({ [key]: 2 }) + Object.defineProperty(this, key, { value, enumerable: true }) + }, + }) + try { + let conversionError: unknown + try { + rows.item(0) + } catch (error) { + conversionError = error + } + expect(conversionError instanceof Error && conversionError.message).toBe( + 'row conversion failed', + ) + shouldThrow = false + const first = rows.item(0) + expect(rows.toArray()).toEqual([{ [key]: 1 }, { [key]: 2 }]) + expect(rows.item(0)).toBe(first) + expect(rows.length).toBe(2) + } 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, diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp index c57de31d1..b4fe62b19 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -23,12 +23,22 @@ namespace { if (const auto* text = std::get_if(&*value)) { bytes += stringAllocationSize(*text); } else if (const auto* blob = std::get_if>(&*value)) { - bytes += (*blob)->getExternalMemorySize(); + bytes += (*blob)->size(); } } return bytes; } + void defineOwnProperty(jsi::Runtime& runtime, const jsi::Object& target, const char* name, jsi::Value value) { + auto object = runtime.global().getPropertyAsObject(runtime, "Object"); + auto descriptor = object.getPropertyAsFunction(runtime, "create").call(runtime, jsi::Value::null()).asObject(runtime); + descriptor.setProperty(runtime, "value", std::move(value)); + descriptor.setProperty(runtime, "enumerable", true); + descriptor.setProperty(runtime, "writable", true); + descriptor.setProperty(runtime, "configurable", true); + object.getPropertyAsFunction(runtime, "defineProperty").call(runtime, target, jsi::String::createFromAscii(runtime, name), descriptor); + } + jsi::Value bindAccessor(jsi::Runtime& runtime, const jsi::Object& owner, const char* name, unsigned int arity, jsi::HostFunctionType accessor) { auto function = jsi::Function::createFromHostFunction(runtime, jsi::PropNameID::forAscii(runtime, name), arity, std::move(accessor)); @@ -38,9 +48,9 @@ namespace { } // namespace SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, std::vector rows) - : HybridObject("SQLiteLazyQueryRows"), _data{std::move(columnNames), std::move(rows)}, - _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + - _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { + : HybridObject("SQLiteLazyQueryRows"), _data{std::move(columnNames), std::move(rows)}, _rowCount(_data.rows.size()), + _remainingRows(_rowCount), _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + + _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { for (const auto& name : _data.columnNames) { _retainedBytes += stringAllocationSize(name); } @@ -51,28 +61,34 @@ SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, s jsi::Object SQLiteLazyQueryRows::toRows(jsi::Runtime& runtime) { auto owner = toObject(runtime).asObject(runtime); - if (!owner.hasProperty(runtime, "cache")) { - auto object = runtime.global().getPropertyAsObject(runtime, "Object"); + auto object = runtime.global().getPropertyAsObject(runtime, "Object"); + auto hasOwnProperty = object.getPropertyAsObject(runtime, "prototype").getPropertyAsFunction(runtime, "hasOwnProperty"); + if (!hasOwnProperty.callWithThis(runtime, owner, jsi::String::createFromAscii(runtime, "cache")).getBool()) { auto cache = object.getPropertyAsFunction(runtime, "create").call(runtime, jsi::Value::null()); - owner.setProperty(runtime, "cache", std::move(cache)); + defineOwnProperty(runtime, owner, "cache", std::move(cache)); } // The bound functions keep the owner and its cache on the JS heap. Native code holds // no strong JS references, so even a cached row that references its result can be collected. jsi::Object result(runtime); - result.setProperty(runtime, "length", static_cast(_data.rows.size())); - result.setProperty( - runtime, "item", + defineOwnProperty(runtime, result, "length", jsi::Value(static_cast(_rowCount))); + defineOwnProperty( + runtime, result, "item", bindAccessor(runtime, owner, "item", 1, [](jsi::Runtime& rt, const jsi::Value& receiver, const jsi::Value* args, size_t count) { auto state = receiver.asObject(rt); - return dynamic_cast(*state.getNativeState(rt)).item(rt, state, args, count); - })); - result.setProperty( - runtime, "toArray", - bindAccessor(runtime, owner, "toArray", 0, [](jsi::Runtime& rt, const jsi::Value& receiver, const jsi::Value*, size_t) { - auto state = receiver.asObject(rt); - return dynamic_cast(*state.getNativeState(rt)).toArray(rt, state); + auto rows = std::dynamic_pointer_cast(state.getNativeState(rt)); + if (!rows) + throw jsi::JSError(rt, "Invalid SQLite lazy rows owner"); + return rows->item(rt, state, args, count); })); + defineOwnProperty(runtime, result, "toArray", + bindAccessor(runtime, owner, "toArray", 0, [](jsi::Runtime& rt, const jsi::Value& receiver, const jsi::Value*, size_t) { + auto state = receiver.asObject(rt); + auto rows = std::dynamic_pointer_cast(state.getNativeState(rt)); + if (!rows) + throw jsi::JSError(rt, "Invalid SQLite lazy rows owner"); + return rows->toArray(rt, state); + })); return result; } @@ -84,7 +100,7 @@ jsi::Value SQLiteLazyQueryRows::item(jsi::Runtime& runtime, const jsi::Object& o if (count == 0 || !args[0].isNumber()) return jsi::Value::undefined(); const double index = args[0].getNumber(); - if (!(index >= 0 && index < _data.rows.size() && std::trunc(index) == index)) { + if (!(index >= 0 && index < _rowCount && std::trunc(index) == index)) { return jsi::Value::undefined(); } @@ -94,8 +110,8 @@ jsi::Value SQLiteLazyQueryRows::item(jsi::Runtime& runtime, const jsi::Object& o jsi::Array SQLiteLazyQueryRows::toArray(jsi::Runtime& runtime, const jsi::Object& owner) { const auto cache = owner.getPropertyAsObject(runtime, "cache"); const auto names = makeQueryColumnNames(runtime, _data.columnNames); - jsi::Array array(runtime, _data.rows.size()); - for (size_t index = 0; index < _data.rows.size(); index++) { + jsi::Array array(runtime, _rowCount); + for (size_t index = 0; index < _rowCount; index++) { array.setValueAtIndex(runtime, index, materialize(runtime, owner, cache, index, &names)); } return array; @@ -131,6 +147,11 @@ jsi::Value SQLiteLazyQueryRows::materialize(jsi::Runtime& runtime, const jsi::Ob // Nitro now accounts for any BLOB buffers on their JS ArrayBuffers. _retainedBytes -= rowAllocationSize(nativeRow); SQLiteQueryResultRow{}.swap(nativeRow); + if (--_remainingRows == 0) { + _retainedBytes = sizeof(*this); + std::vector{}.swap(_data.rows); + std::vector{}.swap(_data.columnNames); + } owner.setExternalMemoryPressure(runtime, _retainedBytes); return row; } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp index 72a2c7e45..03b46636e 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp @@ -21,6 +21,8 @@ class SQLiteLazyQueryRows final : public HybridObject { const std::vector* names = nullptr); SQLiteNativeQueryResults _data; + const size_t _rowCount; + size_t _remainingRows; size_t _retainedBytes; }; diff --git a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts index 01c2f021f..ac1ed0904 100644 --- a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts +++ b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts @@ -2,7 +2,11 @@ import type { CustomType } from 'nitro-core' import type { QueryResultRow } from '../types' import type { QueryColumnMetadata } from './NativeQueryResult' -/** Rows of a completed query, converted to JavaScript on demand. */ +/** Rows of a completed query, converted to JavaScript on demand. + * Only `length`, `item()` and `toArray()` are available. Numeric indexing, + * iteration and `_array` are unsupported. JSON serialization includes `length` + * but no row values. Serialize `toArray()` to include the rows. + */ export interface LazyQueryRows { /** Number of rows in the completed result. Reading it does not convert rows. */ readonly length: number @@ -14,6 +18,8 @@ export interface LazyQueryRows { /** Return all rows in SQL result order in a new array. * Each element is the same object that `item` returns for that index. + * Conversion runs synchronously and may throw. + * @returns A new array containing every cached row. */ toArray(): Row[] } @@ -28,6 +34,8 @@ export type SQLiteLazyQueryRows = CustomType< /** Native result of a completed statement with on-demand conversion. * The rows can outlive the statement and connection. Unconverted rows occupy * native memory while the rows object or one of its accessors is reachable. + * Conversion releases each native row, and converting every row releases the + * remaining positional storage. Otherwise GC determines when storage is released. */ export interface NativeLazyQueryResult { /** SQLite's latest row change count. For a read-only query it may reflect an earlier write. */ diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh new file mode 100644 index 000000000..babdac0ca --- /dev/null +++ b/scripts/check-lazy-cpp.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +# CocoaPods and CMake flatten Nitro's public headers into NitroModules/. +headers=$(mktemp -d) +trap 'rm -rf "$headers"' EXIT +python3 - "$headers" "${NITRO_CPP_DIR:-node_modules/react-native-nitro-modules/cpp}" <<'PY' +from pathlib import Path +import sys +output = Path(sys.argv[1]) / 'NitroModules' +output.mkdir() +for header in Path(sys.argv[2]).resolve().rglob('*.hpp'): + (output / header.name).symlink_to(header) +PY + +for source in NitroSQLiteLazyQueryRows.cpp NitroSQLiteOperations.cpp; do + clang++ -std=c++20 -fsyntax-only \ + -I"$headers" \ + -Inode_modules/react-native/ReactCommon/jsi \ + -Ipackages/react-native-nitro-sqlite/cpp \ + -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ + -Ipackages/react-native-nitro-sqlite/nitrogen/generated/shared/c++ \ + "packages/react-native-nitro-sqlite/cpp/$source" +done diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index f33895320..0a5e1a52e 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -450,3 +450,13 @@ function enabled(checks: ReturnType): string[] { .filter(([, selected]) => selected) .map(([name]) => name) } + +test('lazy conversion changes always select host C++ checks', () => { + for (const file of [ + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteLazyQueryRows.cpp', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp', + 'scripts/check-lazy-cpp.sh', + ]) { + assert.equal(selectChecks([file], false).cpp_tests, true, file) + } +}) diff --git a/scripts/ci.ts b/scripts/ci.ts index 0839153cd..f7dfb1926 100644 --- a/scripts/ci.ts +++ b/scripts/ci.ts @@ -83,6 +83,7 @@ function main(): void { throw new Error('GITHUB_OUTPUT is required') } const dependencies = + checks.cpp_tests || checks.typescript || checks.expo_plugin || checks.docs || From fd6c7deb19f12dc768100796f3d37c3641dc23fb Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:45:54 +0100 Subject: [PATCH 04/10] test: compile lazy conversion to native objects Co-authored-by: Codex --- scripts/check-lazy-cpp.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh index babdac0ca..9ce952f51 100644 --- a/scripts/check-lazy-cpp.sh +++ b/scripts/check-lazy-cpp.sh @@ -14,7 +14,7 @@ for header in Path(sys.argv[2]).resolve().rglob('*.hpp'): PY for source in NitroSQLiteLazyQueryRows.cpp NitroSQLiteOperations.cpp; do - clang++ -std=c++20 -fsyntax-only \ + clang++ -std=c++20 -c -o "$headers/$source.o" \ -I"$headers" \ -Inode_modules/react-native/ReactCommon/jsi \ -Ipackages/react-native-nitro-sqlite/cpp \ From 3dc0192144fe6f03da8a0abbd8c20f6dea56f5e1 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:47:15 +0100 Subject: [PATCH 05/10] test: compile portable lazy rows on Linux CI Leave Operations to native application jobs because its filesystem wrapper does not compile on Linux hosts. Co-authored-by: Codex --- scripts/check-lazy-cpp.sh | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh index 9ce952f51..45ac27966 100644 --- a/scripts/check-lazy-cpp.sh +++ b/scripts/check-lazy-cpp.sh @@ -13,12 +13,11 @@ for header in Path(sys.argv[2]).resolve().rglob('*.hpp'): (output / header.name).symlink_to(header) PY -for source in NitroSQLiteLazyQueryRows.cpp NitroSQLiteOperations.cpp; do - clang++ -std=c++20 -c -o "$headers/$source.o" \ - -I"$headers" \ - -Inode_modules/react-native/ReactCommon/jsi \ - -Ipackages/react-native-nitro-sqlite/cpp \ - -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - -Ipackages/react-native-nitro-sqlite/nitrogen/generated/shared/c++ \ - "packages/react-native-nitro-sqlite/cpp/$source" -done +# Native application jobs compile Operations with the target platform's filesystem APIs. +clang++ -std=c++20 -c -o "$headers/lazy-rows.o" \ + -I"$headers" \ + -Inode_modules/react-native/ReactCommon/jsi \ + -Ipackages/react-native-nitro-sqlite/cpp \ + -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ + -Ipackages/react-native-nitro-sqlite/nitrogen/generated/shared/c++ \ + packages/react-native-nitro-sqlite/cpp/NitroSQLiteLazyQueryRows.cpp From 7658ace31e2b203050d9d84c2fec543a6b9d351a Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:04:33 +0100 Subject: [PATCH 06/10] fix: cover lazy dependencies and release empty row storage Co-authored-by: Codex --- .github/ci-paths.json | 5 +++++ .../tests/unit/specs/operations/executeLazy.spec.ts | 11 +++++++++++ .../nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp | 6 ++++++ scripts/ci.test.ts | 12 ++++++++++++ 4 files changed, 34 insertions(+) diff --git a/.github/ci-paths.json b/.github/ci-paths.json index 4f4cb6f85..3e1c1fc65 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -87,6 +87,11 @@ ".github/actions/**", ".github/ci-paths.json", "scripts/ci*", + "bun.lock", + "package.json", + "example/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.*", diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts index 8a6ea8b5e..bdfc5f213 100644 --- a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -4,6 +4,17 @@ import { it } from '@tests/TestApi' import { TEST_DB_NAME } from '@tests/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('converts native async rows only when read and caches them by index', async () => { const key = 'nitroSQLiteLazyTestValue' let conversions = 0 diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp index b4fe62b19..1cd9f7b40 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -51,6 +51,12 @@ SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, s : HybridObject("SQLiteLazyQueryRows"), _data{std::move(columnNames), std::move(rows)}, _rowCount(_data.rows.size()), _remainingRows(_rowCount), _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { + if (_rowCount == 0) { + std::vector{}.swap(_data.rows); + std::vector{}.swap(_data.columnNames); + _retainedBytes = sizeof(*this); + return; + } for (const auto& name : _data.columnNames) { _retainedBytes += stringAllocationSize(name); } diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index 0a5e1a52e..3fc107ff0 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -460,3 +460,15 @@ test('lazy conversion changes always select host C++ checks', () => { assert.equal(selectChecks([file], false).cpp_tests, true, file) } }) + +test('lazy native dependencies select compatibility compilation on drafts', () => { + for (const file of [ + 'bun.lock', + 'package.json', + 'example/package.json', + 'packages/react-native-nitro-sqlite/package.json', + 'patches/react-native-nitro-modules+0.37.2.patch', + ]) { + assert.equal(selectChecks([file], false).cpp_tests, true, file) + } +}) From 6ae1b09c8858b9c65a2c7cb553e448efd7844d9e Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 13:08:51 +0100 Subject: [PATCH 07/10] fix: adapt lazy results to shared Nitro v1 storage Co-authored-by: Codex --- .github/ci-paths.json | 3 +- .../unit/specs/operations/executeLazy.spec.ts | 47 +++++++--------- .../cpp/SQLiteLazyQueryRows.cpp | 12 ++--- .../cpp/SQLiteOperations.cpp | 21 ++++---- .../cpp/SQLiteOperations.hpp | 4 +- .../cpp/SQLiteQueryResults.hpp | 8 ++- .../cpp/hybridObjects/HybridNitroSQLite.cpp | 15 +++--- .../cpp/hybridObjects/HybridNitroSQLite.hpp | 7 +-- .../hybridObjects/HybridPreparedStatement.cpp | 10 ++-- .../cpp/results/QueryColumnMetadata.hpp | 25 +++++++++ packages/nitro-sqlite-core/src/deprecated.ts | 2 +- packages/nitro-sqlite-core/src/index.ts | 5 +- .../src/specs/NativeLazyQueryResult.ts | 9 +++- .../src/specs/NitroSQLite.nitro.ts | 4 ++ .../src/specs/PreparedStatement.nitro.ts | 4 +- .../android/RNNitroSQLite+autolinking.cmake | 1 + .../c++/HybridNitroSQLiteSpecClass.cpp | 3 ++ .../c++/HybridPreparedStatementSpecClass.cpp | 3 ++ .../apple/c++/HybridNitroSQLiteSpecClass.cpp | 3 ++ .../c++/HybridPreparedStatementSpecClass.cpp | 3 ++ .../shared/c++/NativeLazyQueryResult.cpp | 53 +++++++++++++++++++ .../RNNitroSQLite/HybridNitroSQLiteSpec.hpp | 3 ++ .../HybridPreparedStatementSpec.hpp | 3 ++ .../RNNitroSQLite/NativeLazyQueryResult.hpp | 50 +++++++++++++++++ scripts/check-lazy-cpp.sh | 46 +++++++++------- scripts/ci.test.ts | 7 +-- 26 files changed, 259 insertions(+), 92 deletions(-) create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeLazyQueryResult.cpp create mode 100644 packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeLazyQueryResult.hpp diff --git a/.github/ci-paths.json b/.github/ci-paths.json index 3e1c1fc65..a71339663 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -89,7 +89,7 @@ "scripts/ci*", "bun.lock", "package.json", - "example/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.*", @@ -145,6 +145,7 @@ "packages/nitro-sqlite/platform/cpp/**", "packages/nitro-sqlite/src/specs/**", "packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteLazyQueryRows.*", "scripts/check-lazy-cpp.sh" ], "docs": [ diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts index bdfc5f213..09baf5eea 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 'react-native-nitro-sqlite' -import { expect } from '@tests/unit/common' -import { it } from '@tests/TestApi' -import { TEST_DB_NAME } from '@tests/db' +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', () => { @@ -94,37 +94,30 @@ export default function registerExecuteLazyUnitTests() { } }) - it('restores a row after conversion throws and handles nested row conversion', () => { + it('keeps inherited columns as own properties without invoking setters', () => { const key = 'nitroSQLiteLazyReentrantValue' - const { rows } = NitroSQLite.native.executeLazy( - TEST_DB_NAME, - `SELECT 1 AS ${key} UNION ALL SELECT 2`, - ) - let shouldThrow = true - // eslint-disable-next-line no-extend-native -- Exercise conversion failure and nested access to the same result. + 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(this: object, value: unknown) { - if (shouldThrow) throw new Error('row conversion failed') - if (value === 1) expect(rows.item(1)).toEqual({ [key]: 2 }) - Object.defineProperty(this, key, { value, enumerable: true }) + set() { + setterCalls++ + throw new Error('inherited setter must not run') }, }) try { - let conversionError: unknown - try { - rows.item(0) - } catch (error) { - conversionError = error - } - expect(conversionError instanceof Error && conversionError.message).toBe( - 'row conversion failed', - ) - shouldThrow = false + 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([{ [key]: 1 }, { [key]: 2 }]) + expect(rows.toArray()).toEqual(eager.results) expect(rows.item(0)).toBe(first) - expect(rows.length).toBe(2) + 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) } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp index 1cd9f7b40..4cbad6cc6 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -22,8 +22,8 @@ namespace { continue; if (const auto* text = std::get_if(&*value)) { bytes += stringAllocationSize(*text); - } else if (const auto* blob = std::get_if>(&*value)) { - bytes += (*blob)->size(); + } else if (const auto* blob = std::get_if(&*value)) { + bytes += blob->size(); } } return bytes; @@ -48,9 +48,9 @@ namespace { } // namespace SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, std::vector rows) - : HybridObject("SQLiteLazyQueryRows"), _data{std::move(columnNames), std::move(rows)}, _rowCount(_data.rows.size()), - _remainingRows(_rowCount), _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + - _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { + : _data{std::move(columnNames), std::move(rows)}, _rowCount(_data.rows.size()), _remainingRows(_rowCount), + _retainedBytes(sizeof(*this) + _data.columnNames.capacity() * sizeof(std::string) + + _data.rows.capacity() * sizeof(SQLiteQueryResultRow)) { if (_rowCount == 0) { std::vector{}.swap(_data.rows); std::vector{}.swap(_data.columnNames); @@ -139,7 +139,7 @@ jsi::Value SQLiteLazyQueryRows::materialize(jsi::Runtime& runtime, const jsi::Ob if (slot.empty()) { throw jsi::JSError(runtime, "Cannot access a SQLite row while it is being converted"); } - // A column setter on Object.prototype can call back into this accessor. + // Keep the row recoverable if conversion or cache insertion throws. SQLiteQueryResultRow nativeRow; nativeRow.swap(slot); jsi::Value row; diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index f2dfce150..6ce7a564e 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -1,6 +1,6 @@ #include "SQLiteOperations.hpp" -#include "SQLiteLazyQueryRows.hpp" #include "SQLiteException.hpp" +#include "SQLiteLazyQueryRows.hpp" #include "SQLiteStatementGroup.hpp" #include "SQLiteStatementTail.hpp" #include "SQLiteUtils.hpp" @@ -282,7 +282,8 @@ namespace { std::optional> columnNames; std::vector rows; consumeStatement(db, statement, [&](sqlite3_stmt* currentStatement) { - if (!columnNames) columnNames = readResultColumnNames(db, currentStatement); + if (!columnNames) + columnNames = readResultColumnNames(db, currentStatement); SQLiteQueryResultRow row; row.reserve(columnNames->size()); for (size_t index = 0; index < columnNames->size(); index++) { @@ -290,13 +291,11 @@ namespace { } rows.push_back(std::move(row)); }); - if (!columnNames) columnNames = readResultColumnNames(db, statement); - NativeLazyQueryResult result; - result.rowsAffected = sqlite3_changes(db); - result.insertId = static_cast(sqlite3_last_insert_rowid(db)); - result.metadata = getQueryMetadata(statement, *columnNames); - result.rows = std::make_shared(std::move(*columnNames), std::move(rows)); - return result; + if (!columnNames) + columnNames = readResultColumnNames(db, statement); + auto metadata = getQueryMetadata(statement, *columnNames); + return NativeLazyQueryResult(sqlite3_changes(db), static_cast(sqlite3_last_insert_rowid(db)), + std::make_shared(std::move(*columnNames), std::move(rows)), std::move(metadata)); } NativeRawQueryResult executeStatementRaw(sqlite3* db, sqlite3_stmt* statement) { @@ -351,8 +350,8 @@ NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std } NativeLazyQueryResult sqliteExecuteLazy(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params) { - return executeCached(connection, query, params, false, executeStatementLazy); + const std::optional& params, bool requireTransaction) { + return executeCached(connection, query, params, requireTransaction, executeStatementLazy); } NativeRawQueryResult sqliteExecuteRaw(const SQLiteConnectionPtr& connection, const std::string& query, diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index 19e7c816c..ff1903075 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -2,8 +2,8 @@ #include "SQLiteDatabaseConnections.hpp" #include "results/NativeQueryResult.hpp" -#include #include "sqlite/sqlite3.h" +#include #include #include #include @@ -78,7 +78,7 @@ NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std /** Execute one statement, retaining all rows independently of the connection for on-demand conversion. */ NativeLazyQueryResult sqliteExecuteLazy(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params); + const std::optional& params, bool requireTransaction = false); /** Execute one statement, returning rows as arrays of column values. * @param requireTransaction Reject under the execution lock if SQLite has ended the transaction. diff --git a/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp b/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp index 4a83ee3fb..a44748168 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteQueryResults.hpp @@ -3,6 +3,7 @@ #include "SQLiteTypes.hpp" #include #include +#include #include #include #include @@ -117,11 +118,16 @@ inline std::vector makeQueryColumnNames(jsi::Runtime& runtime, } inline jsi::Object convertQueryRow(jsi::Runtime& runtime, const std::vector& names, const SQLiteQueryResultRow& row) { - jsi::Object object(runtime); + jsi::Object probe(runtime); + const bool hasInheritedName = std::any_of(names.begin(), names.end(), [&](const auto& name) { return probe.hasProperty(runtime, name); }); + const auto prototype = hasInheritedName ? probe.getPrototype(runtime) : jsi::Value::undefined(); + auto object = hasInheritedName ? jsi::Object::create(runtime, jsi::Value::null()) : std::move(probe); for (size_t columnIndex = 0; columnIndex < names.size(); columnIndex++) { // Repeated aliases overwrite earlier values, as the former row map did. object.setProperty(runtime, names[columnIndex], JSIConverter::toJSI(runtime, row[columnIndex])); } + if (hasInheritedName) + object.setPrototype(runtime, prototype); return object; } diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index 39721ce7c..91162c3c7 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -266,12 +266,14 @@ void HybridNitroSQLite::setRowBatchHandler(const Callback& params) { - return sqliteExecuteLazy(_connections.get(dbName), query, params); + const std::optional& params, + const std::optional& requireTransaction) { + return sqliteExecuteLazy(_connections.get(dbName), query, params, requireTransaction.value_or(false)); } -Promise -HybridNitroSQLite::executeLazyAsync(const std::string& dbName, const std::string& query, const std::optional& params) { +Promise HybridNitroSQLite::executeLazyAsync(const std::string& dbName, const std::string& query, + const std::optional& params, + const std::optional& requireTransaction) { const auto copiedParams = copyArrayBufferParamsForBackground(params); SQLiteConnectionPtr connection; try { @@ -279,8 +281,9 @@ HybridNitroSQLite::executeLazyAsync(const std::string& dbName, const std::string } catch (...) { return Promise::rejected(std::current_exception()); } - return enqueueConnectionOperation( - connection, [connection, query, copiedParams]() { return sqliteExecuteLazy(connection, query, copiedParams); }); + return enqueueConnectionOperation(connection, [connection, query, copiedParams, requireTransaction]() { + return sqliteExecuteLazy(connection, query, copiedParams, requireTransaction.value_or(false)); + }); } void HybridNitroSQLite::setChangeHandler(const std::string& dbName, diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp index f00cfad3f..85b94eaac 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -92,11 +92,12 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { const std::optional&)>>& handler) override; /** Execute one SQL statement on the calling thread, retaining rows for on-demand conversion. */ - NativeLazyQueryResult executeLazy(const std::string& dbName, const std::string& query, - const std::optional& params) override; + NativeLazyQueryResult executeLazy(const std::string& dbName, const std::string& query, const std::optional& params, + const std::optional& requireTransaction) override; /** Execute one SQL statement on the background worker, retaining rows for on-demand conversion. */ Promise executeLazyAsync(const std::string& dbName, const std::string& query, - const std::optional& params) override; + const std::optional& params, + const std::optional& requireTransaction) override; /** Require a live SQLite transaction when @p requireTransaction is true; checked under the execution lock. * Execute one SQL statement on the calling thread, returning rows as arrays of column values. */ diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp index 106bc941b..8a0d2b04d 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -49,16 +49,14 @@ NativeLazyQueryResult HybridPreparedStatement::executeLazy(const std::optionalexecuteLazy(params); } -Promise -HybridPreparedStatement::executeLazyAsync(const std::optional& params) { +Promise HybridPreparedStatement::executeLazyAsync(const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; - return enqueueConnectionOperation( - statement->connection(), [statement, copiedParams]() { return statement->executeLazy(copiedParams); }); + return enqueueConnectionOperation(statement->connection(), + [statement, copiedParams]() { return statement->executeLazy(copiedParams); }); } -Promise -HybridPreparedStatement::executeRawAsync(const std::optional& params) { +Promise HybridPreparedStatement::executeRawAsync(const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; return enqueueConnectionOperation( diff --git a/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp index 730760814..2514039a0 100644 --- a/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp +++ b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp @@ -2,6 +2,7 @@ #include "ColumnType.hpp" #include +#include #include #include @@ -21,3 +22,27 @@ struct QueryColumnMetadata final { }; } // namespace margelo::nitro::nitrosqlite + +namespace margelo::nitro { + +/** Converts metadata emitted by lazy results using the shared column declaration. */ +template <> +struct JSIConverter final { + static jsi::Value toJSI(jsi::Runtime& runtime, const nitrosqlite::QueryColumnMetadata& column) { + jsi::Object result(runtime); + result.setProperty(runtime, "name", JSIConverter::toJSI(runtime, column.name)); + result.setProperty(runtime, "type", JSIConverter::toJSI(runtime, column.type)); + result.setProperty(runtime, "index", column.index); + return result; + } + + static nitrosqlite::QueryColumnMetadata fromJSI(jsi::Runtime&, const jsi::Value&) { + throw std::logic_error("SQLite column metadata cannot be passed from JavaScript"); + } + + static bool canConvert(jsi::Runtime&, const jsi::Value&) { + return false; + } +}; + +} // namespace margelo::nitro diff --git a/packages/nitro-sqlite-core/src/deprecated.ts b/packages/nitro-sqlite-core/src/deprecated.ts index 5d723f724..c8a628657 100644 --- a/packages/nitro-sqlite-core/src/deprecated.ts +++ b/packages/nitro-sqlite-core/src/deprecated.ts @@ -16,7 +16,7 @@ export type { /** @deprecated Use {@linkcode NativeRawQueryRows}. */ NativeRawQueryRows as NitroSQLiteRawQueryRows, /** @deprecated Use {@linkcode QueryColumnMetadata}. */ - QueryColumnMetadata as QueryColumnMetadata, + QueryColumnMetadata as NitroSQLiteQueryColumnMetadata, } from './specs/NativeQueryResult' export type { /** @deprecated Use {@linkcode NativePreparedStatement}. */ diff --git a/packages/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index 52d93b1e4..e01dc6e7b 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -33,13 +33,14 @@ export { open } from './operations/session' export { SQLiteError, SQLiteExceptionType, - SQLiteError, - SQLiteExceptionType, + NitroSQLiteError, + NitroSQLiteExceptionType, } from './errors' export type { DatabaseQueueKey } from './DatabaseQueue' export type { NitroSQLite as NativeSQLite } from './specs/NitroSQLite.nitro' export type { PreparedStatement as NativePreparedStatement } from './specs/PreparedStatement.nitro' export type { + LazyQueryColumnMetadata, LazyQueryRows, NativeLazyQueryResult, SQLiteLazyQueryRows, diff --git a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts index ac1ed0904..b4d85b07f 100644 --- a/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts +++ b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts @@ -31,6 +31,13 @@ export type SQLiteLazyQueryRows = CustomType< { include: 'SQLiteLazyQueryRows.hpp' } > +/** Column metadata mapped to the shared native declaration. */ +export type LazyQueryColumnMetadata = CustomType< + QueryColumnMetadata, + 'margelo::nitro::nitrosqlite::QueryColumnMetadata', + { include: 'results/QueryColumnMetadata.hpp' } +> + /** Native result of a completed statement with on-demand conversion. * The rows can outlive the statement and connection. Unconverted rows occupy * native memory while the rows object or one of its accessors is reachable. @@ -45,5 +52,5 @@ export interface NativeLazyQueryResult { /** The backed rows of this result. */ readonly rows: SQLiteLazyQueryRows /** Column metadata keyed by result column name, when available. */ - readonly metadata?: Record + readonly metadata?: Record } diff --git a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index f8b993029..7ef9c6aaa 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -182,6 +182,7 @@ export declare class NitroSQLite extends HybridObject { * @param dbName Name or ID of an open database connection. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param requireTransaction Reject if SQLite has ended the managed transaction. * @returns The completed result with individually accessible rows. * @throws If the connection is closed or the statement fails. */ @@ -189,18 +190,21 @@ export declare class NitroSQLite extends HybridObject { dbName: string, query: string, params?: SQLiteQueryParams, + requireTransaction?: boolean, ): NativeLazyQueryResult /** Execute like `executeLazy` on the connection's background worker. * The promise resolves after SQLite has read the whole result and rejects on failure. * @param dbName Name or ID of an open database connection. * @param query SQL statement with optional positional placeholders. * @param params Values bound to the placeholders. + * @param requireTransaction Reject if SQLite has ended the managed transaction. * @returns A promise of the completed result with individually accessible rows. */ executeLazyAsync( dbName: string, query: string, params?: SQLiteQueryParams, + requireTransaction?: boolean, ): Promise /** Execute one SQL statement synchronously on the calling thread, returning rows as arrays of column values. * @param dbName Name of an open database. diff --git a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts index 0deaf8f09..fe3e8c525 100644 --- a/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/PreparedStatement.nitro.ts @@ -51,9 +51,7 @@ export declare class PreparedStatement extends HybridObject { * @param params Values bound to positional placeholders. * @returns A promise that resolves with the completed result and rejects on failure. */ - executeLazyAsync( - params?: SQLiteQueryParams, - ): Promise + executeLazyAsync(params?: SQLiteQueryParams): Promise /** Execute on the calling thread like `execute`, returning rows as arrays of column values. * @param params Values bound to positional placeholders. * @returns Column names, rows as value arrays, affected row count, and insert ID. diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake index eac5b3282..576da3ba2 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake @@ -22,6 +22,7 @@ target_sources(RNNitroSQLite PRIVATE "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/FileLoadResult.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridNitroSQLiteSpec.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridPreparedStatementSpec.cpp" + "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NativeLazyQueryResult.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NativeRawQueryResult.cpp" ) diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp index 943d77455..556fe155b 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,8 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridMethod("executeAsync", &HybridNitroSQLiteSpec::executeAsync); clazz.registerHybridMethod("setRowBatchHandler", &HybridNitroSQLiteSpec::setRowBatchHandler); clazz.registerHybridMethod("setChangeHandler", &HybridNitroSQLiteSpec::setChangeHandler); + clazz.registerHybridMethod("executeLazy", &HybridNitroSQLiteSpec::executeLazy); + clazz.registerHybridMethod("executeLazyAsync", &HybridNitroSQLiteSpec::executeLazyAsync); clazz.registerHybridMethod("executeRaw", &HybridNitroSQLiteSpec::executeRaw); clazz.registerHybridMethod("executeRawAsync", &HybridNitroSQLiteSpec::executeRawAsync); clazz.registerHybridMethod("prepare", &HybridNitroSQLiteSpec::prepare); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp index 26c229a67..f6648f1e6 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -26,6 +27,8 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridProperty("isFinalized", &HybridPreparedStatementSpec::getIsFinalized); clazz.registerHybridMethod("execute", &HybridPreparedStatementSpec::execute); clazz.registerHybridMethod("executeAsync", &HybridPreparedStatementSpec::executeAsync); + clazz.registerHybridMethod("executeLazy", &HybridPreparedStatementSpec::executeLazy); + clazz.registerHybridMethod("executeLazyAsync", &HybridPreparedStatementSpec::executeLazyAsync); clazz.registerHybridMethod("executeRaw", &HybridPreparedStatementSpec::executeRaw); clazz.registerHybridMethod("executeRawAsync", &HybridPreparedStatementSpec::executeRawAsync); clazz.registerHybridMethod("finalize", &HybridPreparedStatementSpec::finalize); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp index 943d77455..556fe155b 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridNitroSQLiteSpecClass.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,8 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridMethod("executeAsync", &HybridNitroSQLiteSpec::executeAsync); clazz.registerHybridMethod("setRowBatchHandler", &HybridNitroSQLiteSpec::setRowBatchHandler); clazz.registerHybridMethod("setChangeHandler", &HybridNitroSQLiteSpec::setChangeHandler); + clazz.registerHybridMethod("executeLazy", &HybridNitroSQLiteSpec::executeLazy); + clazz.registerHybridMethod("executeLazyAsync", &HybridNitroSQLiteSpec::executeLazyAsync); clazz.registerHybridMethod("executeRaw", &HybridNitroSQLiteSpec::executeRaw); clazz.registerHybridMethod("executeRawAsync", &HybridNitroSQLiteSpec::executeRawAsync); clazz.registerHybridMethod("prepare", &HybridNitroSQLiteSpec::prepare); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp index 26c229a67..f6648f1e6 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/apple/c++/HybridPreparedStatementSpecClass.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include @@ -26,6 +27,8 @@ namespace margelo::nitro::rnnitrosqlite { clazz.registerHybridProperty("isFinalized", &HybridPreparedStatementSpec::getIsFinalized); clazz.registerHybridMethod("execute", &HybridPreparedStatementSpec::execute); clazz.registerHybridMethod("executeAsync", &HybridPreparedStatementSpec::executeAsync); + clazz.registerHybridMethod("executeLazy", &HybridPreparedStatementSpec::executeLazy); + clazz.registerHybridMethod("executeLazyAsync", &HybridPreparedStatementSpec::executeLazyAsync); clazz.registerHybridMethod("executeRaw", &HybridPreparedStatementSpec::executeRaw); clazz.registerHybridMethod("executeRawAsync", &HybridPreparedStatementSpec::executeRawAsync); clazz.registerHybridMethod("finalize", &HybridPreparedStatementSpec::finalize); diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeLazyQueryResult.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeLazyQueryResult.cpp new file mode 100644 index 000000000..bd26eb4e1 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeLazyQueryResult.cpp @@ -0,0 +1,53 @@ +/// +/// NativeLazyQueryResult.cpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#include +#include +#include +#include +#include "SQLiteLazyQueryRows.hpp" +#include +#include "results/QueryColumnMetadata.hpp" +#include + +namespace margelo::nitro { + + margelo::nitro::rnnitrosqlite::NativeLazyQueryResult JSIConverter::fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + jsi::Object obj = arg.asObject(runtime); + return margelo::nitro::rnnitrosqlite::NativeLazyQueryResult( + JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "insertId"))), + JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rows"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata"))) + ); + } + + jsi::Value JSIConverter::toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NativeLazyQueryResult& arg) { + jsi::Object obj(runtime); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected"), JSIConverter::toJSI(runtime, arg.rowsAffected)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "insertId"), JSIConverter>::toJSI(runtime, arg.insertId)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "rows"), JSIConverter>::toJSI(runtime, arg.rows)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "metadata"), JSIConverter>>::toJSI(runtime, arg.metadata)); + return obj; + } + + bool JSIConverter::canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) { + return false; + } + jsi::Object obj = value.getObject(runtime); + if (!nitro::isPlainObject(runtime, obj)) { + return false; + } + if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "insertId")))) return false; + if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rows")))) return false; + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata")))) return false; + return true; + } + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp index e583eeb41..5e5e1a5d5 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include // Forward declaration of `HybridPreparedStatementSpec` to properly resolve imports. @@ -77,6 +78,8 @@ namespace margelo::nitro::rnnitrosqlite { virtual Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional>& onRows, const std::optional& rowBatchId, const std::optional& requireTransaction) = 0; virtual void setRowBatchHandler(const Callback& handler) = 0; virtual void setChangeHandler(const std::string& dbName, const std::optional& /* changes */)>>& handler) = 0; + virtual NativeLazyQueryResult executeLazy(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; + virtual Promise executeLazyAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; virtual NativeRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; virtual Promise executeRawAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional& requireTransaction) = 0; virtual std::shared_ptr prepare(const std::string& dbName, const std::string& query) = 0; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp index aa6819b49..dffa2ffc5 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include namespace margelo::nitro::rnnitrosqlite { @@ -58,6 +59,8 @@ namespace margelo::nitro::rnnitrosqlite { // Methods virtual margelo::nitro::rnnitrosqlite::NativeQueryResult execute(const std::optional>>>& params) = 0; virtual Promise executeAsync(const std::optional>>>& params) = 0; + virtual NativeLazyQueryResult executeLazy(const std::optional>>>& params) = 0; + virtual Promise executeLazyAsync(const std::optional>>>& params) = 0; virtual NativeRawQueryResult executeRaw(const std::optional>>>& params) = 0; virtual Promise executeRawAsync(const std::optional>>>& params) = 0; virtual void finalize() = 0; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeLazyQueryResult.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeLazyQueryResult.hpp new file mode 100644 index 000000000..15d480a1d --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeLazyQueryResult.hpp @@ -0,0 +1,50 @@ +/// +/// NativeLazyQueryResult.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include +#include +#include "SQLiteLazyQueryRows.hpp" +#include +#include "results/QueryColumnMetadata.hpp" +#include +#include + +namespace margelo::nitro::rnnitrosqlite { + + /** + * A struct which can be represented as a JavaScript object (NativeLazyQueryResult). + */ + struct NativeLazyQueryResult final { + public: + double rowsAffected SWIFT_PRIVATE; + std::optional insertId SWIFT_PRIVATE; + std::shared_ptr rows SWIFT_PRIVATE; + std::optional> metadata SWIFT_PRIVATE; + + public: + explicit NativeLazyQueryResult(double rowsAffected, std::optional insertId, std::shared_ptr rows, std::optional> metadata): rowsAffected(rowsAffected), insertId(std::move(insertId)), rows(rows), metadata(std::move(metadata)) {} + + public: + // NativeLazyQueryResult is not equatable because these properties are not equatable: rows, metadata + }; + +} // namespace margelo::nitro::rnnitrosqlite + +namespace margelo::nitro { + + // C++ NativeLazyQueryResult <> JS NativeLazyQueryResult (object) + template <> + struct JSIConverter final { + static margelo::nitro::rnnitrosqlite::NativeLazyQueryResult fromJSI(jsi::Runtime& runtime, const jsi::Value& arg); + static jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NativeLazyQueryResult& arg); + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value); + }; + +} // namespace margelo::nitro diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh index 45ac27966..3e857b078 100644 --- a/scripts/check-lazy-cpp.sh +++ b/scripts/check-lazy-cpp.sh @@ -1,23 +1,31 @@ #!/usr/bin/env bash set -euo pipefail -# CocoaPods and CMake flatten Nitro's public headers into NitroModules/. -headers=$(mktemp -d) -trap 'rm -rf "$headers"' EXIT -python3 - "$headers" "${NITRO_CPP_DIR:-node_modules/react-native-nitro-modules/cpp}" <<'PY' -from pathlib import Path -import sys -output = Path(sys.argv[1]) / 'NitroModules' -output.mkdir() -for header in Path(sys.argv[2]).resolve().rglob('*.hpp'): - (output / header.name).symlink_to(header) -PY +node scripts/prepare-workspace-sources.mjs +(cd packages/nitro-sqlite && node_modules/.bin/nitrogen) +(cd packages/react-native-nitro-sqlite && ../../node_modules/.bin/nitrogen) -# Native application jobs compile Operations with the target platform's filesystem APIs. -clang++ -std=c++20 -c -o "$headers/lazy-rows.o" \ - -I"$headers" \ - -Inode_modules/react-native/ReactCommon/jsi \ - -Ipackages/react-native-nitro-sqlite/cpp \ - -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - -Ipackages/react-native-nitro-sqlite/nitrogen/generated/shared/c++ \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteLazyQueryRows.cpp +build_dir=$(mktemp -d) +trap 'rm -rf "$build_dir"' EXIT +nitro_core_manifest=$(node -p 'require.resolve("nitro-core/package.json", { paths: ["./packages/nitro-sqlite"] })') +nitro_manifest=$(node -p 'require.resolve("react-native-nitro-modules/package.json", { paths: ["./packages/react-native-nitro-sqlite"] })') +react_manifest=$(node -p 'require.resolve("react-native/package.json")') + +for host in standalone react-native; do + if [ "$host" = standalone ]; then + sources=packages/nitro-sqlite-core/cpp + generated=packages/nitro-sqlite/nitrogen/generated/shared/c++/include + includes=(-I"${nitro_core_manifest%/package.json}/native/cpp/include") + else + sources=packages/react-native-nitro-sqlite/cpp + generated=packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include + nitro_cpp=${NITRO_CPP_DIR:-${nitro_manifest%/package.json}/cpp} + includes=(-I"$nitro_cpp/core/include" -I"${nitro_manifest%/package.json}/apple/core/include") + fi + for source in SQLiteLazyQueryRows.cpp SQLiteOperations.cpp hybridObjects/HybridNitroSQLite.cpp hybridObjects/HybridPreparedStatement.cpp; do + clang++ -std=c++20 -Wall -Wextra -Werror -c \ + -I"$sources" -I"$sources/sqlite" -I"$generated" \ + -I"${react_manifest%/package.json}/ReactCommon/jsi" "${includes[@]}" \ + "$sources/$source" -o "$build_dir/$host-$(basename "$source").o" + done +done diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index 3fc107ff0..ebc800c48 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -453,8 +453,9 @@ function enabled(checks: ReturnType): string[] { test('lazy conversion changes always select host C++ checks', () => { for (const file of [ - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteLazyQueryRows.cpp', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteLazyQueryRows.cpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.hpp', + 'packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp', 'scripts/check-lazy-cpp.sh', ]) { assert.equal(selectChecks([file], false).cpp_tests, true, file) @@ -465,7 +466,7 @@ test('lazy native dependencies select compatibility compilation on drafts', () = for (const file of [ 'bun.lock', 'package.json', - 'example/package.json', + 'examples/react-native/package.json', 'packages/react-native-nitro-sqlite/package.json', 'patches/react-native-nitro-modules+0.37.2.patch', ]) { From 31424de65c13a0c9ae8c1ee8423af6f9fdba45bb Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 13:14:28 +0100 Subject: [PATCH 08/10] ci: keep platform filesystem compilation on macOS Co-authored-by: Codex --- scripts/check-lazy-cpp.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh index 3e857b078..484748cbc 100644 --- a/scripts/check-lazy-cpp.sh +++ b/scripts/check-lazy-cpp.sh @@ -22,7 +22,12 @@ for host in standalone react-native; do nitro_cpp=${NITRO_CPP_DIR:-${nitro_manifest%/package.json}/cpp} includes=(-I"$nitro_cpp/core/include" -I"${nitro_manifest%/package.json}/apple/core/include") fi - for source in SQLiteLazyQueryRows.cpp SQLiteOperations.cpp hybridObjects/HybridNitroSQLite.cpp hybridObjects/HybridPreparedStatement.cpp; do + sources_to_compile=(SQLiteLazyQueryRows.cpp hybridObjects/HybridNitroSQLite.cpp hybridObjects/HybridPreparedStatement.cpp) + # Operations includes the platform filesystem helper. Mobile app jobs cover it on Linux CI. + if [ "$(uname -s)" = Darwin ]; then + sources_to_compile+=(SQLiteOperations.cpp) + fi + for source in "${sources_to_compile[@]}"; do clang++ -std=c++20 -Wall -Wextra -Werror -c \ -I"$sources" -I"$sources/sqlite" -I"$generated" \ -I"${react_manifest%/package.json}/ReactCommon/jsi" "${includes[@]}" \ From ac2af1850816667d369377bce05be1ca05724d86 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 13:27:11 +0100 Subject: [PATCH 09/10] test: preserve lazy row identity without inherited setters Co-authored-by: Codex --- .../unit/specs/operations/executeLazy.spec.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts index 09baf5eea..fc436ec63 100644 --- a/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -15,13 +15,13 @@ export default function registerExecuteLazyUnitTests() { expect(lazy.rows.toArray()).toEqual([]) }) - it('converts native async rows only when read and caches them by index', async () => { + it('caches native async rows by index without invoking inherited setters', async () => { const key = 'nitroSQLiteLazyTestValue' - let conversions = 0 + let setterCalls = 0 Object.defineProperty(Object.prototype, key, { configurable: true, set(this: object, value: unknown) { - if (typeof value === 'number') conversions++ + if (typeof value === 'number') setterCalls++ Object.defineProperty(this, key, { value, enumerable: true, @@ -42,18 +42,18 @@ export default function registerExecuteLazyUnitTests() { for (const index of [-1, 0.5, 600, NaN, Infinity]) { expect(rows.item(index)).toBe(undefined) } - expect(conversions).toBe(0) + expect(setterCalls).toBe(0) const { item } = rows const last = item(599) expect(last).toEqual({ [key]: 600 }) expect(rows.item(599)).toBe(last) - expect(conversions).toBe(1) + expect(setterCalls).toBe(0) const all = rows.toArray() - expect(conversions).toBe(600) + expect(setterCalls).toBe(0) expect(all[0]).toEqual({ [key]: 1 }) expect(all[599]).toBe(last) expect(rows.toArray()[599]).toBe(last) - expect(conversions).toBe(600) + expect(setterCalls).toBe(0) } finally { Reflect.deleteProperty(Object.prototype, key) } From 7c6a393292bd87a0f22ac4f6f037048d42668dd7 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Fri, 4 Dec 2026 17:09:16 +0100 Subject: [PATCH 10/10] fix: preserve inherited column names in query metadata Co-authored-by: Codex --- .../docs/guides/parameters-and-results.mdx | 2 ++ .../cpp/NativeQueryResult.cpp | 5 ++- .../cpp/results/QueryColumnMetadata.hpp | 26 +++++++++++++++ .../tests/cpp/nativeQueryResult.test.cpp | 32 +++++++++++++++++++ 4 files changed, 64 insertions(+), 1 deletion(-) diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 62430329b..83b19a890 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -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 diff --git a/packages/nitro-sqlite-core/cpp/NativeQueryResult.cpp b/packages/nitro-sqlite-core/cpp/NativeQueryResult.cpp index 4b490099e..523720ed7 100644 --- a/packages/nitro-sqlite-core/cpp/NativeQueryResult.cpp +++ b/packages/nitro-sqlite-core/cpp/NativeQueryResult.cpp @@ -64,7 +64,9 @@ 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::toJSI(runtime, column.name)); @@ -72,6 +74,7 @@ namespace { columnObj.setProperty(runtime, keys.index, JSIConverter::toJSI(runtime, column.index)); obj.setProperty(runtime, getColumnName(runtime, keys, columnName), std::move(columnObj)); } + obj.setPrototype(runtime, prototype); return obj; } diff --git a/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp index 2514039a0..7d39a2694 100644 --- a/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp +++ b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include namespace margelo::nitro::nitrosqlite { @@ -45,4 +46,29 @@ struct JSIConverter final { } }; +/** Converts column aliases to own data properties without invoking inherited setters. */ +template <> +struct JSIConverter> final { + using Metadata = std::unordered_map; + + static jsi::Value toJSI(jsi::Runtime& runtime, const Metadata& metadata) { + const auto prototype = jsi::Object(runtime).getPrototype(runtime); + auto result = jsi::Object::create(runtime, jsi::Value::null()); + for (const auto& [name, column] : metadata) { + result.setProperty(runtime, jsi::PropNameID::forUtf8(runtime, name), + JSIConverter::toJSI(runtime, column)); + } + result.setPrototype(runtime, prototype); + return result; + } + + static Metadata fromJSI(jsi::Runtime&, const jsi::Value&) { + throw std::logic_error("SQLite column metadata cannot be passed from JavaScript"); + } + + static bool canConvert(jsi::Runtime&, const jsi::Value&) { + return false; + } +}; + } // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/tests/cpp/nativeQueryResult.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/nativeQueryResult.test.cpp index 6abed40ca..ea32c2f68 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/nativeQueryResult.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/nativeQueryResult.test.cpp @@ -122,6 +122,37 @@ void checkManyAliases(jsi::Runtime& runtime) { } } +void checkInheritedMetadata(jsi::Runtime& runtime) { + SQLiteQueryTableMetadata metadata; + for (const auto* name : {"liveSetter", "__proto__", "constructor"}) { + metadata.try_emplace(name, name, ColumnType::INT64, 0); + } + expect(evaluate(runtime, R"((() => { + Object.defineProperty(Object.prototype, 'liveSetter', { + configurable: true, + set() { throw new Error('metadata reached an inherited setter'); } + }); + return true; + })())"), + "install metadata setter"); + const NativeQueryResult result(0, std::nullopt, SQLiteQueryResults(), std::nullopt, metadata, 0); + for (const bool lazy : {false, true}) { + auto converted = lazy ? JSIConverter::toJSI(runtime, metadata) + : JSIConverter::toJSI(runtime, result).asObject(runtime).getProperty(runtime, "metadata"); + runtime.global().setProperty(runtime, "metadata", std::move(converted)); + expect(evaluate(runtime, R"((() => { + return Object.getPrototypeOf(metadata) === Object.prototype && + ['liveSetter', '__proto__', 'constructor'].every(name => { + const property = Object.getOwnPropertyDescriptor(metadata, name); + return property && property.enumerable && property.writable && property.configurable && + property.value.name === name && property.value.type === 2 && property.value.index === 0; + }); + })())"), + "metadata aliases must remain own data properties"); + } + expect(evaluate(runtime, "delete Object.prototype.liveSetter"), "remove metadata setter"); +} + } // namespace int main() { @@ -131,6 +162,7 @@ int main() { checkOneLookupPerResult(*first); checkWithoutMetadata(*first); checkManyAliases(*first); + checkInheritedMetadata(*first); checkResult(*first, 1); checkResult(*second, 2); checkResult(*first, 3);