diff --git a/.github/ci-paths.json b/.github/ci-paths.json index abc96865..cc80e566 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -51,12 +51,12 @@ ".github/actions/**", ".github/ci-paths.json", "scripts/ci*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp", + "packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteOperations.*", + "packages/react-native-nitro-sqlite/cpp/SQLiteStatementGroup.hpp", + "packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3.*", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3-symbol-prefix.h", "packages/react-native-nitro-sqlite-vec/cpp/**", diff --git a/docs/content/docs/guides/attach-databases.mdx b/docs/content/docs/guides/attach-databases.mdx index 67824835..841103ed 100644 --- a/docs/content/docs/guides/attach-databases.mdx +++ b/docs/content/docs/guides/attach-databases.mdx @@ -28,6 +28,6 @@ db.close() ## File paths and aliases -The example assumes the tables and files already exist. SQLite can create the attached file when it is missing, so verify the intended path when opening prepopulated data. `attach()` and `detach()` are synchronous connection operations; they fail while the connection queue is busy. A failed attach or detach throws `NitroSQLiteError` through the connection wrapper. +The example assumes the tables and files already exist. SQLite can create the attached file when it is missing, so verify the intended path when opening prepopulated data. `attach()` and `detach()` are synchronous connection operations; they fail while the connection queue is busy. A failed attach or detach throws `SQLiteError` through the connection wrapper. -Only pass database names, locations, and aliases you control. The library does not bind these as parameters. Query values still belong in `?` parameters. See [database lifecycle](/docs/guides/database-lifecycle) for the location convention and the generated [`NitroSQLiteConnection` reference](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteConnection) for signatures. +Only pass database names, locations, and aliases you control. The library does not bind these as parameters. Query values still belong in `?` parameters. See [database lifecycle](/docs/guides/database-lifecycle) for the location convention and the generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) for signatures. diff --git a/docs/content/docs/guides/database-lifecycle.mdx b/docs/content/docs/guides/database-lifecycle.mdx index 585651e6..837ee6c4 100644 --- a/docs/content/docs/guides/database-lifecycle.mdx +++ b/docs/content/docs/guides/database-lifecycle.mdx @@ -47,7 +47,7 @@ Only pass database names and locations you control. The library does not validat To open a prepopulated database, copy the SQLite file into the intended app directory before calling `open()`. Use the same `name` and `location` when you open it. A missing file creates a new, empty database, so verify the copy if your schema must already exist. See [file lifetimes](/docs/concepts/databases-and-connections#file-lifetimes) for WAL companion files. -The platform pages describe the database roots and storage settings for [iOS](/docs/configuration/ios#database-location), [Android](/docs/configuration/android#database-location), and [macOS](/docs/configuration/macos). The generated [`NitroSQLiteConnection` reference](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteConnection) lists the lifecycle methods. +The platform pages describe the database roots and storage settings for [iOS](/docs/configuration/ios#database-location), [Android](/docs/configuration/android#database-location), and [macOS](/docs/configuration/macos). The generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) lists the lifecycle methods. ## Runtime teardown diff --git a/docs/content/docs/guides/encryption.mdx b/docs/content/docs/guides/encryption.mdx index d2a55edd..f411b615 100644 --- a/docs/content/docs/guides/encryption.mdx +++ b/docs/content/docs/guides/encryption.mdx @@ -61,17 +61,17 @@ export function openPrivateDatabase(encryptionKey: string) { Use a new database name when adding encryption to an app. Passing a key to an existing plaintext database fails; it does not encrypt that file. To migrate, open the old file without a key, create a separate keyed database, copy the data, and verify the new file before removing the old one. See [database lifecycle](/docs/guides/database-lifecycle) for file and connection cleanup. -The [`open()` reference](/api/react-native-nitro-sqlite/functions/open) documents the managed call, and [`NitroSQLiteConnectionOptions`](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteConnectionOptions) lists its options. Raw native callers can pass the key as the fourth argument to [`NitroSQLiteNative.open()`](/api/react-native-nitro-sqlite/hybrid-objects/NitroSQLiteNative) or `openConnection()`, after `readOnly`. The [TypeORM integration](/docs/integrations/typeorm#encrypt-a-typeorm-database) passes the key through `extra`. +The [`open()` reference](/api/react-native-nitro-sqlite/functions/open) documents the managed call, and [`ConnectionOptions`](/api/react-native-nitro-sqlite/interfaces/ConnectionOptions) lists its options. Raw native callers can pass the key as the fourth argument to [`NativeSQLite.open()`](/api/react-native-nitro-sqlite/hybrid-objects/NativeSQLite) or `openConnection()`, after `readOnly`. The [TypeORM integration](/docs/integrations/typeorm#encrypt-a-typeorm-database) passes the key through `extra`. ## Handle open failures -Managed `open()` throws `NitroSQLiteError`. Check its `type` when you need to tell a missing SEE build from a bad key: +Managed `open()` throws `SQLiteError`. Check its `type` when you need to tell a missing SEE build from a bad key: | `error.type` | Cause | What to do | | --------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `EncryptionNotEnabled` | You supplied a key, but the native build does not include SEE. | Check the source replacement and compile flag, then rebuild the app. | | `DatabaseCannotBeDecrypted` | The key is empty or contains a NUL byte, the file is plaintext, or SEE cannot read it with that key. | Check the key and file. Migrate a plaintext database before opening it with a key. | -A keyed open checks the database header and reads its schema before returning, so these failures surface during `open()`. Omitting the key keeps the usual unencrypted open path; an encrypted file then fails when SQLite first tries to read it. Calls through `NitroSQLite.native` throw raw native errors rather than `NitroSQLiteError`. +A keyed open checks the database header and reads its schema before returning, so these failures surface during `open()`. Omitting the key keeps the usual unencrypted open path; an encrypted file then fails when SQLite first tries to read it. Calls through `NitroSQLite.native` throw raw native errors rather than `SQLiteError`. SEE does not encrypt TEMP tables or in-memory databases. Keep sensitive data in the keyed database file rather than those locations. A keyed open adds a header read and schema query; query and write costs depend on the SEE algorithm you choose. Measure those costs on your target devices. See [SQLite's SEE documentation](https://www.sqlite.org/see/doc/trunk/www/readme.wiki) for its encryption variants and limits. diff --git a/docs/content/docs/guides/load-sql-file.mdx b/docs/content/docs/guides/load-sql-file.mdx index 4930859a..42837072 100644 --- a/docs/content/docs/guides/load-sql-file.mdx +++ b/docs/content/docs/guides/load-sql-file.mdx @@ -30,6 +30,6 @@ The loader counts executed lines in `commands` and adds their affected row count SQLite can reject a statement or fail to commit the import. NitroSQLite attempts one rollback after a failed import transaction, preserving the source path and the original SQL error. Statement failures also include the one-based file line and failing command. A failed BEGIN does not trigger rollback of an existing transaction. If rollback itself fails, its error is appended to the original import error. -The managed methods throw or reject with `NitroSQLiteError` and native category `CouldNotLoadFile`. After a successful rollback, completed statements from the file are discarded and the connection can be used again. The error includes the failing SQL text, so avoid including sensitive literal values in files whose errors may be logged. +The managed methods throw or reject with `SQLiteError` and native category `CouldNotLoadFile`. After a successful rollback, completed statements from the file are discarded and the connection can be used again. The error includes the failing SQL text, so avoid including sensitive literal values in files whose errors may be logged. Both methods return a [`FileLoadResult`](/api/react-native-nitro-sqlite/interfaces/FileLoadResult) with optional `commands` and `rowsAffected` numbers. diff --git a/docs/content/docs/guides/meta.json b/docs/content/docs/guides/meta.json index bd57f350..4d03210f 100644 --- a/docs/content/docs/guides/meta.json +++ b/docs/content/docs/guides/meta.json @@ -13,6 +13,7 @@ "attach-databases", "load-sql-file", "performance", + "migrate-to-nitro-v1", "migrate-from-quick-sqlite", "ai-agents" ] diff --git a/docs/content/docs/guides/migrate-to-nitro-v1.mdx b/docs/content/docs/guides/migrate-to-nitro-v1.mdx new file mode 100644 index 00000000..6e1dd0e0 --- /dev/null +++ b/docs/content/docs/guides/migrate-to-nitro-v1.mdx @@ -0,0 +1,51 @@ +--- +title: Migrate to Nitro V1 +description: Update type imports for the Nitro V1 migration. +--- + +A SQLite connection owns a database handle. A prepared statement belongs to that connection, and a query result contains the rows and metadata returned by a statement. Nitro SQLite uses shorter names for these types with Nitro V1. + +Update your type imports using the table below. The old names remain available as deprecated aliases. + +| Previous name | Replacement | +| -------------------------------- | ------------------------- | +| `NitroSQLiteConnection` | `Connection` | +| `NitroSQLiteConnectionOptions` | `ConnectionOptions` | +| `NitroSQLiteQueryResultRows` | `QueryResultRows` | +| `NitroSQLiteQueryColumnMetadata` | `QueryColumnMetadata` | +| `NitroSQLiteQueryResult` | `NativeQueryResult` | +| `NitroSQLiteQueryRows` | `NativeQueryRows` | +| `NitroSQLitePreparedStatement` | `NativePreparedStatement` | +| `NitroSQLiteNative` | `NativeSQLite` | +| `NitroSQLiteError` | `SQLiteError` | +| `NitroSQLiteExceptionType` | `SQLiteExceptionType` | +| `TypeOrmNitroSQLiteConnection` | `TypeOrmConnection` | + +`NativeQueryResult`, `NativePreparedStatement`, and `NativeSQLite` describe values exposed through `NitroSQLite.native`. The managed API keeps its `QueryResult` and `PreparedStatement` names. + +```ts +import { open, SQLiteError } from 'react-native-nitro-sqlite' +import type { ConnectionOptions } from 'react-native-nitro-sqlite' + +const options: ConnectionOptions = { name: 'app.sqlite' } +const db = open(options) + +try { + const { results } = db.execute('SELECT sqlite_version() AS version') + console.log(results[0]?.version) +} catch (error) { + if (error instanceof SQLiteError) { + console.error(error.type, error.message) + } else { + throw error + } +} finally { + db.close() +} +``` + +`SQLiteError` and `NitroSQLiteError` refer to the same constructor, and both exception-category exports refer to the same object. The error's `name` remains `NitroSQLiteError`. + +If your native code includes helper headers, replace their `NitroSQLite` filename prefix with `SQLite`, for example `NitroSQLiteOperations.hpp` becomes `SQLiteOperations.hpp`. The package name, `NitroSQLite` entry point, and native module names stay the same. + +See [Getting Started](/docs) for Nitro V1's platform requirements and Swift Package Manager setup. diff --git a/docs/content/docs/guides/parameters-and-results.mdx b/docs/content/docs/guides/parameters-and-results.mdx index 9bf62830..29460318 100644 --- a/docs/content/docs/guides/parameters-and-results.mdx +++ b/docs/content/docs/guides/parameters-and-results.mdx @@ -33,7 +33,7 @@ SQLite INTEGER and REAL result values both arrive as JavaScript numbers. BLOB va ## Column metadata -For a query with result columns, `metadata` maps column names to `{ name, type, index }`. `index` is the zero-based result column position. The [`ColumnType` values](/api/react-native-nitro-sqlite/enumerations/ColumnType) are `BOOLEAN = 0`, `NUMBER = 1`, `INT64 = 2`, `TEXT = 3`, `ARRAY_BUFFER = 4`, and `NULL_VALUE = 5`. The package exports `ColumnType` as a TypeScript type, not a runtime enum object. In the current native implementation, `metadata.type` is unreliable for detecting a column's declared SQL type. Use your schema for that decision. An expression without a declared type maps to `NULL_VALUE`, which does not mean the result itself is null. The exact shape is in [`NitroSQLiteQueryColumnMetadata`](/api/react-native-nitro-sqlite/type-aliases/NitroSQLiteQueryColumnMetadata). +For a query with result columns, `metadata` maps column names to `{ name, type, index }`. `index` is the zero-based result column position. The [`ColumnType` values](/api/react-native-nitro-sqlite/enumerations/ColumnType) are `BOOLEAN = 0`, `NUMBER = 1`, `INT64 = 2`, `TEXT = 3`, `ARRAY_BUFFER = 4`, and `NULL_VALUE = 5`. The package exports `ColumnType` as a TypeScript type, not a runtime enum object. In the current native implementation, `metadata.type` is unreliable for detecting a column's declared SQL type. Use your schema for that decision. An expression without a declared type maps to `NULL_VALUE`, which does not mean the result itself is null. The exact shape is in [`QueryColumnMetadata`](/api/react-native-nitro-sqlite/type-aliases/QueryColumnMetadata). ```ts const result = db.execute('SELECT name FROM people LIMIT 1') @@ -48,20 +48,20 @@ Be especially careful with nullable columns and expressions when specifying a ro ## Errors -The connection's JavaScript helpers normalize database failures to `NitroSQLiteError`. Async methods reject; sync methods throw. An empty SQL string or one containing only comments also fails with the native category `SqlExecutionError`, because SQLite produces no statement to execute. Each query runs one statement, so SQL that contains another statement after the first fails with the same category instead of running only the first one; trailing whitespace, comments, and semicolons are allowed. Use [batch operations](/docs/guides/batch-operations) to run several statements. Catch the error around the operation you can recover from: +The connection's JavaScript helpers normalize database failures to `SQLiteError`. Async methods reject; sync methods throw. An empty SQL string or one containing only comments also fails with the native category `SqlExecutionError`, because SQLite produces no statement to execute. Each query runs one statement, so SQL that contains another statement after the first fails with the same category instead of running only the first one; trailing whitespace, comments, and semicolons are allowed. Use [batch operations](/docs/guides/batch-operations) to run several statements. Catch the error around the operation you can recover from: ```ts import { - NitroSQLiteError, - NitroSQLiteExceptionType, + SQLiteError, + SQLiteExceptionType, } from 'react-native-nitro-sqlite/errors' try { await db.executeAsync('SELECT * FROM missing_table') } catch (error) { if ( - error instanceof NitroSQLiteError && - error.type === NitroSQLiteExceptionType.SqlExecutionError + error instanceof SQLiteError && + error.type === SQLiteExceptionType.SqlExecutionError ) { console.error(error.message) } else { @@ -70,12 +70,12 @@ try { } ``` -[`NitroSQLiteError`](/api/react-native-nitro-sqlite/classes/NitroSQLiteError) extends `Error`. `NitroSQLiteError.fromError(error)` returns an existing instance unchanged, copies an `Error`'s message, cause, and stack, or uses a string as its message. For other values, it sets the message to `'Unknown error occurred'` and keeps the original value as `cause`. +[`SQLiteError`](/api/react-native-nitro-sqlite/classes/SQLiteError) extends `Error`. `SQLiteError.fromError(error)` returns an existing instance unchanged, copies an `Error`'s message, cause, and stack, or uses a string as its message. For other values, it sets the message to `'Unknown error occurred'` and keeps the original value as `cause`. -When a native `NitroSQLiteException` reaches a managed helper, `error.type` holds a [`NitroSQLiteExceptionType`](/api/react-native-nitro-sqlite/type-aliases/NitroSQLiteExceptionType) such as `SqlExecutionError`. It is `undefined` for JavaScript errors, including connection queue errors, and unrecognized native categories. These categories are not SQLite's numeric error codes. The native categories are `UnknownError`, `DatabaseCannotBeOpened`, `EncryptionNotEnabled`, `DatabaseCannotBeDecrypted`, `DatabaseNotOpen`, `UnableToAttachToDatabase`, `SqlExecutionError`, `CouldNotLoadFile`, and `NoBatchCommandsProvided`. See [encrypt a database](/docs/guides/encryption#handle-open-failures) for the encryption errors. The current native `DatabaseNotOpen` helper emits `UnableToAttachToDatabase`, and a missing database file emits `SqlExecutionError`. Calls through `NitroSQLite.native` throw raw native errors. +When a native `NitroSQLiteException` reaches a managed helper, `error.type` holds a [`SQLiteExceptionType`](/api/react-native-nitro-sqlite/type-aliases/SQLiteExceptionType) such as `SqlExecutionError`. It is `undefined` for JavaScript errors, including connection queue errors, and unrecognized native categories. These categories are not SQLite's numeric error codes. The native categories are `UnknownError`, `DatabaseCannotBeOpened`, `EncryptionNotEnabled`, `DatabaseCannotBeDecrypted`, `DatabaseNotOpen`, `UnableToAttachToDatabase`, `SqlExecutionError`, `CouldNotLoadFile`, and `NoBatchCommandsProvided`. See [encrypt a database](/docs/guides/encryption#handle-open-failures) for the encryption errors. The current native `DatabaseNotOpen` helper emits `UnableToAttachToDatabase`, and a missing database file emits `SqlExecutionError`. Calls through `NitroSQLite.native` throw raw native errors. -The [`NitroSQLiteExceptionType` constants](/api/react-native-nitro-sqlite/variables/NitroSQLiteExceptionType) expose these categories as runtime strings. The object and the TypeScript union share the same name, so existing type-only imports still work. Both the constants and `NitroSQLiteError` are available from the package root and `react-native-nitro-sqlite/errors`. The `/errors` entry point does not import React Native or initialize Nitro's native module, so shared classifiers and Node tests can use it without a native runtime. `error.name` remains `NitroSQLiteError` for every managed failure; use `error.type` to distinguish categories. +The [`SQLiteExceptionType` constants](/api/react-native-nitro-sqlite/variables/SQLiteExceptionType) expose these categories as runtime strings. The object and the TypeScript union share the same name, so existing type-only imports still work. Both the constants and `SQLiteError` are available from the package root and `react-native-nitro-sqlite/errors`. The `/errors` entry point does not import React Native or initialize Nitro's native module, so shared classifiers and Node tests can use it without a native runtime. `error.name` remains `NitroSQLiteError` for every managed failure; use `error.type` to distinguish categories. `DatabaseCannotBeOpened` covers several causes, including invalid paths, an already-open default connection, and filesystem failures. It does not by itself establish that the device is low on storage. -For exact types, see [`QueryResult`](/api/react-native-nitro-sqlite/type-aliases/QueryResult), [`NitroSQLiteQueryResult`](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteQueryResult), and [`NitroSQLiteQueryResultRows`](/api/react-native-nitro-sqlite/type-aliases/NitroSQLiteQueryResultRows). The row generic narrows `rows._array` and `rows.item()`, but not the raw `results` array. Query results are plain JavaScript objects; see [native access](/docs/guides/sync-and-async#global-helpers-and-native-access) for results returned without the connection helper. +For exact types, see [`QueryResult`](/api/react-native-nitro-sqlite/type-aliases/QueryResult), [`NativeQueryResult`](/api/react-native-nitro-sqlite/interfaces/NativeQueryResult), and [`QueryResultRows`](/api/react-native-nitro-sqlite/type-aliases/QueryResultRows). The row generic narrows `rows._array` and `rows.item()`, but not the raw `results` array. Query results are plain JavaScript objects; see [native access](/docs/guides/sync-and-async#global-helpers-and-native-access) for results returned without the connection helper. diff --git a/docs/content/docs/guides/sync-and-async.mdx b/docs/content/docs/guides/sync-and-async.mdx index c58a627d..1af38107 100644 --- a/docs/content/docs/guides/sync-and-async.mdx +++ b/docs/content/docs/guides/sync-and-async.mdx @@ -47,7 +47,7 @@ See [prepared statements](/docs/guides/prepared-statements#connection-ordering-a The [`NitroSQLite` export](/api/react-native-nitro-sqlite/variables/NitroSQLite) also has `execute`, `executeAsync`, `prepare`, `executeBatch`, `executeBatchAsync`, and `transaction` helpers that take a database name. `NitroSQLite.open(options)` is the same helper as the named [`open()` export](/api/react-native-nitro-sqlite/functions/open). Global queries join the default connection's JavaScript queue when the name was opened through `open()`. They do not address independent connections; use the object returned by `open()` for those. Without a default managed connection, global `execute` and `executeAsync` call the native methods directly and still need an open native database handle. Global `prepare`, batches, and transactions need a default connection opened through `open()`. -`NitroSQLite.native` exposes the underlying [`NitroSQLiteNative` hybrid object](/api/react-native-nitro-sqlite/hybrid-objects/NitroSQLiteNative). Its methods take a database name and return raw results without the connection helper's `rows` container. They also throw native errors without converting them to `NitroSQLiteError`. Its `executeAsync()` accepts an optional `onRows` callback that receives leading rows in batches, in order; the resolved `results` then holds only the rows after the last batch. +`NitroSQLite.native` exposes the underlying [`NativeSQLite` hybrid object](/api/react-native-nitro-sqlite/hybrid-objects/NativeSQLite). Its methods take a database name and return raw results without the connection helper's `rows` container. They also throw native errors without converting them to `SQLiteError`. Its `executeAsync()` accepts an optional `onRows` callback that receives leading rows in batches, in order; the resolved `results` then holds only the rows after the last batch. The native promise can resolve before those callbacks run. Its `rowBatchCount` reports how many batches to expect. Wait for all of them before appending `results` to the collected rows. Without `onRows`, the count is zero and `results` contains every row. The managed `executeAsync()` API handles this waiting and assembly for you. diff --git a/docs/content/docs/integrations/typeorm.mdx b/docs/content/docs/integrations/typeorm.mdx index 1e572e32..31928310 100644 --- a/docs/content/docs/integrations/typeorm.mdx +++ b/docs/content/docs/integrations/typeorm.mdx @@ -74,17 +74,17 @@ This small example uses `synchronize: true` to create the table. Choose your app ## Driver export -`typeORMDriver` has one public method, `openDatabase(options, ok, fail)`. The connection passed to `ok` and returned on success has the exported [`TypeOrmNitroSQLiteConnection`](/api/react-native-nitro-sqlite/interfaces/TypeOrmNitroSQLiteConnection) type. The `TypeORMDriver` alias below is used only on this page. +`typeORMDriver` has one public method, `openDatabase(options, ok, fail)`. The connection passed to `ok` and returned on success has the exported [`TypeOrmConnection`](/api/react-native-nitro-sqlite/interfaces/TypeOrmConnection) type. The `TypeORMDriver` alias below is used only on this page. ```ts -import type { TypeOrmNitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { TypeOrmConnection } from 'react-native-nitro-sqlite' type TypeORMDriver = { openDatabase( options: { name: string; location?: string; encryptionKey?: string }, - ok: (connection: TypeOrmNitroSQLiteConnection) => void, + ok: (connection: TypeOrmConnection) => void, fail: (message: string) => void, - ): TypeOrmNitroSQLiteConnection | null + ): TypeOrmConnection | null } ``` diff --git a/docs/content/docs/integrations/vector-search.mdx b/docs/content/docs/integrations/vector-search.mdx index e20aeb7c..9718d83d 100644 --- a/docs/content/docs/integrations/vector-search.mdx +++ b/docs/content/docs/integrations/vector-search.mdx @@ -41,14 +41,14 @@ db.close() `vecVersion(db)` calls `vec_version()` and returns its version string. `isVecAvailable(db)` returns `false` if that call fails. `createVectorTable(db, table, options)` creates a `vec0` virtual table if it does not exist. `knnSearch(db, table, query, k, options?)` returns an array of `{ rowid, distance }` matches, ordered by distance; `query` can be a numeric array or a JSON vector string. -All four helpers are synchronous and take an open `NitroSQLiteConnection`: +All four helpers are synchronous and take an open `Connection`: -| Export | Signature | -| ------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -| `vecVersion` | `(db: NitroSQLiteConnection) => string` | -| `isVecAvailable` | `(db: NitroSQLiteConnection) => boolean` | -| `createVectorTable` | `(db: NitroSQLiteConnection, table: string, options: CreateVectorTableOptions) => void` | -| `knnSearch` | `(db: NitroSQLiteConnection, table: string, query: string \| number[], k: number, options?: KnnSearchOptions) => KnnMatch[]` | +| Export | Signature | +| ------------------- | ----------------------------------------------------------------------------------------------------------------- | +| `vecVersion` | `(db: Connection) => string` | +| `isVecAvailable` | `(db: Connection) => boolean` | +| `createVectorTable` | `(db: Connection, table: string, options: CreateVectorTableOptions) => void` | +| `knnSearch` | `(db: Connection, table: string, query: string \| number[], k: number, options?: KnnSearchOptions) => KnnMatch[]` | `isVecAvailable()` catches any error from `vecVersion()`, so `false` means its availability query failed, not necessarily that the build flag is absent. The other helpers let query errors propagate from `db.execute()`. @@ -56,4 +56,4 @@ All four helpers are synchronous and take an open `NitroSQLiteConnection`: The package's five named type exports are `VectorColumnType`, `VectorDistanceMetric`, `CreateVectorTableOptions`, `KnnSearchOptions`, and `KnnMatch`. `KnnMatch` has `rowid: number`, `distance: number`, and a `[column: string]: unknown` index signature. The current `knnSearch()` helper selects only `rowid` and `distance`; write SQL through the core connection when you need more columns. -The helpers interpolate table and column identifiers into SQL. Only pass identifiers you control. They bind the query vector and `k` as parameters. The core [connection query methods](/api/react-native-nitro-sqlite/interfaces/NitroSQLiteConnection) can also run sqlite-vec SQL directly for features these small helpers do not wrap. +The helpers interpolate table and column identifiers into SQL. Only pass identifiers you control. They bind the query vector and `k` as parameters. The core [connection query methods](/api/react-native-nitro-sqlite/interfaces/Connection) can also run sqlite-vec SQL directly for features these small helpers do not wrap. diff --git a/docs/next.config.mjs b/docs/next.config.mjs index 0d27654e..16e6bdd9 100644 --- a/docs/next.config.mjs +++ b/docs/next.config.mjs @@ -52,16 +52,52 @@ const config = { { source: '/api/react-native-nitro-sqlite/interfaces/NitroSQLiteNative', destination: - '/api/react-native-nitro-sqlite/hybrid-objects/NitroSQLiteNative', + '/api/react-native-nitro-sqlite/hybrid-objects/NativeSQLite', permanent: true, }, { source: '/api/react-native-nitro-sqlite/hybrid-objects/NitroSQLiteQueryResult', destination: - '/api/react-native-nitro-sqlite/interfaces/NitroSQLiteQueryResult', + '/api/react-native-nitro-sqlite/interfaces/NativeQueryResult', permanent: true, }, + ...[ + ['interfaces/NitroSQLiteConnection', 'interfaces/Connection'], + [ + 'interfaces/NitroSQLiteConnectionOptions', + 'interfaces/ConnectionOptions', + ], + ['classes/NitroSQLiteError', 'classes/SQLiteError'], + ['hybrid-objects/NitroSQLiteNative', 'hybrid-objects/NativeSQLite'], + [ + 'hybrid-objects/NitroSQLitePreparedStatement', + 'hybrid-objects/NativePreparedStatement', + ], + ['interfaces/NitroSQLiteQueryResult', 'interfaces/NativeQueryResult'], + [ + 'interfaces/TypeOrmNitroSQLiteConnection', + 'interfaces/TypeOrmConnection', + ], + [ + 'type-aliases/NitroSQLiteQueryColumnMetadata', + 'type-aliases/QueryColumnMetadata', + ], + [ + 'type-aliases/NitroSQLiteQueryResultRows', + 'type-aliases/QueryResultRows', + ], + ['type-aliases/NitroSQLiteQueryRows', 'type-aliases/NativeQueryRows'], + ['variables/NitroSQLiteExceptionType', 'variables/SQLiteExceptionType'], + [ + 'type-aliases/NitroSQLiteExceptionType', + 'type-aliases/SQLiteExceptionType', + ], + ].map(([source, destination]) => ({ + source: `/api/react-native-nitro-sqlite/${source}`, + destination: `/api/react-native-nitro-sqlite/${destination}`, + permanent: true, + })), ] }, } diff --git a/docs/scripts/check-api.mjs b/docs/scripts/check-api.mjs index c1ad4a4f..3df8bea5 100644 --- a/docs/scripts/check-api.mjs +++ b/docs/scripts/check-api.mjs @@ -8,22 +8,40 @@ const api = JSON.parse( ), ) +const deprecatedExports = [ + 'NitroSQLiteConnection', + 'NitroSQLiteConnectionOptions', + 'NitroSQLiteQueryResultRows', + 'NitroSQLiteQueryColumnMetadata', + 'NitroSQLiteQueryResult', + 'NitroSQLiteQueryRows', + 'NitroSQLitePreparedStatement', + 'NitroSQLiteNative', + 'NitroSQLiteError', + 'NitroSQLiteExceptionType', + 'TypeOrmNitroSQLiteConnection', +] + const requiredExports = { 'react-native-nitro-sqlite': [ 'open', 'NitroSQLite', - 'NitroSQLiteConnection', - 'NitroSQLiteConnectionOptions', + 'Connection', + 'ConnectionOptions', 'QueryResult', 'Transaction', 'BatchQueryCommand', - 'NitroSQLiteError', - 'NitroSQLiteExceptionType', - 'NitroSQLiteNative', - 'NitroSQLiteQueryResult', - 'NitroSQLiteQueryColumnMetadata', - 'TypeOrmNitroSQLiteConnection', + 'SQLiteError', + 'SQLiteExceptionType', + 'NativeSQLite', + 'NativePreparedStatement', + 'NativeQueryResult', + 'NativeQueryRows', + 'QueryResultRows', + 'QueryColumnMetadata', + 'TypeOrmConnection', 'typeORMDriver', + ...deprecatedExports, ], 'react-native-nitro-sqlite/mock': [ 'open', @@ -69,7 +87,7 @@ const requiredMembers = { 'executeBatch', 'executeBatchAsync', ], - NitroSQLiteConnection: [ + Connection: [ 'close', 'delete', 'attach', @@ -82,10 +100,10 @@ const requiredMembers = { 'loadFile', 'loadFileAsync', ], - NitroSQLiteConnectionOptions: ['encryptionKey'], + ConnectionOptions: ['encryptionKey'], Transaction: ['commit', 'rollback', 'execute', 'executeAsync'], - NitroSQLiteError: ['type', 'fromError'], - NitroSQLiteNative: [ + SQLiteError: ['type', 'fromError'], + NativeSQLite: [ 'open', 'openConnection', 'close', @@ -99,9 +117,9 @@ const requiredMembers = { 'loadFile', 'loadFileAsync', ], - NitroSQLiteQueryResult: ['rowsAffected', 'insertId', 'results', 'metadata'], - NitroSQLiteQueryColumnMetadata: ['name', 'type', 'index'], - TypeOrmNitroSQLiteConnection: [ + NativeQueryResult: ['rowsAffected', 'insertId', 'results', 'metadata'], + QueryColumnMetadata: ['name', 'type', 'index'], + TypeOrmConnection: [ 'executeSql', 'transaction', 'close', @@ -228,12 +246,55 @@ const corePackageHome = readFileSync( new URL('react-native-nitro-sqlite/index.mdx', output), 'utf8', ) +const corePackage = api.children.find( + (child) => child.name === 'react-native-nitro-sqlite', +) +for (const name of deprecatedExports) { + const alias = corePackage.children.find((child) => child.name === name) + const deprecated = alias.comment?.blockTags?.find( + (tag) => tag.tag === '@deprecated', + ) + assert.ok(deprecated, `Missing deprecation comment: ${name}`) + const target = corePackage.children.find((child) => child.id === alias.target) + assert.ok(target, `Missing reference target: ${name}`) + // A canonical type and value can have separate reflection IDs with the same name. + const canonicalExports = corePackage.children.filter( + (child) => child.name === target.name, + ) + assert.ok( + deprecated.content.some((part) => + canonicalExports.some((child) => child.id === part.target), + ), + `Missing canonical replacement link: ${name}`, + ) + for (const canonical of canonicalExports) { + assert.ok( + !canonical.comment?.blockTags?.some((tag) => tag.tag === '@deprecated'), + `Canonical export is deprecated: ${canonical.name}`, + ) + } + const section = corePackageHome + .split(`### ~~${name}~~\n`)[1] + ?.split(/\n(?:#{1,3} |\*\*\*)/)[0] + assert.ok(section, `Missing reference section: ${name}`) + assert.match( + section, + /\*\*Deprecated\*\*/, + `Missing rendered deprecation: ${name}`, + ) + assert.ok( + section.includes( + `Use [\`${target.name}\`](/api/react-native-nitro-sqlite/`, + ), + `Missing rendered replacement link: ${name}`, + ) +} assert.ok( corePackageHome.indexOf('## Hybrid Objects') < corePackageHome.indexOf('## Classes'), 'Hybrid Objects must appear before other API groups', ) -for (const name of ['NitroSQLiteNative']) { +for (const name of ['NativeSQLite']) { assert.ok( pagePaths.has(`react-native-nitro-sqlite/hybrid-objects/${name}.mdx`), `Missing Hybrid Object page: ${name}`, diff --git a/docs/typedoc-fumadocs.mjs b/docs/typedoc-fumadocs.mjs index 6fa13dd9..15e01990 100644 --- a/docs/typedoc-fumadocs.mjs +++ b/docs/typedoc-fumadocs.mjs @@ -2,9 +2,12 @@ import { execFileSync } from 'node:child_process' import { existsSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath } from 'node:url' +import ts from 'typescript' +import { Application, Converter } from 'typedoc' import { MarkdownPageEvent, MarkdownRendererEvent, + MarkdownTheme, MemberRouter, } from 'typedoc-plugin-markdown' import { addPackageIntro } from './api-package-intros.mjs' @@ -18,6 +21,31 @@ const gitRevision = export function load(app) { app.renderer.defineRouter('nitro-member', NitroMemberRouter) + app.renderer.defineTheme('nitro-markdown', NitroMarkdownTheme) + app.on(Application.EVENT_BOOTSTRAP_END, () => { + app.options.setValue('theme', 'nitro-markdown') + }) + + app.converter.on( + Converter.EVENT_CREATE_DECLARATION, + (context, reflection) => { + if (!reflection.isReference() || reflection.comment) return + + // Follow barrel re-exports without inheriting the canonical declaration's docs. + let symbol = context.getSymbolFromReflection(reflection) + while (symbol?.flags & ts.SymbolFlags.Alias) { + for (const declaration of symbol.declarations ?? []) { + const comment = context.getNodeComment(declaration, false) + if (comment) { + reflection.comment = comment + return + } + } + symbol = context.checker.getImmediateAliasedSymbol(symbol) + } + }, + 100, // Recover comments before TypeDoc processes their tags. + ) app.renderer.on(MarkdownPageEvent.BEGIN, (page) => { page.frontmatter = { ...page.frontmatter, title: page.model.name } @@ -51,23 +79,26 @@ export function load(app) { const withSourceLinks = addMissingSourceLinks(page, withSignatures) const withDefinitionSection = addDefinitionSection(withSourceLinks) - page.contents = withDefinitionSection.replace(/\]\(([^)]+)\)/g, (link, href) => { - if ( - href.startsWith('#') || - href.startsWith('/') || - /^[a-z][a-z\d+.-]*:/i.test(href) - ) { - return link - } + page.contents = withDefinitionSection.replace( + /\]\(([^)]+)\)/g, + (link, href) => { + if ( + href.startsWith('#') || + href.startsWith('/') || + /^[a-z][a-z\d+.-]*:/i.test(href) + ) { + return link + } - const url = new URL(href, `https://docs.example/api/${page.url}`) - const pathname = url.pathname - .replace(/\/index\.mdx$/, '') - .replace(/\.mdx$/, '') - .replace(/\/$/, '') + const url = new URL(href, `https://docs.example/api/${page.url}`) + const pathname = url.pathname + .replace(/\/index\.mdx$/, '') + .replace(/\.mdx$/, '') + .replace(/\/$/, '') - return `](${pathname || '/api'}${url.search}${url.hash})` - }) + return `](${pathname || '/api'}${url.search}${url.hash})` + }, + ) }) app.renderer.on(MarkdownRendererEvent.END, (event) => { @@ -107,6 +138,20 @@ export function load(app) { }) } +class NitroMarkdownTheme extends MarkdownTheme { + getRenderContext(page) { + const context = super.getRenderContext(page) + const referenceMember = context.partials.referenceMember + context.partials.referenceMember = (model) => { + const contents = referenceMember(model) + return model.comment + ? `${contents}\n\n${context.partials.comment(model.comment)}` + : contents + } + return context + } +} + class NitroMemberRouter extends MemberRouter { getReflectionDirectory(reflection) { const directory = super.getReflectionDirectory(reflection) diff --git a/example/src/benchmarks/database.ts b/example/src/benchmarks/database.ts index 46e1e547..3051660d 100644 --- a/example/src/benchmarks/database.ts +++ b/example/src/benchmarks/database.ts @@ -1,9 +1,9 @@ -import { open, type NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import { open, type Connection } from 'react-native-nitro-sqlite' export function createBenchmarkDatabase( name: string, schema: string, -): NitroSQLiteConnection { +): Connection { const db = open({ name }) try { db.execute('DROP TABLE IF EXISTS Bench') @@ -15,7 +15,7 @@ export function createBenchmarkDatabase( } } -export function disposeBenchmarkDatabase(db: NitroSQLiteConnection): void { +export function disposeBenchmarkDatabase(db: Connection): void { db.close() db.delete() } diff --git a/example/src/benchmarks/mixedCase.ts b/example/src/benchmarks/mixedCase.ts index 5a62109f..8bb37e30 100644 --- a/example/src/benchmarks/mixedCase.ts +++ b/example/src/benchmarks/mixedCase.ts @@ -1,4 +1,4 @@ -import { open, type NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import { open, type Connection } from 'react-native-nitro-sqlite' import type { SQLiteQueryParams } from 'react-native-nitro-sqlite' import type { BenchmarkCase, BenchmarkFixture } from './runner' import { assertBenchmark, disposeBenchmarkDatabase } from './database' @@ -15,7 +15,7 @@ export const mixedCase: BenchmarkCase = { async function setupMixedCase(): Promise { const writer = open({ name: 'benchmark_mixed' }) - let reader: NitroSQLiteConnection | undefined + let reader: Connection | undefined try { const mode = writer diff --git a/example/src/benchmarks/readCases.ts b/example/src/benchmarks/readCases.ts index 4c7f34e1..c7532d82 100644 --- a/example/src/benchmarks/readCases.ts +++ b/example/src/benchmarks/readCases.ts @@ -1,4 +1,4 @@ -import { open, type NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import { open, type Connection } from 'react-native-nitro-sqlite' import type { SQLiteQueryParams } from 'react-native-nitro-sqlite' import type { BenchmarkCase, BenchmarkFixture } from './runner' import { @@ -48,7 +48,7 @@ export const readCases: BenchmarkCase[] = [ }, ] -export function resetLargeDbSchema(db: NitroSQLiteConnection): void { +export function resetLargeDbSchema(db: Connection): void { db.executeBatch([ { query: 'DROP TABLE IF EXISTS Test' }, { query: WIDE_SCHEMA }, @@ -202,7 +202,7 @@ async function setupWideRead(): Promise { } } -async function seedNarrowRows(db: NitroSQLiteConnection): Promise { +async function seedNarrowRows(db: Connection): Promise { const params: SQLiteQueryParams[] = Array.from( { length: NARROW_ROWS }, (_, i) => [i, `name_${i}`, i], diff --git a/example/src/benchmarks/runner.ts b/example/src/benchmarks/runner.ts index 75cd102c..839f1938 100644 --- a/example/src/benchmarks/runner.ts +++ b/example/src/benchmarks/runner.ts @@ -1,5 +1,5 @@ import { Platform } from 'react-native' -import { open, type NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import { open, type Connection } from 'react-native-nitro-sqlite' import { version } from '../../package.json' import { getDeviceIdentifier, @@ -8,7 +8,7 @@ import { } from './memory' export interface BenchmarkFixture { - database: NitroSQLiteConnection + database: Connection reset?(): void | Promise run(): | void @@ -248,7 +248,7 @@ async function readEnvironment( } } -function readSQLiteSettings(db: NitroSQLiteConnection): SQLiteSettings { +function readSQLiteSettings(db: Connection): SQLiteSettings { const journal = db .execute<{ journal_mode: string }>('PRAGMA journal_mode') .rows.item(0) diff --git a/example/src/benchmarks/writeCases.ts b/example/src/benchmarks/writeCases.ts index 2cc398aa..4ee6b431 100644 --- a/example/src/benchmarks/writeCases.ts +++ b/example/src/benchmarks/writeCases.ts @@ -1,5 +1,5 @@ import type { - NitroSQLiteConnection, + Connection, PreparedStatement, SQLiteQueryParams, } from 'react-native-nitro-sqlite' @@ -74,7 +74,7 @@ function setupWriteCase(method: WriteMethod): BenchmarkFixture { function runWriteCase( method: WriteMethod, - db: NitroSQLiteConnection, + db: Connection, rows: SQLiteQueryParams[], statement?: PreparedStatement, ): void | Promise { @@ -103,21 +103,21 @@ function runWriteCase( } async function runSequentialAsync( - db: NitroSQLiteConnection, + db: Connection, rows: SQLiteQueryParams[], ): Promise { for (const params of rows) await db.executeAsync(INSERT_SQL, params) } async function runQueuedAsync( - db: NitroSQLiteConnection, + db: Connection, rows: SQLiteQueryParams[], ): Promise { await Promise.all(rows.map((params) => db.executeAsync(INSERT_SQL, params))) } async function runTransaction( - db: NitroSQLiteConnection, + db: Connection, rows: SQLiteQueryParams[], ): Promise { await db.transaction(async (tx) => { diff --git a/example/src/migrationTest.ts b/example/src/migrationTest.ts index 5fbb5103..56c550c2 100644 --- a/example/src/migrationTest.ts +++ b/example/src/migrationTest.ts @@ -1,4 +1,4 @@ -import type { NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { Connection } from 'react-native-nitro-sqlite' import { open } from 'react-native-nitro-sqlite' const MAIN_DATABASE = 'migration-screen-main.sqlite' @@ -87,10 +87,7 @@ function seedDatabase(name: string, marker: string): string { } } -function getDatabasePath( - database: NitroSQLiteConnection, - schema: DatabaseSchema, -): string { +function getDatabasePath(database: Connection, schema: DatabaseSchema): string { const row = database .execute('PRAGMA database_list') .rows._array.find((entry) => entry.name === schema) @@ -117,7 +114,7 @@ function expectLocation( } function expectMarker( - database: NitroSQLiteConnection, + database: Connection, schema: DatabaseSchema, expectedMarker: string, ): void { @@ -136,10 +133,7 @@ function expectMarker( ) } -function expectIntegrity( - database: NitroSQLiteConnection, - schema: DatabaseSchema, -): void { +function expectIntegrity(database: Connection, schema: DatabaseSchema): void { const result = database .execute(`PRAGMA ${schema}.integrity_check`) .rows.item(0)?.integrity_check diff --git a/example/src/screens/SqlConsoleScreen.tsx b/example/src/screens/SqlConsoleScreen.tsx index b746353e..6f20dea3 100644 --- a/example/src/screens/SqlConsoleScreen.tsx +++ b/example/src/screens/SqlConsoleScreen.tsx @@ -14,7 +14,7 @@ import { import { useFocusEffect } from '@react-navigation/native' import Clipboard from '@react-native-clipboard/clipboard' import type { - NitroSQLiteConnection, + Connection, QueryResult, SQLiteValue, } from 'react-native-nitro-sqlite' @@ -36,7 +36,7 @@ type QueryHistoryEntry = { durationMs: number } -function initializeDatabase(db: NitroSQLiteConnection) { +function initializeDatabase(db: Connection) { db.execute('DROP TABLE IF EXISTS products;') db.execute('DROP TABLE IF EXISTS users;') @@ -216,7 +216,7 @@ function ResultCard({ entry }: { entry: QueryHistoryEntry }) { } export function SqlConsoleScreen() { - const dbRef = useRef(null) + const dbRef = useRef(null) const queryInputRef = useRef(null) const [query, setQuery] = useState('') const [history, setHistory] = useState([]) diff --git a/example/tests/db.ts b/example/tests/db.ts index dfdac677..30f1d682 100644 --- a/example/tests/db.ts +++ b/example/tests/db.ts @@ -1,4 +1,4 @@ -import type { NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { Connection } from 'react-native-nitro-sqlite' import { open } from 'react-native-nitro-sqlite' import { getDatabaseQueue, @@ -7,7 +7,7 @@ import { export const TEST_DB_NAME = 'test' -export let testDb: NitroSQLiteConnection +export let testDb: Connection export let testDbQueue: DatabaseQueue export function resetTestDb() { if (testDb != null) { diff --git a/example/tests/unit/common.ts b/example/tests/unit/common.ts index 0344c513..8ef9dcc6 100644 --- a/example/tests/unit/common.ts +++ b/example/tests/unit/common.ts @@ -1,18 +1,18 @@ import { Chance } from 'chance' -import { NitroSQLiteError } from 'react-native-nitro-sqlite' +import { SQLiteError } from 'react-native-nitro-sqlite' import { resetTestDb } from '@tests/db' export { expect } from '@tests/TestApi' export const TEST_ERROR_CODES = { - EXPECT_NITRO_SQLITE_ERROR: 'Should have thrown a valid NitroSQLiteError', + EXPECT_NITRO_SQLITE_ERROR: 'Should have thrown a valid SQLiteError', EXPECT_PROMISE_REJECTION: 'Should have thrown a promise rejection', } as const export const TEST_ERROR_MESSAGE = 'Error from callback' export const TEST_ERROR = new Error(TEST_ERROR_MESSAGE) -export function isNitroSQLiteError(e: unknown): e is NitroSQLiteError { - return e instanceof NitroSQLiteError +export function isSQLiteError(e: unknown): e is SQLiteError { + return e instanceof SQLiteError } export const chance = new Chance() diff --git a/example/tests/unit/specs/Connections.spec.ts b/example/tests/unit/specs/Connections.spec.ts index 1eac5665..9b604f94 100644 --- a/example/tests/unit/specs/Connections.spec.ts +++ b/example/tests/unit/specs/Connections.spec.ts @@ -2,9 +2,9 @@ import { describe, it } from '@tests/TestApi' import { expect } from '@tests/unit/common' import { NitroSQLite, - NitroSQLiteError, + SQLiteError, open, - type NitroSQLiteConnection, + type Connection, } from 'react-native-nitro-sqlite' const TIMEOUT_MS = 5000 @@ -356,10 +356,10 @@ function expectThrows(action: () => unknown) { } catch (caught) { error = caught } - expect(error).toBeInstanceOf(NitroSQLiteError) + expect(error).toBeInstanceOf(SQLiteError) } -function mainPath(connection: NitroSQLiteConnection): string { +function mainPath(connection: Connection): string { const main = connection .execute<{ name: string; file: string }>('PRAGMA database_list') .results.find((row) => row.name === 'main') @@ -368,7 +368,7 @@ function mainPath(connection: NitroSQLiteConnection): string { return main.file } -function databaseNames(connection: NitroSQLiteConnection): string[] { +function databaseNames(connection: Connection): string[] { return connection .execute<{ name: string }>('PRAGMA database_list') .results.map((row) => row.name) diff --git a/example/tests/unit/specs/DatabaseQueue.spec.ts b/example/tests/unit/specs/DatabaseQueue.spec.ts index 930e11f2..faf539f9 100644 --- a/example/tests/unit/specs/DatabaseQueue.spec.ts +++ b/example/tests/unit/specs/DatabaseQueue.spec.ts @@ -1,6 +1,6 @@ import { expect, - isNitroSQLiteError, + isSQLiteError, TEST_ERROR, TEST_ERROR_CODES, TEST_ERROR_MESSAGE, @@ -9,7 +9,7 @@ import { describe, it } from '@tests/TestApi' import { testDb, testDbQueue } from '@tests/db' import { NitroSQLite, - NitroSQLiteError, + SQLiteError, open, type BatchQueryCommand, } from 'react-native-nitro-sqlite' @@ -172,7 +172,7 @@ export default function registerDatabaseQueueUnitTests() { expect(testDbQueue.queue.length).toBe(0) expect(testDbQueue.inProgress).toBe(true) } catch (e) { - if (isNitroSQLiteError(e)) { + if (isSQLiteError(e)) { expect(e.message).toContain(TEST_ERROR_MESSAGE) } else { throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) @@ -185,7 +185,7 @@ export default function registerDatabaseQueueUnitTests() { expect(testDbQueue.queue.length).toBe(0) expect(testDbQueue.inProgress).toBe(false) } catch (e) { - if (isNitroSQLiteError(e)) { + if (isSQLiteError(e)) { expect(e.message).toContain(TEST_ERROR_MESSAGE) } else { throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) @@ -284,7 +284,7 @@ export default function registerDatabaseQueueUnitTests() { await before const batchError = await batchErrorPromise - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) await after expect( testDb.execute<{ value: number }>( @@ -302,7 +302,7 @@ export default function registerDatabaseQueueUnitTests() { } catch (error) { syncError = error } - expect(syncError).toBeInstanceOf(NitroSQLiteError) + expect(syncError).toBeInstanceOf(SQLiteError) expect((syncError as Error).message).toContain( 'Await all tx.executeAsync', ) @@ -410,7 +410,7 @@ export default function registerDatabaseQueueUnitTests() { operationError = error } - expect(operationError).toBeInstanceOf(NitroSQLiteError) + expect(operationError).toBeInstanceOf(SQLiteError) expect((operationError as Error).message).toContain('busy') } @@ -429,7 +429,7 @@ export default function registerDatabaseQueueUnitTests() { loadError = error } - expect(loadError).toBeInstanceOf(NitroSQLiteError) + expect(loadError).toBeInstanceOf(SQLiteError) expect((loadError as Error).message).toContain('Could not load file') expect((await testDb.executeAsync('SELECT 42 AS value')).results).toEqual( [{ value: 42 }], @@ -487,7 +487,7 @@ export default function registerDatabaseQueueUnitTests() { duplicateError = error } - expect(duplicateError).toBeInstanceOf(NitroSQLiteError) + expect(duplicateError).toBeInstanceOf(SQLiteError) expect((duplicateError as Error).message).toContain('already open') expect( db.execute<{ value: string }>('SELECT value FROM ConnectionMarker') diff --git a/example/tests/unit/specs/operations/execute.spec.ts b/example/tests/unit/specs/operations/execute.spec.ts index d5814c21..0c6cd9fa 100644 --- a/example/tests/unit/specs/operations/execute.spec.ts +++ b/example/tests/unit/specs/operations/execute.spec.ts @@ -1,10 +1,10 @@ -import { chance, expect, isNitroSQLiteError } from '@tests/unit/common' +import { chance, expect, isSQLiteError } from '@tests/unit/common' import { describe, it } from '@tests/TestApi' import { createArrayBufferTestDb, testDb } from '@tests/db' import { open } from 'react-native-nitro-sqlite' import { buildJSQueryResult } from '@nitro-sqlite/operations/execute' import type { ColumnType } from 'react-native-nitro-sqlite' -import type { NitroSQLiteQueryResult } from '@nitro-sqlite/specs/NitroSQLiteQueryResult' +import type { NativeQueryResult } from '@nitro-sqlite/specs/NativeQueryResult' const QUERY_RESULT_SIZES = [60, 1_000, 10_000] // Asynchronous reads hand rows to JavaScript in batches of 256; cover the batch edges. @@ -119,7 +119,7 @@ export default function registerExecuteUnitTests() { await run() throw new Error('Expected a multi-statement query to fail') } catch (error) { - if (!isNitroSQLiteError(error)) throw error + if (!isSQLiteError(error)) throw error expect(error.message).toContain( 'Query contains more than one SQL statement', ) @@ -145,7 +145,7 @@ export default function registerExecuteUnitTests() { resultsReads += 1 return [...sourceRows] }, - } as unknown as NitroSQLiteQueryResult + } as unknown as NativeQueryResult const result = buildJSQueryResult(nativeResult) @@ -268,7 +268,7 @@ export default function registerExecuteUnitTests() { [id, name, age, networth], ) } catch (e: unknown) { - if (isNitroSQLiteError(e)) { + if (isSQLiteError(e)) { expect(e.message).toContain( 'cannot store TEXT value in REAL column User.age', ) @@ -503,8 +503,8 @@ export default function registerExecuteUnitTests() { testDb.execute('SELECT ?', [1, extraParameter]) throw new Error('Expected execute to throw for the extra parameter') } catch (error: unknown) { - if (!isNitroSQLiteError(error)) { - throw new Error('Should have thrown a valid NitroSQLiteError') + if (!isSQLiteError(error)) { + throw new Error('Should have thrown a valid SQLiteError') } expect(error.message).toContain('parameter 2') @@ -523,8 +523,8 @@ export default function registerExecuteUnitTests() { 'Expected executeAsync to reject for the extra parameter', ) } catch (error: unknown) { - if (!isNitroSQLiteError(error)) { - throw new Error('Should have thrown a valid NitroSQLiteError') + if (!isSQLiteError(error)) { + throw new Error('Should have thrown a valid SQLiteError') } expect(error.message).toContain('parameter 2') diff --git a/example/tests/unit/specs/operations/executeBatch.spec.ts b/example/tests/unit/specs/operations/executeBatch.spec.ts index f0cbe930..af5ffb43 100644 --- a/example/tests/unit/specs/operations/executeBatch.spec.ts +++ b/example/tests/unit/specs/operations/executeBatch.spec.ts @@ -1,8 +1,5 @@ -import { chance, expect, isNitroSQLiteError } from '@tests/unit/common' -import { - NitroSQLiteError, - type BatchQueryCommand, -} from 'react-native-nitro-sqlite' +import { chance, expect, isSQLiteError } from '@tests/unit/common' +import { SQLiteError, type BatchQueryCommand } from 'react-native-nitro-sqlite' import { describe, it } from '@tests/TestApi' import { testDb } from '@tests/db' @@ -208,7 +205,7 @@ export default function registerExecuteBatchUnitTests() { batchError = error } - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) expect((batchError as Error).message).toContain( 'No SQL batch commands provided', ) @@ -249,7 +246,7 @@ export default function registerExecuteBatchUnitTests() { batchError = error } - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) expect(testDb.execute('SELECT id FROM User').results).toEqual([]) expect( testDb.executeBatch([ @@ -277,7 +274,7 @@ export default function registerExecuteBatchUnitTests() { batchError = error } - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) expect( testDb.execute( "SELECT name FROM sqlite_master WHERE name = 'repeated_schema'", @@ -300,7 +297,7 @@ export default function registerExecuteBatchUnitTests() { batchError = error } - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) expect(testDb.execute('SELECT id FROM User').results).toEqual([]) expect( testDb.executeBatch([ @@ -327,7 +324,7 @@ export default function registerExecuteBatchUnitTests() { batchError = error } - expect(batchError).toBeInstanceOf(NitroSQLiteError) + expect(batchError).toBeInstanceOf(SQLiteError) expect(testDb.execute('SELECT id FROM User').results).toEqual([]) expect( ( @@ -356,8 +353,8 @@ export default function registerExecuteBatchUnitTests() { asyncError = error } - expect(syncError).toBeInstanceOf(NitroSQLiteError) - expect(asyncError).toBeInstanceOf(NitroSQLiteError) + expect(syncError).toBeInstanceOf(SQLiteError) + expect(asyncError).toBeInstanceOf(SQLiteError) expect(testDb.execute('SELECT 1 AS value').results).toEqual([ { value: 1 }, ]) @@ -376,8 +373,8 @@ export default function registerExecuteBatchUnitTests() { 'Expected executeBatch to throw for the extra parameter', ) } catch (error: unknown) { - if (!isNitroSQLiteError(error)) { - throw new Error('Should have thrown a valid NitroSQLiteError') + if (!isSQLiteError(error)) { + throw new Error('Should have thrown a valid SQLiteError') } expect(error.message).toContain('parameter 2') @@ -401,8 +398,8 @@ export default function registerExecuteBatchUnitTests() { 'Expected executeBatchAsync to reject for the extra parameter', ) } catch (error: unknown) { - if (!isNitroSQLiteError(error)) { - throw new Error('Should have thrown a valid NitroSQLiteError') + if (!isSQLiteError(error)) { + throw new Error('Should have thrown a valid SQLiteError') } expect(error.message).toContain('parameter 2') @@ -426,7 +423,7 @@ export default function registerExecuteBatchUnitTests() { else testDb.executeBatch(commands) throw new Error('Expected grouped binding to fail') } catch (error) { - if (!isNitroSQLiteError(error)) throw error + if (!isSQLiteError(error)) throw error expect(error.message).toContain('parameter 2') expect(error.message).toContain('25') expect(error.message.includes(secret)).toBe(false) diff --git a/example/tests/unit/specs/operations/preparedStatement.spec.ts b/example/tests/unit/specs/operations/preparedStatement.spec.ts index ba0585ad..10c99cf4 100644 --- a/example/tests/unit/specs/operations/preparedStatement.spec.ts +++ b/example/tests/unit/specs/operations/preparedStatement.spec.ts @@ -1,7 +1,7 @@ import { chance, expect, - isNitroSQLiteError, + isSQLiteError, TEST_ERROR_CODES, } from '@tests/unit/common' import { describe, it } from '@tests/TestApi' @@ -19,7 +19,7 @@ export default function registerPreparedStatementUnitTests() { else statement.execute([1, secret]) throw new Error('Expected prepared binding to fail') } catch (error) { - if (!isNitroSQLiteError(error)) throw error + if (!isSQLiteError(error)) throw error expect(error.message).toContain('parameter 2') expect(error.message).toContain('25') expect(error.message).toContain('column index out of range') @@ -179,7 +179,7 @@ export default function registerPreparedStatementUnitTests() { statement.execute([42, 'Duplicate', 37, 1]) throw new Error('Expected duplicate key to fail') } catch (error) { - expect(isNitroSQLiteError(error)).toBe(true) + expect(isSQLiteError(error)).toBe(true) } expect(statement.execute([43, 'Grace', 38, 2]).rowsAffected).toBe(1) @@ -194,8 +194,8 @@ export default function registerPreparedStatementUnitTests() { statement.execute() throw new Error('Expected execution to throw after finalization') } catch (error) { - expect(isNitroSQLiteError(error)).toBe(true) - if (isNitroSQLiteError(error)) { + expect(isSQLiteError(error)).toBe(true) + if (isSQLiteError(error)) { expect(error.message).toContain( 'Prepared statement has been finalized', ) @@ -209,7 +209,7 @@ export default function registerPreparedStatementUnitTests() { testDb.prepare(query) throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) } catch (error) { - if (!isNitroSQLiteError(error)) throw error + if (!isSQLiteError(error)) throw error expect(error.message).toContain( 'Query does not contain any SQL statement', ) diff --git a/example/tests/unit/specs/operations/transaction.spec.ts b/example/tests/unit/specs/operations/transaction.spec.ts index 8ab61723..339fb6d9 100644 --- a/example/tests/unit/specs/operations/transaction.spec.ts +++ b/example/tests/unit/specs/operations/transaction.spec.ts @@ -1,14 +1,14 @@ import { chance, expect, - isNitroSQLiteError, + isSQLiteError, TEST_ERROR, TEST_ERROR_MESSAGE, TEST_ERROR_CODES, } from '@tests/unit/common' import { describe, it } from '@tests/TestApi' import type { User } from '@/model/User' -import { NitroSQLiteError } from 'react-native-nitro-sqlite' +import { SQLiteError } from 'react-native-nitro-sqlite' import { testDb } from '@tests/db' const FOREIGN_KEY_COMMIT_ERROR = 'FOREIGN KEY constraint failed' @@ -28,7 +28,7 @@ export default function registerTransactionUnitTests() { try { tx.commit() } catch (error) { - if (!isNitroSQLiteError(error)) throw error + if (!isSQLiteError(error)) throw error expect(error.message).toContain(FOREIGN_KEY_COMMIT_ERROR) } }) @@ -173,7 +173,7 @@ export default function registerTransactionUnitTests() { } catch (e) { queryError = e } - expect(queryError).toBeInstanceOf(NitroSQLiteError) + expect(queryError).toBeInstanceOf(SQLiteError) let asyncQueryError: unknown try { @@ -181,7 +181,7 @@ export default function registerTransactionUnitTests() { } catch (e) { asyncQueryError = e } - expect(asyncQueryError).toBeInstanceOf(NitroSQLiteError) + expect(asyncQueryError).toBeInstanceOf(SQLiteError) }) const res = testDb.execute('SELECT * FROM User') @@ -247,8 +247,7 @@ export default function registerTransactionUnitTests() { await promised throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION) } catch (e) { - if (isNitroSQLiteError(e)) - expect(e.message).toContain(TEST_ERROR_MESSAGE) + if (isSQLiteError(e)) expect(e.message).toContain(TEST_ERROR_MESSAGE) else throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) } }) @@ -265,7 +264,7 @@ export default function registerTransactionUnitTests() { await promised throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION) } catch (e) { - if (isNitroSQLiteError(e)) + if (isSQLiteError(e)) expect(e.message).toContain('no such table: tableThatDoesNotExist') else throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) } @@ -333,7 +332,7 @@ export default function registerTransactionUnitTests() { ) }) } catch (e) { - if (isNitroSQLiteError(e)) { + if (isSQLiteError(e)) { expect(e.message).toContain('SqlExecutionError') expect(e.message).toContain( 'cannot store TEXT value in REAL column User.id', @@ -454,8 +453,7 @@ export default function registerTransactionUnitTests() { await promised throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION) } catch (e) { - if (isNitroSQLiteError(e)) - expect(e.message).toContain(TEST_ERROR_MESSAGE) + if (isSQLiteError(e)) expect(e.message).toContain(TEST_ERROR_MESSAGE) else throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) } }) @@ -473,7 +471,7 @@ export default function registerTransactionUnitTests() { await promised throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION) } catch (e) { - if (isNitroSQLiteError(e)) + if (isSQLiteError(e)) expect(e.message).toContain('no such table: tableThatDoesNotExist') else throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) } @@ -501,7 +499,7 @@ async function expectDeferredForeignKeyCommitFailure( }) throw new Error(TEST_ERROR_CODES.EXPECT_PROMISE_REJECTION) } catch (error) { - if (isNitroSQLiteError(error)) { + if (isSQLiteError(error)) { expect(error.message).toContain(FOREIGN_KEY_COMMIT_ERROR) } else { throw new Error(TEST_ERROR_CODES.EXPECT_NITRO_SQLITE_ERROR) diff --git a/example/tests/unit/specs/sqlite-vec.spec.ts b/example/tests/unit/specs/sqlite-vec.spec.ts index e65df74b..4f8e112e 100644 --- a/example/tests/unit/specs/sqlite-vec.spec.ts +++ b/example/tests/unit/specs/sqlite-vec.spec.ts @@ -1,15 +1,15 @@ import { describe, it, beforeEach, afterAll } from '@tests/TestApi' -import { expect, isNitroSQLiteError } from '@tests/unit/common' +import { expect, isSQLiteError } from '@tests/unit/common' import { open } from 'react-native-nitro-sqlite' -import type { NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { Connection } from 'react-native-nitro-sqlite' type Param = string | number | null type Row = Record const DB_NAME = 'test_vec' -let db: NitroSQLiteConnection +let db: Connection -function closeQuietly(connection: NitroSQLiteConnection | undefined) { +function closeQuietly(connection: Connection | undefined) { if (connection == null) return try { connection.close() @@ -538,7 +538,7 @@ export default function registerSqliteVecUnitTests() { ) } catch (e) { threw = true - expect(isNitroSQLiteError(e)).toBe(true) + expect(isSQLiteError(e)).toBe(true) } expect(threw).toBe(true) }) @@ -551,7 +551,7 @@ export default function registerSqliteVecUnitTests() { ) } catch (e) { threw = true - expect(isNitroSQLiteError(e)).toBe(true) + expect(isSQLiteError(e)).toBe(true) } expect(threw).toBe(true) }) diff --git a/packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecOnLoad.mm b/packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecOnLoad.mm similarity index 85% rename from packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecOnLoad.mm rename to packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecOnLoad.mm index 69dcb7c5..28e55552 100644 --- a/packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecOnLoad.mm +++ b/packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecOnLoad.mm @@ -1,4 +1,4 @@ -#import "NitroSQLiteVecRegisterVectorExtensions.hpp" +#import "SQLiteVecRegisterVectorExtensions.hpp" #import // Swift Package Manager builds this package separately from the core, so register before any database opens. diff --git a/packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecRegisterVectorExtensions.cpp b/packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecRegisterVectorExtensions.cpp similarity index 86% rename from packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecRegisterVectorExtensions.cpp rename to packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecRegisterVectorExtensions.cpp index a7397476..c4731599 100644 --- a/packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecRegisterVectorExtensions.cpp +++ b/packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecRegisterVectorExtensions.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteVecRegisterVectorExtensions.hpp" +#include "SQLiteVecRegisterVectorExtensions.hpp" #include #include "sqlite3.h" diff --git a/packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecRegisterVectorExtensions.hpp b/packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecRegisterVectorExtensions.hpp similarity index 100% rename from packages/react-native-nitro-sqlite-vec/cpp/NitroSQLiteVecRegisterVectorExtensions.hpp rename to packages/react-native-nitro-sqlite-vec/cpp/SQLiteVecRegisterVectorExtensions.hpp diff --git a/packages/react-native-nitro-sqlite-vec/src/__tests__/index.test.ts b/packages/react-native-nitro-sqlite-vec/src/__tests__/index.test.ts index 70887bb3..49c82271 100644 --- a/packages/react-native-nitro-sqlite-vec/src/__tests__/index.test.ts +++ b/packages/react-native-nitro-sqlite-vec/src/__tests__/index.test.ts @@ -1,4 +1,4 @@ -import type { NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { Connection } from 'react-native-nitro-sqlite' import { createVectorTable, isVecAvailable, @@ -7,7 +7,7 @@ import { } from '../index' const execute = jest.fn() -const db = { execute } as unknown as NitroSQLiteConnection +const db = { execute } as unknown as Connection beforeEach(() => execute.mockReset()) diff --git a/packages/react-native-nitro-sqlite-vec/src/index.ts b/packages/react-native-nitro-sqlite-vec/src/index.ts index ad343bf1..c56478f9 100644 --- a/packages/react-native-nitro-sqlite-vec/src/index.ts +++ b/packages/react-native-nitro-sqlite-vec/src/index.ts @@ -1,4 +1,4 @@ -import type { NitroSQLiteConnection } from 'react-native-nitro-sqlite' +import type { Connection } from 'react-native-nitro-sqlite' /** Vector storage types accepted by a `vec0` column. */ export type VectorColumnType = 'float' | 'int8' | 'bit' @@ -34,7 +34,7 @@ export interface KnnSearchOptions { column?: string } -function firstValue(db: NitroSQLiteConnection, sql: string): T { +function firstValue(db: Connection, sql: string): T { const row = db.execute(sql).rows?._array?.[0] return row?.value as T } @@ -44,7 +44,7 @@ function firstValue(db: NitroSQLiteConnection, sql: string): T { * @returns The linked version string, for example `"v0.1.9"`. * @throws If `vec_version()` is unavailable or the query fails. */ -export function vecVersion(db: NitroSQLiteConnection): string { +export function vecVersion(db: Connection): string { return firstValue(db, 'SELECT vec_version() AS value') } @@ -52,7 +52,7 @@ export function vecVersion(db: NitroSQLiteConnection): string { * @param db Open NitroSQLite connection. The check runs synchronously. * @returns `false` if the version query throws for any reason, including a closed connection. */ -export function isVecAvailable(db: NitroSQLiteConnection): boolean { +export function isVecAvailable(db: Connection): boolean { try { vecVersion(db) return true @@ -69,7 +69,7 @@ export function isVecAvailable(db: NitroSQLiteConnection): boolean { * @param options Vector dimensions, storage type, metric, and trusted column identifier. */ export function createVectorTable( - db: NitroSQLiteConnection, + db: Connection, table: string, options: CreateVectorTableOptions, ): void { @@ -92,7 +92,7 @@ export function createVectorTable( * @returns Matching row IDs and distances, or an empty array when no rows are returned. */ export function knnSearch( - db: NitroSQLiteConnection, + db: Connection, table: string, query: string | number[], k: number, diff --git a/packages/react-native-nitro-sqlite/android/CMakeLists.txt b/packages/react-native-nitro-sqlite/android/CMakeLists.txt index 78537f53..6135966b 100644 --- a/packages/react-native-nitro-sqlite/android/CMakeLists.txt +++ b/packages/react-native-nitro-sqlite/android/CMakeLists.txt @@ -35,7 +35,7 @@ if(NITRO_SQLITE_VEC) message(STATUS "[react-native-nitro-sqlite] vector search ENABLED (sqlite-vec from ${NITRO_SQLITE_VEC_CPP_DIR})") set(NITRO_SQLITE_VEC_SOURCES "${NITRO_SQLITE_VEC_CPP_DIR}/sqlite-vec/sqlite-vec.c" - "${NITRO_SQLITE_VEC_CPP_DIR}/NitroSQLiteVecRegisterVectorExtensions.cpp" + "${NITRO_SQLITE_VEC_CPP_DIR}/SQLiteVecRegisterVectorExtensions.cpp" ) target_sources(${CMAKE_PROJECT_NAME} PRIVATE ${NITRO_SQLITE_VEC_SOURCES}) # SQLITE_CORE: link against our bundled sqlite3; SQLITE_VEC_STATIC: drop Windows dllexport. diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp b/packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp deleted file mode 100644 index b0afbb90..00000000 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp +++ /dev/null @@ -1,74 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -const std::string NITRO_SQLITE_EXCEPTION_PREFIX = "[NativeNitroSQLiteException]"; - -enum NitroSQLiteExceptionType { - UnknownError, - DatabaseCannotBeOpened, - EncryptionNotEnabled, - DatabaseCannotBeDecrypted, - DatabaseNotOpen, - UnableToAttachToDatabase, - SqlExecutionError, - CouldNotLoadFile, - NoBatchCommandsProvided -}; - -inline std::unordered_map exceptionTypeStrings = { - {UnknownError, "UnknownError"}, - {DatabaseCannotBeOpened, "DatabaseCannotBeOpened"}, - {EncryptionNotEnabled, "EncryptionNotEnabled"}, - {DatabaseCannotBeDecrypted, "DatabaseCannotBeDecrypted"}, - {DatabaseNotOpen, "DatabaseNotOpen"}, - {UnableToAttachToDatabase, "UnableToAttachToDatabase"}, - {SqlExecutionError, "SqlExecutionError"}, - {CouldNotLoadFile, "CouldNotLoadFile"}, - {NoBatchCommandsProvided, "NoBatchCommandsProvided"}}; - -inline std::string typeToString(NitroSQLiteExceptionType type) { - return exceptionTypeStrings[type]; -} - -class NitroSQLiteException : public std::exception { -public: - explicit NitroSQLiteException(const char* message) : NitroSQLiteException(NitroSQLiteExceptionType::UnknownError, message) {} - explicit NitroSQLiteException(const std::string& message) : NitroSQLiteException(NitroSQLiteExceptionType::UnknownError, message) {} - NitroSQLiteException(const NitroSQLiteExceptionType& type, const char* message) : NitroSQLiteException(type, std::string(message)) {} - NitroSQLiteException(const NitroSQLiteExceptionType& type, const std::string& message) - : _exceptionString(NITRO_SQLITE_EXCEPTION_PREFIX + "[" + typeToString(type) + "] " + message) {} - -private: - const std::string _exceptionString; - -public: - [[nodiscard]] const char* what() const noexcept override { - return this->_exceptionString.c_str(); - } - - static NitroSQLiteException DatabaseAlreadyOpen(const std::string& dbName) { - return NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, - "Database " + dbName + " is already open. There is already a connection to the database."); - } - - static NitroSQLiteException DatabaseNotOpen(const std::string& dbName) { - return NitroSQLiteException(NitroSQLiteExceptionType::UnableToAttachToDatabase, dbName + " is not open"); - } - - static NitroSQLiteException SqlExecution(const std::string& errorMessage) { - return NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, errorMessage); - } - - static NitroSQLiteException DatabaseFileNotFound(const std::string& dbFilePath) { - return NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, "Database file not found: " + dbFilePath); - } - - static NitroSQLiteException CouldNotLoadFile(const std::string& fileLocation, std::optional additionalLine = std::nullopt) { - const auto message = "Could not load file: " + fileLocation + (additionalLine ? (". " + *additionalLine) : ""); - return NitroSQLiteException(NitroSQLiteExceptionType::CouldNotLoadFile, message); - } -}; diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp similarity index 83% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp index 21b01cbe..b7386232 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp @@ -1,7 +1,7 @@ -#include "NitroSQLiteDatabaseConnections.hpp" -#include "NitroSQLiteDatabaseMigration.hpp" -#include "NitroSQLiteException.hpp" -#include "NitroSQLiteLogs.hpp" +#include "SQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseMigration.hpp" +#include "SQLiteException.hpp" +#include "SQLiteLogs.hpp" #include #include #include @@ -76,7 +76,7 @@ namespace { const int prepared = sqlite3_prepare_v2(database, "PRAGMA database_list", -1, &rawStatement, nullptr); std::unique_ptr statement(rawStatement, sqlite3_finalize); if (prepared != SQLITE_OK) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(database)); } int result; while ((result = sqlite3_step(statement.get())) == SQLITE_ROW) { @@ -86,7 +86,7 @@ namespace { } } if (result != SQLITE_DONE) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(database)); } return false; } @@ -105,13 +105,13 @@ namespace { } #ifdef SQLITE_ENABLE_SEE if (encryptionKey->empty()) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeDecrypted, "Encryption key must not be empty"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeDecrypted, "Encryption key must not be empty"); } if (encryptionKey->find('\0') != std::string::npos) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeDecrypted, "Encryption key must not contain a NUL byte"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeDecrypted, "Encryption key must not contain a NUL byte"); } #else - throw NitroSQLiteException(NitroSQLiteExceptionType::EncryptionNotEnabled, "SQLite Encryption Extension is not enabled in this build"); + throw SQLiteException(SQLiteExceptionType::EncryptionNotEnabled, "SQLite Encryption Extension is not enabled in this build"); #endif } @@ -123,8 +123,8 @@ namespace { std::ifstream file(path, std::ios::binary); std::array header{}; if (file.read(header.data(), header.size()) && std::memcmp(header.data(), "SQLite format 3", header.size()) == 0) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeDecrypted, - "Existing database is unencrypted; migrate it before opening with an encryption key"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeDecrypted, + "Existing database is unencrypted; migrate it before opening with an encryption key"); } #else (void)path; @@ -139,7 +139,7 @@ namespace { #ifdef SQLITE_ENABLE_SEE const int keyResult = sqlite3_key_v2(database, "main", encryptionKey->c_str(), -1); if (keyResult != SQLITE_OK) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeDecrypted, sqlite3_errmsg(database)); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeDecrypted, sqlite3_errmsg(database)); } // SEE checks the key when SQLite first reads the file, not when the key is set. @@ -147,7 +147,7 @@ namespace { const int prepared = sqlite3_prepare_v2(database, "SELECT count(*) FROM sqlite_schema", -1, &rawStatement, nullptr); std::unique_ptr statement(rawStatement, sqlite3_finalize); if (prepared != SQLITE_OK || sqlite3_step(statement.get()) != SQLITE_ROW) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeDecrypted, sqlite3_errmsg(database)); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeDecrypted, sqlite3_errmsg(database)); } #else (void)database; @@ -255,7 +255,7 @@ void DatabaseConnections::open(const std::string& key, const fs::path& path, boo std::lock_guard lock(lifecycleMutex); validateDatabaseName(key); if (connections.contains(key)) { - throw NitroSQLiteException::DatabaseAlreadyOpen(key); + throw SQLiteException::DatabaseAlreadyOpen(key); } openKey(key, path, readOnly, encryptionKey); } @@ -263,11 +263,10 @@ void DatabaseConnections::open(const std::string& key, const fs::path& path, boo std::string DatabaseConnections::openIndependent(const fs::path& path, bool readOnly, const std::optional& encryptionKey) { std::lock_guard lock(lifecycleMutex); if (path.string().find('\0') != std::string::npos) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); } if (sqlite3_threadsafe() == 0) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, - "Independent connections require a thread-safe SQLite build"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Independent connections require a thread-safe SQLite build"); } // NUL cannot occur in a filesystem name. The ID cannot collide with a legacy database key. const auto physicalPath = canonicalDatabasePath(path); @@ -280,7 +279,7 @@ std::string DatabaseConnections::openIndependent(const fs::path& path, bool read void DatabaseConnections::openKey(const std::string& key, const fs::path& path, bool readOnly, const std::optional& encryptionKey) { if (path.string().find('\0') != std::string::npos) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); } validateEncryptionKey(encryptionKey); const auto physicalPath = canonicalDatabasePath(path); @@ -293,7 +292,7 @@ void DatabaseConnections::openKey(const std::string& key, const fs::path& path, std::unique_ptr database(rawDatabase, sqlite3_close_v2); if (result != SQLITE_OK) { const std::string message = rawDatabase == nullptr ? sqlite3_errstr(result) : sqlite3_errmsg(rawDatabase); - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, message); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, message); } applyEncryptionKey(database.get(), encryptionKey); if (readOnly) { @@ -311,7 +310,7 @@ void DatabaseConnections::close(const std::string& key) { std::lock_guard lock(lifecycleMutex); const auto found = connections.find(key); if (found == connections.end()) { - throw NitroSQLiteException::DatabaseNotOpen(connectionLabel(key)); + throw SQLiteException::DatabaseNotOpen(connectionLabel(key)); } auto connection = std::move(found->second); connections.erase(found); @@ -330,7 +329,7 @@ SQLiteConnectionPtr DatabaseConnections::get(const std::string& key) { std::lock_guard lock(lifecycleMutex); const auto found = connections.find(key); if (found == connections.end()) { - throw NitroSQLiteException::DatabaseNotOpen(connectionLabel(key)); + throw SQLiteException::DatabaseNotOpen(connectionLabel(key)); } return found->second; } @@ -399,41 +398,40 @@ void DatabaseConnections::drop(const std::string& dbName, const fs::path& path, validateDatabaseName(dbName); const auto target = canonicalDatabasePath(path); if (!fs::exists(target)) { - throw NitroSQLiteException::DatabaseFileNotFound(target.string()); + throw SQLiteException::DatabaseFileNotFound(target.string()); } const auto key = connectionId.value_or(dbName); const auto live = connections.find(key); const auto independent = connectionId ? parseIndependentId(*connectionId) : std::nullopt; if (connectionId && !independent) { - throw NitroSQLiteException::DatabaseNotOpen(connectionLabel(key)); + throw SQLiteException::DatabaseNotOpen(connectionLabel(key)); } if (independent && (!sameFile(independent->physicalPath, target) || independent->readOnly)) { - throw NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, independent->readOnly - ? "A read-only connection cannot delete a database" - : "Connection targets a different database file"); + throw SQLiteException(SQLiteExceptionType::SqlExecutionError, independent->readOnly ? "A read-only connection cannot delete a database" + : "Connection targets a different database file"); } if (live != connections.end()) { if (!sameFile(live->second->physicalPath, target)) { - throw NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, "Connection targets a different database file"); + throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "Connection targets a different database file"); } if (live->second->readOnly) { - throw NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, "A read-only connection cannot delete a database"); + throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "A read-only connection cannot delete a database"); } } const SQLiteConnectionPtr connectionToClose = live == connections.end() ? nullptr : live->second; withConnectionsLocked([&]() { if (isPathInUse(target, connectionToClose) || (otherPath && isPathInUse(*otherPath, connectionToClose))) { - throw NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, "Database is in use by another connection"); + throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "Database is in use by another connection"); } if (!fs::exists(target)) { - throw NitroSQLiteException::DatabaseFileNotFound(target.string()); + throw SQLiteException::DatabaseFileNotFound(target.string()); } if (connectionToClose) { close(key); } if (!removeDatabaseFiles(target.filename().string(), target.parent_path())) { - throw NitroSQLiteException(NitroSQLiteExceptionType::SqlExecutionError, "Could not remove database files"); + throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "Could not remove database files"); } if (otherPath) { removeDatabaseFiles(otherPath->filename().string(), otherPath->parent_path()); @@ -459,7 +457,7 @@ bool DatabaseConnections::isPathInUse(const fs::path& path, const SQLiteConnecti void validateDatabaseName(const std::string& dbName) { if (dbName.find('\0') != std::string::npos) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, "Database name contains a NUL byte"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database name contains a NUL byte"); } } diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.hpp similarity index 99% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.hpp index 31b07c80..8e7fe5e1 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.hpp @@ -3,7 +3,7 @@ #ifdef SQLITE_ENABLE_SEE #define SQLITE_HAS_CODEC 1 #endif -#include "NitroSQLiteStatementCache.hpp" +#include "SQLiteStatementCache.hpp" #include "sqlite/sqlite3.h" #include #include diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp similarity index 98% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp index 04bfba14..f0e67a17 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp @@ -1,5 +1,5 @@ -#include "NitroSQLiteDatabaseMigration.hpp" -#include "NitroSQLiteLogs.hpp" +#include "SQLiteDatabaseMigration.hpp" +#include "SQLiteLogs.hpp" #include #include diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/SQLiteException.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteException.hpp new file mode 100644 index 00000000..b63c29f0 --- /dev/null +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteException.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include +#include + +const std::string NITRO_SQLITE_EXCEPTION_PREFIX = "[NativeNitroSQLiteException]"; + +enum SQLiteExceptionType { + UnknownError, + DatabaseCannotBeOpened, + EncryptionNotEnabled, + DatabaseCannotBeDecrypted, + DatabaseNotOpen, + UnableToAttachToDatabase, + SqlExecutionError, + CouldNotLoadFile, + NoBatchCommandsProvided +}; + +inline std::unordered_map exceptionTypeStrings = { + {UnknownError, "UnknownError"}, + {DatabaseCannotBeOpened, "DatabaseCannotBeOpened"}, + {EncryptionNotEnabled, "EncryptionNotEnabled"}, + {DatabaseCannotBeDecrypted, "DatabaseCannotBeDecrypted"}, + {DatabaseNotOpen, "DatabaseNotOpen"}, + {UnableToAttachToDatabase, "UnableToAttachToDatabase"}, + {SqlExecutionError, "SqlExecutionError"}, + {CouldNotLoadFile, "CouldNotLoadFile"}, + {NoBatchCommandsProvided, "NoBatchCommandsProvided"}}; + +inline std::string typeToString(SQLiteExceptionType type) { + return exceptionTypeStrings[type]; +} + +class SQLiteException : public std::exception { +public: + explicit SQLiteException(const char* message) : SQLiteException(SQLiteExceptionType::UnknownError, message) {} + explicit SQLiteException(const std::string& message) : SQLiteException(SQLiteExceptionType::UnknownError, message) {} + SQLiteException(const SQLiteExceptionType& type, const char* message) : SQLiteException(type, std::string(message)) {} + SQLiteException(const SQLiteExceptionType& type, const std::string& message) + : _exceptionString(NITRO_SQLITE_EXCEPTION_PREFIX + "[" + typeToString(type) + "] " + message) {} + +private: + const std::string _exceptionString; + +public: + [[nodiscard]] const char* what() const noexcept override { + return this->_exceptionString.c_str(); + } + + static SQLiteException DatabaseAlreadyOpen(const std::string& dbName) { + return SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, + "Database " + dbName + " is already open. There is already a connection to the database."); + } + + static SQLiteException DatabaseNotOpen(const std::string& dbName) { + return SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, dbName + " is not open"); + } + + static SQLiteException SqlExecution(const std::string& errorMessage) { + return SQLiteException(SQLiteExceptionType::SqlExecutionError, errorMessage); + } + + static SQLiteException DatabaseFileNotFound(const std::string& dbFilePath) { + return SQLiteException(SQLiteExceptionType::SqlExecutionError, "Database file not found: " + dbFilePath); + } + + static SQLiteException CouldNotLoadFile(const std::string& fileLocation, std::optional additionalLine = std::nullopt) { + const auto message = "Could not load file: " + fileLocation + (additionalLine ? (". " + *additionalLine) : ""); + return SQLiteException(SQLiteExceptionType::CouldNotLoadFile, message); + } +}; diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp b/packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.cpp similarity index 90% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.cpp index fc2ce09a..158b3b7d 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.cpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.cpp @@ -1,9 +1,9 @@ /** * SQL Batch execution implementation using default sqliteBridge implementation */ -#include "NitroSQLiteExecuteBatch.hpp" -#include "NitroSQLiteException.hpp" -#include "NitroSQLiteOperations.hpp" +#include "SQLiteExecuteBatch.hpp" +#include "SQLiteException.hpp" +#include "SQLiteOperations.hpp" #include namespace margelo::nitro::rnnitrosqlite { @@ -42,7 +42,7 @@ std::vector batchParamsToCommands(const std::vector& commands) { std::lock_guard lock(connection->mutex); if (commands.empty()) { - throw NitroSQLiteException(NitroSQLiteExceptionType::NoBatchCommandsProvided, "No SQL batch commands provided"); + throw SQLiteException(SQLiteExceptionType::NoBatchCommandsProvided, "No SQL batch commands provided"); } try { diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.hpp similarity index 96% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.hpp index 25da2358..79b209d3 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteExecuteBatch.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteExecuteBatch.hpp @@ -3,7 +3,7 @@ */ #pragma once -#include "NitroSQLiteTypes.hpp" +#include "SQLiteTypes.hpp" #include #include diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.cpp b/packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.cpp similarity index 87% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.cpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.cpp index 8ee40330..926f29c5 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.cpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.cpp @@ -2,9 +2,9 @@ * SQL File Loader implementation */ -#include "NitroSQLiteImportSqlFile.hpp" -#include "NitroSQLiteException.hpp" -#include "NitroSQLiteOperations.hpp" +#include "SQLiteImportSqlFile.hpp" +#include "SQLiteException.hpp" +#include "SQLiteOperations.hpp" #include #include #include @@ -15,7 +15,7 @@ SQLiteOperationResult importSqlFile(const SQLiteConnectionPtr& connection, const std::lock_guard lock(connection->mutex); std::ifstream sqFile(fileLocation); if (!sqFile.is_open()) { - throw NitroSQLiteException::CouldNotLoadFile(fileLocation); + throw SQLiteException::CouldNotLoadFile(fileLocation); } int rowsAffected = 0; @@ -62,7 +62,7 @@ SQLiteOperationResult importSqlFile(const SQLiteConnectionPtr& connection, const } } - throw NitroSQLiteException::CouldNotLoadFile(fileLocation, errorContext); + throw SQLiteException::CouldNotLoadFile(fileLocation, errorContext); } } diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.hpp similarity index 95% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.hpp index 6c655b29..253abe2e 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.hpp @@ -6,7 +6,7 @@ #pragma once -#include "NitroSQLiteTypes.hpp" +#include "SQLiteTypes.hpp" #include namespace margelo::nitro::rnnitrosqlite { diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteLogs.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteLogs.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteMacros.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteMacros.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteMacros.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteMacros.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp b/packages/react-native-nitro-sqlite/cpp/SQLiteOperations.cpp similarity index 82% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteOperations.cpp index a831fc54..b90e5732 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteOperations.cpp @@ -1,8 +1,8 @@ -#include "NitroSQLiteOperations.hpp" -#include "NitroSQLiteException.hpp" -#include "NitroSQLiteStatementGroup.hpp" -#include "NitroSQLiteStatementTail.hpp" -#include "NitroSQLiteUtils.hpp" +#include "SQLiteOperations.hpp" +#include "SQLiteException.hpp" +#include "SQLiteStatementGroup.hpp" +#include "SQLiteStatementTail.hpp" +#include "SQLiteUtils.hpp" #include "sqlite/sqlite3.h" #include #include @@ -18,7 +18,7 @@ #ifdef NITRO_SQLITE_VEC // Angle-bracket so it resolves via -I (CocoaPods intercepts quoted includes). -#include +#include #endif using namespace facebook; @@ -41,8 +41,7 @@ void sqliteOpenDb(DatabaseConnections& connections, const std::string& dbName, c std::string sqliteOpenConnection(DatabaseConnections& connections, const std::string& dbName, const std::string& docPath, bool readOnly, const std::optional& encryptionKey) { if (sqlite3_threadsafe() == 0) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, - "Independent connections require a thread-safe SQLite build"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Independent connections require a thread-safe SQLite build"); } #ifdef NITRO_SQLITE_VEC margelo::rnnitrosqlitevec::registerVectorExtensions(); @@ -58,9 +57,9 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do try { sqliteExecuteCommand(connection, statement); - } catch (NitroSQLiteException& e) { - throw NitroSQLiteException(NitroSQLiteExceptionType::UnableToAttachToDatabase, - connection->name + " was unable to attach another database: " + std::string(e.what())); + } catch (SQLiteException& e) { + throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, + connection->name + " was unable to attach another database: " + std::string(e.what())); } } @@ -69,9 +68,9 @@ void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& al try { sqliteExecuteCommand(connection, statement); - } catch (NitroSQLiteException& e) { - throw NitroSQLiteException(NitroSQLiteExceptionType::UnableToAttachToDatabase, - connection->name + " was unable to detach database: " + std::string(e.what())); + } catch (SQLiteException& e) { + throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, + connection->name + " was unable to detach database: " + std::string(e.what())); } } @@ -114,8 +113,8 @@ void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { } if (bindStatus != SQLITE_OK) { - throw NitroSQLiteException::SqlExecution("Failed to bind parameter " + std::to_string(sqliteIndex) + " (SQLite error " + - std::to_string(bindStatus) + "): " + sqlite3_errstr(bindStatus)); + throw SQLiteException::SqlExecution("Failed to bind parameter " + std::to_string(sqliteIndex) + " (SQLite error " + + std::to_string(bindStatus) + "): " + sqlite3_errstr(bindStatus)); } } } @@ -139,18 +138,18 @@ namespace { SQLiteStatement statement(rawStatement); if (statementStatus != SQLITE_OK) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(db)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(db)); } // sqlite3_prepare_v2 reports SQLITE_OK with a null statement when the query holds no SQL, // such as an empty string or nothing but comments. if (!statement) { - throw NitroSQLiteException::SqlExecution("Query does not contain any SQL statement"); + throw SQLiteException::SqlExecution("Query does not contain any SQL statement"); } // Only the first statement would run, so reject the query instead of silently skipping the rest. if (hasTrailingStatement(db, tail)) { - throw NitroSQLiteException::SqlExecution("Query contains more than one SQL statement"); + throw SQLiteException::SqlExecution("Query contains more than one SQL statement"); } if (params) { @@ -212,7 +211,7 @@ namespace { return; } - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(db)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(db)); } } @@ -220,7 +219,7 @@ namespace { // and a smaller final batch shortens the conversion left after the statement completes. constexpr size_t kRowBatchSize = 256; - NitroSQLiteQueryResult executeStatement(sqlite3* db, sqlite3_stmt* statement, const SQLiteRowBatchHandler& onRows = nullptr) { + NativeQueryResult executeStatement(sqlite3* db, sqlite3_stmt* statement, const SQLiteRowBatchHandler& onRows = nullptr) { int columnCount = 0; std::vector columnNames; std::vector rows; @@ -233,7 +232,7 @@ namespace { for (int i = 0; i < columnCount; i++) { const char* columnName = sqlite3_column_name(statement, i); if (columnName == nullptr) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(db)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(db)); } columnNames.emplace_back(columnName); } @@ -260,7 +259,7 @@ namespace { case SQLITE_TEXT: { auto columnValue = reinterpret_cast(sqlite3_column_text(currentStatement, i)); if (columnValue == nullptr) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(db)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(db)); } int columnBytes = sqlite3_column_bytes(currentStatement, i); row.emplace_back(std::string(columnValue, static_cast(columnBytes))); @@ -301,7 +300,7 @@ namespace { for (int i = 0; i < columnCount; i++) { const std::string& columnName = columnNames[i]; ColumnType columnDeclaredType = mapSQLiteTypeToColumnType(sqlite3_column_decltype(statement, i)); - auto columnMeta = NitroSQLiteQueryColumnMetadata(columnName, std::move(columnDeclaredType), i); + auto columnMeta = QueryColumnMetadata(columnName, std::move(columnDeclaredType), i); if (!metadata) { metadata = std::make_optional(); @@ -309,19 +308,19 @@ namespace { metadata->insert({columnName, std::move(columnMeta)}); } - return NitroSQLiteQueryResult(sqlite3_changes(db), static_cast(sqlite3_last_insert_rowid(db)), - SQLiteQueryResults(std::move(columnNames), std::move(rows)), std::move(metadata), - static_cast(rowBatchCount)); + return NativeQueryResult(sqlite3_changes(db), static_cast(sqlite3_last_insert_rowid(db)), + SQLiteQueryResults(std::move(columnNames), std::move(rows)), std::move(metadata), + static_cast(rowBatchCount)); } } // namespace -NitroSQLiteQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params, const SQLiteRowBatchHandler& onRows) { +NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, + const std::optional& params, const SQLiteRowBatchHandler& onRows) { std::lock_guard lock(connection->mutex); sqlite3* db = connection->database; if (db == nullptr) { - throw NitroSQLiteException::DatabaseNotOpen(connection->name); + throw SQLiteException::DatabaseNotOpen(connection->name); } CachedStatement statement(*connection, query); @@ -336,7 +335,7 @@ SQLiteOperationResult sqliteExecuteCommand(const SQLiteConnectionPtr& connection std::lock_guard lock(connection->mutex); sqlite3* db = connection->database; if (db == nullptr) { - throw NitroSQLiteException::DatabaseNotOpen(connection->name); + throw SQLiteException::DatabaseNotOpen(connection->name); } auto statement = prepareStatement(db, query, params); @@ -356,14 +355,14 @@ SQLiteOperationResult sqliteExecuteCommandGroup(const SQLiteConnectionPtr& conne std::lock_guard lock(connection->mutex); sqlite3* db = connection->database; if (db == nullptr) { - throw NitroSQLiteException::DatabaseNotOpen(connection->name); + throw SQLiteException::DatabaseNotOpen(connection->name); } 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* database, sqlite3_stmt* statement) { consumeStatement(database, statement, [](sqlite3_stmt*) {}); }, - [](sqlite3* database) { throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); }); + [](sqlite3* database) { throw SQLiteException::SqlExecution(sqlite3_errmsg(database)); }); return {.rowsAffected = rowsAffected, .commands = commands}; } @@ -381,27 +380,27 @@ SQLitePreparedStatement::~SQLitePreparedStatement() { finalize(); } -NitroSQLiteQueryResult SQLitePreparedStatement::execute(const std::optional& params) { +NativeQueryResult SQLitePreparedStatement::execute(const std::optional& params) { std::lock_guard lock(_state->mutex); std::lock_guard connectionLock(_state->connection->mutex); if (!_state->statement) { - throw NitroSQLiteException("Prepared statement has been finalized"); + throw SQLiteException("Prepared statement has been finalized"); } sqlite3* database = _state->connection->database; if (database == nullptr) { - throw NitroSQLiteException("Prepared statement belongs to a closed database connection"); + throw SQLiteException("Prepared statement belongs to a closed database connection"); } int resetStatus = sqlite3_reset(_state->statement.get()); if (resetStatus != SQLITE_OK) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(database)); } int clearBindingsStatus = sqlite3_clear_bindings(_state->statement.get()); if (clearBindingsStatus != SQLITE_OK) { - throw NitroSQLiteException::SqlExecution(sqlite3_errmsg(database)); + throw SQLiteException::SqlExecution(sqlite3_errmsg(database)); } if (params) { @@ -434,7 +433,7 @@ size_t SQLitePreparedStatement::getExternalMemorySize() const noexcept { std::shared_ptr sqlitePrepare(const SQLiteConnectionPtr& connection, const std::string& query) { std::lock_guard lock(connection->mutex); if (connection->database == nullptr) { - throw NitroSQLiteException::DatabaseNotOpen(connection->name); + throw SQLiteException::DatabaseNotOpen(connection->name); } auto statement = prepareStatement(connection->database, query, std::nullopt); diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteOperations.hpp similarity index 88% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteOperations.hpp index ddf6b1f1..50abea51 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteOperations.hpp @@ -1,8 +1,8 @@ #pragma once -#include "NitroSQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseConnections.hpp" #include "sqlite/sqlite3.h" -#include +#include #include #include #include @@ -25,7 +25,7 @@ class SQLitePreparedStatement { ~SQLitePreparedStatement(); /** Reset and execute with new bindings. Throws after finalization or connection closure. */ - NitroSQLiteQueryResult execute(const std::optional& params); + NativeQueryResult execute(const std::optional& params); /** Release the native statement. Repeated calls are safe. */ void finalize(); /** Check whether the native statement has been released. */ @@ -57,8 +57,8 @@ void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& al * returned result holds only the rows after the last batch. Its rowBatchCount reports how many * batches were sent; JavaScript delivery may still be pending when this function returns. */ -NitroSQLiteQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, - const std::optional& params, const SQLiteRowBatchHandler& onRows = nullptr); +NativeQueryResult sqliteExecute(const SQLiteConnectionPtr& connection, const std::string& query, + const std::optional& params, const SQLiteRowBatchHandler& onRows = nullptr); SQLiteOperationResult sqliteExecuteCommand(const SQLiteConnectionPtr& connection, const std::string& query, const std::optional& params = std::nullopt); diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.hpp similarity index 98% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.hpp index e12712c9..7e3e7a92 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.hpp @@ -1,6 +1,6 @@ #pragma once -#include "NitroSQLiteTypes.hpp" +#include "SQLiteTypes.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteStatementCache.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteStatementCache.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteStatementGroup.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteStatementGroup.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteTypes.hpp similarity index 92% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteTypes.hpp index 8b81b2af..e7a52208 100644 --- a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp +++ b/packages/react-native-nitro-sqlite/cpp/SQLiteTypes.hpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include #include @@ -14,7 +14,7 @@ namespace margelo::nitro::rnnitrosqlite { using SQLiteValue = std::optional>; using SQLiteQueryParams = std::vector; -using SQLiteQueryTableMetadata = std::unordered_map; +using SQLiteQueryTableMetadata = std::unordered_map; struct SQLiteOperationResult { int rowsAffected; diff --git a/packages/react-native-nitro-sqlite/cpp/NitroSQLiteUtils.hpp b/packages/react-native-nitro-sqlite/cpp/SQLiteUtils.hpp similarity index 100% rename from packages/react-native-nitro-sqlite/cpp/NitroSQLiteUtils.hpp rename to packages/react-native-nitro-sqlite/cpp/SQLiteUtils.hpp diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp index ae537aad..9484edd4 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -1,11 +1,11 @@ #include "HybridNitroSQLite.hpp" -#include "../NitroSQLiteDatabaseMigration.hpp" -#include "../NitroSQLiteException.hpp" -#include "../NitroSQLiteExecuteBatch.hpp" -#include "../NitroSQLiteImportSqlFile.hpp" -#include "../NitroSQLiteLogs.hpp" -#include "../NitroSQLiteMacros.hpp" -#include "../NitroSQLiteOperations.hpp" +#include "../SQLiteDatabaseMigration.hpp" +#include "../SQLiteException.hpp" +#include "../SQLiteExecuteBatch.hpp" +#include "../SQLiteImportSqlFile.hpp" +#include "../SQLiteLogs.hpp" +#include "../SQLiteMacros.hpp" +#include "../SQLiteOperations.hpp" #include "HybridPreparedStatement.hpp" #include #include @@ -113,7 +113,7 @@ static Promise enqueueConnectionOperation(const SQLiteConnectionPtr& con const std::string getDocPath(const std::string& databaseDirectory, const std::optional& location) { if (location && location->find('\0') != std::string::npos) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, "Database location contains a NUL byte"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database location contains a NUL byte"); } std::string tempDocPath = databaseDirectory; if (location) { @@ -160,7 +160,7 @@ void HybridNitroSQLite::open(const std::string& dbName, const std::optional& readOnly, const std::optional& encryptionKey) { validateDatabaseName(dbName); if (sqlite3_threadsafe() == 0) { - throw NitroSQLiteException(NitroSQLiteExceptionType::DatabaseCannotBeOpened, - "Independent connections require a thread-safe SQLite build"); + throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Independent connections require a thread-safe SQLite build"); } std::lock_guard lock(_connections.lifecycleMutex); const auto docPath = @@ -221,7 +220,7 @@ void HybridNitroSQLite::attach(const std::string& mainDbName, const std::string& validateDatabaseName(dbNameToAttach); std::lock_guard lock(_connections.lifecycleMutex); if (_connections.get(mainDbName)->readOnly) { - throw NitroSQLiteException(NitroSQLiteExceptionType::UnableToAttachToDatabase, "Cannot attach a database to a read-only connection"); + throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, "Cannot attach a database to a read-only connection"); } const auto attachedDocPath = getMigratedDocPath(_connections, _databaseDirectory, _legacyDatabaseDirectory, dbNameToAttach, location); sqliteAttachDb(_connections.get(mainDbName), attachedDocPath, dbNameToAttach, alias); @@ -231,20 +230,20 @@ void HybridNitroSQLite::detach(const std::string& mainDbName, const std::string& sqliteDetachDb(_connections.get(mainDbName), alias); }; -NitroSQLiteQueryResult HybridNitroSQLite::execute(const std::string& dbName, const std::string& query, - const std::optional& params) { +NativeQueryResult HybridNitroSQLite::execute(const std::string& dbName, const std::string& query, + const std::optional& params) { return sqliteExecute(_connections.get(dbName), query, params); }; -Promise HybridNitroSQLite::executeAsync(const std::string& dbName, const std::string& query, - const std::optional& params, - const std::optional>& onRows) { +Promise HybridNitroSQLite::executeAsync(const std::string& dbName, const std::string& query, + const std::optional& params, + const std::optional>& onRows) { const auto copiedParams = copyArrayBufferParamsForBackground(params); SQLiteConnectionPtr connection; try { connection = _connections.get(dbName); } catch (...) { - return Promise::rejected(std::current_exception()); + return Promise::rejected(std::current_exception()); } SQLiteRowBatchHandler rowBatchHandler = nullptr; @@ -252,10 +251,10 @@ Promise HybridNitroSQLite::executeAsync(const std::strin rowBatchHandler = [onRows = *onRows](SQLiteQueryResults rows) { onRows(std::move(rows)); }; } - return enqueueConnectionOperation(connection, - [connection, query, copiedParams, rowBatchHandler]() -> NitroSQLiteQueryResult { - return sqliteExecute(connection, query, copiedParams, rowBatchHandler); - }); + return enqueueConnectionOperation(connection, + [connection, query, copiedParams, rowBatchHandler]() -> NativeQueryResult { + return sqliteExecute(connection, query, copiedParams, rowBatchHandler); + }); }; std::shared_ptr HybridNitroSQLite::prepare(const std::string& dbName, const std::string& query) { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp index 1dbbdcb5..2a20fe74 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridNitroSQLite.hpp @@ -1,7 +1,7 @@ #pragma once -#include "../NitroSQLiteDatabaseConnections.hpp" -#include "../NitroSQLiteTypes.hpp" +#include "../SQLiteDatabaseConnections.hpp" +#include "../SQLiteTypes.hpp" #include #include @@ -68,15 +68,14 @@ class HybridNitroSQLite : public HybridNitroSQLiteSpec { * @param params Optional values bound to the placeholders. * @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; + NativeQueryResult execute(const std::string& dbName, const std::string& query, const std::optional& params) override; /** Execute one SQL statement on a background thread. * @return A promise of the native query result. */ - Promise executeAsync(const std::string& dbName, const std::string& query, - const std::optional& params, - const std::optional>& onRows) override; + Promise executeAsync(const std::string& dbName, const std::string& query, + const std::optional& params, + const std::optional>& onRows) 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/HybridPreparedStatement.cpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.cpp index 75f42151..c9b505dd 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.cpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.cpp @@ -28,16 +28,15 @@ namespace { HybridPreparedStatement::HybridPreparedStatement(std::shared_ptr statement) : _statement(std::move(statement)) {} -NitroSQLiteQueryResult HybridPreparedStatement::execute(const std::optional& params) { +NativeQueryResult HybridPreparedStatement::execute(const std::optional& params) { return _statement->execute(params); } -Promise HybridPreparedStatement::executeAsync(const std::optional& params) { +Promise HybridPreparedStatement::executeAsync(const std::optional& params) { const auto copiedParams = copyArrayBufferParamsForBackground(params); const auto statement = _statement; - return Promise::async( - [statement, copiedParams]() -> NitroSQLiteQueryResult { return statement->execute(copiedParams); }); + return Promise::async([statement, copiedParams]() -> NativeQueryResult { return statement->execute(copiedParams); }); } void HybridPreparedStatement::finalize() { diff --git a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.hpp b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.hpp index d9ade2ae..4eaf6173 100644 --- a/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.hpp +++ b/packages/react-native-nitro-sqlite/cpp/hybridObjects/HybridPreparedStatement.hpp @@ -1,7 +1,7 @@ #pragma once -#include "../NitroSQLiteOperations.hpp" -#include "../NitroSQLiteTypes.hpp" +#include "../SQLiteOperations.hpp" +#include "../SQLiteTypes.hpp" #include #include @@ -14,9 +14,9 @@ class HybridPreparedStatement : public HybridPreparedStatementSpec { explicit HybridPreparedStatement(std::shared_ptr statement); /** Execute with new bindings on the calling thread. */ - NitroSQLiteQueryResult execute(const std::optional& params) override; + NativeQueryResult execute(const std::optional& params) override; /** Execute with new bindings on a background thread. */ - Promise executeAsync(const std::optional& params) override; + Promise executeAsync(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/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake index a5e23273..e6b99247 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/RNNitroSQLite+autolinking.cmake @@ -21,8 +21,8 @@ target_sources(RNNitroSQLite PRIVATE "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/FileLoadResult.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridNitroSQLiteSpec.cpp" "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/HybridPreparedStatementSpec.cpp" - "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NitroSQLiteQueryColumnMetadata.cpp" - "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NitroSQLiteQueryResult.cpp" + "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/NativeQueryResult.cpp" + "${CMAKE_CURRENT_LIST_DIR}/../shared/c++/QueryColumnMetadata.cpp" ) find_package(fbjni REQUIRED CONFIG) diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp index abf341a0..2b49d955 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridNitroSQLiteSpecClass.cpp @@ -8,13 +8,13 @@ #include #include #include -#include +#include #include #include #include #include #include -#include "NitroSQLiteQueryResults.hpp" +#include "SQLiteQueryResults.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp index bd45d58e..26121cbd 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/android/c++/HybridPreparedStatementSpecClass.cpp @@ -6,7 +6,7 @@ /// #include -#include +#include #include #include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridNitroSQLiteSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridNitroSQLiteSpecClass.cpp index abf341a0..2b49d955 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridNitroSQLiteSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridNitroSQLiteSpecClass.cpp @@ -8,13 +8,13 @@ #include #include #include -#include +#include #include #include #include #include #include -#include "NitroSQLiteQueryResults.hpp" +#include "SQLiteQueryResults.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridPreparedStatementSpecClass.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridPreparedStatementSpecClass.cpp index bd45d58e..26121cbd 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridPreparedStatementSpecClass.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/ios/c++/HybridPreparedStatementSpecClass.cpp @@ -6,7 +6,7 @@ /// #include -#include +#include #include #include #include diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryResult.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeQueryResult.cpp similarity index 69% rename from packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryResult.cpp rename to packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeQueryResult.cpp index 71eadeaa..5fe55030 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryResult.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NativeQueryResult.cpp @@ -1,43 +1,43 @@ /// -/// NitroSQLiteQueryResult.cpp +/// NativeQueryResult.cpp /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. /// https://github.com/margelo/nitro /// Copyright © Marc Rousavy @ Margelo /// -#include +#include #include #include #include -#include "NitroSQLiteQueryResults.hpp" +#include "SQLiteQueryResults.hpp" #include -#include +#include #include namespace margelo::nitro { - margelo::nitro::rnnitrosqlite::NitroSQLiteQueryResult JSIConverter::fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + margelo::nitro::rnnitrosqlite::NativeQueryResult JSIConverter::fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { jsi::Object obj = arg.asObject(runtime); - return margelo::nitro::rnnitrosqlite::NitroSQLiteQueryResult( + return margelo::nitro::rnnitrosqlite::NativeQueryResult( JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "insertId"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "results"))), - JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata"))), + JSIConverter>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata"))), JSIConverter>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowBatchCount"))) ); } - jsi::Value JSIConverter::toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NitroSQLiteQueryResult& arg) { + jsi::Value JSIConverter::toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NativeQueryResult& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected"), JSIConverter::toJSI(runtime, arg.rowsAffected)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "insertId"), JSIConverter>::toJSI(runtime, arg.insertId)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "results"), JSIConverter::toJSI(runtime, arg.results)); - obj.setProperty(runtime, PropNameIDCache::get(runtime, "metadata"), JSIConverter>>::toJSI(runtime, arg.metadata)); + obj.setProperty(runtime, PropNameIDCache::get(runtime, "metadata"), JSIConverter>>::toJSI(runtime, arg.metadata)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "rowBatchCount"), JSIConverter>::toJSI(runtime, arg.rowBatchCount)); return obj; } - bool JSIConverter::canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + bool JSIConverter::canConvert(jsi::Runtime& runtime, const jsi::Value& value) { if (!value.isObject()) { return false; } @@ -48,7 +48,7 @@ namespace margelo::nitro { if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowsAffected")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "insertId")))) return false; if (!JSIConverter::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "results")))) return false; - if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata")))) return false; + if (!JSIConverter>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "metadata")))) return false; if (!JSIConverter>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "rowBatchCount")))) return false; return true; } diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryColumnMetadata.cpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/QueryColumnMetadata.cpp similarity index 72% rename from packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryColumnMetadata.cpp rename to packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/QueryColumnMetadata.cpp index 073cde76..5e01ec09 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryColumnMetadata.cpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/QueryColumnMetadata.cpp @@ -1,11 +1,11 @@ /// -/// NitroSQLiteQueryColumnMetadata.cpp +/// QueryColumnMetadata.cpp /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. /// https://github.com/margelo/nitro /// Copyright © Marc Rousavy @ Margelo /// -#include +#include #include #include #include @@ -13,16 +13,16 @@ namespace margelo::nitro { - margelo::nitro::rnnitrosqlite::NitroSQLiteQueryColumnMetadata JSIConverter::fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { + margelo::nitro::rnnitrosqlite::QueryColumnMetadata JSIConverter::fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) { jsi::Object obj = arg.asObject(runtime); - return margelo::nitro::rnnitrosqlite::NitroSQLiteQueryColumnMetadata( + return margelo::nitro::rnnitrosqlite::QueryColumnMetadata( JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "name"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "type"))), JSIConverter::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "index"))) ); } - jsi::Value JSIConverter::toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NitroSQLiteQueryColumnMetadata& arg) { + jsi::Value JSIConverter::toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::QueryColumnMetadata& arg) { jsi::Object obj(runtime); obj.setProperty(runtime, PropNameIDCache::get(runtime, "name"), JSIConverter::toJSI(runtime, arg.name)); obj.setProperty(runtime, PropNameIDCache::get(runtime, "type"), JSIConverter::toJSI(runtime, arg.type)); @@ -30,7 +30,7 @@ namespace margelo::nitro { return obj; } - bool JSIConverter::canConvert(jsi::Runtime& runtime, const jsi::Value& value) { + bool JSIConverter::canConvert(jsi::Runtime& runtime, const jsi::Value& value) { if (!value.isObject()) { return false; } diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp index 8a92174f..2c21464a 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridNitroSQLiteSpec.hpp @@ -11,13 +11,13 @@ #include #include #include -#include +#include #include #include #include #include #include -#include "NitroSQLiteQueryResults.hpp" +#include "SQLiteQueryResults.hpp" #include #include #include @@ -71,8 +71,8 @@ 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>>>& params) = 0; - virtual Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional>& onRows) = 0; + virtual NativeQueryResult execute(const std::string& dbName, const std::string& query, const std::optional>>>& params) = 0; + virtual Promise executeAsync(const std::string& dbName, const std::string& query, const std::optional>>>& params, const std::optional>& onRows) = 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 Promise executeBatchAsync(const std::string& dbName, const std::vector& commands) = 0; diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp index 7bcc0aeb..543bcf53 100644 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/HybridPreparedStatementSpec.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -55,8 +55,8 @@ namespace margelo::nitro::rnnitrosqlite { public: // Methods - virtual NitroSQLiteQueryResult execute(const std::optional>>>& params) = 0; - virtual Promise executeAsync(const std::optional>>>& params) = 0; + virtual NativeQueryResult execute(const std::optional>>>& params) = 0; + virtual Promise executeAsync(const std::optional>>>& params) = 0; virtual void finalize() = 0; protected: diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeQueryResult.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeQueryResult.hpp new file mode 100644 index 00000000..adc9b68f --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeQueryResult.hpp @@ -0,0 +1,51 @@ +/// +/// NativeQueryResult.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include +#include +#include "SQLiteQueryResults.hpp" +#include +#include +#include +#include + +namespace margelo::nitro::rnnitrosqlite { + + /** + * A struct which can be represented as a JavaScript object (NativeQueryResult). + */ + struct NativeQueryResult final { + public: + double rowsAffected SWIFT_PRIVATE; + std::optional insertId SWIFT_PRIVATE; + margelo::nitro::rnnitrosqlite::SQLiteQueryResults results SWIFT_PRIVATE; + std::optional> metadata SWIFT_PRIVATE; + std::optional rowBatchCount SWIFT_PRIVATE; + + public: + explicit NativeQueryResult(double rowsAffected, std::optional insertId, margelo::nitro::rnnitrosqlite::SQLiteQueryResults results, std::optional> metadata, std::optional rowBatchCount): rowsAffected(rowsAffected), insertId(std::move(insertId)), results(results), metadata(std::move(metadata)), rowBatchCount(std::move(rowBatchCount)) {} + + public: + // NativeQueryResult is not equatable because these properties are not equatable: results + }; + +} // namespace margelo::nitro::rnnitrosqlite + +namespace margelo::nitro { + + // C++ NativeQueryResult <> JS NativeQueryResult (object) + template <> + struct JSIConverter final { + static margelo::nitro::rnnitrosqlite::NativeQueryResult fromJSI(jsi::Runtime& runtime, const jsi::Value& arg); + static jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NativeQueryResult& arg); + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value); + }; + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryColumnMetadata.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryColumnMetadata.hpp deleted file mode 100644 index ee839e00..00000000 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryColumnMetadata.hpp +++ /dev/null @@ -1,46 +0,0 @@ -/// -/// NitroSQLiteQueryColumnMetadata.hpp -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/margelo/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -#pragma once - -#include -#include -#include -#include -#include - -namespace margelo::nitro::rnnitrosqlite { - - /** - * A struct which can be represented as a JavaScript object (NitroSQLiteQueryColumnMetadata). - */ - struct NitroSQLiteQueryColumnMetadata final { - public: - std::string name SWIFT_PRIVATE; - ColumnType type SWIFT_PRIVATE; - double index SWIFT_PRIVATE; - - public: - explicit NitroSQLiteQueryColumnMetadata(std::string name, ColumnType type, double index): name(std::move(name)), type(type), index(index) {} - - public: - friend bool operator==(const NitroSQLiteQueryColumnMetadata& lhs, const NitroSQLiteQueryColumnMetadata& rhs) = default; - }; - -} // namespace margelo::nitro::rnnitrosqlite - -namespace margelo::nitro { - - // C++ NitroSQLiteQueryColumnMetadata <> JS NitroSQLiteQueryColumnMetadata (object) - template <> - struct JSIConverter final { - static margelo::nitro::rnnitrosqlite::NitroSQLiteQueryColumnMetadata fromJSI(jsi::Runtime& runtime, const jsi::Value& arg); - static jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NitroSQLiteQueryColumnMetadata& arg); - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value); - }; - -} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryResult.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryResult.hpp deleted file mode 100644 index bbef148e..00000000 --- a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NitroSQLiteQueryResult.hpp +++ /dev/null @@ -1,51 +0,0 @@ -/// -/// NitroSQLiteQueryResult.hpp -/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. -/// https://github.com/margelo/nitro -/// Copyright © Marc Rousavy @ Margelo -/// - -#pragma once - -#include -#include -#include -#include "NitroSQLiteQueryResults.hpp" -#include -#include -#include -#include - -namespace margelo::nitro::rnnitrosqlite { - - /** - * A struct which can be represented as a JavaScript object (NitroSQLiteQueryResult). - */ - struct NitroSQLiteQueryResult final { - public: - double rowsAffected SWIFT_PRIVATE; - std::optional insertId SWIFT_PRIVATE; - margelo::nitro::rnnitrosqlite::SQLiteQueryResults results SWIFT_PRIVATE; - std::optional> metadata SWIFT_PRIVATE; - std::optional rowBatchCount SWIFT_PRIVATE; - - public: - explicit NitroSQLiteQueryResult(double rowsAffected, std::optional insertId, margelo::nitro::rnnitrosqlite::SQLiteQueryResults results, std::optional> metadata, std::optional rowBatchCount): rowsAffected(rowsAffected), insertId(std::move(insertId)), results(results), metadata(std::move(metadata)), rowBatchCount(std::move(rowBatchCount)) {} - - public: - // NitroSQLiteQueryResult is not equatable because these properties are not equatable: results - }; - -} // namespace margelo::nitro::rnnitrosqlite - -namespace margelo::nitro { - - // C++ NitroSQLiteQueryResult <> JS NitroSQLiteQueryResult (object) - template <> - struct JSIConverter final { - static margelo::nitro::rnnitrosqlite::NitroSQLiteQueryResult fromJSI(jsi::Runtime& runtime, const jsi::Value& arg); - static jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::NitroSQLiteQueryResult& arg); - static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value); - }; - -} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/QueryColumnMetadata.hpp b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/QueryColumnMetadata.hpp new file mode 100644 index 00000000..bc644b28 --- /dev/null +++ b/packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/QueryColumnMetadata.hpp @@ -0,0 +1,46 @@ +/// +/// QueryColumnMetadata.hpp +/// This file was generated by nitrogen. DO NOT MODIFY THIS FILE. +/// https://github.com/margelo/nitro +/// Copyright © Marc Rousavy @ Margelo +/// + +#pragma once + +#include +#include +#include +#include +#include + +namespace margelo::nitro::rnnitrosqlite { + + /** + * A struct which can be represented as a JavaScript object (QueryColumnMetadata). + */ + struct QueryColumnMetadata final { + public: + std::string name SWIFT_PRIVATE; + ColumnType type SWIFT_PRIVATE; + double index SWIFT_PRIVATE; + + public: + explicit QueryColumnMetadata(std::string name, ColumnType type, double index): name(std::move(name)), type(type), index(index) {} + + public: + friend bool operator==(const QueryColumnMetadata& lhs, const QueryColumnMetadata& rhs) = default; + }; + +} // namespace margelo::nitro::rnnitrosqlite + +namespace margelo::nitro { + + // C++ QueryColumnMetadata <> JS QueryColumnMetadata (object) + template <> + struct JSIConverter final { + static margelo::nitro::rnnitrosqlite::QueryColumnMetadata fromJSI(jsi::Runtime& runtime, const jsi::Value& arg); + static jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::rnnitrosqlite::QueryColumnMetadata& arg); + static bool canConvert(jsi::Runtime& runtime, const jsi::Value& value); + }; + +} // namespace margelo::nitro diff --git a/packages/react-native-nitro-sqlite/src/DatabaseQueue.ts b/packages/react-native-nitro-sqlite/src/DatabaseQueue.ts index 3e47c224..fddd1f2b 100644 --- a/packages/react-native-nitro-sqlite/src/DatabaseQueue.ts +++ b/packages/react-native-nitro-sqlite/src/DatabaseQueue.ts @@ -1,4 +1,4 @@ -import NitroSQLiteError from './NitroSQLiteError' +import SQLiteError from './SQLiteError' export interface QueuedOperation { kind: 'statement' | 'exclusive' @@ -24,7 +24,7 @@ const databaseQueues = new Map() export function openDatabaseQueue(dbName: DatabaseQueueKey) { if (isDatabaseOpen(dbName)) { - throw new NitroSQLiteError( + throw new SQLiteError( `Database ${String(dbName)} is already open. There is already a connection to the database.`, ) } @@ -41,7 +41,7 @@ export function closeDatabaseQueue(dbName: DatabaseQueueKey) { const databaseQueue = getDatabaseQueue(dbName) if (databaseQueue.inProgress || databaseQueue.queue.length > 0) { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot close database ${String(dbName)}. The database is busy with another operation.`, ) } @@ -55,7 +55,7 @@ export function isDatabaseOpen(dbName: DatabaseQueueKey) { export function throwIfDatabaseIsNotOpen(dbName: DatabaseQueueKey) { if (!isDatabaseOpen(dbName)) - throw new NitroSQLiteError( + throw new SQLiteError( `Database ${String(dbName)} is not open. There is no connection to the database.`, ) } @@ -159,7 +159,7 @@ export function startOperationSync( // Database is busy - cannot execute synchronously if (databaseQueue.inProgress || databaseQueue.queue.length > 0) { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot run synchronous operation on database. Database ${String(dbName)} is busy with another operation.`, ) } diff --git a/packages/react-native-nitro-sqlite/src/NitroSQLiteError.ts b/packages/react-native-nitro-sqlite/src/SQLiteError.ts similarity index 65% rename from packages/react-native-nitro-sqlite/src/NitroSQLiteError.ts rename to packages/react-native-nitro-sqlite/src/SQLiteError.ts index 0d120228..0e12fb39 100644 --- a/packages/react-native-nitro-sqlite/src/NitroSQLiteError.ts +++ b/packages/react-native-nitro-sqlite/src/SQLiteError.ts @@ -1,14 +1,14 @@ -const NITRO_SQLITE_ERROR_NAME = 'NitroSQLiteError' as const +const SQLITE_ERROR_NAME = 'NitroSQLiteError' as const const NATIVE_EXCEPTION_PREFIX = '[NativeNitroSQLiteException][' /** - * Native error categories exposed by {@linkcode NitroSQLiteError.type}. + * Native error categories exposed by {@linkcode SQLiteError.type}. * Compare against these constants when handling a specific failure. The values * are categories, not SQLite's numeric result codes. Import them from * `react-native-nitro-sqlite/errors` to avoid initializing the native module. - * @see {@linkcode NitroSQLiteError} + * @see {@linkcode SQLiteError} */ -export const NitroSQLiteExceptionType = { +export const SQLiteExceptionType = { /** Native failure without a more specific category. */ UnknownError: 'UnknownError', /** Open failure, including invalid paths and an already-open default connection. */ @@ -30,59 +30,59 @@ export const NitroSQLiteExceptionType = { } as const /** - * Category attached to {@linkcode NitroSQLiteError.type} for a recognized native - * failure. The corresponding {@linkcode NitroSQLiteExceptionType} object exposes + * Category attached to {@linkcode SQLiteError.type} for a recognized native + * failure. The corresponding {@linkcode SQLiteExceptionType} object exposes * the same values at runtime. - * @see {@linkcode NitroSQLiteError.type} + * @see {@linkcode SQLiteError.type} */ -export type NitroSQLiteExceptionType = - (typeof NitroSQLiteExceptionType)[keyof typeof NitroSQLiteExceptionType] +export type SQLiteExceptionType = + (typeof SQLiteExceptionType)[keyof typeof SQLiteExceptionType] /** Error thrown by managed NitroSQLite operations. Native errors are wrapped with this class. */ -export default class NitroSQLiteError extends Error { +export default class SQLiteError extends Error { /** - * Recognized native category from {@linkcode NitroSQLiteExceptionType}, or + * Recognized native category from {@linkcode SQLiteExceptionType}, or * `undefined` for JavaScript failures and unrecognized native categories. */ - readonly type: NitroSQLiteExceptionType | undefined + readonly type: SQLiteExceptionType | undefined /** Create an error with a message and optional cause. */ constructor(message: string, options?: ErrorOptions) { super(message, options) - this.name = NITRO_SQLITE_ERROR_NAME + this.name = SQLITE_ERROR_NAME this.type = getNativeExceptionType(message) // Maintains proper prototype chain for instanceof checks - Object.setPrototypeOf(this, NitroSQLiteError.prototype) + Object.setPrototypeOf(this, SQLiteError.prototype) } - /** Convert an unknown thrown value to `NitroSQLiteError`. + /** Convert an unknown thrown value to `SQLiteError`. * Existing instances pass through; `Error` values keep their stack and cause. * @param error Value to normalize. - * @returns A NitroSQLiteError instance. + * @returns A SQLiteError instance. */ - static fromError(error: unknown): NitroSQLiteError { - if (error instanceof NitroSQLiteError) { + static fromError(error: unknown): SQLiteError { + if (error instanceof SQLiteError) { return error } if (error instanceof Error) { - const nitroSQLiteError = new NitroSQLiteError(error.message, { + const sqliteError = new SQLiteError(error.message, { cause: error.cause, }) // Preserve original stack trace if available if (error.stack) { - nitroSQLiteError.stack = error.stack + sqliteError.stack = error.stack } - return nitroSQLiteError + return sqliteError } if (typeof error === 'string') { - return new NitroSQLiteError(error) + return new SQLiteError(error) } - return new NitroSQLiteError('Unknown error occurred', { + return new SQLiteError('Unknown error occurred', { cause: error, }) } @@ -90,7 +90,7 @@ export default class NitroSQLiteError extends Error { function getNativeExceptionType( message: string, -): NitroSQLiteExceptionType | undefined { +): SQLiteExceptionType | undefined { const prefixStart = message.indexOf(NATIVE_EXCEPTION_PREFIX) if (prefixStart === -1) return undefined @@ -99,5 +99,5 @@ function getNativeExceptionType( if (typeEnd === -1) return undefined const type = message.slice(typeStart, typeEnd) - return Object.values(NitroSQLiteExceptionType).find((value) => value === type) + return Object.values(SQLiteExceptionType).find((value) => value === type) } diff --git a/packages/react-native-nitro-sqlite/src/__tests__/DatabaseQueue.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/DatabaseQueue.test.ts index 35886ac6..31fe4ff3 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/DatabaseQueue.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/DatabaseQueue.test.ts @@ -8,7 +8,7 @@ import { startOperationSync, throwIfDatabaseIsNotOpen, } from '../DatabaseQueue' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import { deferred } from './testUtils' const dbName = 'queue-test' @@ -20,7 +20,7 @@ afterEach(() => { describe('DatabaseQueue', () => { it('tracks open connections and rejects duplicate or missing connections', () => { expect(isDatabaseOpen(dbName)).toBe(false) - expect(() => throwIfDatabaseIsNotOpen(dbName)).toThrow(NitroSQLiteError) + expect(() => throwIfDatabaseIsNotOpen(dbName)).toThrow(SQLiteError) expect(() => getDatabaseQueue(dbName)).toThrow('not open') expect(() => closeDatabaseQueue(dbName)).toThrow('not open') diff --git a/packages/react-native-nitro-sqlite/src/__tests__/NitroSQLiteError.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/SQLiteError.test.ts similarity index 66% rename from packages/react-native-nitro-sqlite/src/__tests__/NitroSQLiteError.test.ts rename to packages/react-native-nitro-sqlite/src/__tests__/SQLiteError.test.ts index 82d41367..7c5c2ade 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/NitroSQLiteError.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/SQLiteError.test.ts @@ -2,33 +2,44 @@ jest.mock('react-native-nitro-modules', () => { throw new Error('The errors entry point must not load the native runtime') }) -import { NitroSQLiteError, NitroSQLiteExceptionType } from '../errors' +import { + SQLiteError, + SQLiteExceptionType, + NitroSQLiteError, + NitroSQLiteExceptionType, +} from '../errors' + +describe('SQLiteError', () => { + it('preserves the legacy error constructor and category exports', () => { + expect(NitroSQLiteError).toBe(SQLiteError) + expect(NitroSQLiteExceptionType).toBe(SQLiteExceptionType) + expect(new SQLiteError('query failed')).toBeInstanceOf(NitroSQLiteError) + }) -describe('NitroSQLiteError', () => { it('keeps its name, cause, and prototype', () => { const cause = new Error('underlying') - const error = new NitroSQLiteError('query failed', { cause }) + const error = new SQLiteError('query failed', { cause }) expect(error).toBeInstanceOf(Error) - expect(error).toBeInstanceOf(NitroSQLiteError) + expect(error).toBeInstanceOf(SQLiteError) expect(error.name).toBe('NitroSQLiteError') expect(error.cause).toBe(cause) expect(error.type).toBeUndefined() }) it('supports comparing a native failure against the exported category', () => { - const error = NitroSQLiteError.fromError( + const error = SQLiteError.fromError( '[NativeNitroSQLiteException][DatabaseCannotBeOpened] failed', ) - const category: NitroSQLiteExceptionType = - NitroSQLiteExceptionType.DatabaseCannotBeOpened + const category: SQLiteExceptionType = + SQLiteExceptionType.DatabaseCannotBeOpened expect(error.type).toBe(category) }) - it('returns an existing NitroSQLiteError unchanged', () => { - const error = new NitroSQLiteError('existing') - expect(NitroSQLiteError.fromError(error)).toBe(error) + it('returns an existing SQLiteError unchanged', () => { + const error = new SQLiteError('existing') + expect(SQLiteError.fromError(error)).toBe(error) }) it('converts an Error while preserving its cause and stack', () => { @@ -36,9 +47,9 @@ describe('NitroSQLiteError', () => { const original = new Error('native failure', { cause }) original.stack = 'original stack' - const converted = NitroSQLiteError.fromError(original) + const converted = SQLiteError.fromError(original) - expect(converted).toBeInstanceOf(NitroSQLiteError) + expect(converted).toBeInstanceOf(SQLiteError) expect(converted.message).toBe('native failure') expect(converted.cause).toBe(cause) expect(converted.stack).toBe('original stack') @@ -47,13 +58,13 @@ describe('NitroSQLiteError', () => { it('converts an Error without a stack', () => { const original = new Error('no stack') original.stack = undefined - expect(NitroSQLiteError.fromError(original).message).toBe('no stack') + expect(SQLiteError.fromError(original).message).toBe('no stack') }) it('converts strings and retains unknown values as causes', () => { - expect(NitroSQLiteError.fromError('failure').message).toBe('failure') + expect(SQLiteError.fromError('failure').message).toBe('failure') const value = { code: 42 } - const converted = NitroSQLiteError.fromError(value) + const converted = SQLiteError.fromError(value) expect(converted.message).toBe('Unknown error occurred') expect(converted.cause).toBe(value) }) @@ -74,7 +85,7 @@ describe('NitroSQLiteError', () => { ) original.stack = 'native stack' - const converted = NitroSQLiteError.fromError(original) + const converted = SQLiteError.fromError(original) expect(converted.type).toBe(type) expect(converted.message).toBe(original.message) @@ -82,7 +93,7 @@ describe('NitroSQLiteError', () => { }) it('does not assign a native category for unrecognized exception types', () => { - const error = NitroSQLiteError.fromError( + const error = SQLiteError.fromError( '[NativeNitroSQLiteException][FutureError] failed', ) @@ -93,7 +104,7 @@ describe('NitroSQLiteError', () => { }) it('ignores an incomplete native exception category', () => { - const error = NitroSQLiteError.fromError( + const error = SQLiteError.fromError( '[NativeNitroSQLiteException][SqlExecutionError', ) diff --git a/packages/react-native-nitro-sqlite/src/__tests__/entrypoints.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/entrypoints.test.ts index 81281252..b4e8c045 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/entrypoints.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/entrypoints.test.ts @@ -21,22 +21,17 @@ jest.mock('react-native-nitro-modules', () => ({ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { NitroModules } from 'react-native-nitro-modules' +import { NitroSQLite, SQLiteError, SQLiteExceptionType, open } from '../index' import { - NitroSQLite, - NitroSQLiteError, - NitroSQLiteExceptionType, - open, -} from '../index' -import { - NitroSQLiteError as ErrorFromErrors, - NitroSQLiteExceptionType as ExceptionTypeFromErrors, + SQLiteError as ErrorFromErrors, + SQLiteExceptionType as ExceptionTypeFromErrors, } from '../errors' import { HybridNitroSQLite } from '../nitro' describe('entrypoints', () => { it('shares the error class and category constants with the errors entry point', () => { - expect(NitroSQLiteError).toBe(ErrorFromErrors) - expect(NitroSQLiteExceptionType).toBe(ExceptionTypeFromErrors) + expect(SQLiteError).toBe(ErrorFromErrors) + expect(SQLiteExceptionType).toBe(ExceptionTypeFromErrors) }) it('creates the native object and exposes its native and managed methods', () => { diff --git a/packages/react-native-nitro-sqlite/src/__tests__/execute.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/execute.test.ts index 2347118b..45194048 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/execute.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/execute.test.ts @@ -2,7 +2,7 @@ jest.mock('../nitro') import { HybridNitroSQLite } from '../nitro' import { closeDatabaseQueue, openDatabaseQueue } from '../DatabaseQueue' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import { buildJSQueryResult, execute, @@ -23,7 +23,7 @@ afterEach(() => { closeDatabaseQueue(dbName) } catch (error) { if ( - !(error instanceof NitroSQLiteError) || + !(error instanceof SQLiteError) || !error.message.includes('not open') ) { throw error @@ -81,7 +81,7 @@ describe('execute', () => { throw new Error('SQL failed') }) - expect(() => execute(dbName, query)).toThrow(NitroSQLiteError) + expect(() => execute(dbName, query)).toThrow(SQLiteError) expect(() => execute(dbName, query)).toThrow('SQL failed') }) diff --git a/packages/react-native-nitro-sqlite/src/__tests__/executeBatch.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/executeBatch.test.ts index d39c5f5a..39a4dbf2 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/executeBatch.test.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/executeBatch.test.ts @@ -2,7 +2,7 @@ jest.mock('../nitro') import { HybridNitroSQLite } from '../nitro' import { closeDatabaseQueue, openDatabaseQueue } from '../DatabaseQueue' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import { executeBatch, executeBatchAsync } from '../operations/executeBatch' import { executeAsync } from '../operations/execute' import { deferred, nativeResult } from './testUtils' @@ -17,7 +17,7 @@ afterEach(() => { closeDatabaseQueue(dbName) } catch (error) { if ( - !(error instanceof NitroSQLiteError) || + !(error instanceof SQLiteError) || !error.message.includes('not open') ) { throw error @@ -90,7 +90,7 @@ describe('executeBatch', () => { .mockRejectedValueOnce('async failed') .mockResolvedValueOnce({ rowsAffected: 1 }) - expect(() => executeBatch(dbName, commands)).toThrow(NitroSQLiteError) + expect(() => executeBatch(dbName, commands)).toThrow(SQLiteError) expect(() => executeBatch(dbName, commands)).toThrow('sync failed') await expect(executeBatchAsync(dbName, commands)).rejects.toMatchObject({ name: 'NitroSQLiteError', diff --git a/packages/react-native-nitro-sqlite/src/__tests__/publicTypes.test.ts b/packages/react-native-nitro-sqlite/src/__tests__/publicTypes.test.ts new file mode 100644 index 00000000..ca80645e --- /dev/null +++ b/packages/react-native-nitro-sqlite/src/__tests__/publicTypes.test.ts @@ -0,0 +1,69 @@ +import { join } from 'node:path' +import ts from 'typescript' + +it('preserves legacy constructor types and interface augmentation', () => { + const packageDirectory = join(__dirname, '../..') + const fixturePath = join(__dirname, 'publicTypes.fixture.ts') + const fixture = ` + import type { + NitroSQLiteNative, + NitroSQLitePreparedStatement, + Connection, + ConnectionOptions, + NativeQueryResult, + TypeOrmConnection, + } from '../index' + + type RootArguments = ConstructorParameters + type PreparedPrototype = typeof NitroSQLitePreparedStatement.prototype + + declare module '../index' { + interface NitroSQLiteConnection { legacyConnectionTag?: string } + interface NitroSQLiteConnectionOptions { legacyOptionsTag?: string } + interface NitroSQLiteQueryResult { legacyResultTag?: string } + interface TypeOrmNitroSQLiteConnection { legacyTypeOrmTag?: string } + } + + declare const connection: Connection + const connectionTag: string | undefined = connection.legacyConnectionTag + declare const options: ConnectionOptions + const optionsTag: string | undefined = options.legacyOptionsTag + declare const result: NativeQueryResult + const resultTag: string | undefined = result.legacyResultTag + declare const orm: TypeOrmConnection + const ormTag: string | undefined = orm.legacyTypeOrmTag + ` + const config = ts.readConfigFile( + join(packageDirectory, 'tsconfig.json'), + ts.sys.readFile, + ) + const parsed = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + packageDirectory, + ) + const options: ts.CompilerOptions = { + ...parsed.options, + noEmit: true, + emitDeclarationOnly: false, + composite: false, + incremental: false, + noUnusedLocals: false, + noUnusedParameters: false, + } + const host = ts.createCompilerHost(options) + const getSourceFile = host.getSourceFile.bind(host) + host.getSourceFile = (fileName, languageVersion, onError, createNew) => + fileName === fixturePath + ? ts.createSourceFile(fixturePath, fixture, languageVersion, true) + : getSourceFile(fileName, languageVersion, onError, createNew) + + const program = ts.createProgram([fixturePath], options, host) + const errors = ts + .getPreEmitDiagnostics(program) + .filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error) + .map((diagnostic) => + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), + ) + expect(errors).toEqual([]) +}) diff --git a/packages/react-native-nitro-sqlite/src/__tests__/testUtils.ts b/packages/react-native-nitro-sqlite/src/__tests__/testUtils.ts index a5c13490..4ab5ed2e 100644 --- a/packages/react-native-nitro-sqlite/src/__tests__/testUtils.ts +++ b/packages/react-native-nitro-sqlite/src/__tests__/testUtils.ts @@ -1,10 +1,10 @@ -import type { NitroSQLiteQueryResult } from '../specs/NitroSQLiteQueryResult' +import type { NativeQueryResult } from '../specs/NativeQueryResult' import type { SQLiteValue } from '../types' export function nativeResult( results: Record[] = [], -): NitroSQLiteQueryResult { - return { rowsAffected: results.length, results } as NitroSQLiteQueryResult +): NativeQueryResult { + return { rowsAffected: results.length, results } as NativeQueryResult } export function deferred() { diff --git a/packages/react-native-nitro-sqlite/src/deprecated.ts b/packages/react-native-nitro-sqlite/src/deprecated.ts new file mode 100644 index 00000000..bd482cf5 --- /dev/null +++ b/packages/react-native-nitro-sqlite/src/deprecated.ts @@ -0,0 +1,28 @@ +export type { + /** @deprecated Use {@linkcode ConnectionOptions}. */ + ConnectionOptions as NitroSQLiteConnectionOptions, + /** @deprecated Use {@linkcode Connection}. */ + Connection as NitroSQLiteConnection, + /** @deprecated Use {@linkcode QueryResultRows}. */ + QueryResultRows as NitroSQLiteQueryResultRows, +} from './types' +export type { + /** @deprecated Use {@linkcode NativeQueryResult}. */ + NativeQueryResult as NitroSQLiteQueryResult, + /** @deprecated Use {@linkcode NativeQueryRows}. */ + NativeQueryRows as NitroSQLiteQueryRows, + /** @deprecated Use {@linkcode QueryColumnMetadata}. */ + QueryColumnMetadata as NitroSQLiteQueryColumnMetadata, +} from './specs/NativeQueryResult' +export type { + /** @deprecated Use {@linkcode NativePreparedStatement}. */ + PreparedStatement as NitroSQLitePreparedStatement, +} from './specs/PreparedStatement.nitro' +export type { + /** @deprecated Use {@linkcode NativeSQLite}. */ + NitroSQLite as NitroSQLiteNative, +} from './specs/NitroSQLite.nitro' +export type { + /** @deprecated Use {@linkcode TypeOrmConnection}. */ + TypeOrmConnection as TypeOrmNitroSQLiteConnection, +} from './typeORM' diff --git a/packages/react-native-nitro-sqlite/src/errors.ts b/packages/react-native-nitro-sqlite/src/errors.ts index 5ed13cf8..47addf1e 100644 --- a/packages/react-native-nitro-sqlite/src/errors.ts +++ b/packages/react-native-nitro-sqlite/src/errors.ts @@ -1,4 +1,8 @@ +export { default as SQLiteError, SQLiteExceptionType } from './SQLiteError' + export { + /** @deprecated Use {@linkcode SQLiteError}. */ default as NitroSQLiteError, - NitroSQLiteExceptionType, -} from './NitroSQLiteError' + /** @deprecated Use {@linkcode SQLiteExceptionType}. */ + SQLiteExceptionType as NitroSQLiteExceptionType, +} from './SQLiteError' diff --git a/packages/react-native-nitro-sqlite/src/index.ts b/packages/react-native-nitro-sqlite/src/index.ts index 1f4fa771..e546618b 100644 --- a/packages/react-native-nitro-sqlite/src/index.ts +++ b/packages/react-native-nitro-sqlite/src/index.ts @@ -23,15 +23,21 @@ export const NitroSQLite = { } export { open } from './operations/session' -export { NitroSQLiteError, NitroSQLiteExceptionType } from './errors' +export { + SQLiteError, + SQLiteExceptionType, + NitroSQLiteError, + NitroSQLiteExceptionType, +} from './errors' export type { DatabaseQueueKey } from './DatabaseQueue' -export type { NitroSQLite as NitroSQLiteNative } from './specs/NitroSQLite.nitro' -export type { PreparedStatement as NitroSQLitePreparedStatement } from './specs/PreparedStatement.nitro' +export type { NitroSQLite as NativeSQLite } from './specs/NitroSQLite.nitro' +export type { PreparedStatement as NativePreparedStatement } from './specs/PreparedStatement.nitro' export type { - NitroSQLiteQueryResult, - NitroSQLiteQueryRows, - NitroSQLiteQueryColumnMetadata, -} from './specs/NitroSQLiteQueryResult' -export type { TypeOrmNitroSQLiteConnection } from './typeORM' + NativeQueryResult, + NativeQueryRows, + QueryColumnMetadata, +} from './specs/NativeQueryResult' +export type { TypeOrmConnection } from './typeORM' export type * from './types' +export type * from './deprecated' export { typeORMDriver } from './typeORM' diff --git a/packages/react-native-nitro-sqlite/src/mock.ts b/packages/react-native-nitro-sqlite/src/mock.ts index 0971a4a7..f4e98321 100644 --- a/packages/react-native-nitro-sqlite/src/mock.ts +++ b/packages/react-native-nitro-sqlite/src/mock.ts @@ -15,8 +15,8 @@ import { queueStatementAsync, startOperationSync, } from './DatabaseQueue' -import NitroSQLiteError from './NitroSQLiteError' -import type { NitroSQLiteConnectionOptions, PreparedStatement } from './types' +import SQLiteError from './SQLiteError' +import type { ConnectionOptions, PreparedStatement } from './types' import type { MockConnection } from './mock/MockConnection' import { executeBatch, executePrepared, executeQuery } from './mock/query' import { runTransaction } from './mock/transaction' @@ -47,10 +47,10 @@ let databaseDirectory: string | undefined * cannot be opened, or a default connection already uses the name. * @see {@linkcode MockConnection} */ -export function open(options: NitroSQLiteConnectionOptions): MockConnection { +export function open(options: ConnectionOptions): MockConnection { const { name, connection, readOnly = false } = options if (connection !== 'independent' && defaultConnections.has(name)) { - throw new NitroSQLiteError(`Database ${name} is already open.`) + throw new SQLiteError(`Database ${name} is already open.`) } const path = getDatabasePath(options) if (!readOnly) mkdirSync(dirname(path), { recursive: true }) @@ -89,18 +89,18 @@ export function open(options: NitroSQLiteConnectionOptions): MockConnection { replacement && replacement !== record ) { - throw new NitroSQLiteError( + throw new SQLiteError( 'Database has been reopened with another connection.', ) } if (readOnly) - throw new NitroSQLiteError(`Cannot delete read-only database ${name}.`) + throw new SQLiteError(`Cannot delete read-only database ${name}.`) if ( [...connections].some( (other) => other !== record && other.path === path, ) ) { - throw new NitroSQLiteError('Database is in use by another connection.') + throw new SQLiteError('Database is in use by another connection.') } if (connections.has(record)) close() for (const suffix of ['', '-wal', '-shm', '-journal']) @@ -119,7 +119,7 @@ export function open(options: NitroSQLiteConnectionOptions): MockConnection { ) const execute: PreparedStatement['execute'] = (params) => { if (!statement) - throw new NitroSQLiteError('Prepared statement is finalized.') + throw new SQLiteError('Prepared statement is finalized.') return executePrepared(database, statement, params) } return { @@ -155,7 +155,7 @@ export function resetAllDatabases(): void { for (const { queueKey } of connections) { const queue = getDatabaseQueue(queueKey) if (queue.inProgress || queue.queue.length > 0) { - throw new NitroSQLiteError( + throw new SQLiteError( 'Cannot reset mock databases while a connection is busy.', ) } @@ -166,10 +166,7 @@ export function resetAllDatabases(): void { databaseDirectory = undefined } -function getDatabasePath({ - name, - location = '', -}: NitroSQLiteConnectionOptions): string { +function getDatabasePath({ name, location = '' }: ConnectionOptions): string { if ( !name || name === '.' || @@ -177,14 +174,14 @@ function getDatabasePath({ name.includes('/') || name.includes('\\') ) { - throw new NitroSQLiteError('Database name must be a file name.') + throw new SQLiteError('Database name must be a file name.') } if (!databaseDirectory) databaseDirectory = mkdtempSync(join(tmpdir(), 'nitro-sqlite-test-')) const directory = resolve(databaseDirectory, location) const relativeDirectory = relative(databaseDirectory, directory) if (relativeDirectory === '..' || relativeDirectory.startsWith(`..${sep}`)) { - throw new NitroSQLiteError( + throw new SQLiteError( 'Database location must stay inside the temporary directory.', ) } diff --git a/packages/react-native-nitro-sqlite/src/mock/MockConnection.ts b/packages/react-native-nitro-sqlite/src/mock/MockConnection.ts index fbfc449a..0529d2cb 100644 --- a/packages/react-native-nitro-sqlite/src/mock/MockConnection.ts +++ b/packages/react-native-nitro-sqlite/src/mock/MockConnection.ts @@ -1,14 +1,14 @@ -import type { NitroSQLiteConnection } from '../types' +import type { Connection } from '../types' /** * Connection returned by the Node mock's `open()` factory. * Supports the corresponding managed connection methods and their queue and * transaction lifecycle. Files persist across close/reopen until deletion or * reset. Attachments and SQL file imports are not supported. - * @see {@linkcode NitroSQLiteConnection} + * @see {@linkcode Connection} */ export type MockConnection = Pick< - NitroSQLiteConnection, + Connection, | 'close' | 'delete' | 'execute' diff --git a/packages/react-native-nitro-sqlite/src/mock/transaction.ts b/packages/react-native-nitro-sqlite/src/mock/transaction.ts index a9099b62..93dfc1fa 100644 --- a/packages/react-native-nitro-sqlite/src/mock/transaction.ts +++ b/packages/react-native-nitro-sqlite/src/mock/transaction.ts @@ -1,5 +1,5 @@ import type BetterSqlite3 from 'better-sqlite3' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import type { QueryResultRow, SQLiteQueryParams, Transaction } from '../types' import { executeQuery } from './query' @@ -11,12 +11,12 @@ export async function runTransaction( let finished = false const pending = new Set>() const assertActive = () => { - if (finished) throw new NitroSQLiteError('Transaction is finalized.') + if (finished) throw new SQLiteError('Transaction is finalized.') } const assertSync = () => { assertActive() if (pending.size > 0) { - throw new NitroSQLiteError( + throw new SQLiteError( 'Await all tx.executeAsync calls before a synchronous transaction operation.', ) } diff --git a/packages/react-native-nitro-sqlite/src/operations/execute.ts b/packages/react-native-nitro-sqlite/src/operations/execute.ts index 0cb628ae..ef766b23 100644 --- a/packages/react-native-nitro-sqlite/src/operations/execute.ts +++ b/packages/react-native-nitro-sqlite/src/operations/execute.ts @@ -1,7 +1,7 @@ import { HybridNitroSQLite } from '../nitro' import type { QueryResult, QueryResultRow, SQLiteQueryParams } from '../types' -import NitroSQLiteError from '../NitroSQLiteError' -import type { NitroSQLiteQueryResult } from '../specs/NitroSQLiteQueryResult' +import SQLiteError from '../SQLiteError' +import type { NativeQueryResult } from '../specs/NativeQueryResult' import { isDatabaseOpen, queueStatementAsync, @@ -48,7 +48,7 @@ export function executeNative( const nativeResult = HybridNitroSQLite.execute(dbName, query, params) return buildJSQueryResult(nativeResult) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } @@ -117,12 +117,12 @@ export async function executeAsyncNative( } return buildJSQueryResult(nativeResult, leadingRows) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } export function buildJSQueryResult( - result: NitroSQLiteQueryResult, + result: NativeQueryResult, leadingRows?: Row[], ): QueryResult { const resultWithRows = result as QueryResult & { results: Row[] } diff --git a/packages/react-native-nitro-sqlite/src/operations/executeBatch.ts b/packages/react-native-nitro-sqlite/src/operations/executeBatch.ts index 13a4668c..72d21150 100644 --- a/packages/react-native-nitro-sqlite/src/operations/executeBatch.ts +++ b/packages/react-native-nitro-sqlite/src/operations/executeBatch.ts @@ -4,7 +4,7 @@ import { startOperationSync, throwIfDatabaseIsNotOpen, } from '../DatabaseQueue' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import type { BatchQueryCommand, BatchQueryResult } from '../types' import type { DatabaseQueueKey } from '../DatabaseQueue' @@ -26,7 +26,7 @@ export function executeBatch( HybridNitroSQLite.executeBatch(dbName, commands), ) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } @@ -47,7 +47,7 @@ export async function executeBatchAsync( try { return await HybridNitroSQLite.executeBatchAsync(dbName, commands) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }) } diff --git a/packages/react-native-nitro-sqlite/src/operations/prepare.ts b/packages/react-native-nitro-sqlite/src/operations/prepare.ts index 3451a8df..8a89b6be 100644 --- a/packages/react-native-nitro-sqlite/src/operations/prepare.ts +++ b/packages/react-native-nitro-sqlite/src/operations/prepare.ts @@ -1,5 +1,5 @@ import { HybridNitroSQLite } from '../nitro' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import type { PreparedStatement, QueryResult, @@ -41,7 +41,7 @@ export function prepare( buildJSQueryResult(nativeStatement.execute(params)), ) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }, executeAsync: async ( @@ -52,18 +52,18 @@ export function prepare( buildJSQueryResult(await nativeStatement.executeAsync(params)), ) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }, finalize: () => { try { startOperationSync(queueKey, () => nativeStatement.finalize()) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }, } } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } diff --git a/packages/react-native-nitro-sqlite/src/operations/session.ts b/packages/react-native-nitro-sqlite/src/operations/session.ts index cfc02703..bec9e08a 100644 --- a/packages/react-native-nitro-sqlite/src/operations/session.ts +++ b/packages/react-native-nitro-sqlite/src/operations/session.ts @@ -2,8 +2,8 @@ import { HybridNitroSQLite } from '../nitro' import { transaction } from './transaction' import type { BatchQueryCommand, - NitroSQLiteConnection, - NitroSQLiteConnectionOptions, + Connection, + ConnectionOptions, Transaction, SQLiteQueryParams, QueryResultRow, @@ -12,7 +12,7 @@ import type { import { executeAsyncManaged, executeManaged } from './execute' import { executeBatch, executeBatchAsync } from './executeBatch' import { prepare } from './prepare' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import { closeDatabaseQueue, getDatabaseQueue, @@ -31,14 +31,12 @@ import type { DatabaseQueueKey } from '../DatabaseQueue' * a native build with SQLite SEE; it does not encrypt an existing plaintext file. * @param options Database name, optional directory, connection mode, read-only setting, and SEE key. * @returns A connection bound to the opened native handle. - * @throws `NitroSQLiteError` with type `EncryptionNotEnabled` when a key is + * @throws `SQLiteError` with type `EncryptionNotEnabled` when a key is * supplied without SEE, or `DatabaseCannotBeDecrypted` for an invalid key, * wrong key, or existing plaintext database. * @see [Encryption guide](https://sqlite.margelo.com/docs/guides/encryption) */ -export function open( - options: NitroSQLiteConnectionOptions, -): NitroSQLiteConnection { +export function open(options: ConnectionOptions): Connection { const { name, location: databaseLocation, connection, readOnly } = options const { connectionId, queueKey } = openNativeConnection(options) const connectionQueue = getDatabaseQueue(queueKey) @@ -48,7 +46,7 @@ export function open( !isDatabaseOpen(queueKey) || getDatabaseQueue(queueKey) !== connectionQueue ) { - throw new NitroSQLiteError( + throw new SQLiteError( `Database ${name} is not open. There is no connection to the database.`, ) } @@ -59,7 +57,7 @@ export function open( isDatabaseOpen(queueKey) && getDatabaseQueue(queueKey) !== connectionQueue ) { - throw new NitroSQLiteError( + throw new SQLiteError( `Database ${name} has been reopened with another connection.`, ) } @@ -70,7 +68,7 @@ export function open( assertCurrentConnection() return startOperationSync(queueKey, callback) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } @@ -86,7 +84,7 @@ export function open( }, delete: () => { if (readOnly) { - throw new NitroSQLiteError(`Cannot delete read-only database ${name}.`) + throw new SQLiteError(`Cannot delete read-only database ${name}.`) } let dropFailed = false @@ -121,7 +119,7 @@ export function open( ) { closeDatabaseQueue(queueKey) } - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }, attach: (dbNameToAttach: string, alias: string, location?: string) => @@ -161,14 +159,14 @@ export function open( try { return await HybridNitroSQLite.loadFileAsync(connectionId, location) } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } }), ), } } -function openNativeConnection(options: NitroSQLiteConnectionOptions): { +function openNativeConnection(options: ConnectionOptions): { connectionId: string queueKey: DatabaseQueueKey } { @@ -194,7 +192,7 @@ function openNativeConnection(options: NitroSQLiteConnectionOptions): { openDatabaseQueue(queueKey) return { connectionId, queueKey } } catch (error) { - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } } @@ -212,7 +210,7 @@ function openNativeConnection(options: NitroSQLiteConnectionOptions): { } } catch (error) { closeDatabaseQueue(options.name) - throw NitroSQLiteError.fromError(error) + throw SQLiteError.fromError(error) } return { connectionId: options.name, queueKey: options.name } } diff --git a/packages/react-native-nitro-sqlite/src/operations/transaction.ts b/packages/react-native-nitro-sqlite/src/operations/transaction.ts index 9f879bf2..70f0d542 100644 --- a/packages/react-native-nitro-sqlite/src/operations/transaction.ts +++ b/packages/react-native-nitro-sqlite/src/operations/transaction.ts @@ -6,7 +6,7 @@ import type { QueryResultRow, } from '../types' import { executeAsyncNative, executeNative } from './execute' -import NitroSQLiteError from '../NitroSQLiteError' +import SQLiteError from '../SQLiteError' import type { DatabaseQueueKey } from '../DatabaseQueue' /** Queue a transaction for an open managed connection. @@ -20,7 +20,7 @@ import type { DatabaseQueueKey } from '../DatabaseQueue' * @param isExclusive Begin an exclusive transaction when true. * @param queueKey Managed connection queue identifier; defaults to the database name. * @returns The callback's result after the transaction finishes. - * @throws NitroSQLiteError if BEGIN, the callback, COMMIT, or ROLLBACK fails. + * @throws SQLiteError if BEGIN, the callback, COMMIT, or ROLLBACK fails. */ export const transaction = async ( dbName: string, @@ -38,7 +38,7 @@ export const transaction = async ( const throwIfAsyncPending = () => { if (pendingAsyncStatements.size > 0) { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot run synchronous operation on transaction ${dbName} while async queries are pending. Await all tx.executeAsync calls first.`, ) } @@ -49,7 +49,7 @@ export const transaction = async ( params?: SQLiteQueryParams, ): QueryResult => { if (state.current.kind !== 'active') { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot execute query on finalized transaction: ${dbName}`, ) } @@ -62,7 +62,7 @@ export const transaction = async ( params?: SQLiteQueryParams, ): Promise> => { if (state.current.kind !== 'active') { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot execute query on finalized transaction: ${dbName}`, ) } @@ -77,7 +77,7 @@ export const transaction = async ( const commit = () => { if (state.current.kind !== 'active') { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot execute commit on finalized transaction: ${dbName}`, ) } @@ -97,7 +97,7 @@ export const transaction = async ( state.current.kind !== 'active' && state.current.kind !== 'commitFailed' ) { - throw new NitroSQLiteError( + throw new SQLiteError( `Cannot execute rollback on finalized transaction: ${dbName}`, ) } @@ -161,7 +161,7 @@ export const transaction = async ( } } - throw NitroSQLiteError.fromError(executionError) + throw SQLiteError.fromError(executionError) } }) } @@ -175,10 +175,10 @@ type TransactionState = function transactionFinalizationError( primary: unknown, rollback: unknown, -): NitroSQLiteError { - const primaryError = NitroSQLiteError.fromError(primary) - const rollbackError = NitroSQLiteError.fromError(rollback) - return new NitroSQLiteError( +): SQLiteError { + const primaryError = SQLiteError.fromError(primary) + const rollbackError = SQLiteError.fromError(rollback) + return new SQLiteError( `${primaryError.message}\nRollback failed: ${rollbackError.message}`, { cause: new AggregateError( diff --git a/packages/react-native-nitro-sqlite/src/specs/NitroSQLiteQueryResult.ts b/packages/react-native-nitro-sqlite/src/specs/NativeQueryResult.ts similarity index 85% rename from packages/react-native-nitro-sqlite/src/specs/NitroSQLiteQueryResult.ts rename to packages/react-native-nitro-sqlite/src/specs/NativeQueryResult.ts index 455d3727..3c9cc305 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLiteQueryResult.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NativeQueryResult.ts @@ -2,26 +2,26 @@ import type { CustomType } from 'react-native-nitro-modules' import type { ColumnType, SQLiteValue } from '../types' /** Result rows keyed by column name. Native rows become JavaScript objects on the JavaScript thread. */ -export type NitroSQLiteQueryRows = CustomType< +export type NativeQueryRows = CustomType< Record[], 'margelo::nitro::rnnitrosqlite::SQLiteQueryResults', - { include: 'NitroSQLiteQueryResults.hpp' } + { include: 'SQLiteQueryResults.hpp' } > /** Native result of one SQL statement, delivered as a plain JavaScript object. * The managed API also adds a `rows` adapter. */ -export interface NitroSQLiteQueryResult { +export interface NativeQueryResult { /** SQLite's latest row change count. For a read-only query it may reflect an earlier write. */ readonly rowsAffected: number /** Last insert row ID for this connection. It may refer to an earlier statement. */ readonly insertId?: number /** Rows keyed by result column names. */ - readonly results: NitroSQLiteQueryRows + readonly results: NativeQueryRows /** Column metadata keyed by result column name, when available. */ - readonly metadata?: Record + readonly metadata?: Record /** Number of row batches sent through the native `onRows` callback, or zero when none were sent. * Callbacks may arrive after the native promise resolves. Wait for this many batches before @@ -39,7 +39,7 @@ export interface NitroSQLiteQueryResult { // type NitroQueryResultRow = Record /** Name, declared type, and position of a result column. */ -export type NitroSQLiteQueryColumnMetadata = { +export type QueryColumnMetadata = { /** Name used for this column in the result set. */ name: string 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 ef843e18..bf0e0647 100644 --- a/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/NitroSQLite.nitro.ts @@ -5,10 +5,7 @@ import type { FileLoadResult, SQLiteQueryParams, } from '../types' -import type { - NitroSQLiteQueryResult, - NitroSQLiteQueryRows, -} from './NitroSQLiteQueryResult' +import type { NativeQueryResult, NativeQueryRows } from './NativeQueryResult' import type { PreparedStatement } from './PreparedStatement.nitro' export * from '#nitro/NitroSQLite' @@ -119,7 +116,7 @@ export declare class NitroSQLite extends HybridObject { dbName: string, query: string, params?: SQLiteQueryParams, - ): NitroSQLiteQueryResult + ): NativeQueryResult /** Execute one SQL statement on a background thread. * @param dbName Name of an open database. * @param query SQL statement with optional positional placeholders. @@ -134,8 +131,8 @@ export declare class NitroSQLite extends HybridObject { dbName: string, query: string, params?: SQLiteQueryParams, - onRows?: (rows: NitroSQLiteQueryRows) => void, - ): Promise + onRows?: (rows: NativeQueryRows) => void, + ): 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. diff --git a/packages/react-native-nitro-sqlite/src/specs/PreparedStatement.nitro.ts b/packages/react-native-nitro-sqlite/src/specs/PreparedStatement.nitro.ts index 96ea0f2b..6925f7cd 100644 --- a/packages/react-native-nitro-sqlite/src/specs/PreparedStatement.nitro.ts +++ b/packages/react-native-nitro-sqlite/src/specs/PreparedStatement.nitro.ts @@ -1,6 +1,6 @@ import { Android, iOS, type HybridObject } from 'react-native-nitro-modules' import type { SQLiteQueryParams } from '../types' -import type { NitroSQLiteQueryResult } from './NitroSQLiteQueryResult' +import type { NativeQueryResult } from './NativeQueryResult' export * from '#nitro/PreparedStatement' @@ -28,13 +28,13 @@ export declare class PreparedStatement extends HybridObject { * @param params Values bound to positional placeholders. * @returns Native query rows, affected row count, insert ID, and metadata. */ - execute(params?: SQLiteQueryParams): NitroSQLiteQueryResult + execute(params?: SQLiteQueryParams): NativeQueryResult /** Execute on a background thread, replacing the previous parameter bindings. * 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?: SQLiteQueryParams): Promise /** Release the native statement. Repeated calls are safe. */ finalize(): void } diff --git a/packages/react-native-nitro-sqlite/src/typeORM.ts b/packages/react-native-nitro-sqlite/src/typeORM.ts index 9fca842c..e604c3d4 100644 --- a/packages/react-native-nitro-sqlite/src/typeORM.ts +++ b/packages/react-native-nitro-sqlite/src/typeORM.ts @@ -14,7 +14,7 @@ import type { import * as Operations from './operations/session' /** Callback-oriented connection returned to TypeORM. */ -export interface TypeOrmNitroSQLiteConnection { +export interface TypeOrmConnection { /** Execute SQL asynchronously and report the result through a callback. */ executeSql: ( sql: string, @@ -59,13 +59,13 @@ export const typeORMDriver = { */ encryptionKey?: string }, - ok: (db: TypeOrmNitroSQLiteConnection) => void, + ok: (db: TypeOrmConnection) => void, fail: (msg: string) => void, - ): TypeOrmNitroSQLiteConnection | null => { + ): TypeOrmConnection | null => { try { const db = Operations.open(options) - const connection: TypeOrmNitroSQLiteConnection = { + const connection: TypeOrmConnection = { executeSql: async ( sql: string, params: SQLiteQueryParams | undefined, diff --git a/packages/react-native-nitro-sqlite/src/types.ts b/packages/react-native-nitro-sqlite/src/types.ts index 0d1cc891..2b2c052d 100644 --- a/packages/react-native-nitro-sqlite/src/types.ts +++ b/packages/react-native-nitro-sqlite/src/types.ts @@ -1,7 +1,7 @@ -import type { NitroSQLiteQueryResult } from './specs/NitroSQLiteQueryResult' +import type { NativeQueryResult } from './specs/NativeQueryResult' /** Options for `open()` and `NitroSQLite.open()`. */ -export interface NitroSQLiteConnectionOptions { +export interface ConnectionOptions { /** Database file name. Only one managed connection may use a name at a time. */ name: string /** Directory relative to the platform's database directory. */ @@ -30,7 +30,7 @@ export interface NitroSQLiteConnectionOptions { } /** A managed connection bound to one database name. Do not use it after closing or deleting it. */ -export interface NitroSQLiteConnection { +export interface Connection { /** Close the connection. Throws if a queued operation is running or pending. */ close(): void /** Delete the database file and end this connection. Throws if the connection is busy. @@ -83,7 +83,7 @@ export interface NitroSQLiteConnection { * `location` is a path to the SQL file; multi-line statements are unsupported. * @param location Path to the SQL file. * @returns Number of executed commands and affected rows. - * @throws NitroSQLiteError with native category CouldNotLoadFile on an import + * @throws SQLiteError with native category CouldNotLoadFile on an import * failure, including the path, failing SQL/line, and any rollback failure. * Completed commands are discarded when rollback succeeds. */ @@ -91,7 +91,7 @@ export interface NitroSQLiteConnection { /** Queue the file import and resolve with its command and row counts. * @param location Path to the SQL file. * @returns A promise of the command and affected row counts. - * @throws NitroSQLiteError with native category CouldNotLoadFile, preserving + * @throws SQLiteError with native category CouldNotLoadFile, preserving * the original import error and any rollback failure. Rejects asynchronously. */ loadFileAsync(location: string): Promise @@ -135,13 +135,13 @@ export type QueryResultRow = Record /** Query result with a row adapter for TypeORM-style consumers. */ export type QueryResult = - NitroSQLiteQueryResult & { + NativeQueryResult & { /** Query rows in a TypeORM-compatible collection. */ - rows: NitroSQLiteQueryResultRows + rows: QueryResultRows } /** Indexable view of query rows. */ -export type NitroSQLiteQueryResultRows< +export type QueryResultRows< Row extends Record = Record, > = { /** All returned rows. */ @@ -218,13 +218,13 @@ export interface Transaction { * On failure, only rollback remains available and the wrapper rejects unless * the callback explicitly rolls back. Throws while async queries are pending. */ - commit(): NitroSQLiteQueryResult + commit(): NativeQueryResult /** Roll back now, including after a failed commit. * Marks completion only after SQLite accepts ROLLBACK. A failed rollback * rejects the transaction promise even if caught by the callback. * Throws while async queries are pending or after successful finalization. */ - rollback(): NitroSQLiteQueryResult + rollback(): NativeQueryResult /** Execute within this transaction on the calling thread. */ execute: ExecuteQuery /** Execute within this transaction on a background thread. */ diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp index 8bd6a0c3..3c0bbd3a 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseConnections.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnectionsThreadsafe.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnectionsThreadsafe.test.cpp index f6d5d219..8d6b1502 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnectionsThreadsafe.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnectionsThreadsafe.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseConnections.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp index b8230b70..98d440b7 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteDatabaseMigration.hpp" +#include "SQLiteDatabaseMigration.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/serialWorker.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/serialWorker.test.cpp index 1c86f156..155f17c9 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/serialWorker.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/serialWorker.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseConnections.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp index 84d508a7..a2e097b5 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteStatementCache.hpp" +#include "SQLiteStatementCache.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/statementGroup.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/statementGroup.test.cpp index d1ca5d1b..1b54dbe4 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/statementGroup.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/statementGroup.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteStatementGroup.hpp" +#include "SQLiteStatementGroup.hpp" #include #include #include diff --git a/packages/react-native-nitro-sqlite/tests/cpp/statementTail.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/statementTail.test.cpp index c7d13b49..0ccea1b0 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/statementTail.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/statementTail.test.cpp @@ -1,4 +1,4 @@ -#include "NitroSQLiteStatementTail.hpp" +#include "SQLiteStatementTail.hpp" #include #include #include diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index d07c3a82..a175d286 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -29,9 +29,7 @@ test('platform changes only select their platform', () => { test('shared native sources retain lifecycle and platform coverage', () => { const checks = selectChecks( - [ - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp', - ], + ['packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp'], false, ) assert.deepEqual(enabled(checks), [ diff --git a/scripts/test-cpp.sh b/scripts/test-cpp.sh index be3c558d..134312a5 100644 --- a/scripts/test-cpp.sh +++ b/scripts/test-cpp.sh @@ -17,7 +17,7 @@ clang++ \ -Werror \ -Ipackages/react-native-nitro-sqlite/cpp \ -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp \ packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp \ /tmp/sqlite3.o \ -ldl \ @@ -34,8 +34,8 @@ clang++ \ -Werror \ -Ipackages/react-native-nitro-sqlite/cpp \ -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp \ packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp \ /tmp/sqlite3.o \ -ldl \ @@ -82,8 +82,8 @@ clang++ \ -Werror \ -Ipackages/react-native-nitro-sqlite/cpp \ -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp \ packages/react-native-nitro-sqlite/tests/cpp/serialWorker.test.cpp \ /tmp/sqlite3.o \ -ldl \ @@ -119,8 +119,8 @@ clang++ \ -Werror \ -Ipackages/react-native-nitro-sqlite/cpp \ -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp \ packages/react-native-nitro-sqlite/tests/cpp/databaseConnectionsThreadsafe.test.cpp \ /tmp/sqlite3-threadsafe-0.o \ -ldl \ diff --git a/scripts/test-private-sqlite-symbols.sh b/scripts/test-private-sqlite-symbols.sh index c7d6630e..4eda0684 100644 --- a/scripts/test-private-sqlite-symbols.sh +++ b/scripts/test-private-sqlite-symbols.sh @@ -9,7 +9,7 @@ trap 'rm -rf "$tmp"' EXIT cc -O0 -DSQLITE_ENABLE_RTREE=1 -c "$sqlite/sqlite3.c" -o "$tmp/private.o" cc -O0 -DSQLITE_CORE=1 -DSQLITE_VEC_STATIC=1 -I "$sqlite" -c "$vec/sqlite-vec/sqlite-vec.c" -o "$tmp/vec.o" -c++ -std=c++20 -DSQLITE_CORE=1 -I "$sqlite" -I "$vec" -c "$vec/NitroSQLiteVecRegisterVectorExtensions.cpp" -o "$tmp/vec-register.o" +c++ -std=c++20 -DSQLITE_CORE=1 -I "$sqlite" -I "$vec" -c "$vec/SQLiteVecRegisterVectorExtensions.cpp" -o "$tmp/vec-register.o" nm -g "$tmp/private.o" "$tmp/vec.o" "$tmp/vec-register.o" > "$tmp/symbols" if grep -E '[[:space:]](U|T|D|B|S|R|C) _?sqlite3_' "$tmp/symbols"; then @@ -104,7 +104,7 @@ c++ "$tmp/main.o" "$tmp/private-calls.o" "$tmp/system-calls.o" "$tmp/private.o" "$tmp/coexistence" # The Apple system-SQLite option must keep its original, unprefixed imports. -c++ -std=c++20 -DSQLITE_CORE=1 -DNITRO_SQLITE_USE_PHONE_VERSION=1 -I "$sqlite" -I "$vec" -c "$vec/NitroSQLiteVecRegisterVectorExtensions.cpp" -o "$tmp/vec-register-system.o" +c++ -std=c++20 -DSQLITE_CORE=1 -DNITRO_SQLITE_USE_PHONE_VERSION=1 -I "$sqlite" -I "$vec" -c "$vec/SQLiteVecRegisterVectorExtensions.cpp" -o "$tmp/vec-register-system.o" nm -g "$tmp/vec-register-system.o" > "$tmp/system-symbols" if ! grep -Eq '[[:space:]]U _?sqlite3_auto_extension$' "$tmp/system-symbols"; then echo 'The system-SQLite vector pod did not import system SQLite' >&2