Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion .github/ci-paths.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,18 @@
"packages/nitro-sqlite/package.json",
"packages/nitro-sqlite/nitro.json",
"packages/nitro-sqlite/platform/cpp/**",
"packages/nitro-sqlite/src/specs/**"
"packages/nitro-sqlite/src/specs/**",
"packages/nitro-sqlite-core/cpp/*.hpp",
"packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.*",
"packages/nitro-sqlite-core/cpp/hybridObjects/**",
"packages/react-native-nitro-sqlite/cpp/*.hpp",
"packages/react-native-nitro-sqlite/cpp/SQLiteImportSqlFile.*",
"packages/react-native-nitro-sqlite/nitrogen/generated/shared/**",
"packages/nitro-sqlite/nitrogen/generated/shared/**",
"patches/react-native-nitro-modules*",
"bunfig.toml",
"scripts/prepare-cpp-test-headers.cjs",
"examples/react-native/package.json"
],
"docs": [
".github/workflows/**",
Expand Down
76 changes: 76 additions & 0 deletions .github/workflows/test-windows-native.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Test Windows SQLite files

on:
push:
branches: [main]
pull_request:
paths:
- '.github/workflows/test-windows-native.yml'
- 'packages/react-native-nitro-sqlite/cpp/**'
- 'packages/nitro-sqlite-core/**'
- 'packages/react-native-nitro-sqlite/platform/**'
- 'packages/react-native-nitro-sqlite/scripts/**'
- 'packages/react-native-nitro-sqlite/tests/cpp/**'
- 'packages/react-native-nitro-sqlite/nitrogen/generated/shared/**'
- 'scripts/prepare-cpp-test-headers.cjs'
- 'patches/react-native-nitro-modules*'
- 'bunfig.toml'
- 'patches/react-native-nitro-modules*'
- 'package.json'
- 'bun.lock'
workflow_dispatch:

permissions:
contents: read

jobs:
sqlite-files:
runs-on: windows-2025
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.3.14
- run: bun install --frozen-lockfile --ignore-scripts
- run: node packages/react-native-nitro-sqlite/scripts/prepare-sources.mjs
- name: Build and run path, connection and migration tests with MSVC
shell: pwsh
run: |
$PSNativeCommandUseErrorActionPreference = $true
$visualStudio = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
Import-Module "$visualStudio\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"
Enter-VsDevShell -VsInstallPath $visualStudio -SkipAutomaticLocation -DevCmdArguments '-arch=x64'
$package = Resolve-Path packages/react-native-nitro-sqlite
$core = Resolve-Path packages/nitro-sqlite-core
Set-Location $env:RUNNER_TEMP
cl /nologo /c /TC /DSQLITE_THREADSAFE=2 "$core\cpp\sqlite\sqlite3.c" /Fosqlite3.obj
cl /nologo /std:c++20 /EHsc /utf-8 "/I$core\cpp" `
"$core\cpp\SQLiteDatabaseConnections.cpp" "$core\cpp\SQLiteDatabaseMigration.cpp" `
"$package\tests\cpp\databaseConnections.test.cpp" sqlite3.obj /FedatabaseConnectionsTests.exe
.\databaseConnectionsTests.exe
cl /nologo /std:c++20 /EHsc /utf-8 "/I$core\cpp" "/I$core\cpp\sqlite" `
"$core\cpp\SQLiteDatabaseMigration.cpp" "$package\tests\cpp\databaseMigration.test.cpp" `
sqlite3.obj /FedatabaseMigrationTests.exe
.\databaseMigrationTests.exe
cl /nologo /std:c++20 /EHsc /O2 /DNDEBUG /utf-8 "/I$core\cpp" `
"$package\tests\cpp\statementCache.test.cpp" sqlite3.obj /FestatementCacheTests.exe
.\statementCacheTests.exe
Set-Location $env:GITHUB_WORKSPACE
node scripts/prepare-cpp-test-headers.cjs "$env:RUNNER_TEMP/headers"
$includes = @("/I$env:RUNNER_TEMP\headers", "/I$env:RUNNER_TEMP\headers\NitroModules", "/I$env:GITHUB_WORKSPACE\node_modules\react-native\ReactCommon\jsi", "/I$package\cpp", "/I$package\cpp\sqlite", "/I$package\cpp\hybridObjects", "/I$package\nitrogen\generated\shared\c++\include")
$standardHeaders = "/FI$package\tests\cpp\NitroTestStandardHeaders.hpp"
$nitro = "$env:GITHUB_WORKSPACE\node_modules\react-native-nitro-modules\cpp\core"
$jsi = "$env:GITHUB_WORKSPACE\node_modules\react-native\ReactCommon\jsi\jsi\jsi.cpp"
Set-Location $env:RUNNER_TEMP
cl /nologo /std:c++20 /EHsc /utf-8 @includes $standardHeaders `
"$package\cpp\SQLiteDatabaseConnections.cpp" "$package\cpp\SQLiteDatabaseMigration.cpp" `
"$package\cpp\SQLiteOperations.cpp" "$package\cpp\SQLiteImportSqlFile.cpp" `
"$package\cpp\SQLiteQueryResults.cpp" "$package\cpp\SQLiteJSON.cpp" "$package\cpp\NativeQueryResult.cpp" `
"$nitro\src\ArrayBuffer.cpp" $jsi "$package\tests\cpp\databasePaths.test.cpp" `
sqlite3.obj /FedatabasePathsTests.exe
.\databasePathsTests.exe
cl /nologo /c /std:c++20 /EHsc /utf-8 @includes $standardHeaders "$package\cpp\hybridObjects\HybridNitroSQLite.cpp"
12 changes: 11 additions & 1 deletion docs/content/docs/guides/attach-databases.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,14 @@ db.close()

The example assumes the tables and files already exist. SQLite can create the attached file when it is missing, so verify the intended path when opening prepopulated data. `attach()` and `detach()` are synchronous connection operations; they fail while the connection queue is busy. A failed attach or detach throws `SQLiteError` through the connection wrapper.

Only pass database names, locations, and aliases you control. The library does not bind these as parameters. Query values still belong in `?` parameters. See [database lifecycle](/docs/guides/database-lifecycle) for the location convention and the generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) for signatures.
Nitro SQLite binds the filename and schema alias as parameters, including Unicode characters and apostrophes. Aliases can contain spaces or quotes. Quote a schema name as an SQL identifier when using it in a query. Query values still belong in `?` parameters.

Pass literal filenames. If older code doubled apostrophes to work around SQL interpolation, remove that escaping: `café's.sqlite` names a different file from `café''s.sqlite`.

For compatibility, a complete alias enclosed in double quotes, single quotes, backticks, or square brackets is interpreted as the existing quoted name. For example, `db.attach('archive.sqlite', '"sales archive"')` and `db.attach('archive.sqlite', 'sales archive')` both attach the schema `sales archive`. Either form works with `detach()` too. Doubled quote characters inside a quoted name are decoded. Square brackets have no escape syntax.

A full pair of quotes is ambiguous with a literal name that includes those quote characters. Legacy quoting takes precedence. To name a schema `"archive"` including its quote characters, pass the SQL-quoted alias `'"""archive"""'` to both `attach()` and `detach()`. Other raw aliases are preserved, including incomplete quoting. Aliases are never executed as SQL.

Surrounding SQL whitespace is ignored for a single bare identifier too: `' archive '` resolves to `archive`. To retain that whitespace as part of the name, use the quoted alias `'" archive "'`. Names with internal spaces remain literal raw names.

Only pass database names and locations you control. Path segments such as `..` are not validated. See [database lifecycle](/docs/guides/database-lifecycle) for the location convention and the generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) for signatures.
2 changes: 2 additions & 0 deletions docs/content/docs/guides/database-lifecycle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ const db = open({ name: 'catalog.sqlite', location: 'databases' })

Only pass database names and locations you control. The library does not validate path segments such as `..`.

SQLite treats an attached database name as a filename and its alias as a schema name. `attach()` preserves Unicode characters and apostrophes in filenames, including on Windows. Aliases can contain spaces and quotes. Complete SQL-quoted aliases retain their legacy meaning; see [attachment alias compatibility](/docs/guides/attach-databases#file-paths-and-aliases). Use a quoted SQL identifier when querying such an alias, and pass the same alias form to `detach()`.

To open a prepopulated database, copy the SQLite file into the intended app directory before calling `open()`. Use the same `name` and `location` when you open it. A missing file creates a new, empty database, so verify the copy if your schema must already exist. See [file lifetimes](/docs/concepts/databases-and-connections#file-lifetimes) for WAL companion files.

The platform pages describe storage settings for [iOS](/docs/configuration/ios#database-location) and [Android](/docs/configuration/android#database-location) in both hosts, and [macOS](/docs/configuration/macos) in React Native. See [supported platforms](/docs/supported-platforms) for the host and operating system combinations. The generated [`Connection` reference](/api/react-native-nitro-sqlite/interfaces/Connection) lists the lifecycle methods.
Expand Down
23 changes: 12 additions & 11 deletions packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "SQLiteDatabaseMigration.hpp"
#include "SQLiteException.hpp"
#include "SQLiteLogs.hpp"
#include "SQLiteUtils.hpp"
#include <array>
#include <condition_variable>
#include <cstring>
Expand Down Expand Up @@ -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";
}
Expand All @@ -82,7 +83,7 @@ namespace {
int result;
while ((result = sqlite3_step(statement.get())) == SQLITE_ROW) {
const auto* rawPath = reinterpret_cast<const char*>(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;
}
}
Expand Down Expand Up @@ -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<std::string>& 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) {
Expand All @@ -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<std::string>& 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);
Expand All @@ -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<sqlite3, decltype(&sqlite3_close_v2)> database(rawDatabase, sqlite3_close_v2);
if (result != SQLITE_OK) {
const std::string message = rawDatabase == nullptr ? sqlite3_errstr(result) : sqlite3_errmsg(rawDatabase);
Expand Down Expand Up @@ -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);
Expand All @@ -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());
}
});
}
Expand Down
15 changes: 8 additions & 7 deletions packages/nitro-sqlite-core/cpp/SQLiteDatabaseMigration.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "SQLiteDatabaseMigration.hpp"
#include "SQLiteLogs.hpp"
#include "SQLiteUtils.hpp"
#include <array>
#include <system_error>

Expand All @@ -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());
Expand All @@ -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;
}

Expand All @@ -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;
}
Expand All @@ -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;
Expand All @@ -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());
Expand All @@ -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;
}
Expand All @@ -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());
}
Expand Down
3 changes: 2 additions & 1 deletion packages/nitro-sqlite-core/cpp/SQLiteImportSqlFile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "SQLiteImportSqlFile.hpp"
#include "SQLiteException.hpp"
#include "SQLiteOperations.hpp"
#include "SQLiteUtils.hpp"
#include <fstream>
#include <iostream>
#include <optional>
Expand All @@ -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);
}
Expand Down
Loading
Loading