diff --git a/.github/ci-paths.json b/.github/ci-paths.json index ba03fc6a..9afa41c8 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -138,7 +138,18 @@ "packages/nitro-sqlite/package.json", "packages/nitro-sqlite/nitro.json", "packages/nitro-sqlite/platform/cpp/**", - "packages/nitro-sqlite/src/specs/**" + "packages/nitro-sqlite/src/specs/**", + "packages/nitro-sqlite-core/cpp/*.hpp", + "packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*", + "packages/nitro-sqlite-core/cpp/hybridObjects/**", + "packages/react-native-nitro-sqlite/cpp/*.hpp", + "packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.*", + "packages/react-native-nitro-sqlite/nitrogen/generated/shared/**", + "packages/nitro-sqlite/nitrogen/generated/shared/**", + "patches/react-native-nitro-modules*", + "bunfig.toml", + "scripts/prepare-cpp-test-headers.cjs", + "examples/react-native/package.json" ], "docs": [ ".github/workflows/**", diff --git a/.github/workflows/test-windows-native.yml b/.github/workflows/test-windows-native.yml new file mode 100644 index 00000000..a0625b8a --- /dev/null +++ b/.github/workflows/test-windows-native.yml @@ -0,0 +1,76 @@ +name: Test Windows SQLite files + +on: + push: + branches: [main] + pull_request: + paths: + - '.github/workflows/test-windows-native.yml' + - 'packages/react-native-nitro-sqlite/cpp/**' + - 'packages/nitro-sqlite-core/**' + - 'packages/react-native-nitro-sqlite/platform/**' + - 'packages/react-native-nitro-sqlite/scripts/**' + - 'packages/react-native-nitro-sqlite/tests/cpp/**' + - 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/**' + - 'scripts/prepare-cpp-test-headers.cjs' + - 'patches/react-native-nitro-modules*' + - 'bunfig.toml' + - 'patches/react-native-nitro-modules*' + - 'package.json' + - 'bun.lock' + workflow_dispatch: + +permissions: + contents: read + +jobs: + sqlite-files: + runs-on: windows-2025 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.3.14 + - run: bun install --frozen-lockfile --ignore-scripts + - run: node packages/react-native-nitro-sqlite/scripts/prepare-sources.mjs + - name: Build and run path, connection and migration tests with MSVC + shell: pwsh + run: | + $PSNativeCommandUseErrorActionPreference = $true + $visualStudio = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + Import-Module "$visualStudio\Common7\Tools\Microsoft.VisualStudio.DevShell.dll" + Enter-VsDevShell -VsInstallPath $visualStudio -SkipAutomaticLocation -DevCmdArguments '-arch=x64' + $package = Resolve-Path packages/react-native-nitro-sqlite + $core = Resolve-Path packages/nitro-sqlite-core + Set-Location $env:RUNNER_TEMP + cl /nologo /c /TC /DSQLITE_THREADSAFE=2 "$core\cpp\sqlite\sqlite3.c" /Fosqlite3.obj + cl /nologo /std:c++20 /EHsc /utf-8 "/I$core\cpp" ` + "$core\cpp\SQLiteDatabaseConnections.cpp" "$core\cpp\SQLiteDatabaseMigration.cpp" ` + "$package\tests\cpp\databaseConnections.test.cpp" sqlite3.obj /FedatabaseConnectionsTests.exe + .\databaseConnectionsTests.exe + cl /nologo /std:c++20 /EHsc /utf-8 "/I$core\cpp" "/I$core\cpp\sqlite" ` + "$core\cpp\SQLiteDatabaseMigration.cpp" "$package\tests\cpp\databaseMigration.test.cpp" ` + sqlite3.obj /FedatabaseMigrationTests.exe + .\databaseMigrationTests.exe + cl /nologo /std:c++20 /EHsc /O2 /DNDEBUG /utf-8 "/I$core\cpp" ` + "$package\tests\cpp\statementCache.test.cpp" sqlite3.obj /FestatementCacheTests.exe + .\statementCacheTests.exe + Set-Location $env:GITHUB_WORKSPACE + node scripts/prepare-cpp-test-headers.cjs "$env:RUNNER_TEMP/headers" + $includes = @("/I$env:RUNNER_TEMP\headers", "/I$env:RUNNER_TEMP\headers\NitroModules", "/I$env:GITHUB_WORKSPACE\node_modules\react-native\ReactCommon\jsi", "/I$package\cpp", "/I$package\cpp\sqlite", "/I$package\cpp\hybridObjects", "/I$package\nitrogen\generated\shared\c++\include") + $standardHeaders = "/FI$package\tests\cpp\NitroTestStandardHeaders.hpp" + $nitro = "$env:GITHUB_WORKSPACE\node_modules\react-native-nitro-modules\cpp\core" + $jsi = "$env:GITHUB_WORKSPACE\node_modules\react-native\ReactCommon\jsi\jsi\jsi.cpp" + Set-Location $env:RUNNER_TEMP + cl /nologo /std:c++20 /EHsc /utf-8 @includes $standardHeaders ` + "$package\cpp\SQLiteDatabaseConnections.cpp" "$package\cpp\SQLiteDatabaseMigration.cpp" ` + "$package\cpp\SQLiteOperations.cpp" "$package\cpp\SQLiteImportSqlFile.cpp" ` + "$package\cpp\SQLiteQueryResults.cpp" "$package\cpp\SQLiteJSON.cpp" "$package\cpp\NativeQueryResult.cpp" ` + "$nitro\src\ArrayBuffer.cpp" $jsi "$package\tests\cpp\databasePaths.test.cpp" ` + sqlite3.obj /FedatabasePathsTests.exe + .\databasePathsTests.exe + cl /nologo /c /std:c++20 /EHsc /utf-8 @includes $standardHeaders "$package\cpp\hybridObjects\HybridNitroSQLite.cpp" diff --git a/docs/content/docs/guides/attach-databases.mdx b/docs/content/docs/guides/attach-databases.mdx index 9592ac8b..ed659c10 100644 --- a/docs/content/docs/guides/attach-databases.mdx +++ b/docs/content/docs/guides/attach-databases.mdx @@ -32,4 +32,14 @@ db.close() 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 [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) for signatures. +Nitro SQLite binds the filename and schema alias as parameters, including Unicode characters and apostrophes. Aliases can contain spaces or quotes. Quote a schema name as an SQL identifier when using it in a query. Query values still belong in `?` parameters. + +Pass literal filenames. If older code doubled apostrophes to work around SQL interpolation, remove that escaping: `café's.sqlite` names a different file from `café''s.sqlite`. + +For compatibility, a complete alias enclosed in double quotes, single quotes, backticks, or square brackets is interpreted as the existing quoted name. For example, `db.attach('archive.sqlite', '"sales archive"')` and `db.attach('archive.sqlite', 'sales archive')` both attach the schema `sales archive`. Either form works with `detach()` too. Doubled quote characters inside a quoted name are decoded. Square brackets have no escape syntax. + +A full pair of quotes is ambiguous with a literal name that includes those quote characters. Legacy quoting takes precedence. To name a schema `"archive"` including its quote characters, pass the SQL-quoted alias `'"""archive"""'` to both `attach()` and `detach()`. Other raw aliases are preserved, including incomplete quoting. Aliases are never executed as SQL. + +Surrounding SQL whitespace is ignored for a single bare identifier too: `' archive '` resolves to `archive`. To retain that whitespace as part of the name, use the quoted alias `'" archive "'`. Names with internal spaces remain literal raw names. + +Only pass database names and locations you control. Path segments such as `..` are not validated. 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 75b4a93c..6e2c2a67 100644 --- a/docs/content/docs/guides/database-lifecycle.mdx +++ b/docs/content/docs/guides/database-lifecycle.mdx @@ -47,6 +47,8 @@ const db = open({ name: 'catalog.sqlite', location: 'databases' }) Only pass database names and locations you control. The library does not validate path segments such as `..`. +SQLite treats an attached database name as a filename and its alias as a schema name. `attach()` preserves Unicode characters and apostrophes in filenames, including on Windows. Aliases can contain spaces and quotes. Complete SQL-quoted aliases retain their legacy meaning; see [attachment alias compatibility](/docs/guides/attach-databases#file-paths-and-aliases). Use a quoted SQL identifier when querying such an alias, and pass the same alias form to `detach()`. + 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 storage settings for [iOS](/docs/configuration/ios#database-location) and [Android](/docs/configuration/android#database-location) in both hosts, and [macOS](/docs/configuration/macos) in React Native. See [supported platforms](/docs/supported-platforms) for the host and operating system combinations. The generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) lists the lifecycle methods. diff --git a/packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp b/packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp index 8d3fb761..c1490fa7 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp @@ -2,6 +2,7 @@ #include "SQLiteDatabaseMigration.hpp" #include "SQLiteException.hpp" #include "SQLiteLogs.hpp" +#include "SQLiteUtils.hpp" #include #include #include @@ -60,13 +61,13 @@ namespace { if (mode != 'r' && mode != 'w') { return std::nullopt; } - return IndependentId{fs::path(key.substr(separator + 2)), mode == 'r'}; + return IndependentId{pathFromUtf8(key.substr(separator + 2)), mode == 'r'}; } std::string connectionLabel(const std::string& key) { const auto independent = parseIndependentId(key); if (independent) { - return independent->physicalPath.string(); + return pathToUtf8(independent->physicalPath); } return key.find('\0') == std::string::npos ? key : "invalid connection ID"; } @@ -82,7 +83,7 @@ namespace { int result; while ((result = sqlite3_step(statement.get())) == SQLITE_ROW) { const auto* rawPath = reinterpret_cast(sqlite3_column_text(statement.get(), 2)); - if (rawPath != nullptr && rawPath[0] != '\0' && predicate(fs::path(rawPath))) { + if (rawPath != nullptr && rawPath[0] != '\0' && predicate(pathFromUtf8(rawPath))) { return true; } } @@ -354,7 +355,7 @@ 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) { + if (path.native().find(fs::path::value_type{}) != fs::path::string_type::npos) { throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); } if (sqlite3_threadsafe() == 0) { @@ -363,14 +364,14 @@ std::string DatabaseConnections::openIndependent(const fs::path& path, bool read // NUL cannot occur in a filesystem name. The ID cannot collide with a legacy database key. const auto physicalPath = canonicalDatabasePath(path); const std::string key = std::string(1, '\0') + kIndependentPrefix + std::to_string(++processConnections().nextConnectionId) + - std::string(1, '\0') + (readOnly ? "r" : "w") + physicalPath.string(); + std::string(1, '\0') + (readOnly ? "r" : "w") + pathToUtf8(physicalPath); openKey(key, path, readOnly, encryptionKey); return key; } 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) { + if (path.native().find(fs::path::value_type{}) != fs::path::string_type::npos) { throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, "Database path contains a NUL byte"); } validateEncryptionKey(encryptionKey); @@ -380,7 +381,7 @@ void DatabaseConnections::openKey(const std::string& key, const fs::path& path, // per-call connection mutex would only add a lock and unlock to each API call. const int flags = (readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) | SQLITE_OPEN_NOMUTEX; sqlite3* rawDatabase = nullptr; - const int result = sqlite3_open_v2(physicalPath.string().c_str(), &rawDatabase, flags, nullptr); + const int result = sqlite3_open_v2(pathToUtf8(physicalPath).c_str(), &rawDatabase, flags, nullptr); std::unique_ptr database(rawDatabase, sqlite3_close_v2); if (result != SQLITE_OK) { const std::string message = rawDatabase == nullptr ? sqlite3_errstr(result) : sqlite3_errmsg(rawDatabase); @@ -490,7 +491,7 @@ void DatabaseConnections::drop(const std::string& dbName, const fs::path& path, validateDatabaseName(dbName); const auto target = canonicalDatabasePath(path); if (!fs::exists(target)) { - throw SQLiteException::DatabaseFileNotFound(target.string()); + throw SQLiteException::DatabaseFileNotFound(pathToUtf8(target)); } const auto key = connectionId.value_or(dbName); const auto live = connections.find(key); @@ -517,16 +518,16 @@ void DatabaseConnections::drop(const std::string& dbName, const fs::path& path, throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "Database is in use by another connection"); } if (!fs::exists(target)) { - throw SQLiteException::DatabaseFileNotFound(target.string()); + throw SQLiteException::DatabaseFileNotFound(pathToUtf8(target)); } if (connectionToClose) { close(key); } - if (!removeDatabaseFiles(target.filename().string(), target.parent_path())) { + if (!removeDatabaseFiles(pathToUtf8(target.filename()), target.parent_path())) { throw SQLiteException(SQLiteExceptionType::SqlExecutionError, "Could not remove database files"); } if (otherPath) { - removeDatabaseFiles(otherPath->filename().string(), otherPath->parent_path()); + removeDatabaseFiles(pathToUtf8(otherPath->filename()), otherPath->parent_path()); } }); } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteDatabaseMigration.cpp b/packages/nitro-sqlite-core/cpp/SQLiteDatabaseMigration.cpp index 65c0c72e..506d0ea3 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteDatabaseMigration.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteDatabaseMigration.cpp @@ -1,5 +1,6 @@ #include "SQLiteDatabaseMigration.hpp" #include "SQLiteLogs.hpp" +#include "SQLiteUtils.hpp" #include #include @@ -21,7 +22,7 @@ namespace { fs::path migrateDatabase(const std::string& dbName, const fs::path& fromDirectory, const fs::path& toDirectory) { const auto files = getDatabaseFiles(dbName); std::error_code ec; - const bool sourceExists = fs::exists(fromDirectory / dbName, ec); + const bool sourceExists = fs::exists(fromDirectory / pathFromUtf8(dbName), ec); if (ec) { LOGW("Failed to inspect database %s in its old location: %s", dbName.c_str(), ec.message().c_str()); @@ -43,7 +44,7 @@ fs::path migrateDatabase(const std::string& dbName, const fs::path& fromDirector fs::create_directories(toDirectory, ec); if (ec) { - LOGW("Failed to create database migration directory %s: %s", toDirectory.string().c_str(), ec.message().c_str()); + LOGW("Failed to create database migration directory %s: %s", pathToUtf8(toDirectory).c_str(), ec.message().c_str()); return fromDirectory; } @@ -54,7 +55,7 @@ fs::path migrateDatabase(const std::string& dbName, const fs::path& fromDirector // Delete the database first. If this fails, every source journal must remain beside it so the // caller can safely keep using the old location. Leftover journals after a successful database // deletion are harmless and are removed on the next migration attempt. - if (!fs::remove(fromDirectory / dbName, ec) || ec) { + if (!fs::remove(fromDirectory / pathFromUtf8(dbName), ec) || ec) { LOGW("Failed to remove migrated database %s from its old location: %s", dbName.c_str(), ec.message().c_str()); return fromDirectory; } @@ -68,7 +69,7 @@ bool removeDatabaseFiles(const std::string& dbName, const fs::path& directory) { for (const auto& file : files) { std::error_code ec; - fs::remove(directory / file, ec); + fs::remove(directory / pathFromUtf8(file), ec); if (ec) { LOGW("Failed to remove database file %s: %s", file.c_str(), ec.message().c_str()); return false; @@ -87,7 +88,7 @@ namespace { bool copyDatabaseFiles(const DatabaseFiles& files, const fs::path& fromDirectory, const fs::path& toDirectory) { for (const auto& file : files) { std::error_code ec; - const bool sourceExists = fs::exists(fromDirectory / file, ec); + const bool sourceExists = fs::exists(fromDirectory / pathFromUtf8(file), ec); if (ec) { LOGW("Failed to inspect database file %s: %s", file.c_str(), ec.message().c_str()); @@ -98,7 +99,7 @@ namespace { continue; } - if (!fs::copy_file(fromDirectory / file, toDirectory / file, ec) || ec) { + if (!fs::copy_file(fromDirectory / pathFromUtf8(file), toDirectory / pathFromUtf8(file), ec) || ec) { LOGW("Failed to migrate database file %s: %s", file.c_str(), ec.message().c_str()); return false; } @@ -111,7 +112,7 @@ namespace { for (std::size_t index = 1; index < files.size(); index++) { const auto& file = files[index]; std::error_code ec; - fs::remove(directory / file, ec); + fs::remove(directory / pathFromUtf8(file), ec); if (ec) { LOGW("Failed to remove database file %s: %s", file.c_str(), ec.message().c_str()); } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.cpp b/packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.cpp index 378ab3f6..28340421 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.cpp @@ -5,6 +5,7 @@ #include "SQLiteImportSqlFile.hpp" #include "SQLiteException.hpp" #include "SQLiteOperations.hpp" +#include "SQLiteUtils.hpp" #include #include #include @@ -13,7 +14,7 @@ namespace margelo::nitro::nitrosqlite { SQLiteOperationResult importSqlFile(const SQLiteConnectionPtr& connection, const std::string& fileLocation) { std::lock_guard lock(connection->mutex); - std::ifstream sqFile(fileLocation); + std::ifstream sqFile(pathFromUtf8(fileLocation)); if (!sqFile.is_open()) { throw SQLiteException::CouldNotLoadFile(fileLocation); } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index 7ca3e5c2..aaa00042 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -5,6 +5,7 @@ #include "SQLiteUtils.hpp" #include "sqlite/sqlite3.h" #include +#include #include #include #include @@ -14,7 +15,7 @@ #include #include #include -#include +#include #ifdef NITRO_SQLITE_VEC // Angle-bracket so it resolves via -I (CocoaPods intercepts quoted includes). @@ -28,14 +29,55 @@ namespace margelo::nitro::nitrosqlite { static constexpr double kInt64MinAsDouble = static_cast(std::numeric_limits::min()); static constexpr double kInt64UpperBoundAsDouble = -kInt64MinAsDouble; +namespace { + + std::string normalizeDatabaseAlias(const std::string& alias) { + const auto first = alias.find_first_not_of(" \t\r\n\f\v"); + if (first == std::string::npos) + return alias; + const auto last = alias.find_last_not_of(" \t\r\n\f\v"); + const std::string_view token(alias.data() + first, last - first + 1); + const auto isIdentifierStart = [](unsigned char character) { + return character == '_' || character >= 0x80 || (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); + }; + if (alias.find('\v') == std::string::npos && isIdentifierStart(token.front()) && + std::all_of(token.begin() + 1, token.end(), [&](unsigned char character) { + return isIdentifierStart(character) || character == '$' || (character >= '0' && character <= '9'); + })) { + return std::string(token); + } + if (token.size() < 2) + return alias; + const char opening = token.front(); + const char closing = opening == '[' ? ']' : opening; + const bool isQuoted = opening == '"' || opening == '\'' || opening == '`' || opening == '['; + if (!isQuoted || token.back() != closing) + return alias; + + std::string name; + name.reserve(token.size() - 2); + for (size_t index = 1; index < token.size() - 1; index++) { + if (token[index] == closing) { + // Only a complete quoted token is legacy syntax. Other input remains a raw name. + if (opening == '[' || index + 1 == token.size() - 1 || token[index + 1] != closing) + return alias; + index++; + } + name.push_back(token[index]); + } + return name; + } + +} // namespace + void sqliteOpenDb(DatabaseConnections& connections, const std::string& dbName, const std::string& docPath, bool readOnly, const std::optional& encryptionKey) { #ifdef NITRO_SQLITE_VEC // Register before opening so the connection exposes vec0 + vec_*. margelo::nitrosqlitevec::registerVectorExtensions(); #endif - const std::string dbPath = readOnly ? docPath + "/" + dbName : get_db_path(dbName, docPath); - connections.open(dbName, dbPath, readOnly, encryptionKey); + const std::string dbPath = readOnly ? docPath + "/" + dbName : getWritableDatabasePath(dbName, docPath); + connections.open(dbName, pathFromUtf8(dbPath), readOnly, encryptionKey); } std::string sqliteOpenConnection(DatabaseConnections& connections, const std::string& dbName, const std::string& docPath, bool readOnly, @@ -46,17 +88,15 @@ std::string sqliteOpenConnection(DatabaseConnections& connections, const std::st #ifdef NITRO_SQLITE_VEC margelo::nitrosqlitevec::registerVectorExtensions(); #endif - const std::string dbPath = readOnly ? docPath + "/" + dbName : get_db_path(dbName, docPath); - return connections.openIndependent(dbPath, readOnly, encryptionKey); + const std::string dbPath = readOnly ? docPath + "/" + dbName : getWritableDatabasePath(dbName, docPath); + return connections.openIndependent(pathFromUtf8(dbPath), readOnly, encryptionKey); } void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& docPath, const std::string& databaseToAttach, const std::string& alias) { - std::string dbPath = get_db_path(databaseToAttach, docPath); - std::string statement = "ATTACH DATABASE '" + dbPath + "' AS " + alias; - + std::string dbPath = getWritableDatabasePath(databaseToAttach, docPath); try { - sqliteExecuteCommand(connection, statement); + sqliteExecuteCommand(connection, "ATTACH DATABASE ? AS ?", SQLiteQueryParams{dbPath, normalizeDatabaseAlias(alias)}); } catch (SQLiteException& e) { throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, connection->name + " was unable to attach another database: " + std::string(e.what())); @@ -64,10 +104,8 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do } void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& alias) { - std::string statement = "DETACH DATABASE " + alias; - try { - sqliteExecuteCommand(connection, statement); + sqliteExecuteCommand(connection, "DETACH DATABASE ?", SQLiteQueryParams{normalizeDatabaseAlias(alias)}); } catch (SQLiteException& e) { throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, connection->name + " was unable to detach database: " + std::string(e.what())); @@ -78,9 +116,9 @@ void sqliteRemoveDb(DatabaseConnections& connections, const std::string& dbName, const std::optional& connectionId, const std::optional& otherDocPath) { std::optional otherPath; if (otherDocPath) { - otherPath = std::filesystem::path(*otherDocPath) / dbName; + otherPath = pathFromUtf8(*otherDocPath) / pathFromUtf8(dbName); } - connections.drop(dbName, std::filesystem::path(docPath) / dbName, connectionId, otherPath); + connections.drop(dbName, pathFromUtf8(docPath) / pathFromUtf8(dbName), connectionId, otherPath); } void bindStatement(sqlite3_stmt* statement, const SQLiteQueryParams& values) { diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index b1f31a3d..6cda2120 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -58,9 +58,15 @@ void sqliteRemoveDb(DatabaseConnections& connections, const std::string& dbName, const std::optional& connectionId = std::nullopt, const std::optional& otherDocPath = std::nullopt); +/** Attach a UTF-8 filename under a raw or complete SQL-quoted schema alias. Throws UnableToAttachToDatabase on failure. + * Complete legacy double, single, backtick and bracket quoting is decoded before binding. + * Surrounding SQL whitespace is ignored for bare identifiers; quoted names retain their inner whitespace. + * Other aliases and the filename are bound as data, so SQL is never evaluated. + */ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& docPath, const std::string& databaseToAttach, const std::string& alias); +/** Detach a raw or complete SQL-quoted schema alias using the same decoding as attach. Throws UnableToAttachToDatabase on failure. */ void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& alias); /** Execute one statement. With @p onRows, full batches of rows go to it as they are read and the diff --git a/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp index c1d82797..1ddb358b 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp @@ -1,60 +1,48 @@ #pragma once +#include #include +#include +#ifndef _WIN32 +#include #include +#endif namespace margelo::nitro::nitrosqlite { -bool folder_exists(const std::string& foldername) { - struct stat buffer; - return (stat(foldername.c_str(), &buffer) == 0); +// JS and SQLite use UTF-8, while Windows filesystem paths use UTF-16. +inline std::filesystem::path pathFromUtf8(const std::string& path) { +#ifdef _WIN32 + return std::filesystem::u8path(path); +#else + return std::filesystem::path(path); +#endif } -/** - * Portable wrapper for mkdir. Internally used by mkdir() - * @param[in] path the full path of the directory to create. - * @return zero on success, otherwise -1. - */ -int _mkdir(const char* path) { -#if _POSIX_C_SOURCE - return mkdir(path); +inline std::string pathToUtf8(const std::filesystem::path& path) { +#ifdef _WIN32 + const auto utf8 = path.u8string(); + return {utf8.begin(), utf8.end()}; #else - return mkdir(path, 0755); // not sure if this works on mac + return path.native(); #endif } -/** - * Recursive, portable wrapper for mkdir. - * @param[in] path the full path of the directory to create. - * @return zero on success, otherwise -1. - */ -int mkdir(const char* path) { - std::string current_level = "/"; - std::string level; - std::stringstream ss(path); - // First line is empty because it starts with /User - getline(ss, level, '/'); - // split path using slash as a separator - while (getline(ss, level, '/')) { - current_level += level; // append folder to the current level - // create current level - if (!folder_exists(current_level) && _mkdir(current_level.c_str()) != 0) - return -1; - - current_level += "/"; // don't forget to append a slash +inline std::string getWritableDatabasePath(const std::string& dbName, const std::string& directory) { +#ifdef _WIN32 + std::error_code error; + std::filesystem::create_directories(pathFromUtf8(directory), error); +#else + // Keep the existing POSIX creation mode without changing the process-wide umask. + std::filesystem::path current; + for (const auto& component : pathFromUtf8(directory)) { + current /= component; + if (::mkdir(current.c_str(), 0755) != 0 && errno != EEXIST) + break; } - - return 0; -} - -inline bool file_exists(const std::string& path) { - struct stat buffer; - return (stat(path.c_str(), &buffer) == 0); -} - -std::string get_db_path(const std::string& dbName, const std::string& docPath) { - mkdir(docPath.c_str()); - return docPath + "/" + dbName; +#endif + // Let SQLite report an open error if it can't access the directory. + return directory + "/" + dbName; } } // namespace margelo::nitro::nitrosqlite diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index 7b7a048e..be71eb12 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -6,6 +6,7 @@ #include "../SQLiteLogs.hpp" #include "../SQLiteMacros.hpp" #include "../SQLiteOperations.hpp" +#include "../SQLiteUtils.hpp" #include "HybridPreparedStatement.hpp" #include "SQLiteConnectionOperation.hpp" #include "SQLiteRowBatchSender.hpp" @@ -29,7 +30,13 @@ namespace margelo::nitro::nitrosqlite { static void configureTemporaryDirectory(const std::string& temporaryDirectory) { static std::once_flag configureOnce; static bool configured = false; - std::call_once(configureOnce, [&] { configured = setenv("SQLITE_TMPDIR", temporaryDirectory.c_str(), 1) == 0; }); + std::call_once(configureOnce, [&] { +#ifdef _WIN32 + configured = _putenv_s("SQLITE_TMPDIR", temporaryDirectory.c_str()) == 0; +#else + configured = setenv("SQLITE_TMPDIR", temporaryDirectory.c_str(), 1) == 0; +#endif + }); if (!configured) { throw std::runtime_error("Could not configure SQLite temporary directory"); } @@ -110,14 +117,14 @@ const std::string getMigratedDocPath(DatabaseConnections& connections, const std const auto oldDocPath = getOldDocPath(legacyDatabaseDirectory, location); std::string selectedPath; connections.withConnectionsLocked([&]() { - const auto oldPath = std::filesystem::path(oldDocPath) / dbName; - const auto livePath = connections.findLivePath(oldPath, std::filesystem::path(currentDocPath) / dbName); + const auto oldPath = pathFromUtf8(oldDocPath) / pathFromUtf8(dbName); + const auto livePath = connections.findLivePath(oldPath, pathFromUtf8(currentDocPath) / pathFromUtf8(dbName)); if (livePath) { selectedPath = *livePath == oldPath ? oldDocPath : currentDocPath; } else if (readOnly) { - selectedPath = std::filesystem::exists(std::filesystem::path(oldDocPath) / dbName) ? oldDocPath : currentDocPath; + selectedPath = std::filesystem::exists(pathFromUtf8(oldDocPath) / pathFromUtf8(dbName)) ? oldDocPath : currentDocPath; } else { - selectedPath = migrateDatabase(dbName, oldDocPath, currentDocPath).string(); + selectedPath = pathToUtf8(migrateDatabase(dbName, pathFromUtf8(oldDocPath), pathFromUtf8(currentDocPath))); } }); return selectedPath; @@ -167,9 +174,9 @@ void HybridNitroSQLite::drop(const std::string& dbName, const std::optional +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include 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 88bea3ca..d0bba99c 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,7 @@ #include "SQLiteDatabaseConnections.hpp" +#include "SQLiteDatabaseMigration.hpp" +#include "SQLiteException.hpp" +#include "SQLiteUtils.hpp" #include #include #include @@ -381,6 +384,34 @@ int main() { "a replacement handler must only receive changes it recorded, and discard its failed statements"); registry.close("changes.sqlite"); + using margelo::nitro::nitrosqlite::getWritableDatabasePath; + using margelo::nitro::nitrosqlite::migrateDatabase; + using margelo::nitro::nitrosqlite::pathFromUtf8; + using margelo::nitro::nitrosqlite::pathToUtf8; + const std::string unicodeName = "caf\xC3\xA9.sqlite"; + const auto unicodeDirectory = root / pathFromUtf8("\xE6\x95\xB0\xE6\x8D\xAE") / "nested"; + const auto unicodePath = pathFromUtf8(getWritableDatabasePath(unicodeName, pathToUtf8(unicodeDirectory))); + const auto unicodeId = registry.openIndependent(unicodePath, false); + execute(registry.get(unicodeId), "CREATE TABLE example (value INTEGER); INSERT INTO example VALUES (42)"); + expect(fs::exists(unicodeDirectory / pathFromUtf8(unicodeName)), "SQLite must create the UTF-8 database in the requested directory"); + try { + registry.drop(unicodeName, unicodePath, std::nullopt); + throw std::runtime_error("drop must detect a live handle on the UTF-8 path"); + } catch (const SQLiteException& error) { + expect(std::string(error.what()) == "[NativeNitroSQLiteException][SqlExecutionError] Database is in use by another connection", + "drop must report the in-use error, not a missing or misdecoded UTF-8 path"); + } + registry.close(unicodeId); + + const auto migratedDirectory = unicodeDirectory / "moved"; + expect(migrateDatabase(unicodeName, unicodeDirectory, migratedDirectory) == migratedDirectory, + "migration must find and copy a database with a UTF-8 name"); + const auto migratedPath = migratedDirectory / pathFromUtf8(unicodeName); + const auto migratedId = registry.openIndependent(migratedPath, false); + expect(scalar(registry.get(migratedId), "SELECT value FROM example") == 42, "migration must preserve the database contents"); + registry.drop(unicodeName, migratedPath, migratedId); + expect(!fs::exists(migratedPath), "drop must decode the independent ID and remove the UTF-8 database"); + registry.closeAll(); fs::remove_all(root); std::cout << "[PASS] runtime ownership, independent connections, lifecycle, attachments, read-only and concurrent writes\n"; 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 f03d9833..4f332e58 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseMigration.test.cpp @@ -12,8 +12,10 @@ #include #include #include +#ifndef _WIN32 #include #include +#endif namespace fs = std::filesystem; using namespace margelo::nitro::nitrosqlite; @@ -119,9 +121,11 @@ void preservesSourceWhenCopyingAnAuxiliaryFileFails(); void removesOrphanedSourceJournalsAfterAnInterruptedMigration(); void removesEveryDatabaseGenerationFile(); void reportsCleanupFailureForNonemptyDatabaseDirectory(); +#ifndef _WIN32 void recoversCommittedWalAfterMigration(); void rollsBackHotJournalAfterMigration(); void runWithoutCleanShutdown(const std::function& action); +#endif void writeFile(const fs::path& path, const std::string& contents); std::string readFile(const fs::path& path); @@ -142,8 +146,10 @@ int main() { {"removes orphaned source journals after an interrupted migration", removesOrphanedSourceJournalsAfterAnInterruptedMigration}, {"removes every database generation file", removesEveryDatabaseGenerationFile}, {"reports cleanup failure for a nonempty database directory", reportsCleanupFailureForNonemptyDatabaseDirectory}, +#ifndef _WIN32 {"recovers committed WAL content after migration", recoversCommittedWalAfterMigration}, {"rolls back a hot journal after migration", rollsBackHotJournalAfterMigration}, +#endif }; int failures = 0; @@ -293,6 +299,8 @@ void reportsCleanupFailureForNonemptyDatabaseDirectory() { expect(readFile(directory / (dbName + "-wal")) == "must remain untouched", "cleanup should stop before deleting another generation file"); } +#ifndef _WIN32 +// These fixtures simulate a crash with fork(), which is unavailable on Windows. void recoversCommittedWalAfterMigration() { TemporaryDirectory temporaryDirectory; const auto source = temporaryDirectory.path / "Documents"; @@ -402,6 +410,8 @@ void runWithoutCleanShutdown(const std::function& action) { expect(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS, "crash-test child process failed"); } +#endif + void writeFile(const fs::path& path, const std::string& contents) { fs::create_directories(path.parent_path()); std::ofstream file(path, std::ios::binary); diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp new file mode 100644 index 00000000..fac6f66d --- /dev/null +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -0,0 +1,120 @@ +#include "SQLiteImportSqlFile.hpp" +#include "SQLiteOperations.hpp" +#include "SQLiteUtils.hpp" +#include +#include +#include +#include +#include +#ifndef _WIN32 +#include +#endif + +using namespace margelo::nitro::rnnitrosqlite; +namespace fs = std::filesystem; + +int main() { + const auto root = + fs::temp_directory_path() / ("nitro-paths-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + DatabaseConnections connections; + try { +#ifndef _WIN32 + for (mode_t mask : {mode_t(0), mode_t(0077)}) { + const auto directory = root / std::to_string(mask) / "nested"; + const auto previous = umask(mask); + try { + getWritableDatabasePath("permissions.sqlite", pathToUtf8(directory)); + } catch (...) { + umask(previous); + throw; + } + umask(previous); + for (const auto& created : {directory.parent_path(), directory}) { + const auto permissions = fs::status(created).permissions() & fs::perms::all; + if (permissions != static_cast(0755 & ~mask)) + throw std::runtime_error("created database directories must preserve the 0755 permission ceiling and umask"); + } + fs::permissions(directory, fs::perms::owner_all); + getWritableDatabasePath("permissions.sqlite", pathToUtf8(directory)); + if ((fs::status(directory).permissions() & fs::perms::all) != fs::perms::owner_all) + throw std::runtime_error("opening an existing directory must preserve its permissions"); + } +#endif + const auto directory = root / pathFromUtf8("数据's files"); + const auto docPath = pathToUtf8(directory); + const std::string attachedName = "café's.sqlite"; + sqliteOpenDb(connections, "main.sqlite", docPath, false, std::nullopt); + const auto main = connections.get("main.sqlite"); + sqliteAttachDb(main, docPath, attachedName, "my \"quoted\" alias"); + sqliteExecuteCommand(main, R"sql(CREATE TABLE "my ""quoted"" alias".item (value INTEGER))sql"); + sqliteExecuteCommand(main, R"sql(INSERT INTO "my ""quoted"" alias".item VALUES (42))sql"); + sqliteDetachDb(main, "my \"quoted\" alias"); + if (!fs::exists(directory / pathFromUtf8(attachedName))) + throw std::runtime_error("attachment used the wrong UTF-8 filename"); + struct AliasCase { + const char* attachAlias; + const char* schema; + const char* detachAlias; + }; + const AliasCase aliases[] = { + {"archive", "archive", "archive"}, + {" \tarchive\r\n\f", "archive", "archive"}, + {" \t数据_2$\r\n\f", "数据_2$", "数据_2$"}, + {" x ", "x", "x"}, + {R"(" archive ")", " archive ", R"(" archive ")"}, + {" sales archive ", " sales archive ", " sales archive "}, + {"sales archive", "sales archive", R"("sales archive")"}, + {R"("sales archive")", "sales archive", "sales archive"}, + {R"("sales ""archive""")", "sales \"archive\"", R"("sales ""archive""")"}, + {"'sales ''archive'''", "sales 'archive'", "'sales ''archive'''"}, + {"`sales ``archive```", "sales `archive`", "`sales ``archive```"}, + {"[sales archive]", "sales archive", "[sales archive]"}, + {" \t\"sales archive\"\n", "sales archive", " \t[sales archive]\n"}, + {" \v\"sales archive\"\t\v", "sales archive", "sales archive"}, + {R"("""archive""")", R"("archive")", R"("""archive""")"}, + {R"("raw"quote")", R"("raw"quote")", R"("raw"quote")"}, + {"raw; SELECT 1", "raw; SELECT 1", "raw; SELECT 1"}, + }; + for (const auto& test : aliases) { + sqliteAttachDb(main, docPath, attachedName, test.attachAlias); + const auto schema = + sqliteExecuteRaw(main, "SELECT name FROM pragma_database_list WHERE name = ?", SQLiteQueryParams{std::string(test.schema)}); + if (schema.rows.size() != 1) { + throw std::runtime_error(std::string("attachment changed alias compatibility: ") + test.attachAlias); + } + sqliteDetachDb(main, test.detachAlias); + const auto remaining = + sqliteExecuteRaw(main, "SELECT name FROM pragma_database_list WHERE name = ?", SQLiteQueryParams{std::string(test.schema)}); + if (!remaining.rows.empty()) + throw std::runtime_error("detach left the alias attached"); + } + sqliteAttachDb(main, docPath, attachedName, "archive"); + sqliteAttachDb(main, docPath, attachedName, " \tarchive\v"); + sqliteDetachDb(main, " \tarchive\v"); + const auto bareAlias = sqliteExecuteRaw(main, "SELECT name FROM pragma_database_list WHERE name = 'archive'", std::nullopt); + if (bareAlias.rows.size() != 1) + throw std::runtime_error("detaching a raw vertical-tab alias must preserve the separate bare alias"); + sqliteDetachDb(main, "archive"); + sqliteOpenDb(connections, attachedName, docPath, false, std::nullopt); + const auto attached = connections.get(attachedName); + auto result = sqliteExecuteRaw(attached, "SELECT value FROM item", std::nullopt); + if (std::get(*result.rows.at(0).at(0)) != 42) + throw std::runtime_error("attached writes were not saved"); + const auto sqlFile = directory / pathFromUtf8("导入's.sql"); + { + std::ofstream file(sqlFile); + file << "INSERT INTO item VALUES (7)\n"; + } + if (importSqlFile(attached, pathToUtf8(sqlFile)).rowsAffected != 1) + throw std::runtime_error("UTF-8 SQL file import failed"); + connections.closeAll(); + fs::remove_all(root); + std::cout << "[PASS] Unicode and quoted attachment paths, aliases, detach and SQL import\n"; + return 0; + } catch (const std::exception& error) { + connections.closeAll(); + fs::remove_all(root); + std::cerr << "[FAIL] " << error.what() << '\n'; + return 1; + } +} 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 8fa2c0fb..4a44ba62 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/statementCache.test.cpp @@ -126,6 +126,19 @@ void testReuseAfterError(sqlite3* db) { cache.put(sql, statement, checkout); } +void testRepeatedLongSql(sqlite3* db) { + SQLiteStatementCache::Checkout checkout; + SQLiteStatementCache cache; + const std::string sql = "SELECT 1 /* " + std::string(512, 'x') + " */"; + sqlite3_stmt* statement = prepare(db, sql); + cache.put(sql, statement, checkout); + for (size_t i = 0; i < 256; i++) { + expect(cache.take(sql, checkout) == statement, "long SQL keeps its index entry across repeated checkouts"); + cache.put(sql, statement, checkout); + } + expect(liveStatements(db) == 1, "repeated long SQL checkouts retain only one statement"); +} + void testClear(sqlite3* db) { SQLiteStatementCache::Checkout checkout; SQLiteStatementCache cache; @@ -165,6 +178,7 @@ int main() { testEviction(db); testReuseAfterError(db); testClear(db); + testRepeatedLongSql(db); expect(liveStatements(db) == 0, "destroying the cache finalizes its statements"); expect(sqlite3_close(db) == SQLITE_OK, "the database closes without any live statements"); std::cout << "[PASS] statement cache reuse, reentrancy, eviction, error recovery and cleanup\n"; diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index f3389532..6cd81225 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -240,6 +240,33 @@ test('platform test overlays do not rebuild native apps', () => { assert.equal(checks.macos, false) }) +test('UTF-8 path helpers select native C++ regressions', () => { + const checks = selectChecks( + ['packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp'], + false, + ) + assert.equal(checks.cpp_tests, true) +}) + +test('host C++ dependency headers and Nitro patches select regressions', () => { + for (const file of [ + 'package.json', + 'bun.lock', + 'bunfig.toml', + 'examples/react-native/package.json', + 'packages/react-native-nitro-sqlite/package.json', + 'packages/react-native-nitro-sqlite/cpp/SQLiteStatementCache.hpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteException.hpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteLogs.hpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteTypes.hpp', + 'packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.hpp', + 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include/RNNitroSQLite/NativeRawQueryResult.hpp', + 'patches/react-native-nitro-modules+1.0.0.patch', + ]) { + assert.equal(selectChecks([file], false).cpp_tests, true, file) + } +}) + test('generated platform bindings do not trigger the other mobile platform', () => { const checks = selectChecks( [ diff --git a/scripts/ci.ts b/scripts/ci.ts index 0839153c..7a803164 100644 --- a/scripts/ci.ts +++ b/scripts/ci.ts @@ -84,6 +84,7 @@ function main(): void { } const dependencies = checks.typescript || + checks.cpp_tests || checks.expo_plugin || checks.docs || checks.android || diff --git a/scripts/prepare-cpp-test-headers.cjs b/scripts/prepare-cpp-test-headers.cjs new file mode 100644 index 00000000..572175f6 --- /dev/null +++ b/scripts/prepare-cpp-test-headers.cjs @@ -0,0 +1,8 @@ +const fs = require('node:fs') +const path = require('node:path') + +const output = path.resolve(process.argv[2]) +const source = path.resolve( + 'node_modules/react-native-nitro-modules/cpp/core/include', +) +fs.cpSync(source, output, { recursive: true }) diff --git a/scripts/test-cpp.sh b/scripts/test-cpp.sh index 7d834635..986cc057 100644 --- a/scripts/test-cpp.sh +++ b/scripts/test-cpp.sh @@ -177,6 +177,31 @@ clang++ \ -o /tmp/databaseConnectionsThreadsafeTests /tmp/databaseConnectionsThreadsafeTests +header_directory=$(mktemp -d) +trap 'rm -rf "$header_directory"' EXIT +node scripts/prepare-cpp-test-headers.cjs "$header_directory" +clang++ \ + -std=c++20 \ + -Wall -Wextra -Werror \ + -I"$header_directory" -I"$header_directory/NitroModules" \ + -Ipackages/react-native-nitro-sqlite/cpp/sqlite \ + -Inode_modules/react-native/ReactCommon/jsi \ + -Ipackages/react-native-nitro-sqlite/cpp \ + -Ipackages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/include \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseConnections.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteOperations.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.cpp \ + packages/react-native-nitro-sqlite/cpp/SQLiteJSON.cpp \ + packages/react-native-nitro-sqlite/cpp/NativeQueryResult.cpp \ + node_modules/react-native-nitro-modules/cpp/core/src/ArrayBuffer.cpp \ + node_modules/react-native/ReactCommon/jsi/jsi/jsi.cpp \ + packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp \ + /tmp/sqlite3.o -ldl -lm -pthread \ + -o /tmp/databasePathsTests +/tmp/databasePathsTests + if [ -n "${NITRO_SQLITE_HERMES_DIR:-}" ]; then bash scripts/test-cpp-hermes.sh else