From d2d4693206b027a98cafd36e39717edf9fa60e43 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Mon, 30 Nov 2026 13:32:09 +0100 Subject: [PATCH 1/9] fix: preserve Unicode SQLite paths on Windows Use native filesystem paths for file operations and UTF-8 at the SQLite boundary. Run the database connection tests under MSVC to cover Windows file handling. Co-authored-by: Codex --- .github/workflows/test-windows-native.yml | 33 ++++++++++ .../cpp/SQLiteDatabaseConnections.cpp | 23 +++---- .../cpp/SQLiteDatabaseMigration.cpp | 15 +++-- .../cpp/SQLiteImportSqlFile.cpp | 3 +- .../cpp/SQLiteOperations.cpp | 21 +++--- .../nitro-sqlite-core/cpp/SQLiteUtils.hpp | 64 ++++++------------- .../cpp/hybridObjects/HybridNitroSQLite.cpp | 13 ++-- .../tests/cpp/databaseConnections.test.cpp | 24 +++++++ 8 files changed, 114 insertions(+), 82 deletions(-) create mode 100644 .github/workflows/test-windows-native.yml diff --git a/.github/workflows/test-windows-native.yml b/.github/workflows/test-windows-native.yml new file mode 100644 index 00000000..d8b817a3 --- /dev/null +++ b/.github/workflows/test-windows-native.yml @@ -0,0 +1,33 @@ +name: Test Windows SQLite files + +on: + pull_request: + paths: + - '.github/workflows/test-windows-native.yml' + - 'packages/react-native-nitro-sqlite/cpp/**' + - 'packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp' + workflow_dispatch: + +permissions: + contents: read + +jobs: + sqlite-files: + runs-on: windows-2025 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v7 + - name: Build and run the database connection 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 + Set-Location $env:RUNNER_TEMP + cl /nologo /c /TC /DSQLITE_THREADSAFE=2 "$package\cpp\sqlite\sqlite3.c" /Fosqlite3.obj + cl /nologo /std:c++20 /EHsc /utf-8 "/I$package\cpp" ` + "$package\cpp\NitroSQLiteDatabaseConnections.cpp" "$package\cpp\NitroSQLiteDatabaseMigration.cpp" ` + "$package\tests\cpp\databaseConnections.test.cpp" sqlite3.obj /FedatabaseConnectionsTests.exe + .\databaseConnectionsTests.exe 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..6b41dc61 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #ifdef NITRO_SQLITE_VEC // Angle-bracket so it resolves via -I (CocoaPods intercepts quoted includes). @@ -34,8 +33,8 @@ void sqliteOpenDb(DatabaseConnections& connections, const std::string& dbName, c // 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,20 +45,18 @@ 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 " + alias, SQLiteQueryParams{dbPath}); } catch (SQLiteException& e) { throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, - connection->name + " was unable to attach another database: " + std::string(e.what())); + connection->name + " was unable to attach another database: " + std::string(e.what())); } } @@ -78,9 +75,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/SQLiteUtils.hpp b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp index c1d82797..4c25f60d 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp @@ -1,60 +1,34 @@ #pragma once +#include #include -#include +#include namespace margelo::nitro::nitrosqlite { -bool folder_exists(const std::string& foldername) { - struct stat buffer; - return (stat(foldername.c_str(), &buffer) == 0); -} - -/** - * 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); +// 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 mkdir(path, 0755); // not sure if this works on mac + return std::filesystem::path(path); #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 - } - - return 0; -} - -inline bool file_exists(const std::string& path) { - struct stat buffer; - return (stat(path.c_str(), &buffer) == 0); +inline std::string pathToUtf8(const std::filesystem::path& path) { +#ifdef _WIN32 + const auto utf8 = path.u8string(); + return {utf8.begin(), utf8.end()}; +#else + return path.native(); +#endif } -std::string get_db_path(const std::string& dbName, const std::string& docPath) { - mkdir(docPath.c_str()); - return docPath + "/" + dbName; +inline std::string getWritableDatabasePath(const std::string& dbName, const std::string& directory) { + std::error_code error; + std::filesystem::create_directories(pathFromUtf8(directory), error); + // 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..ea877a79 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" @@ -110,14 +111,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 +168,9 @@ void HybridNitroSQLite::drop(const std::string& dbName, const std::optional #include #include @@ -381,6 +383,28 @@ int main() { "a replacement handler must only receive changes it recorded, and discard its failed statements"); registry.close("changes.sqlite"); + using margelo::nitro::rnnitrosqlite::getWritableDatabasePath; + using margelo::nitro::rnnitrosqlite::migrateDatabase; + using margelo::nitro::rnnitrosqlite::pathFromUtf8; + using margelo::nitro::rnnitrosqlite::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"); + expectThrows([&]() { registry.drop(unicodeName, unicodePath, std::nullopt); }, "drop must detect a live handle on the 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"; From 9829f529391e703b3ab9224e41e48708286af247 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:43:42 +0100 Subject: [PATCH 2/9] fix: cover Windows database paths and bind attachment aliases Co-authored-by: Codex --- .github/ci-paths.json | 4 ++ .github/workflows/test-windows-native.yml | 35 ++++++++++++- .../docs/guides/database-lifecycle.mdx | 2 + .../cpp/SQLiteOperations.cpp | 8 ++- .../cpp/SQLiteOperations.hpp | 4 ++ .../src/specs/NitroSQLite.nitro.ts | 5 +- packages/nitro-sqlite-core/src/types.ts | 5 +- .../tests/cpp/NitroTestStandardHeaders.hpp | 14 +++++ .../tests/cpp/databaseConnections.test.cpp | 9 +++- .../tests/cpp/databaseMigration.test.cpp | 10 ++++ .../tests/cpp/databasePaths.test.cpp | 51 +++++++++++++++++++ scripts/ci.test.ts | 8 +++ scripts/prepare-cpp-test-headers.cjs | 17 +++++++ scripts/test-cpp.sh | 22 ++++++++ 14 files changed, 182 insertions(+), 12 deletions(-) create mode 100644 packages/react-native-nitro-sqlite/tests/cpp/NitroTestStandardHeaders.hpp create mode 100644 packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp create mode 100644 scripts/prepare-cpp-test-headers.cjs diff --git a/.github/ci-paths.json b/.github/ci-paths.json index ba03fc6a..13878372 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -95,6 +95,8 @@ "packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.*", "packages/react-native-nitro-sqlite/cpp/SQLiteStatementGroup.hpp", "packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp", + "packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*", + "packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3.*", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3-symbol-prefix.h", "packages/integrations/react-native/vec/cpp/**", @@ -139,6 +141,8 @@ "packages/nitro-sqlite/nitro.json", "packages/nitro-sqlite/platform/cpp/**", "packages/nitro-sqlite/src/specs/**" + "packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*", + "packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp", ], "docs": [ ".github/workflows/**", diff --git a/.github/workflows/test-windows-native.yml b/.github/workflows/test-windows-native.yml index d8b817a3..e222d100 100644 --- a/.github/workflows/test-windows-native.yml +++ b/.github/workflows/test-windows-native.yml @@ -1,11 +1,17 @@ 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/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp' + - 'packages/react-native-nitro-sqlite/tests/cpp/**' + - 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/**' + - 'scripts/prepare-cpp-test-headers.cjs' + - 'package.json' + - 'bun.lock' workflow_dispatch: permissions: @@ -17,7 +23,14 @@ jobs: timeout-minutes: 10 steps: - uses: actions/checkout@v7 - - name: Build and run the database connection tests with MSVC + - uses: actions/setup-node@v7 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.3.1 + - run: bun install --frozen-lockfile --ignore-scripts + - name: Build and run path, connection and migration tests with MSVC shell: pwsh run: | $PSNativeCommandUseErrorActionPreference = $true @@ -31,3 +44,21 @@ jobs: "$package\cpp\NitroSQLiteDatabaseConnections.cpp" "$package\cpp\NitroSQLiteDatabaseMigration.cpp" ` "$package\tests\cpp\databaseConnections.test.cpp" sqlite3.obj /FedatabaseConnectionsTests.exe .\databaseConnectionsTests.exe + cl /nologo /std:c++20 /EHsc /utf-8 "/I$package\cpp" "/I$package\cpp\sqlite" ` + "$package\cpp\NitroSQLiteDatabaseMigration.cpp" "$package\tests\cpp\databaseMigration.test.cpp" ` + sqlite3.obj /FedatabaseMigrationTests.exe + .\databaseMigrationTests.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++") + $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\NitroSQLiteDatabaseConnections.cpp" "$package\cpp\NitroSQLiteDatabaseMigration.cpp" ` + "$package\cpp\NitroSQLiteOperations.cpp" "$package\cpp\NitroSQLiteImportSqlFile.cpp" ` + "$nitro\core\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/database-lifecycle.mdx b/docs/content/docs/guides/database-lifecycle.mdx index 75b4a93c..f2bfa364 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. Use a quoted SQL identifier when querying such an alias, and pass the original alias 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/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index 6b41dc61..d47cb682 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -53,7 +53,7 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do const std::string& alias) { std::string dbPath = getWritableDatabasePath(databaseToAttach, docPath); try { - sqliteExecuteCommand(connection, "ATTACH DATABASE ? AS " + alias, SQLiteQueryParams{dbPath}); + sqliteExecuteCommand(connection, "ATTACH DATABASE ? AS ?", SQLiteQueryParams{dbPath, alias}); } catch (SQLiteException& e) { throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, connection->name + " was unable to attach another database: " + std::string(e.what())); @@ -61,13 +61,11 @@ 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{alias}); } catch (SQLiteException& e) { throw SQLiteException(SQLiteExceptionType::UnableToAttachToDatabase, - connection->name + " was unable to detach database: " + std::string(e.what())); + connection->name + " was unable to detach database: " + std::string(e.what())); } } diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index b1f31a3d..0d923fa6 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -58,9 +58,13 @@ 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 the exact schema alias. Throws UnableToAttachToDatabase on failure. + * Both values are bound as data, so apostrophes, spaces and quotes need no escaping. + */ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& docPath, const std::string& databaseToAttach, const std::string& alias); +/** Detach the exact bound schema alias. 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/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index 3d091374..46958335 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -95,8 +95,9 @@ export declare class NitroSQLite extends HybridObject { drop(dbName: string, location?: string, connectionId?: string): void /** Attach a database file to an open main database under an SQL schema alias. * @param mainDbName Name of the open main database. - * @param dbNameToAttach File name of the database to attach. - * @param alias SQL schema name for the attached database. + * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. + * @param alias SQL schema name for the attached database. Spaces and quotes are preserved. + * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 727ab73d..2ac461d7 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -41,8 +41,9 @@ export interface Connection { */ delete(): void /** Attach another database under `alias` for queries against this connection. - * @param dbNameToAttach File name of the database to attach. - * @param alias SQL schema name for the attached database. + * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. + * @param alias SQL schema name for the attached database. Spaces and quotes are preserved. + * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ attach(dbNameToAttach: string, alias: string, location?: string): void diff --git a/packages/react-native-nitro-sqlite/tests/cpp/NitroTestStandardHeaders.hpp b/packages/react-native-nitro-sqlite/tests/cpp/NitroTestStandardHeaders.hpp new file mode 100644 index 00000000..bf76e6f2 --- /dev/null +++ b/packages/react-native-nitro-sqlite/tests/cpp/NitroTestStandardHeaders.hpp @@ -0,0 +1,14 @@ +#pragma once + +// Nitro 0.37.2 relies on standard headers included transitively by libc++. +#include +#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 12d5d63a..91acfdb4 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp @@ -1,5 +1,6 @@ #include "SQLiteDatabaseConnections.hpp" #include "SQLiteDatabaseMigration.hpp" +#include "SQLiteException.hpp" #include "SQLiteUtils.hpp" #include #include @@ -393,7 +394,13 @@ int main() { 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"); - expectThrows([&]() { registry.drop(unicodeName, unicodePath, std::nullopt); }, "drop must detect a live handle on the UTF-8 path"); + try { + registry.drop(unicodeName, unicodePath, std::nullopt); + throw std::runtime_error("drop must detect a live handle on the UTF-8 path"); + } catch (const NitroSQLiteException& 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"; 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..c1c122c5 --- /dev/null +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -0,0 +1,51 @@ +#include "NitroSQLiteImportSqlFile.hpp" +#include "NitroSQLiteOperations.hpp" +#include "NitroSQLiteUtils.hpp" +#include +#include +#include +#include +#include + +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 { + 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"); + 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.data->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/scripts/ci.test.ts b/scripts/ci.test.ts index f3389532..f52c760b 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -240,6 +240,14 @@ 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('generated platform bindings do not trigger the other mobile platform', () => { const checks = selectChecks( [ diff --git a/scripts/prepare-cpp-test-headers.cjs b/scripts/prepare-cpp-test-headers.cjs new file mode 100644 index 00000000..a49486ee --- /dev/null +++ b/scripts/prepare-cpp-test-headers.cjs @@ -0,0 +1,17 @@ +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') +fs.mkdirSync(path.join(output, 'NitroModules'), { recursive: true }) +for (const header of fs.readdirSync(source, { + recursive: true, + withFileTypes: true, +})) { + if (!header.isFile() || !header.name.endsWith('.hpp')) continue + const file = path.join(header.parentPath, header.name).replaceAll('\\', '/') + fs.writeFileSync( + path.join(output, 'NitroModules', header.name), + `#pragma once\n#include "${file}"\n`, + ) +} diff --git a/scripts/test-cpp.sh b/scripts/test-cpp.sh index 7d834635..d0439e09 100644 --- a/scripts/test-cpp.sh +++ b/scripts/test-cpp.sh @@ -177,6 +177,28 @@ 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++ \ + packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp \ + packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ + packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp \ + packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.cpp \ + node_modules/react-native-nitro-modules/cpp/core/core/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 From 2bbc5da0aa11a2423e28b43bd537abef63c26a1e Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 01:47:23 +0100 Subject: [PATCH 3/9] ci: install Nitro headers for standalone C++ test changes Co-authored-by: Codex --- scripts/ci.ts | 1 + 1 file changed, 1 insertion(+) 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 || From fd77444f1d1c4d68b20bc61242e8dd98941b61c7 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:06:46 +0100 Subject: [PATCH 4/9] fix: preserve quoted attachment aliases and native CI coverage Decode complete legacy SQL-quoted alias tokens before binding. Keep raw aliases as data and document the full-quote ambiguity. Co-authored-by: Codex --- .github/ci-paths.json | 13 ++++++++ .github/workflows/test-windows-native.yml | 1 + docs/content/docs/guides/attach-databases.mdx | 8 ++++- .../docs/guides/database-lifecycle.mdx | 2 +- .../cpp/SQLiteOperations.cpp | 31 +++++++++++++++++-- .../cpp/SQLiteOperations.hpp | 7 +++-- .../src/specs/NitroSQLite.nitro.ts | 5 +-- packages/nitro-sqlite-core/src/types.ts | 5 +-- .../tests/cpp/databasePaths.test.cpp | 30 ++++++++++++++++++ scripts/ci.test.ts | 12 +++++++ 10 files changed, 103 insertions(+), 11 deletions(-) diff --git a/.github/ci-paths.json b/.github/ci-paths.json index 13878372..f6a7cfe2 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -97,6 +97,19 @@ "packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp", "packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*", "packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp", + "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/NitroSQLiteImportSqlFile.*", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp", + "packages/react-native-nitro-sqlite/nitrogen/generated/shared/**", + "patches/react-native-nitro-modules*", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteUtils.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3.*", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3-symbol-prefix.h", "packages/integrations/react-native/vec/cpp/**", diff --git a/.github/workflows/test-windows-native.yml b/.github/workflows/test-windows-native.yml index e222d100..7219b72d 100644 --- a/.github/workflows/test-windows-native.yml +++ b/.github/workflows/test-windows-native.yml @@ -10,6 +10,7 @@ on: - '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*' - 'package.json' - 'bun.lock' workflow_dispatch: diff --git a/docs/content/docs/guides/attach-databases.mdx b/docs/content/docs/guides/attach-databases.mdx index 9592ac8b..bd8b0e45 100644 --- a/docs/content/docs/guides/attach-databases.mdx +++ b/docs/content/docs/guides/attach-databases.mdx @@ -32,4 +32,10 @@ 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. + +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. + +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 f2bfa364..6e2c2a67 100644 --- a/docs/content/docs/guides/database-lifecycle.mdx +++ b/docs/content/docs/guides/database-lifecycle.mdx @@ -47,7 +47,7 @@ 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. Use a quoted SQL identifier when querying such an alias, and pass the original alias to `detach()`. +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. diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index d47cb682..aad3b69a 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -27,6 +27,33 @@ 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) { + if (alias.size() < 2) + return alias; + const char opening = alias.front(); + const char closing = opening == '[' ? ']' : opening; + const bool isQuoted = opening == '"' || opening == '\'' || opening == '`' || opening == '['; + if (!isQuoted || alias.back() != closing) + return alias; + + std::string name; + name.reserve(alias.size() - 2); + for (size_t index = 1; index < alias.size() - 1; index++) { + if (alias[index] == closing) { + // Only a complete quoted token is legacy syntax. Other input remains a raw name. + if (opening == '[' || index + 1 == alias.size() - 1 || alias[index + 1] != closing) + return alias; + index++; + } + name.push_back(alias[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 @@ -53,7 +80,7 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do const std::string& alias) { std::string dbPath = getWritableDatabasePath(databaseToAttach, docPath); try { - sqliteExecuteCommand(connection, "ATTACH DATABASE ? AS ?", SQLiteQueryParams{dbPath, alias}); + 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())); @@ -62,7 +89,7 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& alias) { try { - sqliteExecuteCommand(connection, "DETACH DATABASE ?", SQLiteQueryParams{alias}); + 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())); diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index 0d923fa6..3268bf43 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -58,13 +58,14 @@ 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 the exact schema alias. Throws UnableToAttachToDatabase on failure. - * Both values are bound as data, so apostrophes, spaces and quotes need no escaping. +/** 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. + * 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 the exact bound schema alias. Throws UnableToAttachToDatabase on failure. */ +/** 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/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index 46958335..c5f4ea95 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -96,7 +96,8 @@ export declare class NitroSQLite extends HybridObject { /** Attach a database file to an open main database under an SQL schema alias. * @param mainDbName Name of the open main database. * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. - * @param alias SQL schema name for the attached database. Spaces and quotes are preserved. + * @param alias SQL schema name, either raw or a complete SQL-quoted identifier. + * Complete double, single, backtick, or bracket quoting is decoded for compatibility. * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ @@ -109,7 +110,7 @@ export declare class NitroSQLite extends HybridObject { ): void /** Detach an attached database by its alias. * @param mainDbName Name of the open main database. - * @param alias SQL schema name used when attaching. + * @param alias Raw or SQL-quoted schema name used when attaching. */ detach(mainDbName: string, alias: string): void /** Execute one SQL statement synchronously on the calling thread. diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 2ac461d7..946fbb2f 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -42,13 +42,14 @@ export interface Connection { delete(): void /** Attach another database under `alias` for queries against this connection. * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. - * @param alias SQL schema name for the attached database. Spaces and quotes are preserved. + * @param alias SQL schema name, either raw or a complete SQL-quoted identifier. + * Complete double, single, backtick, or bracket quoting is decoded for compatibility. * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ attach(dbNameToAttach: string, alias: string, location?: string): void /** Detach the database identified by `alias`. - * @param alias SQL schema name used when attaching the database. + * @param alias Raw or SQL-quoted schema name used when attaching the database. */ detach(alias: string): void /** Run a callback in a queued transaction. The callback must use `tx` for database work. diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp index c1c122c5..1b9164db 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -26,6 +26,36 @@ int main() { 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"}, + {"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]"}, + {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.data->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.data->rows.empty()) + throw std::runtime_error("detach left the alias attached"); + } sqliteOpenDb(connections, attachedName, docPath, false, std::nullopt); const auto attached = connections.get(attachedName); auto result = sqliteExecuteRaw(attached, "SELECT value FROM item", std::nullopt); diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index f52c760b..4d5bdcdc 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -248,6 +248,18 @@ test('UTF-8 path helpers select native C++ regressions', () => { assert.equal(checks.cpp_tests, true) }) +test('host C++ dependency headers and Nitro patches select regressions', () => { + for (const file of [ + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp', + 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryResult.hpp', + 'patches/react-native-nitro-modules+0.37.2.patch', + ]) { + assert.equal(selectChecks([file], false).cpp_tests, true, file) + } +}) + test('generated platform bindings do not trigger the other mobile platform', () => { const checks = selectChecks( [ From 42c34df066ef130475c1f78116a7fd8a441d55cf Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:08:02 +0100 Subject: [PATCH 5/9] fix: retain whitespace around legacy quoted aliases Co-authored-by: Codex --- .../cpp/SQLiteOperations.cpp | 22 ++++++++++++------- .../tests/cpp/databasePaths.test.cpp | 1 + 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index aad3b69a..caea45b1 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #ifdef NITRO_SQLITE_VEC // Angle-bracket so it resolves via -I (CocoaPods intercepts quoted includes). @@ -30,24 +31,29 @@ static constexpr double kInt64UpperBoundAsDouble = -kInt64MinAsDouble; namespace { std::string normalizeDatabaseAlias(const std::string& alias) { - if (alias.size() < 2) + const auto first = alias.find_first_not_of(" \t\r\n\f"); + if (first == std::string::npos) return alias; - const char opening = alias.front(); + const auto last = alias.find_last_not_of(" \t\r\n\f"); + const std::string_view token(alias.data() + first, last - first + 1); + 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 || alias.back() != closing) + if (!isQuoted || token.back() != closing) return alias; std::string name; - name.reserve(alias.size() - 2); - for (size_t index = 1; index < alias.size() - 1; index++) { - if (alias[index] == closing) { + 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 == alias.size() - 1 || alias[index + 1] != closing) + if (opening == '[' || index + 1 == token.size() - 1 || token[index + 1] != closing) return alias; index++; } - name.push_back(alias[index]); + name.push_back(token[index]); } return name; } diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp index 1b9164db..1024c15c 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -39,6 +39,7 @@ int main() { {"'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"}, {R"("""archive""")", R"("archive")", R"("""archive""")"}, {R"("raw"quote")", R"("raw"quote")", R"("raw"quote")"}, {"raw; SELECT 1", "raw; SELECT 1", "raw; SELECT 1"}, From 2641766b1d16a6a95cb1e4c4ca4a60db886243ca Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:25:26 +0100 Subject: [PATCH 6/9] fix: preserve SQLite alias whitespace and route host dependencies Co-authored-by: Codex --- .github/ci-paths.json | 7 +++++++ packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp | 4 ++-- .../tests/cpp/databasePaths.test.cpp | 1 + scripts/ci.test.ts | 7 +++++++ 4 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/ci-paths.json b/.github/ci-paths.json index f6a7cfe2..2bca822f 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -83,6 +83,11 @@ "packages/integrations/nitro-ui/vec/cpp/**" ], "cpp_tests": [ + "package.json", + "bun.lock", + "bunfig.toml", + "example/package.json", + "packages/react-native-nitro-sqlite/package.json", ".github/workflows/**", ".github/actions/**", ".github/ci-paths.json", @@ -109,6 +114,8 @@ "patches/react-native-nitro-modules*", "packages/react-native-nitro-sqlite/cpp/NitroSQLiteUtils.hpp", "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp", + "packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp", "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3.*", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3-symbol-prefix.h", diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index caea45b1..c674f1d2 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -31,10 +31,10 @@ 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"); + 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"); + const auto last = alias.find_last_not_of(" \t\r\n\f\v"); const std::string_view token(alias.data() + first, last - first + 1); if (token.size() < 2) return alias; diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp index 1024c15c..24bfe9a0 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -40,6 +40,7 @@ int main() { {"`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"}, diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index 4d5bdcdc..0ffc3484 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -250,6 +250,13 @@ test('UTF-8 path helpers select native C++ regressions', () => { test('host C++ dependency headers and Nitro patches select regressions', () => { for (const file of [ + 'package.json', + 'bun.lock', + 'bunfig.toml', + 'example/package.json', + 'packages/react-native-nitro-sqlite/package.json', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp', + 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp', 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp', 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp', 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp', From 670c0326f09d727e5f596f5cd86bcb859a78a73a Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:48:53 +0100 Subject: [PATCH 7/9] fix: preserve directory permissions and bare aliases Co-authored-by: Codex --- docs/content/docs/guides/attach-databases.mdx | 4 ++ .../cpp/SQLiteOperations.cpp | 10 +++++ .../cpp/SQLiteOperations.hpp | 1 + .../nitro-sqlite-core/cpp/SQLiteUtils.hpp | 14 +++++++ .../src/specs/NitroSQLite.nitro.ts | 1 + packages/nitro-sqlite-core/src/types.ts | 1 + .../tests/cpp/databasePaths.test.cpp | 37 +++++++++++++++++++ 7 files changed, 68 insertions(+) diff --git a/docs/content/docs/guides/attach-databases.mdx b/docs/content/docs/guides/attach-databases.mdx index bd8b0e45..ed659c10 100644 --- a/docs/content/docs/guides/attach-databases.mdx +++ b/docs/content/docs/guides/attach-databases.mdx @@ -34,8 +34,12 @@ The example assumes the tables and files already exist. SQLite can create the at 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/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index c674f1d2..4aa530e2 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 @@ -36,6 +37,15 @@ namespace { 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(); diff --git a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp index 3268bf43..6cda2120 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.hpp @@ -60,6 +60,7 @@ void sqliteRemoveDb(DatabaseConnections& connections, const std::string& dbName, /** 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, diff --git a/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp index 4c25f60d..1ddb358b 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp @@ -3,6 +3,10 @@ #include #include #include +#ifndef _WIN32 +#include +#include +#endif namespace margelo::nitro::nitrosqlite { @@ -25,8 +29,18 @@ inline std::string pathToUtf8(const std::filesystem::path& path) { } 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; + } +#endif // Let SQLite report an open error if it can't access the directory. return directory + "/" + dbName; } diff --git a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts index c5f4ea95..095eabe1 100644 --- a/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts +++ b/packages/nitro-sqlite-core/src/specs/NitroSQLite.nitro.ts @@ -98,6 +98,7 @@ export declare class NitroSQLite extends HybridObject { * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. * @param alias SQL schema name, either raw or a complete SQL-quoted identifier. * Complete double, single, backtick, or bracket quoting is decoded for compatibility. + * Surrounding SQL whitespace is ignored for a bare identifier; quote it to retain that whitespace. * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ diff --git a/packages/nitro-sqlite-core/src/types.ts b/packages/nitro-sqlite-core/src/types.ts index 946fbb2f..ffb8a5de 100644 --- a/packages/nitro-sqlite-core/src/types.ts +++ b/packages/nitro-sqlite-core/src/types.ts @@ -44,6 +44,7 @@ export interface Connection { * @param dbNameToAttach File name of the database to attach, including Unicode characters or apostrophes. * @param alias SQL schema name, either raw or a complete SQL-quoted identifier. * Complete double, single, backtick, or bracket quoting is decoded for compatibility. + * Surrounding SQL whitespace is ignored for a bare identifier; quote it to retain that whitespace. * Quote the alias as an SQL identifier when referencing it in a query. * @param location Directory relative to the platform database directory. */ diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp index 24bfe9a0..9eff8f24 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -6,6 +6,9 @@ #include #include #include +#ifndef _WIN32 +#include +#endif using namespace margelo::nitro::rnnitrosqlite; namespace fs = std::filesystem; @@ -15,6 +18,28 @@ int main() { 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"; @@ -33,6 +58,11 @@ int main() { }; 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""")"}, @@ -58,6 +88,13 @@ int main() { if (!remaining.rows.data->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.data->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); From eeaf35bbc616ecda10a2226c8b99d150922d4d60 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Tue, 1 Dec 2026 02:56:39 +0100 Subject: [PATCH 8/9] fix: preserve cached SQL keys during index removal Co-authored-by: Codex --- .github/workflows/test-windows-native.yml | 3 +++ .../tests/cpp/statementCache.test.cpp | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/.github/workflows/test-windows-native.yml b/.github/workflows/test-windows-native.yml index 7219b72d..7807d2db 100644 --- a/.github/workflows/test-windows-native.yml +++ b/.github/workflows/test-windows-native.yml @@ -49,6 +49,9 @@ jobs: "$package\cpp\NitroSQLiteDatabaseMigration.cpp" "$package\tests\cpp\databaseMigration.test.cpp" ` sqlite3.obj /FedatabaseMigrationTests.exe .\databaseMigrationTests.exe + cl /nologo /std:c++20 /EHsc /O2 /DNDEBUG /utf-8 "/I$package\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++") 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"; From 74d864ba248e425fb36e48ba5782dc473095d290 Mon Sep 17 00:00:00 2001 From: Christoph Pader Date: Wed, 2 Dec 2026 22:50:21 +0100 Subject: [PATCH 9/9] fix: adapt Windows path checks to shared SQLite sources Use the monorepo's source materialization and Nitro v1 headers in the host and Windows checks. Keep UTF-8 paths, alias compatibility, POSIX permissions and the repeated SQL regression. Co-authored-by: Codex --- .github/ci-paths.json | 35 ++++++------------- .github/workflows/test-windows-native.yml | 30 ++++++++++------ .../cpp/SQLiteOperations.cpp | 4 +-- .../cpp/hybridObjects/HybridNitroSQLite.cpp | 8 ++++- .../tests/cpp/databaseConnections.test.cpp | 10 +++--- .../tests/cpp/databasePaths.test.cpp | 14 ++++---- scripts/ci.test.ts | 16 ++++----- scripts/prepare-cpp-test-headers.cjs | 17 +++------ scripts/test-cpp.sh | 15 ++++---- 9 files changed, 72 insertions(+), 77 deletions(-) diff --git a/.github/ci-paths.json b/.github/ci-paths.json index 2bca822f..9afa41c8 100644 --- a/.github/ci-paths.json +++ b/.github/ci-paths.json @@ -83,11 +83,6 @@ "packages/integrations/nitro-ui/vec/cpp/**" ], "cpp_tests": [ - "package.json", - "bun.lock", - "bunfig.toml", - "example/package.json", - "packages/react-native-nitro-sqlite/package.json", ".github/workflows/**", ".github/actions/**", ".github/ci-paths.json", @@ -100,23 +95,6 @@ "packages/react-native-nitro-sqlite/cpp/SQLiteQueryResults.*", "packages/react-native-nitro-sqlite/cpp/SQLiteStatementGroup.hpp", "packages/react-native-nitro-sqlite/cpp/SQLiteStatementTail.hpp", - "packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*", - "packages/nitro-sqlite-core/cpp/SQLiteUtils.hpp", - "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/NitroSQLiteImportSqlFile.*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp", - "packages/react-native-nitro-sqlite/nitrogen/generated/shared/**", - "patches/react-native-nitro-modules*", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteUtils.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementGroup.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp", - "packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementTail.hpp", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3.*", "packages/react-native-nitro-sqlite/cpp/sqlite/sqlite3-symbol-prefix.h", "packages/integrations/react-native/vec/cpp/**", @@ -160,9 +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/SQLiteUtils.hpp", + "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 index 7807d2db..a0625b8a 100644 --- a/.github/workflows/test-windows-native.yml +++ b/.github/workflows/test-windows-native.yml @@ -7,10 +7,15 @@ on: 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: @@ -29,8 +34,9 @@ jobs: node-version: 24 - uses: oven-sh/setup-bun@v2 with: - bun-version: 1.3.1 + 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: | @@ -39,30 +45,32 @@ jobs: 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 "$package\cpp\sqlite\sqlite3.c" /Fosqlite3.obj - cl /nologo /std:c++20 /EHsc /utf-8 "/I$package\cpp" ` - "$package\cpp\NitroSQLiteDatabaseConnections.cpp" "$package\cpp\NitroSQLiteDatabaseMigration.cpp" ` + 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$package\cpp" "/I$package\cpp\sqlite" ` - "$package\cpp\NitroSQLiteDatabaseMigration.cpp" "$package\tests\cpp\databaseMigration.test.cpp" ` + 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$package\cpp" ` + 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++") + $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\NitroSQLiteDatabaseConnections.cpp" "$package\cpp\NitroSQLiteDatabaseMigration.cpp" ` - "$package\cpp\NitroSQLiteOperations.cpp" "$package\cpp\NitroSQLiteImportSqlFile.cpp" ` - "$nitro\core\ArrayBuffer.cpp" $jsi "$package\tests\cpp\databasePaths.test.cpp" ` + "$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/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp index 4aa530e2..aaa00042 100644 --- a/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp +++ b/packages/nitro-sqlite-core/cpp/SQLiteOperations.cpp @@ -99,7 +99,7 @@ void sqliteAttachDb(const SQLiteConnectionPtr& connection, const std::string& do 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())); + connection->name + " was unable to attach another database: " + std::string(e.what())); } } @@ -108,7 +108,7 @@ void sqliteDetachDb(const SQLiteConnectionPtr& connection, const std::string& al 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())); + connection->name + " was unable to detach database: " + std::string(e.what())); } } diff --git a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp index ea877a79..be71eb12 100644 --- a/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp +++ b/packages/nitro-sqlite-core/cpp/hybridObjects/HybridNitroSQLite.cpp @@ -30,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"); } 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 91acfdb4..d0bba99c 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databaseConnections.test.cpp @@ -384,10 +384,10 @@ int main() { "a replacement handler must only receive changes it recorded, and discard its failed statements"); registry.close("changes.sqlite"); - using margelo::nitro::rnnitrosqlite::getWritableDatabasePath; - using margelo::nitro::rnnitrosqlite::migrateDatabase; - using margelo::nitro::rnnitrosqlite::pathFromUtf8; - using margelo::nitro::rnnitrosqlite::pathToUtf8; + 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))); @@ -397,7 +397,7 @@ int main() { try { registry.drop(unicodeName, unicodePath, std::nullopt); throw std::runtime_error("drop must detect a live handle on the UTF-8 path"); - } catch (const NitroSQLiteException& error) { + } 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"); } diff --git a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp index 9eff8f24..fac6f66d 100644 --- a/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp +++ b/packages/react-native-nitro-sqlite/tests/cpp/databasePaths.test.cpp @@ -1,6 +1,6 @@ -#include "NitroSQLiteImportSqlFile.hpp" -#include "NitroSQLiteOperations.hpp" -#include "NitroSQLiteUtils.hpp" +#include "SQLiteImportSqlFile.hpp" +#include "SQLiteOperations.hpp" +#include "SQLiteUtils.hpp" #include #include #include @@ -79,26 +79,26 @@ int main() { 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.data->rows.size() != 1) { + 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.data->rows.empty()) + 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.data->rows.size() != 1) + 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.data->rows.at(0).at(0)) != 42) + 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"); { diff --git a/scripts/ci.test.ts b/scripts/ci.test.ts index 0ffc3484..6cd81225 100644 --- a/scripts/ci.test.ts +++ b/scripts/ci.test.ts @@ -253,15 +253,15 @@ test('host C++ dependency headers and Nitro patches select regressions', () => { 'package.json', 'bun.lock', 'bunfig.toml', - 'example/package.json', + 'examples/react-native/package.json', 'packages/react-native-nitro-sqlite/package.json', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteStatementCache.hpp', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteException.hpp', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteLogs.hpp', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteTypes.hpp', - 'packages/react-native-nitro-sqlite/cpp/NitroSQLiteQueryResults.hpp', - 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/c++/NitroSQLiteQueryResult.hpp', - 'patches/react-native-nitro-modules+0.37.2.patch', + '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) } diff --git a/scripts/prepare-cpp-test-headers.cjs b/scripts/prepare-cpp-test-headers.cjs index a49486ee..572175f6 100644 --- a/scripts/prepare-cpp-test-headers.cjs +++ b/scripts/prepare-cpp-test-headers.cjs @@ -2,16 +2,7 @@ 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') -fs.mkdirSync(path.join(output, 'NitroModules'), { recursive: true }) -for (const header of fs.readdirSync(source, { - recursive: true, - withFileTypes: true, -})) { - if (!header.isFile() || !header.name.endsWith('.hpp')) continue - const file = path.join(header.parentPath, header.name).replaceAll('\\', '/') - fs.writeFileSync( - path.join(output, 'NitroModules', header.name), - `#pragma once\n#include "${file}"\n`, - ) -} +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 d0439e09..986cc057 100644 --- a/scripts/test-cpp.sh +++ b/scripts/test-cpp.sh @@ -187,12 +187,15 @@ clang++ \ -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++ \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseConnections.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteDatabaseMigration.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteOperations.cpp \ - packages/react-native-nitro-sqlite/cpp/NitroSQLiteImportSqlFile.cpp \ - node_modules/react-native-nitro-modules/cpp/core/core/ArrayBuffer.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 \