From bf37c7f59e29ca29eb9f3ed667bb859b0206e670 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:30:37 +0100 Subject: [PATCH 1/8] refactor: share SQLite value binding and buffer snapshots Co-authored-by: Codex --- .../cpp/NitroSQLiteOperations.cpp | 14 +++++---- .../cpp/hybridObjects/HybridNitroSQLite.cpp | 24 +-------------- .../HybridNitroSQLitePreparedStatement.cpp | 25 +--------------- .../NitroSQLiteBackgroundBindings.hpp | 30 +++++++++++++++++++ 4 files changed, 40 insertions(+), 53 deletions(-) create mode 100644 packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp index 64b782687..d1cb34249 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp @@ -84,10 +84,9 @@ void sqliteRemoveDb(DatabaseConnections& connections, const std::string& dbName, connections.drop(dbName, std::filesystem::path(docPath) / dbName, connectionId, otherPath); } -void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { - for (size_t valueIndex = 0; valueIndex < values.size(); valueIndex++) { - int sqliteIndex = valueIndex + 1; - const auto& optionalValue = values.at(valueIndex); +namespace { + + void bindValue(sqlite3_stmt* statement, int sqliteIndex, const SQLiteValue& optionalValue) { int bindStatus = SQLITE_OK; if (!optionalValue || std::holds_alternative(*optionalValue)) { @@ -115,9 +114,12 @@ void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { std::to_string(bindStatus) + "): " + sqlite3_errstr(bindStatus)); } } -} -namespace { + void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { + for (size_t valueIndex = 0; valueIndex < values.size(); valueIndex++) { + bindValue(statement, valueIndex + 1, values[valueIndex]); + } + } struct SQLiteStatementFinalizer { void operator()(sqlite3_stmt* statement) const noexcept { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp index 0df90487b..ab0d8e9b4 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -7,6 +7,7 @@ #include "../NitroSQLiteMacros.hpp" #include "../NitroSQLiteOperations.hpp" #include "HybridNitroSQLitePreparedStatement.hpp" +#include "NitroSQLiteBackgroundBindings.hpp" #include "NitroSQLiteConnectionOperation.hpp" #include "NitroSQLiteRowBatchSender.hpp" #include @@ -21,29 +22,6 @@ namespace margelo::nitro::rnnitrosqlite { -// Copy any JS-backed ArrayBuffers on the JS thread so they can be safely -// accessed from the connection's background worker. -static std::optional copyArrayBufferParamsForBackground(const std::optional& params) { - if (!params) { - return std::nullopt; - } - - SQLiteQueryParams copiedParams; - copiedParams.reserve(params->size()); - - for (const auto& value : *params) { - if (value && std::holds_alternative>(*value)) { - const auto& buffer = std::get>(*value); - const auto copiedBuffer = ArrayBuffer::copy(buffer); - copiedParams.push_back(copiedBuffer); - } else { - copiedParams.push_back(value); - } - } - - return copiedParams; -} - // Copy ArrayBuffer params inside each grouped batch command. static std::vector copyArrayBufferParamsForBackground(const std::vector& commands) { std::vector copiedCommands; diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp index 133ca35aa..13893063e 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp @@ -1,32 +1,9 @@ #include "HybridNitroSQLitePreparedStatement.hpp" +#include "NitroSQLiteBackgroundBindings.hpp" #include "NitroSQLiteConnectionOperation.hpp" -#include namespace margelo::nitro::rnnitrosqlite { -namespace { - - std::optional copyArrayBufferParamsForBackground(const std::optional& params) { - if (!params) { - return std::nullopt; - } - - SQLiteQueryParams copiedParams; - copiedParams.reserve(params->size()); - - for (const auto& value : *params) { - if (value && std::holds_alternative>(*value)) { - copiedParams.push_back(ArrayBuffer::copy(std::get>(*value))); - } else { - copiedParams.push_back(value); - } - } - - return copiedParams; - } - -} // namespace - HybridNitroSQLitePreparedStatement::HybridNitroSQLitePreparedStatement(std::shared_ptr statement) : HybridObject(TAG), _statement(std::move(statement)) {} diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp new file mode 100644 index 000000000..df458b70e --- /dev/null +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "../NitroSQLiteTypes.hpp" + +namespace margelo::nitro::rnnitrosqlite { + +// Copy any JS-backed ArrayBuffers on the JS thread so they can be safely +// accessed from the connection's background worker. +inline std::optional copyArrayBufferParamsForBackground(const std::optional& params) { + if (!params) { + return std::nullopt; + } + + SQLiteQueryParams copiedParams; + copiedParams.reserve(params->size()); + + for (const auto& value : *params) { + if (value && std::holds_alternative>(*value)) { + const auto& buffer = std::get>(*value); + const auto copiedBuffer = ArrayBuffer::copy(buffer); + copiedParams.push_back(copiedBuffer); + } else { + copiedParams.push_back(value); + } + } + + return copiedParams; +} + +} // namespace margelo::nitro::rnnitrosqlite From 1501f3064ff16f99e138fbf801f4856ef9fc5df1 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:39:10 +0100 Subject: [PATCH 2/8] feat: bind named SQL parameter records #402 Resolve exact placeholder names with SQLite and use the same value binder for positional and named queries. Keep async BLOB bindings safe across worker threads and keep unknown keys out of error messages. Co-authored-by: Codex --- docs/content/docs/guides/batch-operations.mdx | 12 +- docs/content/docs/guides/node-test-mock.mdx | 2 +- .../docs/guides/parameters-and-results.mdx | 19 +- .../docs/guides/prepared-statements.mdx | 4 +- example/tests/unit/index.ts | 5 + .../specs/operations/namedParameters.spec.ts | 196 ++++++++++++++++++ .../src/__tests__/driver.test.ts | 8 +- .../cpp/NitroSQLiteExecuteBatch.cpp | 17 +- .../cpp/NitroSQLiteExecuteBatch.hpp | 2 +- .../cpp/NitroSQLiteOperations.cpp | 39 +++- .../cpp/NitroSQLiteOperations.hpp | 14 +- .../cpp/NitroSQLiteTypes.hpp | 5 + .../cpp/hybridObjects/HybridNitroSQLite.cpp | 10 +- .../cpp/hybridObjects/HybridNitroSQLite.hpp | 8 +- .../HybridNitroSQLitePreparedStatement.cpp | 8 +- .../HybridNitroSQLitePreparedStatement.hpp | 8 +- .../NitroSQLiteBackgroundBindings.hpp | 41 ++-- .../shared/c++/BatchQueryCommand.hpp | 11 +- ...HybridNitroSQLitePreparedStatementSpec.hpp | 9 +- .../shared/c++/HybridNitroSQLiteSpec.hpp | 9 +- .../src/__tests__/mock.test.ts | 59 ++++++ .../src/mock/query.ts | 164 ++++++++------- .../src/mock/transaction.ts | 4 +- .../src/operations/execute.ts | 36 ++-- .../src/operations/prepare.ts | 12 +- .../src/operations/session.ts | 10 +- .../src/operations/transaction.ts | 10 +- .../src/specs/NitroSQLite.nitro.ts | 28 +-- .../NitroSQLitePreparedStatement.nitro.ts | 10 +- .../react-native-nitro-sqlite/src/types.ts | 53 +++-- 30 files changed, 577 insertions(+), 236 deletions(-) create mode 100644 example/tests/unit/specs/operations/namedParameters.spec.ts diff --git a/docs/content/docs/guides/batch-operations.mdx b/docs/content/docs/guides/batch-operations.mdx index cc1bebba6..7c78fa40e 100644 --- a/docs/content/docs/guides/batch-operations.mdx +++ b/docs/content/docs/guides/batch-operations.mdx @@ -28,18 +28,18 @@ const { rowsAffected } = await db.executeBatchAsync(commands) ## Repeat a statement with different values -When the same SQL runs with different values, give one command an array of parameter arrays. The native batch code expands it into separate executions before starting the transaction. +When the same SQL runs with different values, give one command a list of parameter sets. Each set can be a positional array or a [record keyed by exact placeholder names](/docs/guides/parameters-and-results#bind-parameters). SQLite prepares the statement once per command and clears its bindings before each run. A single array of values or a single record runs the command once. -An empty `params` array skips that command. If every command has an empty array, the batch throws or rejects because it has nothing to execute. Omit `params` for a statement that should run once without bindings, such as `CREATE TABLE`. +An empty `params` array skips that command. If every command has an empty array, the batch throws or rejects because it has nothing to execute. Omit `params` or pass an empty record to run a statement once without bindings. ```ts await db.executeBatchAsync([ { - query: 'INSERT INTO events (name, score) VALUES (?, ?)', + query: 'INSERT INTO events (name, score) VALUES ($name, $score)', params: [ - ['alpha', 10], - ['beta', 20], - ['gamma', 30], + { $name: 'alpha', $score: 10 }, + { $name: 'beta', $score: 20 }, + { $name: 'gamma', $score: 30 }, ], }, ]) diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index 0591ad66c..0045a3b35 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -51,7 +51,7 @@ test('stores a note', () => { }) ``` -The mock returns query rows through both `results` and `rows`, supports [rows as arrays](/docs/guides/parameters-and-results#rows-as-arrays) through `executeRaw()` and `executeRawAsync()`, and supports [atomic batches](/docs/guides/batch-operations). Bound `undefined` becomes SQL NULL. A query that fails throws from `execute()` or rejects from `executeAsync()`. +The mock returns query rows through both `results` and `rows`, supports [rows as arrays](/docs/guides/parameters-and-results#rows-as-arrays) through `executeRaw()` and `executeRawAsync()`, and supports [atomic batches](/docs/guides/batch-operations). Use a positional array or a [record keyed by exact placeholder names](/docs/guides/parameters-and-results#bind-parameters). Bound `undefined` becomes SQL NULL. A query that fails throws from `execute()` or rejects from `executeAsync()`. ## Share a database between connections diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index a95bafd3a..3ef077af8 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -3,13 +3,24 @@ title: Parameters and results description: Bind SQLite values, inspect rows and metadata, and handle query failures. --- -Pass values as the second argument to `db.execute()` or `db.executeAsync()`, then read the returned `rows`, `rowsAffected`, and `insertId`. +## Bind parameters -In NitroSQLite, pass positional values in an array for `?` placeholders. The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Both `null` and `undefined` bind as SQL NULL. Keep table and column names in your own SQL; parameters bind values, not identifiers. +SQLite assigns an index to each placeholder when it compiles a statement. An anonymous `?` takes the next index, while `?NNN` specifies an index. Named placeholders such as `:name`, `@name`, and `$name` get separate indices, and repeated uses of the same name share one index. -SQLite leaves omitted placeholders as SQL NULL, so NitroSQLite does not require an exact parameter count. Extra values and other binding failures throw or reject with the one-based parameter index and SQLite error code and text. The error does not include parameter values. This behavior applies to synchronous, asynchronous, batch, and prepared statement execution. +Pass a positional array to bind values by index, starting at SQLite index 1. Pass a record to bind by exact, case-sensitive placeholder name. Include the prefix. For example, `:name` and `@name` are different keys, and the key for `?5` is `'?5'`. If `?NNN` refers to an index SQLite already named, use that index's first name. -For repeated executions of the same SQL, [prepare the statement once](/docs/guides/prepared-statements) and pass a new parameter array on each run. +```ts +const result = await db.executeAsync( + 'SELECT :name AS name, :name AS repeated, @name AS other, ?5 AS rank', + { ':name': 'Ada', '@name': 'Grace', '?5': 5 }, +) +``` + +A plain `?` has no record key. To supply values for both anonymous and named placeholders in one statement, use a positional array ordered by SQLite parameter index. Unbound placeholders, `null`, and `undefined` all produce SQL NULL. Bindings start fresh on every execution, including when you reuse a prepared statement. + +The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. + +## Read results ```ts const name = 'Ada' diff --git a/docs/content/docs/guides/prepared-statements.mdx b/docs/content/docs/guides/prepared-statements.mdx index 297710a97..48931c237 100644 --- a/docs/content/docs/guides/prepared-statements.mdx +++ b/docs/content/docs/guides/prepared-statements.mdx @@ -24,7 +24,7 @@ try { db.close() ``` -Pass a positional array for the SQL's `?` placeholders on each execution. The [parameter types and binding rules](/docs/guides/parameters-and-results) match the connection's execution methods. Each run clears previous bindings, so omitted values do not carry over. Pass every value your query needs each time. +Pass a positional array or a [record keyed by exact placeholder names](/docs/guides/parameters-and-results#bind-parameters) on each execution. Each run clears previous bindings. Omitted values in the new array or record are SQL NULL. ## Read rows and run asynchronously @@ -54,6 +54,6 @@ Do not await a prepared statement's `executeAsync()` from inside `db.transaction ## Choose the right query form -`execute()` and `executeAsync()` prepare and run a query for one call. A prepared statement keeps its compiled SQL for repeated calls on the same connection, but it does not start a transaction. Use [batch operations](/docs/guides/batch-operations) for a fixed group of writes that must commit or roll back together. Use `db.transaction()` when later writes depend on earlier results. A batch with nested parameter arrays runs each expanded command separately; it does not reuse one prepared statement. Measure the workload on your target devices before choosing an approach for speed. +`execute()` and `executeAsync()` prepare and run a query for one call. A prepared statement keeps its compiled SQL for repeated calls on the same connection, but it does not start a transaction. Use [batch operations](/docs/guides/batch-operations) for a fixed group of writes that must commit or roll back together. Use `db.transaction()` when later writes depend on earlier results. A batch with several parameter sets prepares the SQL once per command and reuses it for those sets. Measure the workload on your target devices before choosing an approach for speed. The [`NitroSQLite` export](/api/react-native-nitro-sqlite/variables/NitroSQLite) also has `prepare(dbName, query)`. It requires a default managed connection opened with `open()` and uses that connection's queue. For an independent connection, call `prepare()` on the connection object so the statement uses that connection's own handle and queue. `NitroSQLite.native.prepare(dbName, query)` returns a raw native statement. Native calls bypass the JavaScript queue, return raw results without the managed `rows` adapter, and leave error conversion and coordination to you. See [native access](/docs/guides/sync-and-async#global-helpers-and-native-access) if you use that lower-level API. diff --git a/example/tests/unit/index.ts b/example/tests/unit/index.ts index bea1c1ecd..7f6602008 100644 --- a/example/tests/unit/index.ts +++ b/example/tests/unit/index.ts @@ -6,6 +6,7 @@ import registerExecuteRawUnitTests from './specs/operations/executeRaw.spec' import registerTransactionUnitTests from './specs/operations/transaction.spec' import registerExecuteBatchUnitTests from './specs/operations/executeBatch.spec' import registerPreparedStatementUnitTests from './specs/operations/preparedStatement.spec' +import registerNamedParameterUnitTests from './specs/operations/namedParameters.spec' import registerChangeListenerUnitTests from './specs/operations/changeListener.spec' import registerTypeORMUnitTestsSpecs from './specs/typeorm.spec' import registerDatabaseQueueUnitTests from './specs/DatabaseQueue.spec' @@ -18,6 +19,10 @@ export function registerUnitTests() { beforeEach(setupTestDb) describe('operations/execute.spec.ts', registerExecuteUnitTests) + describe( + 'operations/namedParameters.spec.ts', + registerNamedParameterUnitTests, + ) describe('operations/executeRaw.spec.ts', registerExecuteRawUnitTests) describe('operations/transaction.spec.ts', registerTransactionUnitTests) describe('operations/executeBatch.spec.ts', registerExecuteBatchUnitTests) diff --git a/example/tests/unit/specs/operations/namedParameters.spec.ts b/example/tests/unit/specs/operations/namedParameters.spec.ts new file mode 100644 index 000000000..da0f64e38 --- /dev/null +++ b/example/tests/unit/specs/operations/namedParameters.spec.ts @@ -0,0 +1,196 @@ +import { + NitroSQLite, + NitroSQLiteError, + NitroSQLiteExceptionType, +} from 'react-native-nitro-sqlite' +import { TEST_DB_NAME, testDb } from '@tests/db' +import { expect, it } from '@tests/TestApi' + +export default function registerNamedParameterUnitTests() { + it('binds repeated, prefixed and numbered placeholders by exact name', async () => { + const query = + 'SELECT :value AS first, @value AS second, $value AS third, :value AS repeated, ?6 AS numbered, ? AS anonymous' + const params = { + '?6': 6, + '$value': 3.5, + '@value': 'second', + ':value': true, + } + const expected = { + first: 1, + second: 'second', + third: 3.5, + repeated: 1, + numbered: 6, + anonymous: null, + } + + expect(testDb.execute(query, params).results).toEqual([expected]) + expect((await testDb.executeAsync(query, params)).results).toEqual([ + expected, + ]) + expect(testDb.executeRaw(query, params).rows).toEqual([ + [1, 'second', 3.5, 1, 6, null], + ]) + expect((await testDb.executeRawAsync(query, params)).rows).toEqual([ + [1, 'second', 3.5, 1, 6, null], + ]) + expect( + testDb.executeRaw(query, [10, 20, 30, null, null, 60, 70]).rows, + ).toEqual([[10, 20, 30, 10, 60, 70]]) + expect( + testDb.executeRaw('SELECT :value, ?1', { ':value': 7 }).rows, + ).toEqual([[7, 7]]) + expect(testDb.executeRaw('SELECT ?, ?1', { '?1': 8 }).rows).toEqual([ + [8, 8], + ]) + expect(testDb.executeRaw(query, {}).rows).toEqual([ + [null, null, null, null, null, null], + ]) + }) + + it('clears prior bindings when reusing a prepared statement', async () => { + const statement = testDb.prepare('SELECT :one AS one, :two AS two') + try { + expect(statement.execute({ ':one': 1, ':two': 2 }).results).toEqual([ + { one: 1, two: 2 }, + ]) + const next = await statement.executeAsync({ ':one': 3 }) + expect(next.results).toEqual([{ one: 3, two: null }]) + expect( + statement.executeRaw({ ':one': undefined, ':two': null }).rows, + ).toEqual([[null, null]]) + expect((await statement.executeRawAsync({ ':two': 4 })).rows).toEqual([ + [null, 4], + ]) + expect(statement.executeRaw([5, 6]).rows).toEqual([[5, 6]]) + } finally { + statement.finalize() + } + }) + + it('binds named values inside a managed transaction', async () => { + await testDb.transaction(async (tx) => { + tx.execute('INSERT INTO User (id, name) VALUES (:id, $name)', { + ':id': 1, + '$name': 'Ada', + }) + const result = await tx.executeRawAsync( + 'SELECT name FROM User WHERE id = @id', + { '@id': 1 }, + ) + expect(result.rows).toEqual([['Ada']]) + }) + }) + + it('copies named BLOB values before native background execution', async () => { + const bytes = new Uint8Array([0, 255, 16]) + const params = { ':blob': bytes.buffer } + const query = 'SELECT hex(:blob) AS value' + const native = NitroSQLite.native + + expect(native.execute(TEST_DB_NAME, query, params).results).toEqual([ + { value: '00FF10' }, + ]) + const ordinary = native.executeAsync(TEST_DB_NAME, query, params) + const statement = native.prepare(TEST_DB_NAME, query) + try { + const prepared = statement.executeAsync(params) + bytes.fill(1) + expect((await ordinary).results).toEqual([{ value: '00FF10' }]) + expect((await prepared).results).toEqual([{ value: '00FF10' }]) + } finally { + statement.finalize() + } + + testDb.execute('CREATE TABLE data (blob BLOB)') + const batch = native.executeBatchAsync(TEST_DB_NAME, [ + { query: 'INSERT INTO data VALUES (:blob)', params: [params] }, + ]) + bytes.fill(2) + await batch + expect( + testDb.executeRaw('SELECT typeof(blob), hex(blob) FROM data').rows, + ).toEqual([['blob', '010101']]) + }) + + it('rejects unknown keys without disclosing parameter values', async () => { + const value = 'private-value' + const query = 'SELECT :known, ?' + for (const key of ['known', ':KNOWN', '@known', '?', ':known\0suffix']) { + try { + testDb.execute(query, { [key]: value }) + throw new Error('Expected a binding error') + } catch (error) { + if (!(error instanceof NitroSQLiteError)) throw error + expect(error.type).toBe(NitroSQLiteExceptionType.SqlExecutionError) + expect(error.message.includes(value)).toBe(false) + } + } + + const statement = testDb.prepare(query) + try { + try { + await statement.executeAsync({ ':unknown': value }) + throw new Error('Expected a binding error') + } catch (error) { + if (!(error instanceof NitroSQLiteError)) throw error + expect(error.type).toBe(NitroSQLiteExceptionType.SqlExecutionError) + expect(error.message.includes(value)).toBe(false) + } + expect(statement.executeRaw({ ':known': 42 }).rows).toEqual([[42, null]]) + } finally { + statement.finalize() + } + }) + + it('runs single records and mixed groups and rolls back on unknown keys', async () => { + const query = 'INSERT INTO User (id, name, age) VALUES (:id, @name, $age)' + testDb.executeBatch([ + { query, params: { ':id': 1, '@name': 'one', '$age': 5 } }, + ]) + await testDb.executeBatchAsync([ + { query: 'CREATE TABLE skipped (id INTEGER)', params: [] }, + { query: 'CREATE TABLE executed (id INTEGER)', params: {} }, + { + query, + params: [ + { ':id': 2, '@name': 'two', '$age': 9 }, + { ':id': 3, '@name': 'three' }, + [4, 'four', undefined], + ], + }, + ]) + + try { + await testDb.executeBatchAsync([ + { + query, + params: [ + { ':id': 5, '@name': 'rolled-back' }, + { ':id': 6, '@name': 'bad', ':unknown': 'private-value' }, + ], + }, + ]) + throw new Error('Expected the batch to fail') + } catch (error) { + if (!(error instanceof NitroSQLiteError)) throw error + expect(error.type).toBe(NitroSQLiteExceptionType.SqlExecutionError) + expect(error.message.includes('private-value')).toBe(false) + } + + expect( + testDb.executeRaw('SELECT id, name, age FROM User ORDER BY id').rows, + ).toEqual([ + [1, 'one', 5], + [2, 'two', 9], + [3, 'three', null], + [4, 'four', null], + ]) + expect( + testDb.executeRaw( + "SELECT name FROM sqlite_schema WHERE name IN ('executed', 'skipped')", + ).rows, + ).toEqual([['executed']]) + }) +} diff --git a/packages/react-native-nitro-sqlite-drizzle/src/__tests__/driver.test.ts b/packages/react-native-nitro-sqlite-drizzle/src/__tests__/driver.test.ts index bb6c5bbee..6352a74bc 100644 --- a/packages/react-native-nitro-sqlite-drizzle/src/__tests__/driver.test.ts +++ b/packages/react-native-nitro-sqlite-drizzle/src/__tests__/driver.test.ts @@ -43,9 +43,11 @@ describe('drizzle', () => { await db.insert(files).values({ content: bytes, metadata }) const params = execute.mock.calls[0]?.[1] - expect(params?.[0]).toBeInstanceOf(ArrayBuffer) - expect(params?.[1]).toBeInstanceOf(ArrayBuffer) - expect(params?.[0]).toEqual(Uint8Array.from([1, 2]).buffer) + if (!Array.isArray(params)) + throw new Error('Expected positional parameters') + expect(params[0]).toBeInstanceOf(ArrayBuffer) + expect(params[1]).toBeInstanceOf(ArrayBuffer) + expect(params[0]).toEqual(Uint8Array.from([1, 2]).buffer) expect(await db.select().from(files)).toEqual([ { content: Buffer.from([1, 2]), metadata }, ]) diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp index fc2ce09ae..02462f802 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp @@ -15,17 +15,14 @@ std::vector batchParamsToCommands(const std::vector; - - if (std::holds_alternative(*command.params)) { - groupedCommand.parameterSets = std::get(*command.params); + using ParameterSets = std::vector; + if (const auto* sets = std::get_if(&*command.params)) { + groupedCommand.parameterSets = *sets; } else { - const auto& params = std::get(*command.params); - // An empty JavaScript array matches the flat variant first. It still - // represents an empty group, so only omitted params execute once. - if (!params.empty()) { - groupedCommand.parameterSets.push_back(params); + const auto& bindings = std::get(*command.params); + const auto* positional = std::get_if(&bindings); + if (positional == nullptr || !positional->empty()) { + groupedCommand.parameterSets.push_back(bindings); } } } else { diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp index b96deae70..f64bd424f 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp @@ -13,7 +13,7 @@ struct SQLiteConnection; struct BatchQuery { std::string sql; - std::vector parameterSets; + std::vector parameterSets; }; /** diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp index d1cb34249..29cd116a8 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #ifdef NITRO_SQLITE_VEC @@ -115,12 +116,28 @@ namespace { } } - void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { + void bindPositionalParameters(sqlite3_stmt* statement, const SQLiteQueryParams& values) { for (size_t valueIndex = 0; valueIndex < values.size(); valueIndex++) { bindValue(statement, valueIndex + 1, values[valueIndex]); } } + void bindStatement(sqlite3_stmt* statement, const SQLiteQueryBindings& bindings) { + if (const auto* positional = std::get_if(&bindings)) { + bindPositionalParameters(statement, *positional); + return; + } + + for (const auto& [name, value] : std::get(bindings)) { + const bool hasValidPrefix = !name.empty() && std::string_view(":@$?").find(name.front()) != std::string_view::npos; + const int index = hasValidPrefix && name.find('\0') == std::string::npos ? sqlite3_bind_parameter_index(statement, name.c_str()) : 0; + if (index == 0) { + throw NitroSQLiteException::SqlExecution("Unknown SQL parameter name. Use the exact placeholder, including its prefix."); + } + bindValue(statement, index, value); + } + } + struct SQLiteStatementFinalizer { void operator()(sqlite3_stmt* statement) const noexcept { if (statement != nullptr) { @@ -131,7 +148,7 @@ namespace { using SQLiteStatement = std::unique_ptr; - SQLiteStatement prepareStatement(sqlite3* db, const std::string& query, const std::optional& params) { + SQLiteStatement prepareStatement(sqlite3* db, const std::string& query, const std::optional& params) { sqlite3_stmt* rawStatement = nullptr; const char* tail = nullptr; int statementStatus = sqlite3_prepare_v2(db, query.c_str(), -1, &rawStatement, &tail); @@ -347,7 +364,7 @@ namespace { // Runs a query on the connection's cached statement for it, bound to params. template - auto executeCached(const SQLiteConnectionPtr& connection, const std::string& query, const std::optional& params, + auto executeCached(const SQLiteConnectionPtr& connection, const std::string& query, const std::optional& params, Execute&& execute) { std::lock_guard lock(connection->mutex); sqlite3* db = connection->database; @@ -366,18 +383,18 @@ namespace { } // namespace NitroSQLiteQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params, const SQLiteRowBatchHandler& onRows) { + const std::optional& params, const SQLiteRowBatchHandler& onRows) { return executeCached(connection, query, params, [&](sqlite3* db, sqlite3_stmt* statement) { return executeStatement(db, statement, onRows); }); } NitroSQLiteRawQueryResult sqliteExecuteRaw(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params) { + const std::optional& params) { return executeCached(connection, query, params, executeStatementRaw); } SQLiteOperationResult sqliteExecuteCommand(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params) { + const std::optional& params) { std::lock_guard lock(connection->mutex); sqlite3* db = connection->database; if (db == nullptr) { @@ -394,7 +411,7 @@ SQLiteOperationResult sqliteExecuteCommand(const SQLiteConnectionPtr& connection } SQLiteOperationResult sqliteExecuteCommandGroup(const SQLiteConnectionPtr& connection, const std::string& query, - const std::vector& parameterSets) { + const std::vector& parameterSets) { if (parameterSets.empty()) { return {.rowsAffected = 0, .commands = 0}; } @@ -408,7 +425,7 @@ SQLiteOperationResult sqliteExecuteCommandGroup(const SQLiteConnectionPtr& conne SQLiteChangeScope changes(*connection); const auto [rowsAffected, commands] = executeStatementGroup( db, query, parameterSets, [](sqlite3* database, const std::string& sql) { return prepareStatement(database, sql, std::nullopt); }, - [](sqlite3_stmt* statement, const SQLiteQueryParams& params) { bindStatement(statement, params); }, + [](sqlite3_stmt* statement, const SQLiteQueryBindings& params) { bindStatement(statement, params); }, [](sqlite3* database, sqlite3_stmt* statement) { consumeStatement(database, statement, [](sqlite3_stmt*) {}); }, [](sqlite3* database) { throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); }); return {.rowsAffected = rowsAffected, .commands = commands}; @@ -429,7 +446,7 @@ SQLitePreparedStatement::~SQLitePreparedStatement() { } template -auto SQLitePreparedStatement::executeBound(const std::optional& params, Execute&& execute) { +auto SQLitePreparedStatement::executeBound(const std::optional& params, Execute&& execute) { std::lock_guard lock(_state->mutex); std::lock_guard connectionLock(_state->connection->mutex); @@ -465,11 +482,11 @@ auto SQLitePreparedStatement::executeBound(const std::optional& params) { +NitroSQLiteQueryResult SQLitePreparedStatement::execute(const std::optional& params) { return executeBound(params, [](sqlite3* database, sqlite3_stmt* statement) { return executeStatement(database, statement); }); } -NitroSQLiteRawQueryResult SQLitePreparedStatement::executeRaw(const std::optional& params) { +NitroSQLiteRawQueryResult SQLitePreparedStatement::executeRaw(const std::optional& params) { return executeBound(params, executeStatementRaw); } diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp index 369f60558..0a0594bd3 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp @@ -26,9 +26,9 @@ class SQLitePreparedStatement { ~SQLitePreparedStatement(); /** Reset and execute with new bindings. Throws after finalization or connection closure. */ - NitroSQLiteQueryResult execute(const std::optional& params); + NitroSQLiteQueryResult execute(const std::optional& params); /** Reset and execute with new bindings, returning rows as arrays of column values. */ - NitroSQLiteRawQueryResult executeRaw(const std::optional& params); + NitroSQLiteRawQueryResult executeRaw(const std::optional& params); /** Release the native statement. Repeated calls are safe. */ void finalize(); /** Check whether the native statement has been released. */ @@ -44,7 +44,7 @@ class SQLitePreparedStatement { explicit SQLitePreparedStatement(std::shared_ptr state); template - auto executeBound(const std::optional& params, Execute&& execute); + auto executeBound(const std::optional& params, Execute&& execute); std::shared_ptr _state; @@ -65,18 +65,18 @@ void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& al * returned result holds only the rows after the last batch. */ NitroSQLiteQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params, const SQLiteRowBatchHandler& onRows = nullptr); + const std::optional& params, const SQLiteRowBatchHandler& onRows = nullptr); /** Execute one statement, returning rows as arrays of column values. */ NitroSQLiteRawQueryResult sqliteExecuteRaw(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params); + const std::optional& params); SQLiteOperationResult sqliteExecuteCommand(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params = std::nullopt); + const std::optional& params = std::nullopt); /** Execute one SQL statement for each parameter set, preparing it once. */ SQLiteOperationResult sqliteExecuteCommandGroup(const SQLiteConnectionPtr& connection, const std::string& query, - const std::vector& parameterSets); + const std::vector& parameterSets); /** Prepare one SQL statement on an open default or independent connection. */ std::shared_ptr sqlitePrepare(const SQLiteConnectionPtr& connection, const std::string& query); diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp index 375a6ac82..22598299b 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp @@ -12,7 +12,12 @@ namespace margelo::nitro::rnnitrosqlite { using SQLiteValue = std::optional, std::string, double>>; +/** Positional bindings, ordered by SQLite parameter index. */ using SQLiteQueryParams = std::vector; +/** Exact SQLite parameter names, including their prefix. */ +using SQLiteNamedQueryParams = std::unordered_map; +/** One set of positional or named bindings for a statement. */ +using SQLiteQueryBindings = std::variant; using SQLiteQueryTableMetadata = std::unordered_map; struct SQLiteOperationResult { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp index ab0d8e9b4..cd209ce14 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -31,7 +31,7 @@ static std::vector copyArrayBufferParamsForBackground(const std::vec BatchQuery copiedCommand{command.sql, {}}; copiedCommand.parameterSets.reserve(command.parameterSets.size()); for (const auto& params : command.parameterSets) { - copiedCommand.parameterSets.push_back(*copyArrayBufferParamsForBackground(params)); + copiedCommand.parameterSets.push_back(copyArrayBufferParamsForBackground(params)); } copiedCommands.push_back(std::move(copiedCommand)); @@ -158,12 +158,12 @@ void HybridNitroSQLite::detach(const std::string& mainDbName, const std::string& }; NitroSQLiteQueryResult HybridNitroSQLite::execute(const std::string& dbName, const std::string& query, - const std::optional& params) { + const std::optional& params) { return sqliteExecute(_connections.get(dbName), query, params); }; std::shared_ptr> HybridNitroSQLite::executeAsync(const std::string& dbName, const std::string& query, - const std::optional& params, + const std::optional& params, const std::optional& onRows, std::optional rowBatchId) { const auto copiedParams = copyArrayBufferParamsForBackground(params); @@ -221,12 +221,12 @@ void HybridNitroSQLite::setChangeHandler(const std::string& dbName, } NitroSQLiteRawQueryResult HybridNitroSQLite::executeRaw(const std::string& dbName, const std::string& query, - const std::optional& params) { + const std::optional& params) { return sqliteExecuteRaw(_connections.get(dbName), query, params); } std::shared_ptr> HybridNitroSQLite::executeRawAsync(const std::string& dbName, const std::string& query, - const std::optional& params) { + const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); SQLiteConnectionPtr connection; try { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp index e36195f94..f2acaa673 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -66,14 +66,14 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { * @return Native rows, affected row count, insert ID, and metadata. */ NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, - const std::optional& params) override; + const std::optional& params) override; /** Execute one SQL statement on a background thread. Leading row batches go to @p onRows, or else to * the handler from setRowBatchHandler, tagged with @p rowBatchId. * @return A promise of the native query result. */ std::shared_ptr> executeAsync(const std::string& dbName, const std::string& query, - const std::optional& params, + const std::optional& params, const std::optional& onRows, std::optional rowBatchId) override; @@ -86,11 +86,11 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { /** Execute one SQL statement on the calling thread, returning rows as arrays of column values. */ NitroSQLiteRawQueryResult executeRaw(const std::string& dbName, const std::string& query, - const std::optional& params) override; + const std::optional& params) override; /** Execute one SQL statement on a background thread, returning rows as arrays of column values. */ std::shared_ptr> executeRawAsync(const std::string& dbName, const std::string& query, - const std::optional& params) override; + const std::optional& params) override; /** Prepare one SQL statement for repeated execution on an open connection. */ std::shared_ptr prepare(const std::string& dbName, const std::string& query) override; diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp index 13893063e..95a57d418 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.cpp @@ -7,12 +7,12 @@ namespace margelo::nitro::rnnitrosqlite { HybridNitroSQLitePreparedStatement::HybridNitroSQLitePreparedStatement(std::shared_ptr statement) : HybridObject(TAG), _statement(std::move(statement)) {} -NitroSQLiteQueryResult HybridNitroSQLitePreparedStatement::execute(const std::optional& params) { +NitroSQLiteQueryResult HybridNitroSQLitePreparedStatement::execute(const std::optional& params) { return _statement->execute(params); } std::shared_ptr> -HybridNitroSQLitePreparedStatement::executeAsync(const std::optional& params) { +HybridNitroSQLitePreparedStatement::executeAsync(const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; @@ -22,12 +22,12 @@ HybridNitroSQLitePreparedStatement::executeAsync(const std::optionalconnection(), [statement, copiedParams]() -> NitroSQLiteQueryResult { return statement->execute(copiedParams); }); } -NitroSQLiteRawQueryResult HybridNitroSQLitePreparedStatement::executeRaw(const std::optional& params) { +NitroSQLiteRawQueryResult HybridNitroSQLitePreparedStatement::executeRaw(const std::optional& params) { return _statement->executeRaw(params); } std::shared_ptr> -HybridNitroSQLitePreparedStatement::executeRawAsync(const std::optional& params) { +HybridNitroSQLitePreparedStatement::executeRawAsync(const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.hpp index 0a09c1389..6a510d969 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLitePreparedStatement.hpp @@ -14,13 +14,13 @@ class HybridNitroSQLitePreparedStatement : public HybridNitroSQLitePreparedState explicit HybridNitroSQLitePreparedStatement(std::shared_ptr statement); /** Execute with new bindings on the calling thread. */ - NitroSQLiteQueryResult execute(const std::optional& params) override; + NitroSQLiteQueryResult execute(const std::optional& params) override; /** Execute with new bindings on the connection's worker, in call order. */ - std::shared_ptr> executeAsync(const std::optional& params) override; + std::shared_ptr> executeAsync(const std::optional& params) override; /** Execute with new bindings on the calling thread, returning rows as arrays of column values. */ - NitroSQLiteRawQueryResult executeRaw(const std::optional& params) override; + NitroSQLiteRawQueryResult executeRaw(const std::optional& params) override; /** Execute with new bindings on the connection's worker, returning rows as arrays of column values. */ - std::shared_ptr> executeRawAsync(const std::optional& params) override; + std::shared_ptr> executeRawAsync(const std::optional& params) override; /** Release the native statement. */ void finalize() override; /** Check whether the native statement has been released. */ diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp index df458b70e..914c12072 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp @@ -4,27 +4,34 @@ namespace margelo::nitro::rnnitrosqlite { -// Copy any JS-backed ArrayBuffers on the JS thread so they can be safely -// accessed from the connection's background worker. -inline std::optional copyArrayBufferParamsForBackground(const std::optional& params) { - if (!params) { - return std::nullopt; - } - - SQLiteQueryParams copiedParams; - copiedParams.reserve(params->size()); +// JS-backed ArrayBuffers must be copied on the JS thread before work is queued. +inline SQLiteQueryBindings copyArrayBufferParamsForBackground(SQLiteQueryBindings bindings) { + auto copyBuffer = [](SQLiteValue& value) { + if (value) { + if (auto* buffer = std::get_if>(&*value)) { + *buffer = ArrayBuffer::copy(*buffer); + } + } + }; - for (const auto& value : *params) { - if (value && std::holds_alternative>(*value)) { - const auto& buffer = std::get>(*value); - const auto copiedBuffer = ArrayBuffer::copy(buffer); - copiedParams.push_back(copiedBuffer); - } else { - copiedParams.push_back(value); + if (auto* positional = std::get_if(&bindings)) { + for (auto& value : *positional) { + copyBuffer(value); + } + } else { + for (auto& [name, value] : std::get(bindings)) { + copyBuffer(value); } } - return copiedParams; + return bindings; +} + +inline std::optional copyArrayBufferParamsForBackground(const std::optional& params) { + if (!params) { + return std::nullopt; + } + return copyArrayBufferParamsForBackground(*params); } } // namespace margelo::nitro::rnnitrosqlite diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp index ff0895ff3..28149a3b7 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp @@ -36,6 +36,7 @@ #include #include #include +#include namespace margelo::nitro::rnnitrosqlite { @@ -45,11 +46,11 @@ namespace margelo::nitro::rnnitrosqlite { struct BatchQueryCommand final { public: std::string query SWIFT_PRIVATE; - std::optional, std::string, double>>>, std::vector, std::string, double>>>>>> params SWIFT_PRIVATE; + std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>> params SWIFT_PRIVATE; public: BatchQueryCommand() = default; - explicit BatchQueryCommand(std::string query, std::optional, std::string, double>>>, std::vector, std::string, double>>>>>> params): query(query), params(params) {} + explicit BatchQueryCommand(std::string query, std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>> params): query(query), params(params) {} public: friend bool operator==(const BatchQueryCommand& lhs, const BatchQueryCommand& rhs) = default; @@ -66,13 +67,13 @@ namespace margelo::nitro { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::rnnitrosqlite::BatchQueryCommand( JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "query"))), - JSIConverter, std::string, double>>>, std::vector, std::string, double>>>>>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params"))) + JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::BatchQueryCommand& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "query"), JSIConverter::toJSI(runtime, arg.query)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "params"), JSIConverter, std::string, double>>>, std::vector, std::string, double>>>>>>>::toJSI(runtime, arg.params)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "params"), JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::toJSI(runtime, arg.params)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -84,7 +85,7 @@ namespace margelo::nitro { return false; } if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "query")))) return false; - if (!JSIConverter, std::string, double>>>, std::vector, std::string, double>>>>>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params")))) return false; + if (!JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params")))) return false; return true; } }; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp index 80f480ea3..c4b36fa30 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp @@ -25,6 +25,7 @@ namespace margelo::nitro::rnnitrosqlite { struct NitroSQLiteRawQueryResult; } #include #include #include +#include #include #include "NitroSQLiteRawQueryResult.hpp" @@ -59,10 +60,10 @@ namespace margelo::nitro::rnnitrosqlite { public: // Methods - virtual NitroSQLiteQueryResult execute(const std::optional, std::string, double>>>>& params) = 0; - virtual std::shared_ptr> executeAsync(const std::optional, std::string, double>>>>& params) = 0; - virtual NitroSQLiteRawQueryResult executeRaw(const std::optional, std::string, double>>>>& params) = 0; - virtual std::shared_ptr> executeRawAsync(const std::optional, std::string, double>>>>& params) = 0; + virtual NitroSQLiteQueryResult execute(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual std::shared_ptr> executeAsync(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual NitroSQLiteRawQueryResult executeRaw(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual std::shared_ptr> executeRawAsync(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; virtual void finalize() = 0; protected: diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp index 08df0527e..97c60a3e2 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp @@ -35,6 +35,7 @@ namespace margelo::nitro::rnnitrosqlite { struct FileLoadResult; } #include #include #include +#include #include #include "NitroSQLiteQueryResults.hpp" #include @@ -84,12 +85,12 @@ namespace margelo::nitro::rnnitrosqlite { virtual void drop(const std::string& dbName, const std::optional& location, const std::optional& connectionId) = 0; virtual void attach(const std::string& mainDbName, const std::string& dbNameToAttach, const std::string& alias, const std::optional& location) = 0; virtual void detach(const std::string& mainDbName, const std::string& alias) = 0; - virtual NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>>& params) = 0; - virtual std::shared_ptr> executeAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>>& params, const std::optional>& onRows, std::optional rowBatchId) = 0; + virtual NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual std::shared_ptr> executeAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params, const std::optional>& onRows, std::optional rowBatchId) = 0; virtual void setRowBatchHandler(const std::function& handler) = 0; virtual void setChangeHandler(const std::string& dbName, const std::optional& /* changes */)>>& handler) = 0; - virtual NitroSQLiteRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>>& params) = 0; - virtual std::shared_ptr> executeRawAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>>& params) = 0; + virtual NitroSQLiteRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual std::shared_ptr> executeRawAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; virtual std::shared_ptr prepare(const std::string& dbName, const std::string& query) = 0; virtual BatchQueryResult executeBatch(const std::string& dbName, const std::vector& commands) = 0; virtual std::shared_ptr> executeBatchAsync(const std::string& dbName, const std::vector& commands) = 0; diff --git a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts index 64b552145..ffc1189cf 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts @@ -125,6 +125,65 @@ describe('Node SQLite mock', () => { ).toEqual([{ literal: ':ignored', bound: 'value' }]) }) + it('binds named records with exact prefixes and SQLite slot numbers', async () => { + const database = open({ name: 'named-record' }) + const query = `SELECT :name, @name, $name, :name, ?8, ?, ':literal', 1 AS "a$column" /* :comment */` + const statement = database.prepare(query) + expect( + statement.executeRaw({ + ':name': 'colon', + '@name': 'at', + '$name': 'dollar', + '?8': 8, + }).rows, + ).toEqual([['colon', 'at', 'dollar', 'colon', 8, null, ':literal', 1]]) + expect( + (await statement.executeRawAsync({ ':name': undefined })).rows, + ).toEqual([[null, null, null, null, null, null, ':literal', 1]]) + expect( + database.executeRaw('SELECT :token, ?1', { ':token': 17 }).rows, + ).toEqual([[17, 17]]) + expect(database.executeRaw('SELECT ?, ?01', { '?01': 19 }).rows).toEqual([ + [19, 19], + ]) + expect( + database.executeRaw('SELECT :é, :__proto__', { + ':é': 5, + ':__proto__': 6, + }).rows, + ).toEqual([[5, 6]]) + await expect( + statement.executeAsync({ name: 'private-value' }), + ).rejects.toMatchObject({ + type: 'SqlExecutionError', + message: expect.not.stringContaining('private-value'), + }) + statement.finalize() + }) + + it('runs single named batch commands and groups of mixed bindings', async () => { + const database = open({ name: 'named-batch' }) + database.execute('CREATE TABLE items (value INTEGER)') + const query = 'INSERT INTO items VALUES (:value)' + database.executeBatch([{ query, params: { ':value': 1 } }]) + await database.executeBatchAsync([ + { query, params: [{ ':value': 2 }, [3], {}] }, + ]) + expect( + database.executeRaw('SELECT value FROM items ORDER BY rowid').rows, + ).toEqual([[1], [2], [3], [null]]) + await expect( + database.executeBatchAsync([ + { query, params: [{ ':value': 4 }, { ':typo': 5 }] }, + ]), + ).rejects.toMatchObject({ + type: 'SqlExecutionError', + }) + expect(database.executeRaw('SELECT COUNT(*) FROM items').rows).toEqual([ + [4], + ]) + }) + it('expands batch parameters and rolls the batch back on error', async () => { const database = open({ name: 'batch' }) database.execute('CREATE TABLE items (id INTEGER PRIMARY KEY, value TEXT)') diff --git a/packages/react-native-nitro-sqlite/src/mock/query.ts b/packages/react-native-nitro-sqlite/src/mock/query.ts index 517bc48f2..d9828760f 100644 --- a/packages/react-native-nitro-sqlite/src/mock/query.ts +++ b/packages/react-native-nitro-sqlite/src/mock/query.ts @@ -1,10 +1,11 @@ import type BetterSqlite3 from 'better-sqlite3' +import { NitroSQLiteError, NitroSQLiteExceptionType } from '../errors' import type { NitroSQLiteRawQueryResult } from '../specs/NitroSQLiteQueryResult.nitro' import type { BatchQueryCommand, QueryResult, QueryResultRow, - SQLiteQueryParams, + SQLiteQueryBindings, SQLiteValue, } from '../types' @@ -12,13 +13,25 @@ type Database = InstanceType type Statement = BetterSqlite3.Statement> type RawStatement = BetterSqlite3.Statement type BoundValue = string | number | Buffer | null -type ExpandedBatchCommand = { query: string; params?: SQLiteQueryParams } +type ExpandedBatchCommand = { query: string; params?: SQLiteQueryBindings } + +// Skip comments, quoted tokens, and identifiers before matching parameters. +const SQL_TOKENS = new RegExp( + [ + /--[^\n]*/.source, + /\/\*[\s\S]*?(?:\*\/|$)/.source, + /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]/.source, + /[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*/u.source, + /(\?\d*|[:@$#](?:[\w$\u0080-\u{10FFFF}]|::)+(?:\([^\s)]*\))?)/u.source, + ].join('|'), + 'gu', +) /** @internal Execute an already prepared statement with fresh parameter bindings. */ export function executePrepared( database: Database, statement: Statement, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult { const bindings = getBindings(statement.source, params) const results: QueryResultRow[] = [] @@ -43,7 +56,7 @@ export function executePrepared( export function executePreparedRaw( database: Database, statement: Statement, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult { const bindings = getBindings(statement.source, params) let columnNames: string[] = [] @@ -76,7 +89,7 @@ export function executePreparedRaw( export function executeRawQuery( database: Database, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult { return executePreparedRaw(database, database.prepare(query), params) } @@ -85,7 +98,7 @@ export function executeRawQuery( export function executeQuery( database: Database, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult { return executePrepared(database, database.prepare(query), params) } @@ -112,76 +125,72 @@ export function executeBatch( return { rowsAffected } } -function getBindings(query: string, params?: SQLiteQueryParams) { - const { names, positionalCount } = extractParameters(query) - if (names.length === 0) { - const values = params?.map(toBoundValue) ?? [] - while (values.length < positionalCount) values.push(null) - return values - } - const values: Record = {} - for (const [index, name] of names.entries()) { - values[name] = toBoundValue(params?.[index] ?? null) +function getBindings(query: string, params: SQLiteQueryBindings = []) { + const { names, namedIndices, parameterCount } = extractParameters(query) + let values: BoundValue[] + if (Array.isArray(params)) { + if (params.length > parameterCount) { + throw new RangeError('Too many parameter values were provided') + } + values = params.map(toBoundValue) + } else { + values = [] + for (const [name, value] of Object.entries(params)) { + const index = names.get(name) + if (index === undefined || name.startsWith('#')) { + throw new NitroSQLiteError( + `[NativeNitroSQLiteException][${NitroSQLiteExceptionType.SqlExecutionError}] Unknown SQL parameter name. Use the exact placeholder, including its prefix.`, + ) + } + values[index - 1] = toBoundValue(value) + } } - return [values] -} -function extractParameters(query: string) { - const names = new Set() - let positionalCount = 0 - let quote: string | undefined - let lineComment = false - let blockComment = false + const valuesByBareName = new Map() + // better-sqlite3 strips prefixes and reads one property per named slot, in + // SQLite index order. A getter supplies distinct values for :id and @id. + for (const [name, index] of [...names].sort((a, b) => a[1] - b[1])) { + const bareName = name.slice(1) + const value = values[index - 1] ?? null + const group = valuesByBareName.get(bareName) + if (group) group.push(value) + else valuesByBareName.set(bareName, [value]) + } - for (let index = 0; index < query.length; index++) { - const char = query[index] - const next = query[index + 1] + const named: Record = {} + for (const [name, group] of valuesByBareName) { + let index = 0 + Object.defineProperty(named, name, { + get: () => group[index++], + }) + } + // better-sqlite3 expects a value for anonymous slots, including gaps before ?NNN. + const anonymous: BoundValue[] = [] + for (let index = 1; index <= parameterCount; index++) { + if (!namedIndices.has(index)) anonymous.push(values[index - 1] ?? null) + } + return [named, anonymous] +} - if (lineComment) { - if (char === '\n') lineComment = false - continue - } - if (blockComment) { - if (char === '*' && next === '/') { - blockComment = false - index++ - } - continue - } - if (quote) { - if (char === quote) { - if (next === quote) index++ - else quote = undefined - } - continue - } - if (char === '-' && next === '-') { - lineComment = true - index++ - continue - } - if (char === '/' && next === '*') { - blockComment = true - index++ - continue - } - if (char === "'" || char === '"' || char === '`' || char === '[') { - quote = char === '[' ? ']' : char - continue - } - if (char === '?') positionalCount++ - if (!char || !':@$'.includes(char) || !/[A-Za-z_]/.test(next ?? '')) { - continue - } +function extractParameters(source: string) { + const names = new Map() + const namedIndices = new Set() + let parameterCount = 0 + for (const [, name] of source.matchAll(SQL_TOKENS)) { + if (name === undefined || names.has(name)) continue - const start = index + 1 - index = start - while (/[A-Za-z0-9_]/.test(query[index + 1] ?? '')) { - index++ + const index = + name.startsWith('?') && name.length > 1 + ? Number(name.slice(1)) + : parameterCount + 1 + parameterCount = Math.max(parameterCount, index) + // SQLite keeps the first name for a numbered slot. A plain ? leaves it unnamed. + if (name !== '?' && !namedIndices.has(index)) { + names.set(name, index) + namedIndices.add(index) } - names.add(query.slice(start, index + 1)) } - return { names: [...names], positionalCount } + return { names, namedIndices, parameterCount } } function expandBatchCommands( @@ -189,7 +198,8 @@ function expandBatchCommands( ): ExpandedBatchCommand[] { const expanded: ExpandedBatchCommand[] = [] for (const { query, params } of commands) { - if (params && isNestedParams(params)) { + if (Array.isArray(params) && params.length === 0) continue + if (isNestedParams(params)) { for (const rowParams of params) { expanded.push({ query, params: rowParams }) } @@ -201,9 +211,17 @@ function expandBatchCommands( } function isNestedParams( - params: SQLiteQueryParams | SQLiteQueryParams[], -): params is SQLiteQueryParams[] { - return params.length > 0 && params.every(Array.isArray) + params: BatchQueryCommand['params'], +): params is SQLiteQueryBindings[] { + return ( + Array.isArray(params) && + params.every( + (value) => + value !== null && + typeof value === 'object' && + !(value instanceof ArrayBuffer), + ) + ) } function toBoundValue(value: SQLiteValue): BoundValue { diff --git a/packages/react-native-nitro-sqlite/src/mock/transaction.ts b/packages/react-native-nitro-sqlite/src/mock/transaction.ts index c425cc0d8..54c9d1599 100644 --- a/packages/react-native-nitro-sqlite/src/mock/transaction.ts +++ b/packages/react-native-nitro-sqlite/src/mock/transaction.ts @@ -1,6 +1,6 @@ import type BetterSqlite3 from 'better-sqlite3' import NitroSQLiteError from '../NitroSQLiteError' -import type { QueryResultRow, SQLiteQueryParams, Transaction } from '../types' +import type { QueryResultRow, SQLiteQueryBindings, Transaction } from '../types' import { executeQuery, executeRawQuery } from './query' /** @internal Run a callback while the connection's exclusive queue item owns it. */ @@ -42,7 +42,7 @@ export async function runTransaction( }, executeAsync: async ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => { assertActive() return track( diff --git a/packages/react-native-nitro-sqlite/src/operations/execute.ts b/packages/react-native-nitro-sqlite/src/operations/execute.ts index d9a87963e..f4ec2d167 100644 --- a/packages/react-native-nitro-sqlite/src/operations/execute.ts +++ b/packages/react-native-nitro-sqlite/src/operations/execute.ts @@ -1,5 +1,5 @@ import { HybridNitroSQLite } from '../nitro' -import type { QueryResult, QueryResultRow, SQLiteQueryParams } from '../types' +import type { QueryResult, QueryResultRow, SQLiteQueryBindings } from '../types' import NitroSQLiteError from '../NitroSQLiteError' import { callNativeAsync, rejectWithNitroSQLiteError } from '../nativePromise' import type { @@ -16,14 +16,14 @@ import type { DatabaseQueueKey } from '../DatabaseQueue' /** Execute one SQL statement synchronously by database name. * Uses the managed queue when the database has an open managed connection. * @param dbName Name of an open native database. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @param params Values bound to the placeholders. * @returns The query result with typed rows. */ export function execute( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult { if (!isDatabaseOpen(dbName)) { return executeNative(dbName, query, params) @@ -35,7 +35,7 @@ export function execute( export function executeManaged( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, queueKey: DatabaseQueueKey = dbName, ): QueryResult { return startOperationSync(queueKey, () => @@ -46,7 +46,7 @@ export function executeManaged( export function executeNative( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult { try { const nativeResult = HybridNitroSQLite.execute(dbName, query, params) @@ -59,14 +59,14 @@ export function executeNative( /** Execute one SQL statement asynchronously by database name. * Uses the managed queue when the database has an open managed connection. * @param dbName Name of an open native database. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @param params Values bound to the placeholders. * @returns A promise of the query result with typed rows. */ export function executeAsync( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> { if (!isDatabaseOpen(dbName)) { return executeAsyncNative(dbName, query, params) @@ -78,7 +78,7 @@ export function executeAsync( export function executeAsyncManaged( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, queueKey: DatabaseQueueKey = dbName, ): Promise> { return queueStatementAsync(queueKey, () => @@ -89,7 +89,7 @@ export function executeAsyncManaged( export function executeAsyncNative( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> { // Not `async`: every extra promise layer is a measurable part of a short query's cost. // Large results arrive in batches, so rows are converted while SQLite reads the rest. @@ -179,7 +179,7 @@ function takeLeadingRows(rowBatchId: number): Row[] | undefined { function executeAsyncWithRowCallback( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> { let leadingRows: Row[] | undefined return callNativeAsync(() => @@ -199,7 +199,7 @@ function appendRows(leadingRows: Row[] | undefined, rows: Row[]): Row[] { * Uses the default managed connection's queue when the database was opened through `open()`. * Otherwise, calls the open native database directly. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @param params Values bound to the placeholders. * @returns Rows and column names in SQL column order, with affected row count and insert ID. * @throws NitroSQLiteError if the managed connection is busy or the query fails. @@ -207,7 +207,7 @@ function appendRows(leadingRows: Row[] | undefined, rows: Row[]): Row[] { export function executeRaw( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult { if (!isDatabaseOpen(dbName)) { return executeRawNative(dbName, query, params) @@ -219,7 +219,7 @@ export function executeRaw( export function executeRawManaged( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, queueKey: DatabaseQueueKey = dbName, ): NitroSQLiteRawQueryResult { return startOperationSync(queueKey, () => @@ -230,7 +230,7 @@ export function executeRawManaged( export function executeRawNative( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult { try { return HybridNitroSQLite.executeRaw(dbName, query, params) @@ -243,7 +243,7 @@ export function executeRawNative( * Uses the default managed connection's queue when the database was opened through `open()`. * Otherwise, calls the open native database directly. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @param params Values bound to the placeholders. * @returns A promise of rows and column names in SQL column order, with affected row count and insert ID. * @throws NitroSQLiteError as a rejected promise if the query fails. @@ -251,7 +251,7 @@ export function executeRawNative( export function executeRawAsync( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise { if (!isDatabaseOpen(dbName)) { return executeRawAsyncNative(dbName, query, params) @@ -263,7 +263,7 @@ export function executeRawAsync( export function executeRawAsyncManaged( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, queueKey: DatabaseQueueKey = dbName, ): Promise { return queueStatementAsync(queueKey, () => @@ -274,7 +274,7 @@ export function executeRawAsyncManaged( export function executeRawAsyncNative( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise { return callNativeAsync(() => HybridNitroSQLite.executeRawAsync(dbName, query, params), diff --git a/packages/react-native-nitro-sqlite/src/operations/prepare.ts b/packages/react-native-nitro-sqlite/src/operations/prepare.ts index 20011a7ef..2e15ea015 100644 --- a/packages/react-native-nitro-sqlite/src/operations/prepare.ts +++ b/packages/react-native-nitro-sqlite/src/operations/prepare.ts @@ -4,7 +4,7 @@ import type { PreparedStatement, QueryResult, QueryResultRow, - SQLiteQueryParams, + SQLiteQueryBindings, } from '../types' import type { NitroSQLiteRawQueryResult } from '../specs/NitroSQLiteQueryResult.nitro' import { buildJSQueryResult } from './execute' @@ -17,7 +17,7 @@ import type { DatabaseQueueKey } from '../DatabaseQueue' * Synchronous preparation throws if the connection is busy. Finalize the returned * statement before closing the connection. * @param dbName Database name or independent connection ID. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @param queueKey Internal managed queue key; omit when using the public API. * @returns A statement whose executions use the same connection queue. */ @@ -36,7 +36,7 @@ export function prepare( return nativeStatement.isFinalized }, execute: ( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult => { try { return startOperationSync(queueKey, () => @@ -50,14 +50,14 @@ export function prepare( // Native code runs executions on the connection's worker in call order, so they // queue as statements and several can be submitted without waiting for each result. executeAsync: ( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> => queueStatementAsync(queueKey, () => nativeStatement .executeAsync(params) .then((result) => buildJSQueryResult(result)), ).catch(rejectWithNitroSQLiteError), - executeRaw: (params?: SQLiteQueryParams): NitroSQLiteRawQueryResult => { + executeRaw: (params?: SQLiteQueryBindings): NitroSQLiteRawQueryResult => { try { return startOperationSync(queueKey, () => nativeStatement.executeRaw(params), @@ -67,7 +67,7 @@ export function prepare( } }, executeRawAsync: ( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise => queueStatementAsync(queueKey, () => nativeStatement.executeRawAsync(params), diff --git a/packages/react-native-nitro-sqlite/src/operations/session.ts b/packages/react-native-nitro-sqlite/src/operations/session.ts index 15933f90e..84a086ffc 100644 --- a/packages/react-native-nitro-sqlite/src/operations/session.ts +++ b/packages/react-native-nitro-sqlite/src/operations/session.ts @@ -5,7 +5,7 @@ import type { NitroSQLiteConnection, NitroSQLiteConnectionOptions, Transaction, - SQLiteQueryParams, + SQLiteQueryBindings, QueryResultRow, QueryResult, } from '../types' @@ -157,21 +157,21 @@ export function open( runAsyncOperation(() => transaction(connectionId, fn, false, queueKey)), execute: ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult => runOperation(() => executeManaged(connectionId, query, params, queueKey)), executeAsync: ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> => runAsyncOperation(() => executeAsyncManaged(connectionId, query, params, queueKey), ), - executeRaw: (query: string, params?: SQLiteQueryParams) => + executeRaw: (query: string, params?: SQLiteQueryBindings) => runOperation(() => executeRawManaged(connectionId, query, params, queueKey), ), - executeRawAsync: (query: string, params?: SQLiteQueryParams) => + executeRawAsync: (query: string, params?: SQLiteQueryBindings) => runAsyncOperation(() => executeRawAsyncManaged(connectionId, query, params, queueKey), ), diff --git a/packages/react-native-nitro-sqlite/src/operations/transaction.ts b/packages/react-native-nitro-sqlite/src/operations/transaction.ts index 09b3742d1..5275079a8 100644 --- a/packages/react-native-nitro-sqlite/src/operations/transaction.ts +++ b/packages/react-native-nitro-sqlite/src/operations/transaction.ts @@ -1,7 +1,7 @@ import { queueOperationAsync } from '../DatabaseQueue' import type { Transaction, - SQLiteQueryParams, + SQLiteQueryBindings, QueryResult, QueryResultRow, } from '../types' @@ -77,25 +77,25 @@ export const transaction = ( const executeOnTransaction = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): QueryResult => runOnTransaction(() => executeNative(dbName, query, params)) const executeAsyncOnTransaction = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise> => runAsyncOnTransaction(() => executeAsyncNative(dbName, query, params)) const executeRawOnTransaction = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult => runOnTransaction(() => executeRawNative(dbName, query, params)) const executeRawAsyncOnTransaction = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise => runAsyncOnTransaction(() => executeRawAsyncNative(dbName, query, params)) diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts index bce8c9224..5372a3310 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts @@ -4,7 +4,7 @@ import type { BatchQueryResult, DatabaseChange, FileLoadResult, - SQLiteQueryParams, + SQLiteQueryBindings, } from '../types' import type { NitroSQLiteQueryResult, @@ -86,19 +86,19 @@ export interface NitroSQLite detach(mainDbName: string, alias: string): void /** Execute one SQL statement synchronously on the calling thread. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. - * @param params Positional values bound to SQL placeholders. + * @param query SQL statement with optional placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names. * @returns Native query rows, affected row count, insert ID, and metadata. */ execute( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteQueryResult /** Execute one SQL statement on a background thread. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. - * @param params Positional values bound to SQL placeholders. + * @param query SQL statement with optional placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names. * @param onRows Receives leading rows in batches, in order, while SQLite still reads the rest, so * JavaScript can convert a batch while the next one is read. Batched rows are not repeated in the * result's `results`, which then holds only the rows after the last batch. The promise can settle @@ -111,7 +111,7 @@ export interface NitroSQLite executeAsync( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, onRows?: (rows: NitroSQLiteQueryRows) => void, rowBatchId?: number, ): Promise @@ -141,30 +141,30 @@ export interface NitroSQLite ): void /** 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. - * @param params Positional values bound to SQL placeholders. + * @param query SQL statement with optional placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names. * @returns Column names, rows as value arrays, affected row count, and insert ID. */ executeRaw( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): NitroSQLiteRawQueryResult /** Execute one SQL statement on a background thread, returning rows as arrays of column values. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. - * @param params Positional values bound to SQL placeholders. + * @param query SQL statement with optional placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names. * @returns A promise of the native raw query result. */ executeRawAsync( dbName: string, query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise /** Prepare one SQL statement on an open native connection for repeated execution. * Finalize the returned statement before closing its connection. * @param dbName Name or ID of an open database connection. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional placeholders. * @returns A native statement with synchronous and asynchronous execution methods. */ prepare(dbName: string, query: string): NitroSQLitePreparedStatement diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts index c8c287bcb..f756be3f8 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts @@ -1,5 +1,5 @@ import type { HybridObject } from 'react-native-nitro-modules' -import type { SQLiteQueryParams } from '../types' +import type { SQLiteQueryBindings } from '../types' import type { NitroSQLiteQueryResult, NitroSQLiteRawQueryResult, @@ -19,25 +19,25 @@ export interface NitroSQLitePreparedStatement * @param params Values bound to positional placeholders. * @returns Native query rows, affected row count, insert ID, and metadata. */ - execute(params?: SQLiteQueryParams): NitroSQLiteQueryResult + execute(params?: SQLiteQueryBindings): NitroSQLiteQueryResult /** Execute on the connection's background thread, replacing the previous parameter bindings. * Executions run in call order with the connection's other async calls. * Rejects after finalization or connection closure. * @param params Values bound to positional placeholders. * @returns A promise of the native query result. */ - executeAsync(params?: SQLiteQueryParams): Promise + executeAsync(params?: SQLiteQueryBindings): 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. */ - executeRaw(params?: SQLiteQueryParams): NitroSQLiteRawQueryResult + executeRaw(params?: SQLiteQueryBindings): NitroSQLiteRawQueryResult /** Execute on a background thread like `executeAsync`, returning rows as arrays of column values. * @param params Values bound to positional placeholders. * @returns A promise of the native raw query result. */ executeRawAsync( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ): Promise /** Release the native statement. Repeated calls are safe. */ finalize(): void diff --git a/packages/react-native-nitro-sqlite/src/types.ts b/packages/react-native-nitro-sqlite/src/types.ts index 2f68e2f5b..23cd9e2c0 100644 --- a/packages/react-native-nitro-sqlite/src/types.ts +++ b/packages/react-native-nitro-sqlite/src/types.ts @@ -176,6 +176,27 @@ export type SQLiteValue = */ export type SQLiteQueryParams = SQLiteValue[] +/** + * Values keyed by exact, case-sensitive SQLite placeholder names. Include the + * prefix, such as `:name`, `@name`, `$name` or `?5`. A repeated placeholder + * uses the same value at each occurrence. A plain `?` has no name. If a + * numbered placeholder aliases an existing slot, use SQLite's first name for it. + * + * Unknown keys throw or reject with a SQL execution error. Omitted placeholders + * and values set to `undefined` or `null` produce SQL NULL on every execution. + * Binding errors omit parameter values. + */ +export type SQLiteNamedQueryParams = Record + +/** + * Bind one statement with either {@link SQLiteQueryParams | a positional array} + * or {@link SQLiteNamedQueryParams | a record of exact placeholder names}. + */ +export type SQLiteQueryBindings = + | SQLiteQueryParams + // Nitrogen recognizes Record directly and treats a record alias as a struct. + | Record + /** A row keyed by result column names. */ export type QueryResultRow = Record @@ -208,7 +229,7 @@ export type NitroSQLiteQueryResultRows< */ export type ExecuteQuery = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => QueryResult /** Queue one SQL statement and resolve with its typed rows. @@ -217,7 +238,7 @@ export type ExecuteQuery = ( */ export type ExecuteAsyncQuery = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => Promise> /** Execute one SQL statement synchronously and return rows as arrays of column values. @@ -227,7 +248,7 @@ export type ExecuteAsyncQuery = ( */ export type ExecuteRawQuery = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => NitroSQLiteRawQueryResult /** Queue one SQL statement and resolve with rows as arrays of column values. @@ -236,7 +257,7 @@ export type ExecuteRawQuery = ( */ export type ExecuteRawAsyncQuery = ( query: string, - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => Promise /** @@ -260,42 +281,42 @@ export interface PreparedStatement { } /** - * Execute a prepared statement with optional positional values and return typed rows. + * Execute a prepared statement with optional bindings and return typed rows. * Each call replaces the previous parameter bindings. - * @param params Values bound to the statement's positional placeholders. + * @param params Values bound to the statement's placeholders. */ export type ExecutePreparedStatement = < Row extends QueryResultRow = QueryResultRow, >( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => QueryResult /** * Queue a prepared statement execution and resolve with typed rows. Calls on the * same managed connection run in queue order. - * @param params Values bound to the statement's positional placeholders. + * @param params Values bound to the statement's placeholders. */ export type ExecutePreparedStatementAsync = < Row extends QueryResultRow = QueryResultRow, >( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => Promise> /** * Execute a prepared statement and return rows as arrays of column values. * Each call replaces the previous parameter bindings. - * @param params Values bound to the statement's positional placeholders. + * @param params Values bound to the statement's placeholders. */ export type ExecuteRawPreparedStatement = ( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => NitroSQLiteRawQueryResult /** * Queue a prepared statement execution and resolve with rows as arrays of column values. - * @param params Values bound to the statement's positional placeholders. + * @param params Values bound to the statement's placeholders. */ export type ExecuteRawPreparedStatementAsync = ( - params?: SQLiteQueryParams, + params?: SQLiteQueryBindings, ) => Promise /** Handle valid only while its transaction callback is active. */ @@ -325,10 +346,10 @@ export interface Transaction { export interface BatchQueryCommand { /** SQL statement to execute. */ query: string - /** One parameter set, or several sets for repeated execution. - * An empty array skips the command. Omit this field to execute once without bindings. + /** One positional array or named record, or a list of either for repeated execution. + * An empty array skips the command. An empty record or omitted field executes once without bindings. */ - params?: SQLiteQueryParams | SQLiteQueryParams[] + params?: SQLiteQueryBindings | SQLiteQueryBindings[] } /** Result of a committed SQL batch. Errors are thrown rather than returned here. */ From fa2faebf0e0a6b52f12772126c55725f215e626b Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:51:41 +0100 Subject: [PATCH 3/8] fix: align mock binding errors and document named parameters Cover numbered aliases that share an existing named slot and use the SQL execution error category for excess mock bindings. Co-authored-by: Codex --- .../specs/operations/namedParameters.spec.ts | 15 ++++++++++++--- .../src/__tests__/mock.test.ts | 9 +++++++++ .../react-native-nitro-sqlite/src/mock/query.ts | 12 +++++++++--- .../src/specs/NitroSQLite.nitro.ts | 16 ++++++++++------ .../specs/NitroSQLitePreparedStatement.nitro.ts | 12 ++++++++---- 5 files changed, 48 insertions(+), 16 deletions(-) diff --git a/example/tests/unit/specs/operations/namedParameters.spec.ts b/example/tests/unit/specs/operations/namedParameters.spec.ts index da0f64e38..829a54c7d 100644 --- a/example/tests/unit/specs/operations/namedParameters.spec.ts +++ b/example/tests/unit/specs/operations/namedParameters.spec.ts @@ -116,8 +116,15 @@ export default function registerNamedParameterUnitTests() { it('rejects unknown keys without disclosing parameter values', async () => { const value = 'private-value' - const query = 'SELECT :known, ?' - for (const key of ['known', ':KNOWN', '@known', '?', ':known\0suffix']) { + const query = 'SELECT :known, ?1, ?' + for (const key of [ + 'known', + ':KNOWN', + '@known', + '?1', + '?', + ':known\0suffix', + ]) { try { testDb.execute(query, { [key]: value }) throw new Error('Expected a binding error') @@ -138,7 +145,9 @@ export default function registerNamedParameterUnitTests() { expect(error.type).toBe(NitroSQLiteExceptionType.SqlExecutionError) expect(error.message.includes(value)).toBe(false) } - expect(statement.executeRaw({ ':known': 42 }).rows).toEqual([[42, null]]) + expect(statement.executeRaw({ ':known': 42 }).rows).toEqual([ + [42, 42, null], + ]) } finally { statement.finalize() } diff --git a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts index ffc1189cf..b67ffe0db 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts @@ -158,6 +158,15 @@ describe('Node SQLite mock', () => { type: 'SqlExecutionError', message: expect.not.stringContaining('private-value'), }) + await expect( + database.executeAsync('SELECT :token, ?1', { '?1': 1 }), + ).rejects.toMatchObject({ type: 'SqlExecutionError' }) + await expect( + database.executeAsync('SELECT :token', [1, 'private-value']), + ).rejects.toMatchObject({ + type: 'SqlExecutionError', + message: expect.not.stringContaining('private-value'), + }) statement.finalize() }) diff --git a/packages/react-native-nitro-sqlite/src/mock/query.ts b/packages/react-native-nitro-sqlite/src/mock/query.ts index d9828760f..6866f5803 100644 --- a/packages/react-native-nitro-sqlite/src/mock/query.ts +++ b/packages/react-native-nitro-sqlite/src/mock/query.ts @@ -130,7 +130,7 @@ function getBindings(query: string, params: SQLiteQueryBindings = []) { let values: BoundValue[] if (Array.isArray(params)) { if (params.length > parameterCount) { - throw new RangeError('Too many parameter values were provided') + throw sqlBindingError('Too many parameter values were provided') } values = params.map(toBoundValue) } else { @@ -138,8 +138,8 @@ function getBindings(query: string, params: SQLiteQueryBindings = []) { for (const [name, value] of Object.entries(params)) { const index = names.get(name) if (index === undefined || name.startsWith('#')) { - throw new NitroSQLiteError( - `[NativeNitroSQLiteException][${NitroSQLiteExceptionType.SqlExecutionError}] Unknown SQL parameter name. Use the exact placeholder, including its prefix.`, + throw sqlBindingError( + 'Unknown SQL parameter name. Use the exact placeholder, including its prefix.', ) } values[index - 1] = toBoundValue(value) @@ -172,6 +172,12 @@ function getBindings(query: string, params: SQLiteQueryBindings = []) { return [named, anonymous] } +function sqlBindingError(message: string): NitroSQLiteError { + return new NitroSQLiteError( + `[NativeNitroSQLiteException][${NitroSQLiteExceptionType.SqlExecutionError}] ${message}`, + ) +} + function extractParameters(source: string) { const names = new Map() const namedIndices = new Set() diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts index 5372a3310..83b6de646 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts @@ -87,7 +87,8 @@ export interface NitroSQLite /** Execute one SQL statement synchronously on the calling thread. * @param dbName Name of an open database. * @param query SQL statement with optional placeholders. - * @param params Positional values or a record keyed by exact SQL placeholder names. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns Native query rows, affected row count, insert ID, and metadata. */ execute( @@ -98,7 +99,8 @@ export interface NitroSQLite /** Execute one SQL statement on a background thread. * @param dbName Name of an open database. * @param query SQL statement with optional placeholders. - * @param params Positional values or a record keyed by exact SQL placeholder names. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @param onRows Receives leading rows in batches, in order, while SQLite still reads the rest, so * JavaScript can convert a batch while the next one is read. Batched rows are not repeated in the * result's `results`, which then holds only the rows after the last batch. The promise can settle @@ -142,7 +144,8 @@ export interface NitroSQLite /** 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 placeholders. - * @param params Positional values or a record keyed by exact SQL placeholder names. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns Column names, rows as value arrays, affected row count, and insert ID. */ executeRaw( @@ -153,7 +156,8 @@ export interface NitroSQLite /** Execute one SQL statement on a background thread, returning rows as arrays of column values. * @param dbName Name of an open database. * @param query SQL statement with optional placeholders. - * @param params Positional values or a record keyed by exact SQL placeholder names. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns A promise of the native raw query result. */ executeRawAsync( @@ -171,14 +175,14 @@ export interface NitroSQLite /** Execute commands in one exclusive transaction on the calling thread. * An empty batch throws; a failed command rolls back the batch. * @param dbName Name of an open database. - * @param commands SQL commands and optional parameter sets. + * @param commands SQL commands with optional {@link BatchQueryCommand.params | parameter sets}. * @returns Total affected row count. */ executeBatch(dbName: string, commands: BatchQueryCommand[]): BatchQueryResult /** Execute commands in one exclusive transaction on a background thread. * An empty batch rejects; a failed command rolls back the batch. * @param dbName Name of an open database. - * @param commands SQL commands and optional parameter sets. + * @param commands SQL commands with optional {@link BatchQueryCommand.params | parameter sets}. * @returns A promise of the total affected row count. */ executeBatchAsync( diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts index f756be3f8..778a06b7d 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts @@ -16,24 +16,28 @@ export interface NitroSQLitePreparedStatement /** Execute on the calling thread, replacing the previous parameter bindings. * Throws after finalization or connection closure. - * @param params Values bound to positional placeholders. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns Native query rows, affected row count, insert ID, and metadata. */ execute(params?: SQLiteQueryBindings): NitroSQLiteQueryResult /** Execute on the connection's background thread, replacing the previous parameter bindings. * Executions run in call order with the connection's other async calls. * Rejects after finalization or connection closure. - * @param params Values bound to positional placeholders. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns A promise of the native query result. */ executeAsync(params?: SQLiteQueryBindings): Promise /** Execute on the calling thread like `execute`, returning rows as arrays of column values. - * @param params Values bound to positional placeholders. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns Column names, rows as value arrays, affected row count, and insert ID. */ executeRaw(params?: SQLiteQueryBindings): NitroSQLiteRawQueryResult /** Execute on a background thread like `executeAsync`, returning rows as arrays of column values. - * @param params Values bound to positional placeholders. + * @param params Positional values or a record keyed by exact placeholder names, including their prefixes. + * An unknown key raises a SQL execution error. Unbound parameters are SQL NULL. * @returns A promise of the native raw query result. */ executeRawAsync( From b4f2696747446aec3d1013ecc63eb457aa964dd6 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:58:35 +0100 Subject: [PATCH 4/8] fix: align named parameter mocks with SQLite tokenization Co-authored-by: Codex --- .../docs/guides/parameters-and-results.mdx | 4 ++++ docs/releases/named-parameters.md | 7 +++++++ .../specs/operations/namedParameters.spec.ts | 17 +++++++++++++++++ .../cpp/NitroSQLiteOperations.cpp | 4 +++- .../src/__tests__/mock.test.ts | 19 +++++++++++++++++++ .../src/mock/query.ts | 10 +++++++--- .../react-native-nitro-sqlite/src/types.ts | 18 +++++++++--------- 7 files changed, 66 insertions(+), 13 deletions(-) create mode 100644 docs/releases/named-parameters.md diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 3ef077af8..43b7174f6 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -20,6 +20,10 @@ A plain `?` has no record key. To supply values for both anonymous and named pla The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. +### Update typed wrappers and test doubles + +The exported query function types now accept `SQLiteQueryBindings`, a positional array or a named record. Existing calls with arrays keep working. If you implement these types in a wrapper or test double, accept both forms. Narrow recorded parameters with `Array.isArray(params)` before indexing them as an array. + ## Read results ```ts diff --git a/docs/releases/named-parameters.md b/docs/releases/named-parameters.md new file mode 100644 index 000000000..206844fc1 --- /dev/null +++ b/docs/releases/named-parameters.md @@ -0,0 +1,7 @@ +# Named parameter records + +Query, prepared-statement, transaction and batch APIs now accept records keyed by exact SQLite placeholder names, including their prefixes. Existing calls with positional arrays continue to work. + +The exported query function types accept `SQLiteQueryBindings`, which includes both arrays and records. Wrappers and test doubles that implement those types must accept both forms. Code that inspects recorded parameters must narrow with `Array.isArray(params)` before indexing them as an array. + +Include this compatibility note in the versioned release announcement that ships named parameter records. diff --git a/example/tests/unit/specs/operations/namedParameters.spec.ts b/example/tests/unit/specs/operations/namedParameters.spec.ts index 829a54c7d..99b2b8c35 100644 --- a/example/tests/unit/specs/operations/namedParameters.spec.ts +++ b/example/tests/unit/specs/operations/namedParameters.spec.ts @@ -49,6 +49,21 @@ export default function registerNamedParameterUnitTests() { ]) }) + it('uses SQLite token boundaries for BOM, Unicode and padded slot names', () => { + for (const [query, name] of [ + ['SELECT \uFEFF$x', '$x'], + ['SELECT :a𐍊', ':a𐍊'], + ['SELECT ?0000012', '?0000012'], + ] as const) { + expect(testDb.executeRaw(query, { [name]: 7 }).rows).toEqual([[7]]) + } + expect(testDb.executeRaw('SELECT \uFEFF$x', [7]).rows).toEqual([[7]]) + expect(testDb.executeRaw('SELECT 1 AS a\uFEFF$x', []).rows).toEqual([[1]]) + expect( + testDb.executeRaw('SELECT :a\uFEFF$x', { ':a\uFEFF$x': 9 }).rows, + ).toEqual([[9]]) + }) + it('clears prior bindings when reusing a prepared statement', async () => { const statement = testDb.prepare('SELECT :one AS one, :two AS two') try { @@ -132,6 +147,8 @@ export default function registerNamedParameterUnitTests() { if (!(error instanceof NitroSQLiteError)) throw error expect(error.type).toBe(NitroSQLiteExceptionType.SqlExecutionError) expect(error.message.includes(value)).toBe(false) + expect(error.message.includes('including its prefix.')).toBe(true) + expect(error.message.includes('\0')).toBe(false) } } diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp index 29cd116a8..caf56722b 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp @@ -132,7 +132,9 @@ namespace { const bool hasValidPrefix = !name.empty() && std::string_view(":@$?").find(name.front()) != std::string_view::npos; const int index = hasValidPrefix && name.find('\0') == std::string::npos ? sqlite3_bind_parameter_index(statement, name.c_str()) : 0; if (index == 0) { - throw NitroSQLiteException::SqlExecution("Unknown SQL parameter name. Use the exact placeholder, including its prefix."); + const auto diagnosticName = name.find('\0') == std::string::npos ? name : ""; + throw NitroSQLiteException::SqlExecution("Unknown SQL parameter name \"" + diagnosticName + + "\". Use the exact placeholder, including its prefix."); } bindValue(statement, index, value); } diff --git a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts index b67ffe0db..fb48d2d17 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts @@ -170,6 +170,25 @@ describe('Node SQLite mock', () => { statement.finalize() }) + it('matches SQLite parameter token boundaries', () => { + const database = open({ name: 'parameter-tokens' }) + expect(() => database.execute('SELECT :x', { ':x\0suffix': 7 })).toThrow( + 'Unknown SQL parameter name "". Use the exact placeholder, including its prefix.', + ) + for (const [query, name] of [ + ['SELECT \uFEFF$x', '$x'], + ['SELECT :a𐍊', ':a𐍊'], + ['SELECT ?0000012', '?0000012'], + ] as const) { + expect(database.executeRaw(query, { [name]: 7 }).rows).toEqual([[7]]) + } + expect(database.executeRaw('SELECT \uFEFF$x', [7]).rows).toEqual([[7]]) + expect(database.executeRaw('SELECT 1 AS a\uFEFF$x', []).rows).toEqual([[1]]) + expect( + database.executeRaw('SELECT :a\uFEFF$x', { ':a\uFEFF$x': 9 }).rows, + ).toEqual([[9]]) + }) + it('runs single named batch commands and groups of mixed bindings', async () => { const database = open({ name: 'named-batch' }) database.execute('CREATE TABLE items (value INTEGER)') diff --git a/packages/react-native-nitro-sqlite/src/mock/query.ts b/packages/react-native-nitro-sqlite/src/mock/query.ts index 6866f5803..e6705d9ac 100644 --- a/packages/react-native-nitro-sqlite/src/mock/query.ts +++ b/packages/react-native-nitro-sqlite/src/mock/query.ts @@ -15,14 +15,16 @@ type RawStatement = BetterSqlite3.Statement type BoundValue = string | number | Buffer | null type ExpandedBatchCommand = { query: string; params?: SQLiteQueryBindings } +// Keep Unicode ranges in strings: Babel rewrites regex literals before .source is read. // Skip comments, quoted tokens, and identifiers before matching parameters. const SQL_TOKENS = new RegExp( [ + /\uFEFF/.source, /--[^\n]*/.source, /\/\*[\s\S]*?(?:\*\/|$)/.source, /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]/.source, - /[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*/u.source, - /(\?\d*|[:@$#](?:[\w$\u0080-\u{10FFFF}]|::)+(?:\([^\s)]*\))?)/u.source, + String.raw`[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*`, + String.raw`(\?\d*|[:@$#](?:[\w$\u0080-\u{10FFFF}]|::)+(?:\([^\s)]*\))?)`, ].join('|'), 'gu', ) @@ -139,7 +141,9 @@ function getBindings(query: string, params: SQLiteQueryBindings = []) { const index = names.get(name) if (index === undefined || name.startsWith('#')) { throw sqlBindingError( - 'Unknown SQL parameter name. Use the exact placeholder, including its prefix.', + 'Unknown SQL parameter name "' + + (name.includes('\0') ? '' : name) + + '". Use the exact placeholder, including its prefix.', ) } values[index - 1] = toBoundValue(value) diff --git a/packages/react-native-nitro-sqlite/src/types.ts b/packages/react-native-nitro-sqlite/src/types.ts index 23cd9e2c0..bab0fa758 100644 --- a/packages/react-native-nitro-sqlite/src/types.ts +++ b/packages/react-native-nitro-sqlite/src/types.ts @@ -73,7 +73,7 @@ export interface NitroSQLiteConnection { /** * Prepare one SQL statement on this connection for repeated execution. * Finalize the returned statement before closing the connection. - * @param query SQL statement with optional positional placeholders. + * @param query SQL statement with optional positional or named placeholders. */ prepare(query: string): PreparedStatement /** Execute commands in one exclusive transaction. Throws while the connection is busy. @@ -224,8 +224,8 @@ export type NitroSQLiteQueryResultRows< } /** Execute one SQL statement synchronously and return its typed rows. - * @param query SQL statement with optional positional placeholders. - * @param params Values bound to the placeholders. + * @param query SQL statement with optional positional or named placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names, including their prefixes. */ export type ExecuteQuery = ( query: string, @@ -233,8 +233,8 @@ export type ExecuteQuery = ( ) => QueryResult /** Queue one SQL statement and resolve with its typed rows. - * @param query SQL statement with optional positional placeholders. - * @param params Values bound to the placeholders. + * @param query SQL statement with optional positional or named placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names, including their prefixes. */ export type ExecuteAsyncQuery = ( query: string, @@ -243,8 +243,8 @@ export type ExecuteAsyncQuery = ( /** Execute one SQL statement synchronously and return rows as arrays of column values. * Repeated column names are kept, in the order of `columnNames`. - * @param query SQL statement with optional positional placeholders. - * @param params Values bound to the placeholders. + * @param query SQL statement with optional positional or named placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names, including their prefixes. */ export type ExecuteRawQuery = ( query: string, @@ -252,8 +252,8 @@ export type ExecuteRawQuery = ( ) => NitroSQLiteRawQueryResult /** Queue one SQL statement and resolve with rows as arrays of column values. - * @param query SQL statement with optional positional placeholders. - * @param params Values bound to the placeholders. + * @param query SQL statement with optional positional or named placeholders. + * @param params Positional values or a record keyed by exact SQL placeholder names, including their prefixes. */ export type ExecuteRawAsyncQuery = ( query: string, From 7d3eb2d77df190a666a80bd7bba715992711da11 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:20:50 +0100 Subject: [PATCH 5/8] fix: preserve SQLite parameter suffix whitespace in mock scanning Co-authored-by: Codex --- docs/content/docs/guides/node-test-mock.mdx | 2 ++ docs/content/docs/guides/performance.mdx | 2 +- .../specs/operations/namedParameters.spec.ts | 18 ++++++++++++++++++ .../cpp/hybridObjects/HybridNitroSQLite.hpp | 4 ++-- .../src/__tests__/mock.test.ts | 10 ++++++++++ .../src/mock/query.ts | 5 +++-- 6 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/content/docs/guides/node-test-mock.mdx b/docs/content/docs/guides/node-test-mock.mdx index 0045a3b35..de0d6d800 100644 --- a/docs/content/docs/guides/node-test-mock.mdx +++ b/docs/content/docs/guides/node-test-mock.mdx @@ -128,6 +128,8 @@ The reset throws if any connection is busy. Await that work and retry. No connec ## API reference and limits +The installed `better-sqlite3` build disables Tcl-style parameter names such as `$name(suffix)` and `$name::part` with `SQLITE_OMIT_TCL_VARIABLE`. Use ordinary named placeholders in shared Node tests, and native integration tests for these extended SQLite names. Matching a name in the binding scanner does not enable SQL syntax omitted by the backend. + The generated [mock API reference](/api/react-native-nitro-sqlite/mock) documents `open()`, `NitroSQLite.open()`, `MockConnection`, and `resetAllDatabases()`. Connection methods use the same parameter and result types as the native API. The mock does not implement attachments, SQL file imports, or direct `NitroSQLite.native` methods. Its SQL runs synchronously on Node's thread; async methods schedule that work and return promises. It uses the SQLite version bundled with `better-sqlite3`, which can differ from the library's native SQLite build. Use device tests for native integration, thread behavior, lock contention, and performance. diff --git a/docs/content/docs/guides/performance.mdx b/docs/content/docs/guides/performance.mdx index 0927cd56c..553019d05 100644 --- a/docs/content/docs/guides/performance.mdx +++ b/docs/content/docs/guides/performance.mdx @@ -36,7 +36,7 @@ for (const metric of metrics) { ## Group related writes -One `executeBatchAsync()` call executes a fixed set of statements inside a native transaction. Use nested parameter arrays for repeated SQL. Use `db.transaction()` when application logic must inspect a result between writes. Both keep a transaction open while they work; keep the scope short and await each operation inside a transaction callback. +One `executeBatchAsync()` call executes a fixed set of statements inside a native transaction. Use a list of positional arrays or named records for repeated SQL. Use `db.transaction()` when application logic must inspect a result between writes. Both keep a transaction open while they work; keep the scope short and await each operation inside a transaction callback. ```ts await db.executeBatchAsync([ diff --git a/example/tests/unit/specs/operations/namedParameters.spec.ts b/example/tests/unit/specs/operations/namedParameters.spec.ts index 99b2b8c35..353873deb 100644 --- a/example/tests/unit/specs/operations/namedParameters.spec.ts +++ b/example/tests/unit/specs/operations/namedParameters.spec.ts @@ -53,6 +53,8 @@ export default function registerNamedParameterUnitTests() { for (const [query, name] of [ ['SELECT \uFEFF$x', '$x'], ['SELECT :a𐍊', ':a𐍊'], + ['SELECT $x(\uFEFF)', '$x(\uFEFF)'], + ['SELECT $x(\u00A0)', '$x(\u00A0)'], ['SELECT ?0000012', '?0000012'], ] as const) { expect(testDb.executeRaw(query, { [name]: 7 }).rows).toEqual([[7]]) @@ -129,6 +131,22 @@ export default function registerNamedParameterUnitTests() { ).toEqual([['blob', '010101']]) }) + it('keeps a flat batch of BLOB values as one positional binding set', () => { + testDb.execute('CREATE TABLE blob_batch (first BLOB, second BLOB)') + const result = NitroSQLite.native.executeBatch(TEST_DB_NAME, [ + { + query: 'INSERT INTO blob_batch VALUES (?, ?)', + params: [new ArrayBuffer(0), new Uint8Array([0, 255]).buffer], + }, + ]) + expect(result.rowsAffected).toBe(1) + expect( + testDb.executeRaw( + 'SELECT typeof(first), hex(first), typeof(second), hex(second) FROM blob_batch', + ).rows, + ).toEqual([['blob', '', 'blob', '00FF']]) + }) + it('rejects unknown keys without disclosing parameter values', async () => { const value = 'private-value' const query = 'SELECT :known, ?1, ?' diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp index f2acaa673..1488c80d2 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -61,8 +61,8 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { /** Execute one SQL statement on the calling thread. * @param dbName Name of an open database. - * @param query SQL statement with optional positional placeholders. - * @param params Optional values bound to the placeholders. + * @param query SQL statement with optional positional or named placeholders. + * @param params Optional positional values or a record keyed by exact placeholder names, including prefixes. * @return Native rows, affected row count, insert ID, and metadata. */ NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, diff --git a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts index fb48d2d17..60a5ef885 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/mock.test.ts @@ -1,5 +1,6 @@ import { NitroSQLite, open, resetAllDatabases } from '../mock' import type { Transaction } from '../types' +import { extractParameters } from '../mock/query' afterEach(resetAllDatabases) @@ -170,6 +171,15 @@ describe('Node SQLite mock', () => { statement.finalize() }) + it('scans native SQLite suffix names independently of Node compile options', () => { + // The Node backend omits Tcl variables; these names come from bundled SQLite. + for (const name of ['$x(\uFEFF)', '$x(\u00A0)', '$x(value)']) { + const { names, parameterCount } = extractParameters(`SELECT ${name}`) + expect([...names]).toEqual([[name, 1]]) + expect(parameterCount).toBe(1) + } + }) + it('matches SQLite parameter token boundaries', () => { const database = open({ name: 'parameter-tokens' }) expect(() => database.execute('SELECT :x', { ':x\0suffix': 7 })).toThrow( diff --git a/packages/react-native-nitro-sqlite/src/mock/query.ts b/packages/react-native-nitro-sqlite/src/mock/query.ts index e6705d9ac..d82f01b05 100644 --- a/packages/react-native-nitro-sqlite/src/mock/query.ts +++ b/packages/react-native-nitro-sqlite/src/mock/query.ts @@ -24,7 +24,7 @@ const SQL_TOKENS = new RegExp( /\/\*[\s\S]*?(?:\*\/|$)/.source, /'(?:''|[^'])*'|"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\]/.source, String.raw`[A-Za-z_\u0080-\u{10FFFF}][\w$\u0080-\u{10FFFF}]*`, - String.raw`(\?\d*|[:@$#](?:[\w$\u0080-\u{10FFFF}]|::)+(?:\([^\s)]*\))?)`, + String.raw`(\?\d*|[:@$#](?:[\w$\u0080-\u{10FFFF}]|::)+(?:\([^\x09-\x0D\x20)]*\))?)`, ].join('|'), 'gu', ) @@ -182,7 +182,8 @@ function sqlBindingError(message: string): NitroSQLiteError { ) } -function extractParameters(source: string) { +/** @internal Scan SQLite parameter names and slot indices before mapping bindings. */ +export function extractParameters(source: string) { const names = new Map() const namedIndices = new Set() let parameterCount = 0 From a2a83bcd6bdf140f319405ddf4332a7c7ddd3b2e Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:49:15 +0100 Subject: [PATCH 6/8] docs: explain native rollout for named bindings Co-authored-by: Codex --- docs/content/docs/guides/parameters-and-results.mdx | 2 ++ docs/releases/named-parameters.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 43b7174f6..c22ed7268 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -20,6 +20,8 @@ A plain `?` has no record key. To supply values for both anonymous and named pla The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. +Named records require an app built with the matching native library. Rebuild and distribute the native app before using record bindings in an over-the-air JavaScript update. + ### Update typed wrappers and test doubles The exported query function types now accept `SQLiteQueryBindings`, a positional array or a named record. Existing calls with arrays keep working. If you implement these types in a wrapper or test double, accept both forms. Narrow recorded parameters with `Array.isArray(params)` before indexing them as an array. diff --git a/docs/releases/named-parameters.md b/docs/releases/named-parameters.md index 206844fc1..a9cef13ae 100644 --- a/docs/releases/named-parameters.md +++ b/docs/releases/named-parameters.md @@ -2,6 +2,8 @@ Query, prepared-statement, transaction and batch APIs now accept records keyed by exact SQLite placeholder names, including their prefixes. Existing calls with positional arrays continue to work. +Named records require the matching native library in the installed app. Rebuild and distribute the native app before enabling record bindings in an over-the-air JavaScript update; older native binaries accept only positional arrays. + The exported query function types accept `SQLiteQueryBindings`, which includes both arrays and records. Wrappers and test doubles that implement those types must accept both forms. Code that inspects recorded parameters must narrow with `Array.isArray(params)` before indexing them as an array. Include this compatibility note in the versioned release announcement that ships named parameter records. From c439c4585feb45e5cf52c17770e0ba3e3e0ea53d Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:57:08 +0100 Subject: [PATCH 7/8] docs: scope named-binding updates to compatible binaries Co-authored-by: Codex --- docs/content/docs/guides/parameters-and-results.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index c22ed7268..47c606f27 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -20,7 +20,7 @@ A plain `?` has no record key. To supply values for both anonymous and named pla The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. -Named records require an app built with the matching native library. Rebuild and distribute the native app before using record bindings in an over-the-air JavaScript update. +Named records require an app built with the matching native library. Older binaries reject record bindings and accept only positional arrays. Rebuild and distribute the native app first, then target over-the-air JavaScript updates that use records only to compatible binaries. Keep positional bindings in updates for older binaries. ### Update typed wrappers and test doubles From 1ca737e9edf57e24e4fd9aaad5ab9413b3b58670 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 13:31:49 +0100 Subject: [PATCH 8/8] fix: preserve Unicode bindings and empty BLOB values Co-authored-by: Codex --- .github/ci-paths.json | 5 +- .github/workflows/test-macos.yml | 3 + .../docs/guides/parameters-and-results.mdx | 2 +- .../specs/operations/namedParameters.spec.ts | 74 ++++++-- .../cpp/NitroSQLiteNamedQueryParams.hpp | 53 ++++++ .../cpp/NitroSQLiteOperations.cpp | 6 +- .../NitroSQLiteBackgroundBindings.hpp | 3 +- .../shared/c++/BatchQueryCommand.hpp | 14 +- ...HybridNitroSQLitePreparedStatementSpec.hpp | 10 +- .../shared/c++/HybridNitroSQLiteSpec.hpp | 10 +- .../src/__tests__/namedBindingTypes.test.ts | 18 ++ .../src/specs/NitroSQLite.nitro.ts | 12 +- .../NitroSQLitePreparedStatement.nitro.ts | 2 +- .../src/specs/SQLiteQueryBindings.ts | 21 +++ .../react-native-nitro-sqlite/src/types.ts | 9 +- .../tests/cpp/namedBindings.test.cpp | 158 ++++++++++++++++++ scripts/ci.test.ts | 11 ++ scripts/test-bindings-jsi.py | 102 +++++++++++ 18 files changed, 468 insertions(+), 45 deletions(-) create mode 100644 packages/react-native-nitro-sqlite/cpp/NitroSQLiteNamedQueryParams.hpp create mode 100644 packages/react-native-nitro-sqlite/src/__tests__/namedBindingTypes.test.ts create mode 100644 packages/react-native-nitro-sqlite/src/specs/SQLiteQueryBindings.ts create mode 100644 packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp create mode 100644 scripts/test-bindings-jsi.py diff --git a/.github/ci-paths.json b/.github/ci-paths.json index bbe86bf6d..96052c6dc 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -209,6 +209,9 @@ "packages/react-native-nitro-sqlite-drizzle/src/**", "packages/react-native-nitro-sqlite-drizzle/package.json", "!packages/react-native-nitro-sqlite-drizzle/src/__tests__/**", - "packages/react-native-nitro-sqlite-drizzle/src/__tests__/fixtures/**" + "packages/react-native-nitro-sqlite-drizzle/src/__tests__/fixtures/**", + "scripts/test-bindings-jsi.py", + "packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp", + "bunfig.toml" ] } diff --git a/.github/workflows/test-macos.yml b/.github/workflows/test-macos.yml index 283d4bca9..eb0710ded 100644 --- a/.github/workflows/test-macos.yml +++ b/.github/workflows/test-macos.yml @@ -52,6 +52,9 @@ jobs: - name: Select Xcode 26.5 run: sudo xcode-select -s "/Applications/Xcode_26.5.app/Contents/Developer" + - name: Test named bindings and empty BLOBs in JavaScriptCore + run: python3 scripts/test-bindings-jsi.py + - name: Restore Pods cache uses: actions/cache@v6 with: diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 47c606f27..dbbbbc5d0 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -18,7 +18,7 @@ const result = await db.executeAsync( A plain `?` has no record key. To supply values for both anonymous and named placeholders in one statement, use a positional array ordered by SQLite parameter index. Unbound placeholders, `null`, and `undefined` all produce SQL NULL. Bindings start fresh on every execution, including when you reuse a prepared statement. -The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. +The public `SQLiteValue` type permits `boolean`, `number`, `string`, `ArrayBuffer`, `null`, and `undefined`. An empty `ArrayBuffer` stores a zero-length BLOB, distinct from SQL NULL. Keep table and column names in your SQL. Parameters only bind values. An unknown record key or extra array value throws or rejects with `SqlExecutionError`. Binding errors omit parameter values. These rules apply to synchronous, asynchronous, batch, and prepared statement execution. Named records require an app built with the matching native library. Older binaries reject record bindings and accept only positional arrays. Rebuild and distribute the native app first, then target over-the-air JavaScript updates that use records only to compatible binaries. Keep positional bindings in updates for older binaries. diff --git a/example/tests/unit/specs/operations/namedParameters.spec.ts b/example/tests/unit/specs/operations/namedParameters.spec.ts index 353873deb..4c29314a6 100644 --- a/example/tests/unit/specs/operations/namedParameters.spec.ts +++ b/example/tests/unit/specs/operations/namedParameters.spec.ts @@ -49,16 +49,28 @@ export default function registerNamedParameterUnitTests() { ]) }) - it('uses SQLite token boundaries for BOM, Unicode and padded slot names', () => { - for (const [query, name] of [ - ['SELECT \uFEFF$x', '$x'], - ['SELECT :a𐍊', ':a𐍊'], - ['SELECT $x(\uFEFF)', '$x(\uFEFF)'], - ['SELECT $x(\u00A0)', '$x(\u00A0)'], - ['SELECT ?0000012', '?0000012'], - ] as const) { - expect(testDb.executeRaw(query, { [name]: 7 }).rows).toEqual([[7]]) - } + for (const [query, name] of [ + ['SELECT \uFEFF$x', '$x'], + ['SELECT :a𐍊', ':a𐍊'], + ['SELECT $x(\uFEFF)', '$x(\uFEFF)'], + ['SELECT $x(\u00A0)', '$x(\u00A0)'], + ['SELECT ?0000012', '?0000012'], + ] as const) { + it(`binds the exact SQLite token ${JSON.stringify(name)}`, async () => { + const params = { [name]: 7 } + expect(testDb.executeRaw(query, params).rows).toEqual([[7]]) + expect((await testDb.executeRawAsync(query, params)).rows).toEqual([[7]]) + const statement = testDb.prepare(query) + try { + expect(statement.executeRaw(params).rows).toEqual([[7]]) + expect((await statement.executeRawAsync(params)).rows).toEqual([[7]]) + } finally { + statement.finalize() + } + }) + } + + it('preserves SQLite token boundaries around BOM characters', () => { expect(testDb.executeRaw('SELECT \uFEFF$x', [7]).rows).toEqual([[7]]) expect(testDb.executeRaw('SELECT 1 AS a\uFEFF$x', []).rows).toEqual([[1]]) expect( @@ -131,7 +143,29 @@ export default function registerNamedParameterUnitTests() { ).toEqual([['blob', '010101']]) }) - it('keeps a flat batch of BLOB values as one positional binding set', () => { + it('preserves empty BLOBs separately from NULL in both binding forms', async () => { + const query = 'SELECT typeof(:blob), length(:blob), :missing IS NULL' + const statement = testDb.prepare(query) + try { + for (const params of [ + [new ArrayBuffer(0), null], + { ':blob': new ArrayBuffer(0), ':missing': null }, + ]) { + expect(testDb.executeRaw(query, params).rows).toEqual([['blob', 0, 1]]) + expect((await testDb.executeRawAsync(query, params)).rows).toEqual([ + ['blob', 0, 1], + ]) + expect(statement.executeRaw(params).rows).toEqual([['blob', 0, 1]]) + expect((await statement.executeRawAsync(params)).rows).toEqual([ + ['blob', 0, 1], + ]) + } + } finally { + statement.finalize() + } + }) + + it('keeps a flat batch of BLOB values as one positional binding set', async () => { testDb.execute('CREATE TABLE blob_batch (first BLOB, second BLOB)') const result = NitroSQLite.native.executeBatch(TEST_DB_NAME, [ { @@ -145,6 +179,24 @@ export default function registerNamedParameterUnitTests() { 'SELECT typeof(first), hex(first), typeof(second), hex(second) FROM blob_batch', ).rows, ).toEqual([['blob', '', 'blob', '00FF']]) + await NitroSQLite.native.executeBatchAsync(TEST_DB_NAME, [ + { + query: 'INSERT INTO blob_batch VALUES (:first, :second)', + params: [ + { + ':first': new ArrayBuffer(0), + ':second': new Uint8Array([0, 255]).buffer, + }, + ], + }, + ]) + expect( + testDb.executeRaw('SELECT typeof(first), length(first) FROM blob_batch') + .rows, + ).toEqual([ + ['blob', 0], + ['blob', 0], + ]) }) it('rejects unknown keys without disclosing parameter values', async () => { diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteNamedQueryParams.hpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteNamedQueryParams.hpp new file mode 100644 index 000000000..f3007165c --- /dev/null +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteNamedQueryParams.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include "NitroSQLiteTypes.hpp" +#include +#include + +namespace margelo::nitro { + +/** Convert named SQLite bindings using their original JavaScript property names. + * SQLite names can contain Unicode, so they cannot use Nitro's ASCII property-name cache. + */ +template <> +struct JSIConverter final { + static rnnitrosqlite::SQLiteNamedQueryParams fromJSI(jsi::Runtime& runtime, const jsi::Value& value) { + auto object = value.asObject(runtime); + auto names = object.getPropertyNames(runtime); + const size_t count = names.size(runtime); + rnnitrosqlite::SQLiteNamedQueryParams bindings; + bindings.reserve(count); + for (size_t index = 0; index < count; index++) { + auto name = names.getValueAtIndex(runtime, index).asString(runtime); + bindings.emplace(name.utf8(runtime), JSIConverter::fromJSI(runtime, object.getProperty(runtime, name))); + } + return bindings; + } + + static jsi::Value toJSI(jsi::Runtime& runtime, const rnnitrosqlite::SQLiteNamedQueryParams& bindings) { + jsi::Object object(runtime); + for (const auto& [name, value] : bindings) { + object.setProperty(runtime, jsi::String::createFromUtf8(runtime, name), + JSIConverter::toJSI(runtime, value)); + } + return object; + } + + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + if (!value.isObject()) + return false; + auto object = value.getObject(runtime); + if (!isPlainObject(runtime, object)) + return false; + auto names = object.getPropertyNames(runtime); + const size_t count = names.size(runtime); + for (size_t index = 0; index < count; index++) { + auto name = names.getValueAtIndex(runtime, index).asString(runtime); + if (!JSIConverter::canConvert(runtime, object.getProperty(runtime, name))) + return false; + } + return true; + } +}; + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp index caf56722b..61a975565 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp +++ b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp @@ -107,7 +107,11 @@ namespace { bindStatus = sqlite3_bind_text(statement, sqliteIndex, stringValue.c_str(), stringValue.length(), SQLITE_TRANSIENT); } else if (std::holds_alternative>(*optionalValue)) { const auto& arrayBufferValue = std::get>(*optionalValue); - bindStatus = sqlite3_bind_blob(statement, sqliteIndex, arrayBufferValue->data(), arrayBufferValue->size(), SQLITE_TRANSIENT); + if (arrayBufferValue->size() == 0) { + bindStatus = sqlite3_bind_zeroblob(statement, sqliteIndex, 0); + } else { + bindStatus = sqlite3_bind_blob(statement, sqliteIndex, arrayBufferValue->data(), arrayBufferValue->size(), SQLITE_TRANSIENT); + } } if (bindStatus != SQLITE_OK) { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp index 914c12072..d625c689a 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/NitroSQLiteBackgroundBindings.hpp @@ -9,7 +9,8 @@ inline SQLiteQueryBindings copyArrayBufferParamsForBackground(SQLiteQueryBinding auto copyBuffer = [](SQLiteValue& value) { if (value) { if (auto* buffer = std::get_if>(&*value)) { - *buffer = ArrayBuffer::copy(*buffer); + // Empty JS buffers can have a null data pointer, which Nitro cannot copy. + *buffer = (*buffer)->size() == 0 ? ArrayBuffer::allocate(0) : ArrayBuffer::copy(*buffer); } } }; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp index 28149a3b7..4540c692a 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/BatchQueryCommand.hpp @@ -36,7 +36,7 @@ #include #include #include -#include +#include "NitroSQLiteNamedQueryParams.hpp" namespace margelo::nitro::rnnitrosqlite { @@ -46,14 +46,14 @@ namespace margelo::nitro::rnnitrosqlite { struct BatchQueryCommand final { public: std::string query SWIFT_PRIVATE; - std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>> params SWIFT_PRIVATE; + std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>, std::variant, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>> params SWIFT_PRIVATE; public: BatchQueryCommand() = default; - explicit BatchQueryCommand(std::string query, std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>> params): query(query), params(params) {} + explicit BatchQueryCommand(std::string query, std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>, std::variant, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>> params): query(query), params(params) {} public: - friend bool operator==(const BatchQueryCommand& lhs, const BatchQueryCommand& rhs) = default; + // BatchQueryCommand is not equatable because these properties are not equatable: params }; } // namespace margelo::nitro::rnnitrosqlite @@ -67,13 +67,13 @@ namespace margelo::nitro { jsi::Object obj = arg.asObject(runtime); return margelo::nitro::rnnitrosqlite::BatchQueryCommand( JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "query"))), - JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params"))) + JSIConverter, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>, std::variant, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params"))) ); } static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::BatchQueryCommand& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "query"), JSIConverter::toJSI(runtime, arg.query)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "params"), JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::toJSI(runtime, arg.params)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "params"), JSIConverter, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>, std::variant, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>>>::toJSI(runtime, arg.params)); return obj; } static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) { @@ -85,7 +85,7 @@ namespace margelo::nitro { return false; } if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "query")))) return false; - if (!JSIConverter, std::string, double>>>, std::unordered_map, std::string, double>>>>>, std::variant, std::string, double>>>, std::unordered_map, std::string, double>>>>>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params")))) return false; + if (!JSIConverter, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>, std::variant, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "params")))) return false; return true; } }; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp index c4b36fa30..afd0f9de2 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLitePreparedStatementSpec.hpp @@ -25,7 +25,7 @@ namespace margelo::nitro::rnnitrosqlite { struct NitroSQLiteRawQueryResult; } #include #include #include -#include +#include "NitroSQLiteNamedQueryParams.hpp" #include #include "NitroSQLiteRawQueryResult.hpp" @@ -60,10 +60,10 @@ namespace margelo::nitro::rnnitrosqlite { public: // Methods - virtual NitroSQLiteQueryResult execute(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; - virtual std::shared_ptr> executeAsync(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; - virtual NitroSQLiteRawQueryResult executeRaw(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; - virtual std::shared_ptr> executeRawAsync(const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual NitroSQLiteQueryResult execute(const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; + virtual std::shared_ptr> executeAsync(const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; + virtual NitroSQLiteRawQueryResult executeRaw(const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; + virtual std::shared_ptr> executeRawAsync(const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; virtual void finalize() = 0; protected: diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp index 97c60a3e2..5fc48cd6c 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/HybridNitroSQLiteSpec.hpp @@ -35,7 +35,7 @@ namespace margelo::nitro::rnnitrosqlite { struct FileLoadResult; } #include #include #include -#include +#include "NitroSQLiteNamedQueryParams.hpp" #include #include "NitroSQLiteQueryResults.hpp" #include @@ -85,12 +85,12 @@ namespace margelo::nitro::rnnitrosqlite { virtual void drop(const std::string& dbName, const std::optional& location, const std::optional& connectionId) = 0; virtual void attach(const std::string& mainDbName, const std::string& dbNameToAttach, const std::string& alias, const std::optional& location) = 0; virtual void detach(const std::string& mainDbName, const std::string& alias) = 0; - virtual NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; - virtual std::shared_ptr> executeAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params, const std::optional>& onRows, std::optional rowBatchId) = 0; + virtual NitroSQLiteQueryResult execute(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; + virtual std::shared_ptr> executeAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params, const std::optional>& onRows, std::optional rowBatchId) = 0; virtual void setRowBatchHandler(const std::function& handler) = 0; virtual void setChangeHandler(const std::string& dbName, const std::optional& /* changes */)>>& handler) = 0; - virtual NitroSQLiteRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; - virtual std::shared_ptr> executeRawAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, std::unordered_map, std::string, double>>>>>& params) = 0; + virtual NitroSQLiteRawQueryResult executeRaw(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; + virtual std::shared_ptr> executeRawAsync(const std::string& dbName, const std::string& query, const std::optional, std::string, double>>>, margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams>>& params) = 0; virtual std::shared_ptr prepare(const std::string& dbName, const std::string& query) = 0; virtual BatchQueryResult executeBatch(const std::string& dbName, const std::vector& commands) = 0; virtual std::shared_ptr> executeBatchAsync(const std::string& dbName, const std::vector& commands) = 0; diff --git a/packages/react-native-nitro-sqlite/src/__tests__/namedBindingTypes.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/namedBindingTypes.test.ts new file mode 100644 index 000000000..e405ce7e2 --- /dev/null +++ b/packages/react-native-nitro-sqlite/src/__tests__/namedBindingTypes.test.ts @@ -0,0 +1,18 @@ +import type { SQLiteNamedQueryParams, SQLiteValue } from '../types' + +function values(params: SQLiteNamedQueryParams): SQLiteValue[] { + return Object.values(params) +} + +function entries(params: SQLiteNamedQueryParams): [string, SQLiteValue][] { + return Object.entries(params) +} + +it('keeps named records compatible with standard object enumeration', () => { + const params: SQLiteNamedQueryParams = { ':value': 7, ':empty': null } + expect(values(params)).toEqual([7, null]) + expect(entries(params)).toEqual([ + [':value', 7], + [':empty', null], + ]) +}) diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts index 83b6de646..556a156b2 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts @@ -1,16 +1,14 @@ import type { HybridObject } from 'react-native-nitro-modules' -import type { - BatchQueryCommand, - BatchQueryResult, - DatabaseChange, - FileLoadResult, - SQLiteQueryBindings, -} from '../types' +import type { BatchQueryResult, DatabaseChange, FileLoadResult } from '../types' import type { NitroSQLiteQueryResult, NitroSQLiteQueryRows, NitroSQLiteRawQueryResult, } from './NitroSQLiteQueryResult.nitro' +import type { + BatchQueryCommand, + SQLiteQueryBindings, +} from './SQLiteQueryBindings' import type { NitroSQLitePreparedStatement } from './NitroSQLitePreparedStatement.nitro' /** Native database operations exposed through `NitroSQLite.native`. diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts index 778a06b7d..764ff3d97 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLitePreparedStatement.nitro.ts @@ -1,5 +1,5 @@ import type { HybridObject } from 'react-native-nitro-modules' -import type { SQLiteQueryBindings } from '../types' +import type { SQLiteQueryBindings } from './SQLiteQueryBindings' import type { NitroSQLiteQueryResult, NitroSQLiteRawQueryResult, diff --git a/packages/react-native-nitro-sqlite/src/specs/SQLiteQueryBindings.ts b/packages/react-native-nitro-sqlite/src/specs/SQLiteQueryBindings.ts new file mode 100644 index 000000000..7119c7590 --- /dev/null +++ b/packages/react-native-nitro-sqlite/src/specs/SQLiteQueryBindings.ts @@ -0,0 +1,21 @@ +import type { CustomType } from 'react-native-nitro-modules' +import type { SQLiteNamedQueryParams, SQLiteQueryParams } from '../types' + +/** Native bridge bindings. Records use the Unicode-aware property converter. */ +export type SQLiteQueryBindings = + | SQLiteQueryParams + | CustomType< + SQLiteNamedQueryParams, + 'margelo::nitro::rnnitrosqlite::SQLiteNamedQueryParams', + { include: 'NitroSQLiteNamedQueryParams.hpp' } + > + +/** Native batch command with the same input shape as the public batch API. */ +export interface BatchQueryCommand { + /** SQL statement to execute. */ + query: string + /** One binding set or a list of binding sets for repeated execution. + * An empty array skips the command; an empty record or omitted field executes once. + */ + params?: SQLiteQueryBindings | SQLiteQueryBindings[] +} diff --git a/packages/react-native-nitro-sqlite/src/types.ts b/packages/react-native-nitro-sqlite/src/types.ts index bab0fa758..7038848e2 100644 --- a/packages/react-native-nitro-sqlite/src/types.ts +++ b/packages/react-native-nitro-sqlite/src/types.ts @@ -159,7 +159,9 @@ export enum ColumnType { NULL_VALUE, } -/** SQL value. `undefined` binds as SQL NULL; result rows return `null`. */ +/** SQL value. `undefined` binds as SQL NULL; result rows return `null`. + * An empty `ArrayBuffer` binds as a zero-length BLOB, distinct from SQL NULL. + */ export type SQLiteValue = | boolean | number @@ -192,10 +194,7 @@ export type SQLiteNamedQueryParams = Record * Bind one statement with either {@link SQLiteQueryParams | a positional array} * or {@link SQLiteNamedQueryParams | a record of exact placeholder names}. */ -export type SQLiteQueryBindings = - | SQLiteQueryParams - // Nitrogen recognizes Record directly and treats a record alias as a struct. - | Record +export type SQLiteQueryBindings = SQLiteQueryParams | SQLiteNamedQueryParams /** A row keyed by result column names. */ export type QueryResultRow = Record diff --git a/packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp new file mode 100644 index 000000000..c987a86bb --- /dev/null +++ b/packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp @@ -0,0 +1,158 @@ +#ifndef NITRO_SQLITE_TEST_STOCK_CONVERTER +#include "NitroSQLiteNamedQueryParams.hpp" +#endif +#include "NitroSQLiteOperations.hpp" +#include "hybridObjects/NitroSQLiteBackgroundBindings.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace facebook; +using namespace margelo::nitro; +using namespace margelo::nitro::rnnitrosqlite; + +namespace { + +// JSC accepts UTF-8 in its ASCII API, masking the invalid input that breaks Hermes. +class AsciiCheckedRuntime final : public jsi::RuntimeDecorator<> { +public: + explicit AsciiCheckedRuntime(jsi::Runtime& runtime) : RuntimeDecorator(runtime) {} + + jsi::PropNameID createPropNameIDFromAscii(const char* name, size_t length) override { + if (std::any_of(name, name + length, [](unsigned char byte) { return byte > 0x7f; })) { + throw std::runtime_error("non-ASCII parameter passed to the ASCII-only JSI property-name API"); + } + return RuntimeDecorator::createPropNameIDFromAscii(name, length); + } +}; + +// A zero-length buffer has no bytes to read, regardless of its storage pointer. +class EmptyBufferWithoutReadableData final : public ArrayBuffer { +public: + uint8_t* data() override { + throw std::runtime_error("empty buffer data must not be read for async copying"); + } + size_t size() const override { + return 0; + } + bool isOwner() const noexcept override { + return false; + } +}; + +void expect(bool condition, const std::string& message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +jsi::Value evaluate(jsi::Runtime& runtime, const std::string& code) { + return runtime.evaluateJavaScript(std::make_shared(code), "named-bindings-test.js"); +} + +void expectNumber(const SQLiteValue& value, double expected, const std::string& message) { + expect(value && std::holds_alternative(*value) && std::get(*value) == expected, message); +} + +void expectText(const SQLiteValue& value, const std::string& expected, const std::string& message) { + expect(value && std::holds_alternative(*value) && std::get(*value) == expected, message); +} + +void checkUnicodeBinding(jsi::Runtime& runtime, const SQLiteConnectionPtr& connection, const std::string& name) { + auto input = evaluate(runtime, "({'" + name + "': 42})"); + expect(JSIConverter::canConvert(runtime, input), "valid named bindings must be accepted"); + auto bindings = JSIConverter::fromJSI(runtime, input); + const auto& named = std::get(bindings); + expect(named.size() == 1 && named.contains(name), "conversion must preserve the exact parameter name"); + auto result = sqliteExecute(connection, "SELECT " + name, bindings); + expectNumber(result.results.data->rows.at(0).at(0), 42, "Unicode parameter must reach SQLite as 42, not NULL"); + + auto roundTrip = JSIConverter::toJSI(runtime, named).asObject(runtime); + auto value = roundTrip.getProperty(runtime, jsi::String::createFromUtf8(runtime, name)); + expect(value.isNumber() && value.asNumber() == 42, "round trip must preserve the Unicode property and value"); +} + +void checkUnsupportedValue(jsi::Runtime& runtime, const std::string& name) { + auto input = evaluate(runtime, "({'" + name + "': {unsupported: true}})"); + expect(!JSIConverter::canConvert(runtime, input), "unsupported Unicode-keyed value must be rejected"); +} + +void checkBlob(const SQLiteConnectionPtr& connection, const SQLiteQueryBindings& bindings, const std::string& placeholder, double length) { + auto result = + sqliteExecute(connection, "SELECT typeof(" + placeholder + "), length(" + placeholder + "), " + placeholder + " IS NULL", bindings); + const auto& row = result.results.data->rows.at(0); + expectText(row.at(0), "blob", "ArrayBuffer must bind as BLOB, not NULL"); + expectNumber(row.at(1), length, "BLOB length must match the buffer size"); + expectNumber(row.at(2), 0, "BLOB must remain distinct from SQL NULL"); +} + +} // namespace + +int main() { + int failures = 0; + auto run = [&failures](const std::string& name, const std::function& test) { + try { + test(); + std::cout << "[PASS] " << name << '\n'; + } catch (const std::exception& error) { + failures++; + std::cerr << "[FAIL] " << name << ": " << error.what() << '\n'; + } + }; + + auto engine = jsc::makeJSCRuntime(); + auto runtime = std::make_unique(*engine); + DatabaseConnections connections; + connections.open("bindings", std::filesystem::temp_directory_path() / "named-bindings.sqlite", false); + auto connection = connections.get("bindings"); + const std::vector> names = { + {"ASCII", ":value"}, {"accented", ":caf\u00e9"}, {"supplementary", ":\U00010437"}, {"BOM", ":\ufeffvalue"}, {"NBSP", ":\u00a0value"}}; + for (const auto& [label, name] : names) { + run(label + " exact name and SQL value", [&] { checkUnicodeBinding(*runtime, connection, name); }); + run(label + " unsupported value", [&] { checkUnsupportedValue(*runtime, name); }); + } + + for (const size_t size : {0, 3}) { + auto buffer = ArrayBuffer::allocate(size); + std::fill_n(buffer->data(), size, 42); + run("native positional BLOB size " + std::to_string(size), [&] { checkBlob(connection, SQLiteQueryParams{buffer}, "?1", size); }); + run("native named BLOB size " + std::to_string(size), + [&] { checkBlob(connection, SQLiteNamedQueryParams{{":buffer", buffer}}, ":buffer", size); }); + } + // Moving an empty vector supplies a null data pointer on libc++, unlike allocate(0). + auto emptyVectorBuffer = ArrayBuffer::move(std::vector{}); + run("native moved empty positional BLOB", [&] { checkBlob(connection, SQLiteQueryParams{emptyVectorBuffer}, "?1", 0); }); + run("native moved empty named BLOB", + [&] { checkBlob(connection, SQLiteNamedQueryParams{{":buffer", emptyVectorBuffer}}, ":buffer", 0); }); + run("async positional empty buffer snapshot", [&] { + SQLiteQueryBindings params = SQLiteQueryParams{std::make_shared()}; + checkBlob(connection, copyArrayBufferParamsForBackground(std::move(params)), "?1", 0); + }); + run("async named empty buffer snapshot", [&] { + SQLiteQueryBindings params = SQLiteNamedQueryParams{{":buffer", std::make_shared()}}; + checkBlob(connection, copyArrayBufferParamsForBackground(std::move(params)), ":buffer", 0); + }); + run("JavaScript positional empty ArrayBuffer", [&] { + auto input = evaluate(*runtime, "[new ArrayBuffer(0)]"); + checkBlob(connection, JSIConverter::fromJSI(*runtime, input), "?1", 0); + }); + run("JavaScript named empty ArrayBuffer", [&] { + auto input = evaluate(*runtime, "({':buffer': new ArrayBuffer(0)})"); + checkBlob(connection, JSIConverter::fromJSI(*runtime, input), ":buffer", 0); + }); + run("explicit null remains SQL NULL", [&] { + auto input = evaluate(*runtime, "({':value': null})"); + auto result = + sqliteExecute(connection, "SELECT typeof(:value), :value IS NULL", JSIConverter::fromJSI(*runtime, input)); + const auto& row = result.results.data->rows.at(0); + expectText(row.at(0), "null", "explicit null must remain SQL NULL"); + expectNumber(row.at(1), 1, "SQL must recognize explicit null"); + }); + connections.close("bindings"); + return failures == 0 ? 0 : 1; +} diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index fc23abc59..47d57faaf 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -274,3 +274,14 @@ function enabled(checks: ReturnType): string[] { .filter(([, selected]) => selected) .map(([name]) => name) } + +test('native binding bridge regression inputs select macOS validation', () => { + for (const path of [ + 'scripts/test-bindings-jsi.py', + 'packages/react-native-nitro-sqlite/tests/cpp/namedBindings.test.cpp', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteNamedQueryParams.hpp', + 'bunfig.toml', + ]) { + assert.equal(selectChecks([path], false).macos, true, path) + } +}) diff --git a/scripts/test-bindings-jsi.py b/scripts/test-bindings-jsi.py new file mode 100644 index 000000000..fbde035ca --- /dev/null +++ b/scripts/test-bindings-jsi.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Run named-binding and empty-BLOB regressions with real Nitro, JSI, and SQLite.""" + +import argparse +import json +import os +import pathlib +import re +import subprocess +import sys +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--nitro-root", type=pathlib.Path, + help="Installed react-native-nitro-modules package to compile against") + parser.add_argument("--stock-nitro-converter", action="store_true", + help="Use Nitro's stock map converter to reproduce the Unicode failure") + args = parser.parse_args() + if sys.platform != "darwin": + parser.error("This test requires the macOS JavaScriptCore framework") + + root = pathlib.Path(__file__).resolve().parent.parent + nitro = (args.nitro_root or root / "node_modules/react-native-nitro-modules").resolve() + # Nitro 0.37 moved the platform-independent and Apple sources into core folders. + nitro_cpp = nitro / "cpp/core" if (nitro / "apple/core").is_dir() else nitro / "cpp" + nitro_apple = nitro / "apple/core" if (nitro / "apple/core").is_dir() else nitro / "ios" + react = root / "node_modules/react-native/ReactCommon" + package = root / "packages/react-native-nitro-sqlite" + cpp = package / "cpp" + generated = package / "nitrogen/generated/shared/c++" + version = json.loads((nitro / "package.json").read_text())["version"] + converter = "stock Nitro" if args.stock_nitro_converter else "SQLite named bindings" + print(f"Nitro {version}; {converter} converter; JavaScriptCore; bundled SQLite", flush=True) + + with tempfile.TemporaryDirectory(prefix="nitro-bindings-jsi-") as temporary: + build = pathlib.Path(temporary) + headers = build / "headers" + headers.mkdir() + public_headers = build / "NitroModules" + public_headers.mkdir() + podspec = (nitro / "NitroModules.podspec").read_text() + public_list = podspec.split("s.public_header_files = [", 1)[1].split("]", 1)[0] + for pattern in re.findall(r'"([^"\n]+)"', public_list): + for header in nitro.glob(pattern): + (public_headers / header.name).symlink_to(header.resolve()) + for tree in (nitro_cpp, nitro_apple): + for header in tree.rglob("*.hpp"): + target = headers / header.name + if not target.exists(): + target.symlink_to(header) + + sqlite = build / "sqlite.o" + subprocess.run([ + "clang", "-std=c11", "-DSQLITE_THREADSAFE=2", "-c", + str(cpp / "sqlite/sqlite3.c"), "-o", str(sqlite), + ], check=True) + sources = [cpp / name for name in ( + "NitroSQLiteDatabaseConnections.cpp", + "NitroSQLiteDatabaseMigration.cpp", + "NitroSQLiteOperations.cpp", + )] + sources.extend(( + react / "jsi/jsi/jsi.cpp", + react / "jsc/JSCRuntime.cpp", + nitro_apple / "platform/NitroLogger.cpp", + nitro_apple / "platform/ThreadUtils.cpp", + nitro_apple / "threading/UIThreadDispatcher.cpp", + )) + sources.extend( + source for source in nitro_cpp.rglob("*.cpp") + if source.name not in { + "InstallNitro.cpp", "HybridNitroModulesProxy.cpp", + "BoxedHybridObject.cpp", "HybridObjectRegistry.cpp", + } + ) + includes = (build, headers, cpp, cpp / "sqlite", generated, + react / "jsi", react, react / "jsc") + defines = ["-DNITRO_SQLITE_TEST_STOCK_CONVERTER"] if args.stock_nitro_converter else [] + compiler = ["clang++", "-std=c++20", "-DNDEBUG", "-fblocks", *defines, + *("-I" + str(path) for path in includes)] + if not args.stock_nitro_converter: + print("Checking generated root and prepared-statement bindings", flush=True) + subprocess.run([ + *compiler, "-fsyntax-only", + str(generated / "HybridNitroSQLiteSpec.cpp"), + str(generated / "HybridNitroSQLitePreparedStatementSpec.cpp"), + ], check=True) + executable = build / "named-bindings-test" + subprocess.run([ + *compiler, + *(str(source) for source in sources), + str(package / "tests/cpp/namedBindings.test.cpp"), str(sqlite), + "-framework", "JavaScriptCore", "-pthread", "-o", str(executable), + ], check=True) + result = subprocess.run([str(executable)], env={**os.environ, "TMPDIR": temporary}) + return result.returncode + + +if __name__ == "__main__": + sys.exit(main())