diff --git a/.github/ci-paths.json b/.github/ci-paths.json index ba03fc6a8..a71339663 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", + "examples/react-native/package.json", + "packages/react-native-nitro-sqlite/package.json", + "patches/react-native-nitro-modules*", "packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.*", "packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.*", "packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.*", @@ -138,7 +143,10 @@ "packages/nitro-sqlite/package.json", "packages/nitro-sqlite/nitro.json", "packages/nitro-sqlite/platform/cpp/**", - "packages/nitro-sqlite/src/specs/**" + "packages/nitro-sqlite/src/specs/**", + "packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteLazyQueryRows.*", + "scripts/check-lazy-cpp.sh" ], "docs": [ ".github/workflows/**", 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/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/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..fc436ec63 --- /dev/null +++ b/examples/shared/tests/unit/specs/operations/executeLazy.spec.ts @@ -0,0 +1,160 @@ +import { NitroSQLite } from '@example-sqlite/core' +import { expect } from '../../common' +import { it } from '../../../TestApi' +import { TEST_DB_NAME } from '../../../db' + +export default function registerExecuteLazyUnitTests() { + it('keeps metadata and row access valid for an empty native result', () => { + const query = 'SELECT 1 AS value WHERE 0' + const eager = NitroSQLite.native.execute(TEST_DB_NAME, query) + const lazy = NitroSQLite.native.executeLazy(TEST_DB_NAME, query) + expect(lazy.metadata).toEqual(eager.metadata) + expect(lazy.rows.length).toBe(0) + expect(lazy.rows.item(0)).toBe(undefined) + expect(lazy.rows.toArray()).toEqual([]) + expect(lazy.rows.toArray()).toEqual([]) + }) + + it('caches native async rows by index without invoking inherited setters', async () => { + const key = 'nitroSQLiteLazyTestValue' + let setterCalls = 0 + Object.defineProperty(Object.prototype, key, { + configurable: true, + set(this: object, value: unknown) { + if (typeof value === 'number') setterCalls++ + Object.defineProperty(this, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }) + }, + }) + + try { + const { rows } = await NitroSQLite.native.executeLazyAsync( + TEST_DB_NAME, + `WITH RECURSIVE seq(n) AS ( + VALUES (1) UNION ALL SELECT n + 1 FROM seq WHERE n < 600 + ) SELECT n AS ${key} FROM seq ORDER BY n`, + ) + expect(rows.length).toBe(600) + for (const index of [-1, 0.5, 600, NaN, Infinity]) { + expect(rows.item(index)).toBe(undefined) + } + expect(setterCalls).toBe(0) + const { item } = rows + const last = item(599) + expect(last).toEqual({ [key]: 600 }) + expect(rows.item(599)).toBe(last) + expect(setterCalls).toBe(0) + const all = rows.toArray() + expect(setterCalls).toBe(0) + expect(all[0]).toEqual({ [key]: 1 }) + expect(all[599]).toBe(last) + expect(rows.toArray()[599]).toBe(last) + expect(setterCalls).toBe(0) + } finally { + Reflect.deleteProperty(Object.prototype, key) + } + }) + + it('ignores inherited caches and setters on its row accessors', () => { + const keys = ['cache', 'item', 'toArray', 'length'] + const inherited = { cache: { 0: { value: 'inherited' } } } + let setterCalls = 0 + try { + for (const key of keys) { + // eslint-disable-next-line no-extend-native -- Exercise inherited cache values and swallowed assignments. + Object.defineProperty(Object.prototype, key, { + configurable: true, + get() { + return key === 'cache' ? inherited.cache : undefined + }, + set() { + setterCalls++ + }, + }) + } + const { rows } = NitroSQLite.native.executeLazy( + TEST_DB_NAME, + 'SELECT 42 AS value UNION ALL SELECT 7', + ) + const first = rows.item(0) + const all = rows.toArray() + expect(first).toEqual({ value: 42 }) + expect(rows.item(0)).toBe(first) + expect(all[0]).toBe(first) + expect(rows.item(1)).toBe(all[1]) + expect(rows.length).toBe(2) + expect(rows.toArray()).toEqual(all) + expect(setterCalls).toBe(0) + } finally { + for (const key of keys) Reflect.deleteProperty(Object.prototype, key) + } + }) + + it('keeps inherited columns as own properties without invoking setters', () => { + const key = 'nitroSQLiteLazyReentrantValue' + const query = `SELECT 1 AS ${key}, x'00ff' AS "__proto__" UNION ALL SELECT 2, x'01'` + let setterCalls = 0 + // eslint-disable-next-line no-extend-native -- Match eager conversion of inherited column names. + Object.defineProperty(Object.prototype, key, { + configurable: true, + set() { + setterCalls++ + throw new Error('inherited setter must not run') + }, + }) + try { + const eager = NitroSQLite.native.execute(TEST_DB_NAME, query) + const { rows } = NitroSQLite.native.executeLazy(TEST_DB_NAME, query) + const first = rows.item(0) + expect(rows.toArray()).toEqual(eager.results) + expect(rows.item(0)).toBe(first) + expect(Object.getPrototypeOf(first)).toBe(Object.prototype) + expect(Object.prototype.hasOwnProperty.call(first, '__proto__')).toBe( + true, + ) + expect(Object.prototype.hasOwnProperty.call(first, key)).toBe(true) + expect(setterCalls).toBe(0) + } finally { + Reflect.deleteProperty(Object.prototype, key) + } + }) + + it('matches native eager values and metadata, including duplicate aliases and BLOBs', async () => { + const query = ` + SELECT id, 'old' AS label, ? AS label, 1.5 AS "café", NULL AS nullable, + x'00ff' AS payload, zeroblob(0) AS empty + FROM User ORDER BY id + ` + NitroSQLite.native.execute( + TEST_DB_NAME, + "INSERT INTO User (id, name, age, networth) VALUES (1, 'Ada', 37, 1)", + ) + const params = ['a\0b'] + const eager = NitroSQLite.native.execute(TEST_DB_NAME, query, params) + const lazy = NitroSQLite.native.executeLazy(TEST_DB_NAME, query, params) + expect(lazy.metadata).toEqual(eager.metadata) + expect(lazy.rowsAffected).toBe(eager.rowsAffected) + expect(lazy.insertId).toBe(eager.insertId) + expect(lazy.rows.toArray()).toEqual(eager.results) + const row = lazy.rows.item(0) + expect(row?.label).toBe('a\0b') + expect(Array.from(new Uint8Array(row?.payload as ArrayBuffer))).toEqual([ + 0, 255, + ]) + expect((row?.empty as ArrayBuffer).byteLength).toBe(0) + expect(lazy.rows.item(0)?.payload).toBe(row?.payload) + }) + + it('keeps native prepared results after reuse and finalization', async () => { + const statement = NitroSQLite.native.prepare(TEST_DB_NAME, 'SELECT ? AS x') + const first = statement.executeLazy([1]) + const second = await statement.executeLazyAsync([2]) + statement.finalize() + expect(first.rows.item(0)).toEqual({ x: 1 }) + expect(second.rows.item(0)).toEqual({ x: 2 }) + }) +} 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/SQLiteLazyQueryRows.cpp b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp new file mode 100644 index 000000000..4cbad6cc6 --- /dev/null +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.cpp @@ -0,0 +1,165 @@ +#include "SQLiteLazyQueryRows.hpp" +#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->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)); + return function.getPropertyAsFunction(runtime, "bind").callWithThis(runtime, function, owner); + } + +} // namespace + +SQLiteLazyQueryRows::SQLiteLazyQueryRows(std::vector columnNames, std::vector rows) + : _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); + } + for (const auto& row : _data.rows) { + _retainedBytes += rowAllocationSize(row); + } +} + +jsi::Object SQLiteLazyQueryRows::toRows(jsi::Runtime& runtime) { + auto owner = toObject(runtime).asObject(runtime); + 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()); + 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); + 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); + 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; +} + +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 < _rowCount && 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, _rowCount); + for (size_t index = 0; index < _rowCount; 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"); + } + // Keep the row recoverable if conversion or cache insertion throws. + 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); + if (--_remainingRows == 0) { + _retainedBytes = sizeof(*this); + std::vector{}.swap(_data.rows); + std::vector{}.swap(_data.columnNames); + } + 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..03b46636e --- /dev/null +++ b/packages/nitro-sqlite-core/cpp/SQLiteLazyQueryRows.hpp @@ -0,0 +1,50 @@ +#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; + const size_t _rowCount; + size_t _remainingRows; + 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..6ce7a564e 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -1,5 +1,6 @@ #include "SQLiteOperations.hpp" #include "SQLiteException.hpp" +#include "SQLiteLazyQueryRows.hpp" #include "SQLiteStatementGroup.hpp" #include "SQLiteStatementTail.hpp" #include "SQLiteUtils.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,33 @@ 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); + 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) { std::optional> columnNames; std::vector rows; @@ -322,6 +349,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, bool requireTransaction) { + return executeCached(connection, query, params, requireTransaction, 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 +452,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..ff1903075 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -3,6 +3,7 @@ #include "SQLiteDatabaseConnections.hpp" #include "results/NativeQueryResult.hpp" #include "sqlite/sqlite3.h" +#include #include #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, 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 54e91445b..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 @@ -107,6 +108,29 @@ 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 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; +} + } // 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..91162c3c7 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -265,6 +265,27 @@ void HybridNitroSQLite::setRowBatchHandler(const Callback& 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, + const std::optional& requireTransaction) { + 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, requireTransaction]() { + return sqliteExecuteLazy(connection, query, copiedParams, requireTransaction.value_or(false)); + }); +} + 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..85b94eaac 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -91,6 +91,14 @@ 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, + 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, + 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. */ 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..8a0d2b04d 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -45,8 +45,19 @@ NativeRawQueryResult HybridPreparedStatement::executeRaw(const std::optionalexecuteRaw(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) { - auto copiedParams = copyArrayBufferParamsForBackground(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/cpp/results/QueryColumnMetadata.hpp b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp index 730760814..7d39a2694 100644 --- a/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp +++ b/packages/nitro-sqlite-core/cpp/results/QueryColumnMetadata.hpp @@ -2,7 +2,9 @@ #include "ColumnType.hpp" #include +#include #include +#include #include namespace margelo::nitro::nitrosqlite { @@ -21,3 +23,52 @@ 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; + } +}; + +/** 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/nitro-sqlite-core/src/index.ts b/packages/nitro-sqlite-core/src/index.ts index deac167a8..e01dc6e7b 100644 --- a/packages/nitro-sqlite-core/src/index.ts +++ b/packages/nitro-sqlite-core/src/index.ts @@ -39,6 +39,12 @@ export { 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, +} 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..b4d85b07f --- /dev/null +++ b/packages/nitro-sqlite-core/src/specs/NativeLazyQueryResult.ts @@ -0,0 +1,56 @@ +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. + * 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 + + /** 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. + * Conversion runs synchronously and may throw. + * @returns A new array containing every cached row. + */ + toArray(): Row[] +} + +/** Native-backed rows passed from SQLite to JavaScript. */ +export type SQLiteLazyQueryRows = CustomType< + LazyQueryRows, + 'std::shared_ptr', + { 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. + * 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. */ + 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..7ef9c6aaa 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,34 @@ 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. + * @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. + */ + executeLazy( + 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. * @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..fe3e8c525 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,18 @@ 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/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/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(() => { 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); diff --git a/scripts/check-lazy-cpp.sh b/scripts/check-lazy-cpp.sh new file mode 100644 index 000000000..484748cbc --- /dev/null +++ b/scripts/check-lazy-cpp.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +node scripts/prepare-workspace-sources.mjs +(cd packages/nitro-sqlite && node_modules/.bin/nitrogen) +(cd packages/react-native-nitro-sqlite && ../../node_modules/.bin/nitrogen) + +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 + 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[@]}" \ + "$sources/$source" -o "$build_dir/$host-$(basename "$source").o" + done +done diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index f33895320..ebc800c48 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -450,3 +450,26 @@ 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/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) + } +}) + +test('lazy native dependencies select compatibility compilation on drafts', () => { + for (const file of [ + 'bun.lock', + 'package.json', + 'examples/react-native/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) + } +}) 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 ||