Path: redb/redb.SQLite/Data/SqliteDataSource.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.SQLite/Data/SqliteDataSource.cs ---- using System; using System.IO; using System.Threading.Tasks; using Microsoft.Data.Sqlite; namespace redb.SQLite.Data { /// /// Lightweight stand-in for Npgsql's NpgsqlDataSource concept. /// Microsoft.Data.Sqlite has no DataSource type — it pools connections /// internally, keyed by connection string. This wrapper centralizes /// connection creation and applies the per-connection PRAGMAs that SQLite /// requires on EVERY connection (they are not persistent): /// - foreign_keys=ON (so ON DELETE CASCADE / SET NULL fire) /// - busy_timeout (so a second writer waits instead of failing with /// SQLITE_BUSY — SQLite is single-writer) /// public sealed class SqliteDataSource : IDisposable { private const int BusyTimeoutMs = 5000; static SqliteDataSource() { // SQLite stores datetimes as REAL Julian day (UTC). Object reads go through // get_object_json (already ISO), but analytics paths (Min/Max, AggregateRedbAsync, // Window, GroupBy) select the raw column and hand the bare NUMBER to core's // converters. Register the numeric→temporal decoder so core can turn it back into a // DateTime/DateTimeOffset/DateOnly — without core knowing anything about Julian days. // Runs once whenever SQLite is configured (Free and Pro both create a SqliteDataSource); // no-op for PostgreSQL/SQL Server, which never return a number for a temporal column. Core.Query.Utils.TemporalDecoder.NumericDecoder = static (julian, targetType) => { var dto = SqliteJulian.FromJulian(julian); if (targetType == typeof(DateTimeOffset)) return dto; if (targetType == typeof(DateOnly)) return DateOnly.FromDateTime(dto.UtcDateTime); return dto.UtcDateTime; // DateTime }; } /// /// Path to the REDB native loadable extension (redbsqlite.dll/.so/.dylib, WITHOUT /// the file suffix — SQLite appends it). When set, every connection loads it /// after PRAGMAs, so the FREE tier's in-DB functions (get_object_json, /// save_object_json, pvt_build_query_sql, ...) become callable. REQUIRED for /// the Free tier; harmless for Pro (which never calls those functions). /// Defaults to the REDB_SQLITE_EXTENSION env var. Load is per-connection /// (SQLite extensions are not persistent across connections). /// public static string? NativeExtensionPath { get; set; } = Environment.GetEnvironmentVariable("REDB_SQLITE_EXTENSION"); /// /// Size, in bytes, of the part of the database file every connection maps into memory /// (PRAGMA mmap_size). 0, the default, leaves SQLite as it is: pages are read through /// its own page cache, which is 2 MB per connection. On a database of several gigabytes that /// cache is the cost of every query that reads more than a few thousand rows: measured on /// 2.5 GB, the same statements ran 2-4 times faster with the file mapped. A mapping takes /// address space, not memory of its own - the pages live in the file cache of the operating /// system and are shared by all connections. SQLite caps the value at its compile-time limit /// (about 2 GB in the bundled build); what lies beyond the mapped part is read as before. /// public static long MmapSizeBytes { get; set; } /// /// Size, in bytes, of the page cache of every connection (PRAGMA cache_size). 0, the /// default, leaves SQLite's own 2 MB. Unlike this is memory of /// the process and it is per connection: the pool holds as many caches as it holds /// connections. Next to a mapped file a moderate cache is enough - measured on 2.5 GB, /// 64 MB on top of the mapping took another quarter to a third off the same statements, /// and 256 MB added nothing to that. /// public static long CacheSizeBytes { get; set; } /// Connection string this data source opens. public string ConnectionString { get; } private SqliteDataSource(string connectionString) { ConnectionString = connectionString; } /// Create a data source for the given connection string. public static SqliteDataSource Create(string connectionString) => new SqliteDataSource(connectionString); /// /// Create a data source that additionally installs Unicode-aware case folding on every /// connection it opens. See for why this is a connection /// concern in SQLite rather than a SQL one. /// public static SqliteDataSource Create(string connectionString, bool unicodeCaseFolding) => new SqliteDataSource(connectionString) { UnicodeCaseFolding = unicodeCaseFolding }; /// V4 (LAZY Л2): also arms the lazy-references connection flag of the native extension. public static SqliteDataSource Create(string connectionString, bool unicodeCaseFolding, bool lazyReferences) => new SqliteDataSource(connectionString) { UnicodeCaseFolding = unicodeCaseFolding, LazyReferences = lazyReferences }; /// /// When true, every opened connection gets like, lower and upper /// replaced by Unicode-aware implementations. Off by default: generated SQL and stock /// behaviour stay exactly as they were. /// public bool UnicodeCaseFolding { get; private init; } /// V4 (LAZY Л2): arm redb_lazy_refs(1) on every open (the native extension keeps the flag per connection). public bool LazyReferences { get; private init; } // V4 (LAZY Л2): the SQLite counterpart of the PostgreSQL GUC - the extension keeps the // flag in per-connection clientdata; unset means off, so old extensions and the off state // are byte-for-byte the previous behaviour. private void InstallLazyRefs(SqliteConnection conn) { if (!LazyReferences) return; using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT redb_lazy_refs(1)"; cmd.ExecuteNonQuery(); } /// /// Releases the connection pool of this data source's connection string. The pools of /// Microsoft.Data.Sqlite are static, keyed by connection string, and a pooled handle keeps /// the database FILE open (locked, on Windows) - so without this, a container that dies /// (test host teardown, a hot-reloaded module) leaves the file locked until process exit. /// The DI registrations are factories, so the container disposes the data source it /// created. ClearPool touches only this connection string; another live container on the /// same string is unaffected beyond refilling the pool on its next open. /// public void Dispose() { using var probe = new SqliteConnection(ConnectionString); SqliteConnection.ClearPool(probe); } /// Open a new pooled connection with REDB pragmas applied. public SqliteConnection OpenConnection() { var conn = new SqliteConnection(ConnectionString); conn.Open(); LoadNativeExtension(conn); ApplyPragmas(conn); SqliteCaseFolding.Install(conn, UnicodeCaseFolding); SqliteRegexFunctions.Install(conn); EnsureCleanTransactionState(conn); InstallLazyRefs(conn); return conn; } /// Open a new pooled connection with REDB pragmas applied. public async Task OpenConnectionAsync() { var conn = new SqliteConnection(ConnectionString); await conn.OpenAsync(); LoadNativeExtension(conn); await ApplyPragmasAsync(conn); SqliteCaseFolding.Install(conn, UnicodeCaseFolding); SqliteRegexFunctions.Install(conn); await EnsureCleanTransactionStateAsync(conn); InstallLazyRefs(conn); return conn; } /// Load the REDB native extension on this connection (Free tier). No-op /// when NativeExtensionPath is unset; both registrations locate the packaged one (object JSON). private static void LoadNativeExtension(SqliteConnection conn) { var path = NativeExtensionPath; if (string.IsNullOrEmpty(path)) return; conn.EnableExtensions(true); try { // Explicit entry point: the file is redbsqlite. but the C init symbol is // sqlite3_redb_init, so we can't rely on SQLite's basename derivation. conn.LoadExtension(path, "sqlite3_redb_init"); } finally { // Loading is done, so turn the loader back off. Leaving it enabled turned any SQL // injection on this connection into load_extension(), i.e. arbitrary code // (SQLI-PoC: load_extension amplifier). conn.EnableExtensions(false); } } /// /// Locate the REDB native extension shipped inside the NuGet package, relative to /// the running application (). Returns the full /// path (suffix included) or null if not found. /// /// Probes the runtimes/<rid>/native layout, then a flattened copy next to the /// app. Note the package does NOT ship that layout: the binaries live under /// buildTransitive/native/<rid>/ so platform SDKs (notably .NET Android, which /// harvests every runtimes/*/native/*.so into the APK) cannot pick them up. The /// package's .targets reproduces this layout in consumer output instead. Used by the /// Free DI registration to auto-configure without /// an explicit REDB_SQLITE_EXTENSION env var. As a dev fallback it also walks /// up the source tree to the CMake build output, so a ProjectReference run straight /// from the repo (a worker, tests) loads the extension with no manual setup. /// public static string? LocatePackagedExtension() { var lib = OperatingSystem.IsWindows() ? "redbsqlite.dll" : OperatingSystem.IsMacOS() ? "redbsqlite.dylib" : "redbsqlite.so"; var baseDir = AppContext.BaseDirectory; var rid = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier; // 1. Exact RID path, then flattened next to the app (RID publish / manual copy). foreach (var candidate in new[] { Path.Combine(baseDir, "runtimes", rid, "native", lib), Path.Combine(baseDir, lib), }) { if (File.Exists(candidate)) return candidate; } // 2. RID-agnostic scan: any runtimes//native/ under the app base. var runtimesRoot = Path.Combine(baseDir, "runtimes"); if (Directory.Exists(runtimesRoot)) { foreach (var ridDir in Directory.EnumerateDirectories(runtimesRoot)) { var candidate = Path.Combine(ridDir, "native", lib); if (File.Exists(candidate)) return candidate; } } // 3. Dev fallback: walk up the source tree to the CMake build output // (redb.SQLite/native/build/redbsqlite.). Lets a ProjectReference run // straight from the repo (worker, tests, console) load the extension // without REDB_SQLITE_EXTENSION — mirrors redb.Examples' resolver. for (var dir = new DirectoryInfo(baseDir); dir != null; dir = dir.Parent) { // Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src). var devCandidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", lib); if (!File.Exists(devCandidate)) devCandidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", lib); if (File.Exists(devCandidate)) return devCandidate; } return null; } private static void ApplyPragmas(SqliteConnection conn) { using var cmd = conn.CreateCommand(); // journal_mode=WAL → writers don't block readers (concurrent reads // during an open write tx are crucial for redb's check-then-save // patterns and for any visibility-of-uncommitted-writes probe). // synchronous=NORMAL is the WAL-recommended balance; matches what // most production SQLite deployments use under Microsoft.Data.Sqlite. cmd.CommandText = $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMs}; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;{MmapPragma()}"; cmd.ExecuteNonQuery(); } private static async Task ApplyPragmasAsync(SqliteConnection conn) { await using var cmd = conn.CreateCommand(); // journal_mode=WAL → writers don't block readers (concurrent reads // during an open write tx are crucial for redb's check-then-save // patterns and for any visibility-of-uncommitted-writes probe). // synchronous=NORMAL is the WAL-recommended balance; matches what // most production SQLite deployments use under Microsoft.Data.Sqlite. cmd.CommandText = $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMs}; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;{MmapPragma()}"; await cmd.ExecuteNonQueryAsync(); } // Nothing is added while both sizes are 0, so the statement stays what it was. // A negative cache_size is a size in KiB; a positive one would be a number of pages. private static string MmapPragma() => (MmapSizeBytes > 0 ? $" PRAGMA mmap_size={MmapSizeBytes};" : "") + (CacheSizeBytes > 0 ? $" PRAGMA cache_size=-{Math.Max(1, CacheSizeBytes / 1024)};" : ""); // Defensive pool-poisoning guard. Microsoft.Data.Sqlite's pool returns // SqliteConnection wrappers without inspecting the underlying sqlite3 // handle's autocommit state, so a prior caller that failed to COMMIT or // ROLLBACK (e.g. swallowed rollback in a dispose path) hands us a handle // with autocommit=0 — the next conn.BeginTransaction(...) then fails // with SQLITE_ERROR(1) "cannot start a transaction within a transaction". // A speculative ROLLBACK clears any leaked tx; the "no tx active" error // is the normal/clean case and is silently caught. // // Same idiom as Npgsql's DISCARD ALL / RESET ALL on connection acquire. private static void EnsureCleanTransactionState(SqliteConnection conn) { try { using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; cmd.ExecuteNonQuery(); // Reached only when the pooled connection HAD a leaked tx — log // so the source of the leak surfaces in operator logs. // Console.WriteLine("[Diag-TXLOCK] POOL-CLEANUP: rolled back leaked tx on pooled connection acquire (sync path)."); } catch (SqliteException ex) when (ex.SqliteErrorCode == 1) { // SQLITE_ERROR(1): "cannot rollback - no transaction is active" — clean handle, expected. } } private static async Task EnsureCleanTransactionStateAsync(SqliteConnection conn) { try { await using var cmd = conn.CreateCommand(); cmd.CommandText = "ROLLBACK"; await cmd.ExecuteNonQueryAsync(); // Console.WriteLine("[Diag-TXLOCK] POOL-CLEANUP: rolled back leaked tx on pooled connection acquire (async path)."); } catch (SqliteException ex) when (ex.SqliteErrorCode == 1) { // SQLITE_ERROR(1): "cannot rollback - no transaction is active" — clean handle, expected. } } } }