Bundle: redb / redb.SQLite (redb.SQLite.txt), 72 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb/_index.txt
====
Path: redb/redb.SQLite/Data/SqliteBulkOperations.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/SqliteBulkOperations.cs
----
using redb.Core.Data;
using redb.Core.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace redb.SQLite.Data
{
///
/// SQLite implementation of IBulkOperations.
/// SQLite has no COPY/binary-import protocol — the fast path is a single
/// transaction wrapping chunked multi-row INSERTs (one prepared statement
/// per chunk). The big win versus N individual statements is the single
/// transaction (one fsync instead of one per row). Parameter count per
/// statement is chunked under SQLite's limit.
///
public class SqliteBulkOperations : IBulkOperations
{
private readonly IRedbConnection _db;
// Conservative cap on bound parameters per statement (SQLite default
// SQLITE_MAX_VARIABLE_NUMBER is 999 on older builds, 32766 on 3.32+).
private const int MaxParamsPerStatement = 900;
public SqliteBulkOperations(IRedbConnection db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
// ===== INSERTS =====
private static readonly string[] ObjectColumns =
{
"_id", "_id_parent", "_id_scheme", "_name", "_id_owner", "_id_who_change",
"_date_create", "_date_modify", "_date_begin", "_date_complete", "_key",
"_value_long", "_value_string", "_value_guid", "_value_bool", "_value_double",
"_value_numeric", "_value_datetime", "_value_bytes", "_note", "_hash", "_value_unique"
};
private static object?[] ObjectRowValues(RedbObjectRow o) => new object?[]
{
o.Id, o.IdParent, o.IdScheme, o.Name, o.IdOwner, o.IdWhoChange,
o.DateCreate, o.DateModify, o.DateBegin, o.DateComplete, o.Key,
o.ValueLong, o.ValueString, o.ValueGuid, o.ValueBool, o.ValueDouble,
o.ValueNumeric, o.ValueDatetime, o.ValueBytes, o.Note, o.Hash, o.ValueUnique
};
private static readonly string[] ValueColumns =
{
"_id", "_id_structure", "_id_object", "_String", "_Long", "_Guid",
"_Double", "_DateTimeOffset", "_Boolean", "_ByteArray", "_Numeric",
"_ListItem", "_Object", "_unique", "_array_parent_id", "_array_index"
};
private static object?[] ValueRowValues(RedbValue v) => new object?[]
{
v.Id, v.IdStructure, v.IdObject, v.String, v.Long, v.Guid,
v.Double, v.DateTimeOffset, v.Boolean, v.ByteArray, v.Numeric,
v.ListItem, v.Object, v.Unique, v.ArrayParentId, v.ArrayIndex
};
public async Task BulkInsertObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default)
{
var rows = objects.Select(ObjectRowValues).ToList();
await BulkInsertAsync("_objects", ObjectColumns, rows, cancellationToken);
}
public async Task BulkInsertValuesAsync(IEnumerable values, CancellationToken cancellationToken = default)
{
var rows = values.Select(ValueRowValues).ToList();
await BulkInsertAsync("_values", ValueColumns, rows, cancellationToken);
}
///
/// Insert into using chunked
/// multi-row INSERTs inside one transaction.
///
private async Task BulkInsertAsync(string table, string[] columns, List rows, CancellationToken cancellationToken)
{
if (rows.Count == 0) return;
int colCount = columns.Length;
int rowsPerChunk = Math.Max(1, MaxParamsPerStatement / colCount);
string columnList = string.Join(", ", columns);
await _db.ExecuteAtomicAsync(async () =>
{
foreach (var chunk in Chunk(rows, rowsPerChunk))
{
var sb = new StringBuilder();
sb.Append("INSERT INTO ").Append(table).Append(" (").Append(columnList).Append(") VALUES ");
var parameters = new List(chunk.Count * colCount);
int p = 0;
for (int r = 0; r < chunk.Count; r++)
{
if (r > 0) sb.Append(", ");
sb.Append('(');
for (int c = 0; c < colCount; c++)
{
if (c > 0) sb.Append(", ");
// _hash is BLOB(16) written from the uuid TEXT parameter (SqliteHash).
var placeholder = "$" + (++p);
sb.Append(columns[c] is "_hash" or "_unique" ? SqliteHash.FromText(placeholder) : placeholder);
parameters.Add(chunk[r][c]);
}
sb.Append(')');
}
cancellationToken.ThrowIfCancellationRequested();
await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken);
}
});
}
// ===== UPDATES (per-row inside one transaction — simple and reliable) =====
public async Task BulkUpdateObjectsAsync(IEnumerable objects, CancellationToken cancellationToken = default)
{
var list = objects.ToList();
if (list.Count == 0) return;
// All columns except _id and _date_create (creation time is immutable).
const string setSql =
"_id_parent=$1, _id_scheme=$2, _name=$3, _id_owner=$4, _id_who_change=$5, " +
"_date_modify=$6, _date_begin=$7, _date_complete=$8, _key=$9, _value_long=$10, " +
"_value_string=$11, _value_guid=$12, _value_bool=$13, _value_double=$14, " +
"_value_numeric=$15, _value_datetime=$16, _value_bytes=$17, _note=$18, _hash=unhex(replace($19,'-','')), _value_unique=$20";
const string sql = "UPDATE _objects SET " + setSql + " WHERE _id=$21";
await _db.ExecuteAtomicAsync(async () =>
{
foreach (var o in list)
{
await _db.ExecuteAsync(sql, new object[] { o.IdParent, o.IdScheme, o.Name!, o.IdOwner, o.IdWhoChange,
o.DateModify, o.DateBegin!, o.DateComplete!, o.Key!, o.ValueLong!,
o.ValueString!, o.ValueGuid!, o.ValueBool!, o.ValueDouble!,
o.ValueNumeric!, o.ValueDatetime!, o.ValueBytes!, o.Note!, o.Hash!, o.ValueUnique!, o.Id }, cancellationToken);
}
});
}
public async Task BulkUpdateValuesAsync(IEnumerable values, CancellationToken cancellationToken = default)
{
var list = values.ToList();
if (list.Count == 0) return;
// F6 (perf wave 6): chunked UPDATE ... FROM (VALUES ...) instead of one statement per
// row (each row was its own command through P/Invoke). SQLite names bare VALUES
// columns column1..columnN; _unique keeps its uuid-text -> BLOB(16) conversion, same
// as the old per-row form did with unhex(replace($11,'-','')).
const int colCount = 14; // 13 data columns + _id
int rowsPerChunk = Math.Max(1, MaxParamsPerStatement / colCount);
const string head =
"UPDATE _values SET " +
"_String=u.column1, _Long=u.column2, _Guid=u.column3, _Double=u.column4, " +
"_DateTimeOffset=u.column5, _Boolean=u.column6, _ByteArray=u.column7, " +
"_Numeric=u.column8, _ListItem=u.column9, _Object=u.column10, " +
"_unique=unhex(replace(u.column11,'-','')), _array_parent_id=u.column12, _array_index=u.column13 " +
"FROM (VALUES ";
const string tail = ") AS u WHERE _values._id = u.column14";
await _db.ExecuteAtomicAsync(async () =>
{
foreach (var chunk in Chunk(list, rowsPerChunk))
{
var sb = new StringBuilder(head);
var parameters = new List(chunk.Count * colCount);
int p = 0;
for (int r = 0; r < chunk.Count; r++)
{
var v = chunk[r];
if (r > 0) sb.Append(", ");
sb.Append('(');
for (int c = 0; c < colCount; c++)
{
if (c > 0) sb.Append(", ");
sb.Append('$').Append(++p);
}
sb.Append(')');
parameters.AddRange(new object?[]
{
v.String, v.Long, v.Guid, v.Double, v.DateTimeOffset, v.Boolean,
v.ByteArray, v.Numeric, v.ListItem, v.Object, v.Unique,
v.ArrayParentId, v.ArrayIndex, v.Id
});
}
sb.Append(tail);
cancellationToken.ThrowIfCancellationRequested();
await _db.ExecuteAsync(sb.ToString(), parameters.ToArray()!, cancellationToken);
}
});
}
// ===== DELETES (chunked IN(...) — no PG ANY(array)) =====
public Task BulkDeleteObjectsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default)
=> DeleteByIdsAsync("DELETE FROM _objects WHERE _id IN ", objectIds, cancellationToken);
public Task BulkDeleteValuesAsync(IEnumerable valueIds, CancellationToken cancellationToken = default)
=> DeleteByIdsAsync("DELETE FROM _values WHERE _id IN ", valueIds, cancellationToken);
public Task BulkDeleteValuesByObjectIdsAsync(IEnumerable objectIds, CancellationToken cancellationToken = default)
=> DeleteByIdsAsync("DELETE FROM _values WHERE _id_object IN ", objectIds, cancellationToken);
public Task BulkDeleteValuesByListItemIdsAsync(IEnumerable listItemIds, CancellationToken cancellationToken = default)
=> DeleteByIdsAsync("DELETE FROM _values WHERE _ListItem IN ", listItemIds, cancellationToken);
private async Task DeleteByIdsAsync(string head, IEnumerable ids, CancellationToken cancellationToken)
{
var idList = ids.ToList();
if (idList.Count == 0) return;
await _db.ExecuteAtomicAsync(async () =>
{
foreach (var chunk in Chunk(idList, MaxParamsPerStatement))
{
var sb = new StringBuilder(head).Append('(');
var parameters = new object?[chunk.Count];
for (int i = 0; i < chunk.Count; i++)
{
if (i > 0) sb.Append(", ");
sb.Append('$').Append(i + 1);
parameters[i] = chunk[i];
}
sb.Append(')');
await _db.ExecuteAsync(sb.ToString(), parameters!);
}
});
}
// ===== helpers =====
private static IEnumerable> Chunk(IReadOnlyList source, int size)
{
for (int i = 0; i < source.Count; i += size)
{
int n = Math.Min(size, source.Count - i);
var bucket = new List(n);
for (int j = 0; j < n; j++) bucket.Add(source[i + j]);
yield return bucket;
}
}
}
}
Path: redb/redb.SQLite/Data/SqliteCaseFolding.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/SqliteCaseFolding.cs
----
using System;
using System.Globalization;
using Microsoft.Data.Sqlite;
namespace redb.SQLite.Data
{
///
/// Replaces SQLite's built-in like , lower and upper with Unicode-aware
/// implementations, on one connection.
///
///
/// Why this is a connection concern and not a SQL one. On PostgreSQL the fix is a
/// COLLATE clause in the generated SQL. SQLite has no equivalent to attach: its only
/// case-insensitive collation, NOCASE , folds ASCII and nothing else, and LIKE is
/// implemented as a function, so collations never reach it. Measured on the build redb ships
/// with (3.46.1, no ICU compiled in): 'Привет' LIKE '%привет%' is 0,
/// lower('Привет') returns the string unchanged, and 'Привет' = 'привет' COLLATE
/// NOCASE is 0. Unlike PostgreSQL, where this depends on how the database was created, in
/// SQLite it is unconditional.
///
///
///
/// Overriding a built-in is the supported mechanism, and it is exactly what SQLite's own ICU
/// extension does. Doing it from managed code keeps the whole fix inside the provider: no ICU
/// build, no change to the native extension, no per-platform rebuild.
///
///
///
/// Cost. A managed callback runs per row instead of the C implementation. That matters
/// less than it sounds for the case this exists to serve: LIKE '%x%' cannot use an index
/// in SQLite anyway, so both versions scan, and the difference is call overhead rather than
/// algorithmic. It is opt-in regardless.
///
///
internal static class SqliteCaseFolding
{
///
/// Installs the overrides when ; otherwise does nothing at all, so
/// a connection is byte-for-byte what it was before this type existed.
///
internal static void Install(SqliteConnection connection, bool enabled)
{
if (!enabled) return;
// ToLowerInvariant rather than ToUpperInvariant on purpose. Upper-casing is the
// length-changing direction in several languages (German ß becomes SS), which would make
// lower(upper(x)) disagree with x and make the folded comparison disagree with itself.
// Lower-casing is length-preserving for every mapping we care about here.
connection.CreateFunction(
"lower", s => s?.ToLowerInvariant(), isDeterministic: true);
connection.CreateFunction(
"upper", s => s?.ToUpperInvariant(), isDeterministic: true);
// Both arities. SQLite exposes LIKE as like(pattern, value) and, for the
// "LIKE ... ESCAPE c" form, like(pattern, value, escape). Registering only the first
// would leave every ESCAPE query silently on the ASCII-only built-in — and redb emits
// ESCAPE on its user-search path, so that is not a hypothetical.
connection.CreateFunction(
"like", (pattern, value) => Like(pattern, value, null), isDeterministic: true);
connection.CreateFunction(
"like", (pattern, value, escape) => Like(pattern, value, escape), isDeterministic: true);
}
///
/// SQLite's LIKE semantics, folded for all scripts: % matches any sequence including
/// empty, _ matches exactly one character, and a character preceded by the escape
/// character is literal. NULL in, NULL out, matching the built-in.
///
private static long? Like(string? pattern, string? value, string? escape)
{
if (pattern is null || value is null) return null;
char? esc = null;
if (!string.IsNullOrEmpty(escape))
{
// SQLite raises "ESCAPE expression must be a single character"; mirror that rather
// than silently matching nothing.
if (escape!.Length != 1)
throw new ArgumentException("ESCAPE expression must be a single character.", nameof(escape));
esc = char.ToLowerInvariant(escape[0]);
}
// Fold once, then match on the folded forms. Case folding a pattern is safe: '%' and '_'
// have no case, and the escape character is folded with it so the two stay in step.
return IsMatch(pattern.ToLowerInvariant(), value.ToLowerInvariant(), esc) ? 1L : 0L;
}
///
/// Iterative wildcard match with backtracking. Iterative rather than recursive so a
/// pathological pattern cannot exhaust the stack, and hand-written rather than translated to
/// a regular expression so a user-supplied pattern cannot become a catastrophic-backtracking
/// weapon.
///
private static bool IsMatch(string pattern, string value, char? escape)
{
int p = 0, v = 0;
int starP = -1, starV = 0;
while (v < value.Length)
{
if (p < pattern.Length)
{
var pc = pattern[p];
if (escape.HasValue && pc == escape.Value)
{
// A pattern that ends with the escape character matches nothing at all,
// which is what SQLite's own like() does. Verified against the built-in
// rather than assumed.
if (p + 1 >= pattern.Length) return false;
// Escaped: the next pattern character is literal, wildcards included.
var escLen = RuneLength(pattern, p + 1);
var valLen = RuneLength(value, v);
if (escLen == valLen
&& string.CompareOrdinal(pattern, p + 1, value, v, escLen) == 0)
{
p += 1 + escLen; v += valLen; continue;
}
}
else if (pc == '%')
{
// Remember where the wildcard was so we can extend it on a later mismatch.
starP = p; starV = v; p++; continue;
}
else if (pc == '_')
{
// Exactly one CHARACTER, and in SQLite a character is a code point, not a
// UTF-16 code unit. Counting units would make '_' fail to match an emoji
// or any other astral character, where the built-in matches it.
v += RuneLength(value, v); p++; continue;
}
else
{
var patLen = RuneLength(pattern, p);
var valLen = RuneLength(value, v);
if (patLen == valLen
&& string.CompareOrdinal(pattern, p, value, v, patLen) == 0)
{
p += patLen; v += valLen; continue;
}
}
}
if (starP >= 0)
{
// Let the last '%' swallow one more code point and retry from just after it.
starV += RuneLength(value, starV);
p = starP + 1; v = starV; continue;
}
return false;
}
// Trailing '%' are allowed to match nothing; anything else left over is a mismatch.
while (p < pattern.Length && pattern[p] == '%') p++;
// ... including a lone trailing escape character, per the built-in.
if (escape.HasValue && p == pattern.Length - 1 && pattern[p] == escape.Value)
return false;
return p == pattern.Length;
}
///
/// Length in UTF-16 units of the code point starting at : 2 for a
/// well-formed surrogate pair, 1 otherwise. A lone surrogate counts as 1, so malformed
/// input degrades instead of throwing.
///
private static int RuneLength(string s, int i)
=> char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]) ? 2 : 1;
}
}
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.
}
}
}
}
Path: redb/redb.SQLite/Data/SqliteHash.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/SqliteHash.cs
----
using System;
namespace redb.SQLite.Data;
///
/// The stored form of a 128-bit hash in SQLite — _objects._hash , _schemes._structure_hash ,
/// _users._hash : BLOB(16) in RFC 4122 byte order, i.e. the bytes of the canonical text
/// form read left to right (00112233-4455-6677-8899-aabbccddeeff is 00 11 22 33 44 55 … ).
///
///
/// One place for the byte order, because several code paths write it and several read it. Writes go
/// through the Guid's TEXT parameter and the SQL wrapper — unhex() of the
/// text without dashes is by construction the order the text shows; the native extension does the same
/// in its own statements. Reads get a byte[] from the driver and use .
/// The two must agree, and Guid.ToByteArray() without the big-endian flag does not: it puts the
/// first three groups in little-endian order.
///
///
///
/// Only hashes. _values._Guid , _objects._value_guid , _users._code_guid are data and
/// stay TEXT — they are compared with values users write and read as text.
///
///
///
/// A database created before V4 holds the hashes as 36-character TEXT. SQLite keeps the storage class
/// a value was written with regardless of the declared type, so no ALTER is needed: the values
/// are converted in place on open (ApplySchemaUpgradesAsync ), and a reader that meets a TEXT
/// value anyway still understands it.
///
///
public static class SqliteHash
{
///
/// SQL that turns a canonical uuid TEXT expression (a $n parameter, a column) into the
/// 16-byte BLOB. NULL stays NULL. unhex() needs SQLite 3.41+; the bundled library is newer.
///
public static string FromText(string sqlExpression) => $"unhex(replace({sqlExpression},'-',''))";
/// The 16 bytes of in RFC 4122 order.
public static byte[] ToBlob(Guid value)
{
// Guid.ToByteArray() is little-endian in the first three groups; put them back in text order.
var b = value.ToByteArray();
return new[]
{
b[3], b[2], b[1], b[0],
b[5], b[4],
b[7], b[6],
b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
};
}
/// The Guid whose canonical text form spells .
public static Guid FromBlob(ReadOnlySpan bytes)
{
if (bytes.Length != 16)
throw new FormatException($"A stored hash is 16 bytes, got {bytes.Length}.");
return new Guid(
(bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3],
(short)((bytes[4] << 8) | bytes[5]),
(short)((bytes[6] << 8) | bytes[7]),
bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);
}
///
/// A Guid from whatever the driver returned for a uuid-valued column: the BLOB of a hash, the
/// TEXT of a data guid (or of a hash not yet converted), or a Guid already.
///
public static Guid FromDbValue(object value) => value switch
{
Guid g => g,
byte[] b => FromBlob(b),
_ => Guid.Parse(value.ToString()!),
};
}
Path: redb/redb.SQLite/Data/SqliteJulian.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/SqliteJulian.cs
----
using System;
namespace redb.SQLite.Data
{
///
/// SQLite stores REDB datetimes as REAL Julian day numbers in UTC — the native
/// SQLite datetime representation. SQLite's own date/time functions
/// (datetime() , strftime() , julianday() , date() ) consume a
/// REAL Julian day directly, and because it is a plain number, range comparisons
/// (< /> ) are numeric, correct, and index-friendly (sargable) —
/// unlike the previous TEXT-ISO storage whose lexical comparison broke on format drift.
///
/// Offset is normalized to UTC, matching REDB's contract (stored datetimes are UTC
/// instants — see ) and how PostgreSQL
/// keeps timestamptz in UTC.
///
/// The day count is linear in the tick count, truncated to the millisecond - the precision the
/// other providers keep and the hash canon assumes. It was computed through the OLE automation
/// date (ToOADate ), which is not linear: its zero stands for ,
/// so a default date came back as 1899-12-30, and a day before its epoch is encoded as sign and
/// magnitude, so any time of day before 1899-12-30 moved by a day - while the native extension
/// writes through SQLite's own julianday() , which is linear.
///
internal static class SqliteJulian
{
// 1899-12-30 00:00 UTC, the same epoch the OLE date used: for every instant from it on the number
// is bit for bit what was stored before, so existing rows and equality filters keep matching.
private const double EpochJulianDay = 2415018.5;
private const long EpochMillis = 599264352000000000L / TimeSpan.TicksPerMillisecond;
private const double MillisPerDay = 86_400_000.0;
/// DateTimeOffset → UTC Julian day (REAL). Uses the true UTC instant.
public static double ToJulian(DateTimeOffset dto) => ToJulian(dto.UtcDateTime);
///
/// DateTime → UTC Julian day (REAL). The clock value is treated as UTC (REDB's
/// contract:
/// specifies Kind=Utc without converting), so Kind is ignored here.
///
public static double ToJulian(DateTime dt)
{
var millis = dt.Ticks / TimeSpan.TicksPerMillisecond - EpochMillis;
return millis / MillisPerDay + EpochJulianDay;
}
/// UTC Julian day (REAL) → DateTimeOffset (+00:00), to the millisecond.
public static DateTimeOffset FromJulian(double julian)
{
var millis = (long)Math.Round((julian - EpochJulianDay) * MillisPerDay, MidpointRounding.AwayFromZero);
var ticks = (millis + EpochMillis) * TimeSpan.TicksPerMillisecond;
return new DateTimeOffset(new DateTime(ticks, DateTimeKind.Utc), TimeSpan.Zero);
}
}
}
Path: redb/redb.SQLite/Data/SqliteKeyGenerator.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/SqliteKeyGenerator.cs
----
using System;
using Microsoft.Data.Sqlite;
using redb.Core.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace redb.SQLite.Data
{
///
/// SQLite implementation of key generator. Ids come from the native
/// AUTOINCREMENT table _global_identity ; its high-water mark lives in
/// sqlite_sequence . A batch of N ids is reserved with one atomic statement:
/// UPDATE sqlite_sequence SET seq = seq + @n WHERE name='_global_identity'
/// RETURNING seq;
/// which returns the new top; the reserved ids are [top-N+1 .. top].
/// No explicit locking is needed — SQLite serializes writers and the
/// read-modify-write happens inside the single UPDATE (RETURNING: 3.35+).
/// The same sequence is also advanced by the C extension (nextId) and by
/// soft-delete (INSERT DEFAULT VALUES); all consumers only ever increase it,
/// so ids are globally unique. Caching is static in the base class.
///
public class SqliteKeyGenerator : RedbKeyGeneratorBase
{
private readonly SqliteDataSource _dataSource;
// The scope's ambient (connection, transaction) accessor for the single-writer bypass;
// null (the connection-string constructor, tests) keeps the plain pooled-refill path.
private readonly Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? _ambientAccessor;
// AUTOINCREMENT table whose sqlite_sequence row is the id high-water mark.
private const string SEQUENCE_TABLE = "_global_identity";
///
/// The highest id stored in the tables that take their ids from the sequence. Every range starts above it, so
/// the sequence never hands out an id a stored row already has, whatever left it behind: a row committed with an
/// id the application kept from a rolled-back transaction (the sequence bump went back, the row did not), an id
/// another process wrote, a row written with an explicit id. Each term is the last key of a rowid table, read
/// from the end of its b-tree.
///
internal const string IdSpaceTopSql =
"coalesce((SELECT max(_id) FROM _objects), 0), coalesce((SELECT max(_id) FROM _values), 0), " +
"coalesce((SELECT max(_id) FROM _schemes), 0), coalesce((SELECT max(_id) FROM _structures), 0), " +
"coalesce((SELECT max(_id) FROM _users), 0), coalesce((SELECT max(_id) FROM _roles), 0), " +
"coalesce((SELECT max(_id) FROM _users_roles), 0), coalesce((SELECT max(_id) FROM _permissions), 0), " +
"coalesce((SELECT max(_id) FROM _lists), 0), coalesce((SELECT max(_id) FROM _list_items), 0)";
///
/// Create SQLite key generator.
///
public SqliteKeyGenerator(SqliteDataSource dataSource, string? domain = null,
Func<(Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)?>? ambientTransactionAccessor = null) : base(domain)
{
_dataSource = dataSource;
_ambientAccessor = ambientTransactionAccessor;
}
///
/// Create SQLite key generator from connection string.
///
public SqliteKeyGenerator(string connectionString, string? domain = null) : base(domain)
{
_dataSource = SqliteDataSource.Create(connectionString);
}
// === DB-SPECIFIC IMPLEMENTATIONS ===
///
/// Reserve a contiguous batch of ids by bumping the
/// AUTOINCREMENT high-water mark in sqlite_sequence via one atomic UPDATE ... RETURNING.
///
protected override async Task> GenerateKeysAsync(int count)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var tid = System.Environment.CurrentManagedThreadId;
// Console.WriteLine($"[Diag-KeyGen] ENTER count={count} thread={tid}");
await using var conn = await _dataSource.OpenConnectionAsync();
var tConn = sw.ElapsedMilliseconds;
// Console.WriteLine($"[Diag-KeyGen] OpenConnectionAsync +{tConn}ms thread={tid}");
await using var cmd = conn.CreateCommand();
PrepareReserve(cmd, count);
object? scalar;
try
{
scalar = await cmd.ExecuteScalarAsync();
var tScalar = sw.ElapsedMilliseconds - tConn;
// Console.WriteLine($"[Diag-KeyGen] UPDATE sqlite_sequence RETURNING +{tScalar}ms (total {sw.ElapsedMilliseconds}ms) thread={tid}");
}
catch (Microsoft.Data.Sqlite.SqliteException ex)
{
// Console.WriteLine($"[Diag-KeyGen] UPDATE FAILED after {sw.ElapsedMilliseconds}ms thread={tid} errno={ex.SqliteErrorCode} msg='{ex.Message}'");
throw;
}
if (scalar is null || scalar == DBNull.Value)
{
throw new InvalidOperationException(
$"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " +
"Ensure the schema (redbSqlite.sql) was applied — it materializes the sequence row.");
}
long top = Convert.ToInt64(scalar);
RecordIssued(top);
var keys = new List(count);
for (long id = top - count + 1; id <= top; id++)
{
keys.Add(id);
}
// Console.WriteLine($"[Diag-KeyGen] EXIT keys=[{(keys.Count > 0 ? keys[0] : -1)}..{(keys.Count > 0 ? keys[^1] : -1)}] total={sw.ElapsedMilliseconds}ms thread={tid}");
return keys;
}
///
/// The single-writer bypass: the same atomic sequence bump, but on the scope's own
/// connection INSIDE its BEGIN IMMEDIATE - the write lock is already ours, so there is
/// no waiting and no self-deadlock. The keys deliberately do NOT enter the shared
/// cache. A rollback takes the sequence bump back together with the transaction, but
/// the ids stay with whoever got them (an object the application saves again), so
/// every later range starts above the highest id handed out ( ).
///
protected override async Task?> TryGenerateKeysInAmbientTransactionAsync(int count)
{
if (_ambientAccessor?.Invoke() is not { } ambient)
return null;
await using var cmd = ambient.Connection.CreateCommand();
cmd.Transaction = ambient.Transaction;
PrepareReserve(cmd, count);
var scalar = await cmd.ExecuteScalarAsync();
if (scalar is null || scalar == DBNull.Value)
{
throw new InvalidOperationException(
$"sqlite_sequence row for '{SEQUENCE_TABLE}' not found. " +
"Ensure the schema (redbSqlite.sql) was applied - it materializes the sequence row.");
}
long top = Convert.ToInt64(scalar);
RecordIssued(top);
var keys = new List(count);
for (long id = top - count + 1; id <= top; id++)
keys.Add(id);
return keys;
}
///
/// The reserving statement of both paths. The range starts above the sequence and above every id this process
/// handed out before: a range taken inside a transaction that rolled back is gone from sqlite_sequence, yet the
/// application may still hold its ids (since 4.0.0 the next range repeated them, and saving such an object again
/// overwrote the row of the object that got the id second). One statement, no extra write.
///
private void PrepareReserve(SqliteCommand cmd, int count)
{
cmd.CommandText =
"UPDATE sqlite_sequence SET seq = max(seq, @floor, " + IdSpaceTopSql + ") + @n WHERE name = @name RETURNING seq";
cmd.Parameters.AddWithValue("@floor", IssuedHighWater);
cmd.Parameters.AddWithValue("@n", count);
cmd.Parameters.AddWithValue("@name", SEQUENCE_TABLE);
}
}
}
Path: redb/redb.SQLite/Data/SqliteNativeExtension.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/SqliteNativeExtension.cs
----
using System;
namespace redb.SQLite.Data
{
///
/// The version gate of the native extension: the loaded redbsqlite library must report the version the
/// dialect requires (pvt_module_version() ), as the PostgreSQL and SQL Server modules must. A stale build
/// next to the application loaded silently and answered in an old shape - list item JSON in the old form, a regex
/// filter failing with an unrelated error.
///
public static class SqliteNativeExtension
{
///
/// Throws when - what the loaded extension reports, null when it has no
/// pvt_module_version() - is not .
///
public static void EnsureVersion(string path, string? deployed, string required)
{
if (string.Equals(deployed, required, StringComparison.Ordinal))
return;
var found = deployed == null
? "has no pvt_module_version() function"
: $"reports version {deployed}";
throw new InvalidOperationException(
$"The redb native SQLite extension '{path}' {found}; this build of redb.SQLite requires version " +
$"{required}. The library is built from redb.SQLite/native and ships with the package: update the " +
"package, or rebuild the extension (redb.SQLite/native/README.md) and replace the file next to the " +
"application.");
}
}
}
Path: redb/redb.SQLite/Data/SqliteRedbConnection.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/SqliteRedbConnection.cs
----
using Microsoft.Data.Sqlite;
using redb.Core.Data;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
namespace redb.SQLite.Data
{
///
/// SQLite implementation of IRedbConnection using Sqlite.
/// Provides pure ADO.NET database access with automatic transaction management.
///
public class SqliteRedbConnection : IRedbConnection
{
private readonly SqliteDataSource _dataSource;
private SqliteConnection? _connection;
private SqliteRedbTransaction? _currentTransaction;
// The current command's hold on the ambient transaction's connection; released with the command.
private AmbientLease? _ambientLease;
// Identity of the database in AmbientConnectionRegistry (computed on first use).
private string? _databaseKey;
private bool _disposed = false;
public bool IsDisposed => _disposed;
///
/// One command: this wrapper's gate and, inside an ambient transaction, the lease on the
/// transaction's connection taken by - both released when the
/// command ends.
///
private readonly struct CommandScope : IDisposable
{
private readonly SqliteRedbConnection _owner;
private readonly CommandGate.Releaser _releaser;
public CommandScope(SqliteRedbConnection owner, CommandGate.Releaser releaser)
{
_owner = owner;
_releaser = releaser;
}
public void Dispose()
{
var lease = _owner._ambientLease;
_owner._ambientLease = null;
try
{
lease?.Dispose();
}
finally
{
_releaser.Dispose();
}
}
}
/// The database file: two connection strings reaching the same file share one key.
private string DatabaseKey => _databaseKey ??= DatabaseKeyOf(_dataSource.ConnectionString);
private string? _sessionSignature;
// This configuration in AmbientConnectionRegistry: the cache domain of the connection string plus the
// per-connection settings. The file is the database key; the transaction's connection to it is shared only
// when they match.
private string SessionSignature => _sessionSignature ??=
redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(_dataSource.ConnectionString)
+ $"|case_folding={(_dataSource.UnicodeCaseFolding ? 1 : 0)};lazy_refs={(_dataSource.LazyReferences ? 1 : 0)}";
private static string DatabaseKeyOf(string connectionString)
{
var dataSource = new SqliteConnectionStringBuilder(connectionString).DataSource;
var isFile = !string.IsNullOrEmpty(dataSource)
&& dataSource != ":memory:"
&& !dataSource.StartsWith("file:", StringComparison.OrdinalIgnoreCase);
return "sqlite|" + (isFile ? System.IO.Path.GetFullPath(dataSource) : connectionString);
}
/// Opens the connection an ambient transaction holds (pragmas and extension applied by the data source).
private async Task OpenAmbientAsync(CancellationToken cancellationToken)
=> await _dataSource.OpenConnectionAsync();
/// Synchronous .
private System.Data.Common.DbConnection OpenAmbient() => _dataSource.OpenConnection();
///
/// Microsoft.Data.Sqlite never takes part in System.Transactions, so redb begins the transaction the
/// scope commits or rolls back. BEGIN IMMEDIATE takes the single write lock up front, as every
/// explicit redb transaction on SQLite does; it is held until the scope ends (owner decision P4).
///
private static System.Data.Common.DbTransaction BeginAmbientTransaction(System.Data.Common.DbConnection connection)
=> ((SqliteConnection)connection).BeginTransaction(deferred: false);
// Fail-fast concurrency guard. This connection holds ONE persistent SqliteConnection reused for all
// Commands and teardown share ONE exclusion (CommandGate, a production report
// 2026-09-11): this connection is NOT thread-safe, and racing a native SQLite query
// with a handle close is worse than an exception. Two concurrent commands fail fast;
// a command after teardown began is refused with ObjectDisposedException (the lazy
// loader falls back to a detached scope); DisposeAsync WAITS for the in-flight
// command instead of closing under it.
private readonly CommandGate _gate = new(nameof(SqliteRedbConnection));
private CommandScope EnterCommand() => new(this, _gate.Enter());
// ── [Diag-TXLOCK] process-wide BeginTransaction tracker ────────────
//
// Every BeginTransactionAsync call registers an entry keyed by this
// SqliteRedbConnection's HashCode and dumps the current registry
// contents before attempting BEGIN IMMEDIATE. A SqliteException
// (BUSY / locked) on the BEGIN call triggers a second dump so the
// operator can see WHO else is holding a write tx when the failure
// hit. Active entries are removed on Commit / Rollback / Dispose.
// Set DiagEnabled=true to enable [Diag-TXLOCK] BEGIN tracking dump
// (single-writer concurrency triage). Off by default — the instrumentation
// stays in code so it can be flipped back on without a recompile when the
// next live writer-conflict scenario needs to be investigated.
private sealed record BeginEntry(
int ConnHash, int ThreadId, DateTime BeginUtc,
string AmbientTxId, string CallerStack);
private static readonly ConcurrentDictionary _activeBegins = new();
public static bool DiagEnabled { get; set; } = false;
///
/// Connection string.
///
public string ConnectionString => _dataSource.ConnectionString;
///
/// Current active transaction.
///
public IRedbTransaction? CurrentTransaction => _currentTransaction;
///
/// The connection and transaction that hold the write lock for this scope, for the key
/// generator's bypass (see SqliteKeyGenerator): the scope's explicit transaction, or - inside a
/// TransactionScope - the transaction redb began on the transaction's connection. Null when
/// neither exists. A refill on a separate connection would wait for that very lock.
///
internal (Microsoft.Data.Sqlite.SqliteConnection Connection, Microsoft.Data.Sqlite.SqliteTransaction Transaction)? TryGetAmbientTransaction()
{
var tx = _currentTransaction;
if (_connection != null && tx is { IsActive: true })
return (_connection, tx.SqliteTransaction);
if (Transaction.Current is { } ambient)
{
var entry = AmbientConnectionRegistry.GetOrOpen(ambient, DatabaseKey, SessionSignature, OpenAmbient, BeginAmbientTransaction);
return ((SqliteConnection)entry.Connection, (Microsoft.Data.Sqlite.SqliteTransaction)entry.OwnTransaction!);
}
return null;
}
///
/// Whether any transaction is active — explicit or ambient TransactionScope.
/// EF Core pattern: checks both CurrentTransaction and Transaction.Current.
///
public bool IsInTransaction =>
(_currentTransaction != null && _currentTransaction.IsActive) ||
Transaction.Current != null;
///
/// Create connection from data source.
///
/// Sqlite data source (pooled).
public SqliteRedbConnection(SqliteDataSource dataSource)
{
_dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
}
///
/// Create connection from connection string.
///
/// SQLite connection string.
public SqliteRedbConnection(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException(nameof(connectionString));
_dataSource = SqliteDataSource.Create(connectionString);
}
// === CONNECTION MANAGEMENT ===
///
/// Get underlying connection (for bulk operations).
/// This ensures all operations use the same connection and transaction.
///
public async Task GetUnderlyingConnectionAsync(CancellationToken cancellationToken = default)
{
// Outside a command: no lease, which would hold the transaction connection's gate past the command
// and stall the end of the transaction.
if (!_disposed && _currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient)
return (await AmbientConnectionRegistry.GetOrOpenAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, BeginAmbientTransaction, cancellationToken)).Connection;
return await GetOpenConnectionAsync(cancellationToken);
}
///
public async Task LeaseAsync(CancellationToken cancellationToken = default)
{
// One command's hold, as every command of this wrapper takes it: this wrapper's gate, and inside an ambient
// transaction the lease on the transaction's connection. Both are left when the lease is given back.
var command = EnterCommand();
try
{
var connection = await GetOpenConnectionAsync(cancellationToken);
// Microsoft.Data.Sqlite refuses a command without the transaction object on a connection with an open
// transaction: this wrapper's explicit one, or the one redb began on the ambient transaction's connection.
System.Data.Common.DbTransaction? transaction = _currentTransaction is { IsActive: true } explicitTransaction
? explicitTransaction.SqliteTransaction
: _ambientLease?.Entry.OwnTransaction;
return new RedbConnectionLease(connection, transaction, command.Dispose);
}
catch
{
command.Dispose();
throw;
}
}
private async Task GetOpenConnectionAsync(CancellationToken cancellationToken = default)
{
// Dispose nulls _connection; without this check a call after Dispose would open a NEW
// connection on a wrapper whose second Dispose is a no-op, and it would never be closed.
if (_disposed)
throw new ObjectDisposedException(nameof(SqliteRedbConnection),
"The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " +
"instead of reusing one from a finished scope or exchange.");
// Inside an ambient transaction the TRANSACTION holds the connection (AmbientConnectionRegistry)
// and redb's own transaction on it: the driver cannot enlist, and a second connection would wait
// for the write lock that transaction holds. An explicit transaction of this wrapper keeps its own.
if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient)
{
_ambientLease ??= await AmbientConnectionRegistry.AcquireAsync(ambient, DatabaseKey, SessionSignature, OpenAmbientAsync, BeginAmbientTransaction, cancellationToken);
return (SqliteConnection)_ambientLease.Entry.Connection;
}
if (_connection == null)
{
_connection = await _dataSource.OpenConnectionAsync();
}
else if (_connection.State != System.Data.ConnectionState.Open)
{
await _connection.OpenAsync();
}
return _connection;
}
private SqliteCommand CreateCommand(SqliteConnection connection, string sql, object[] parameters)
{
// Convert @p0, @p1 format to SQLite $1, $2 format for cross-platform compatibility
var convertedSql = ConvertParameters(sql, parameters.Length);
var cmd = new SqliteCommand(convertedSql, connection);
// Set transaction if active. The `_currentTransaction` field is
// cleared on Dispose, NOT on Commit/Rollback — so after the caller
// commits but before they dispose, this would otherwise try to
// bind the command to an already-closed SQLite transaction object
// and throw "transaction is not associated with the same connection".
// Gate on IsActive so queries that fire between commit-and-dispose
// (e.g. visibility probes in transaction-integrity tests) bind to
// no transaction and run against the autocommit connection.
if (_currentTransaction != null && _currentTransaction.IsActive)
{
cmd.Transaction = _currentTransaction.SqliteTransaction;
}
else if (_ambientLease?.Entry.OwnTransaction is SqliteTransaction ambientTransaction)
{
// Inside a TransactionScope: bind to the transaction redb began on the transaction's connection.
cmd.Transaction = ambientTransaction;
}
// Add parameters NAMED to match the converted $1,$2,... placeholders
// (Microsoft.Data.Sqlite binds by name, not by position).
for (int i = 0; i < parameters.Length; i++)
{
var param = parameters[i];
var sqliteParam = new SqliteParameter { ParameterName = "$" + (i + 1) };
switch (param)
{
case null:
sqliteParam.Value = DBNull.Value;
break;
case DateTimeOffset dto:
// Datetimes are stored as REAL Julian day (UTC) — the native SQLite
// datetime format → numeric, correct, index-friendly comparisons and
// datetime()/strftime()/julianday() work directly. Covers writes
// (base _date_* + props _DateTimeOffset) AND parameterized query values.
sqliteParam.Value = SqliteJulian.ToJulian(dto);
break;
case DateTime dt2:
// e.g. a LINQ comparison value (DateTime) — same UTC Julian encoding.
sqliteParam.Value = SqliteJulian.ToJulian(dt2);
break;
case decimal dec:
// Microsoft.Data.Sqlite binds decimal as TEXT, but _Numeric/_value_numeric
// are REAL — and in SQLite type-ordering a REAL is always < any TEXT, so
// `Salary(REAL) > '80000'(TEXT)` is always false. Bind decimals as double.
sqliteParam.Value = (double)dec;
break;
case long[]:
case int[]:
case string[]:
// SQLite has no array parameters. Bind arrays as a JSON array
// (TEXT); SQL that needs the elements uses
// `IN (SELECT value FROM json_each($n))`.
sqliteParam.Value = JsonSerializer.Serialize(param);
break;
case Array values when values is not byte[]:
// The same JSON array for the other element types a list of values carries (Contains over a
// list of dates, decimals, flags, Guids): each element spelled as the single value is bound,
// a date as its Julian day, a decimal as a double, so json_each yields what the column holds.
// A DateTime[] reached the driver as it was and failed: "No mapping exists from object type".
sqliteParam.Value = JsonArrayOfStoredValues(values);
break;
default:
sqliteParam.Value = param;
break;
}
cmd.Parameters.Add(sqliteParam);
}
return cmd;
}
///
/// A list of values as the JSON array json_each reads, every element spelled as the column stores it: a
/// date as its Julian day, a decimal as a double, a flag as 1/0, a Guid as the driver writes one (upper-case
/// text). Nulls stay JSON null: IN never matches them. An element of any other type is refused here,
/// before the statement runs, instead of reaching the driver.
///
private static string JsonArrayOfStoredValues(Array values)
{
var items = new List(values.Length);
foreach (var v in values)
{
items.Add(v switch
{
null => null,
DateTimeOffset dto => SqliteJulian.ToJulian(dto),
DateTime dt => SqliteJulian.ToJulian(dt),
decimal dec => (double)dec,
double or float or long or int or short or byte or sbyte or ushort or uint or string => v,
bool flag => flag ? 1 : 0,
Guid g => g.ToString().ToUpperInvariant(),
char c => c.ToString(),
_ => throw new NotSupportedException(
$"SQLite cannot take a list of {v.GetType().Name} values as a parameter.")
});
}
return JsonSerializer.Serialize(items);
}
// === QUERY METHODS ===
///
/// Execute SQL query and map results to list of objects.
/// Uses JsonPropertyName attribute for snake_case to PascalCase mapping.
///
public Task> QueryAsync(string sql, params object[] parameters) where T : new()
=> QueryAsync(sql, parameters, CancellationToken.None);
///
public async Task> QueryAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : new()
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await QueryCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task> QueryCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : new()
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
var results = new List();
var mapper = new RedbRowMapper();
while (await reader.ReadAsync(cancellationToken))
{
results.Add(mapper.MapRow(reader));
}
return results;
}
///
/// Execute SQL query and return first result.
///
public Task QueryFirstOrDefaultAsync(string sql, params object[] parameters) where T : class, new()
=> QueryFirstOrDefaultAsync(sql, parameters, CancellationToken.None);
///
public async Task QueryFirstOrDefaultAsync(string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new()
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await QueryFirstOrDefaultCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task QueryFirstOrDefaultCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken) where T : class, new()
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
if (await reader.ReadAsync(cancellationToken))
{
var mapper = new RedbRowMapper();
return mapper.MapRow(reader);
}
return null;
}
///
/// Execute SQL query and return scalar value.
///
public Task ExecuteScalarAsync(string sql, params object[] parameters)
=> ExecuteScalarAsync(sql, parameters, CancellationToken.None);
///
public async Task ExecuteScalarAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await ExecuteScalarCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task ExecuteScalarCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
var result = await cmd.ExecuteScalarAsync(cancellationToken);
if (result == null || result == DBNull.Value)
return default;
return ConvertScalar(result);
}
// === ORPHAN TRANSACTION HYGIENE ===
private const string OrphanRollbackFailureKey = "redb.OrphanTransactionRollbackFailure";
///
/// A command that failed can leave behind a transaction its own SQL text opened: a root
/// SAVEPOINT or BEGIN, some writes, then an error before RELEASE or COMMIT. This wrapper does
/// not own that transaction, and Microsoft.Data.Sqlite pools the handle as it is - the pool
/// clears it only when that very handle is handed out again, so its write lock stalls every
/// writer of the database meanwhile, and the scope itself cannot start a transaction. It is
/// rolled back here before the failure leaves, unless a transaction of this wrapper or an
/// ambient one owns the connection (its owner ends it). The original exception always
/// propagates; a rollback that fails as well is attached to it instead of replacing it.
///
private void RollbackOrphanTransaction(SqliteConnection conn, Exception failure)
{
if (_currentTransaction is { IsActive: true } || Transaction.Current != null)
return;
if (conn.State != System.Data.ConnectionState.Open || SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) != 0)
return;
try
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "ROLLBACK";
cmd.ExecuteNonQuery();
}
catch (Exception rollbackFailure)
{
failure.Data[OrphanRollbackFailureKey] = rollbackFailure.Message;
}
}
///
/// The last line for a handle about to return to the pool inside a transaction nobody owns -
/// a path that reached the physical connection without the per-command guard. Pooled as it is,
/// its write lock would stall every writer until the pool happened to hand it out again.
/// An ambient transaction still in flight owns the handle and ends it itself. A failing
/// rollback propagates, like any other dispose fault here.
///
private static void ReleaseOrphanTransactionBeforePooling(SqliteConnection conn)
{
// The connection's own state first: Transaction.Current throws between Complete() and Dispose() of
// a TransactionScope, and disposing a scope's services in that window is legal.
if (conn.State != System.Data.ConnectionState.Open || SQLitePCL.raw.sqlite3_get_autocommit(conn.Handle) != 0)
return;
if (Transaction.Current != null)
return;
using var cmd = conn.CreateCommand();
cmd.CommandText = "ROLLBACK";
cmd.ExecuteNonQuery();
}
// === SYNCHRONOUS COUNTERPARTS (thread-pool-free lazy path) ===
// The sync getter of RedbListItem.Object runs the whole load on the calling thread; these
// are true sync ADO calls - no thread-pool continuation anywhere, so a saturated pool
// cannot slow or deadlock them. Same command shape and pragmas as the async twins above
// (SqliteDataSource.OpenConnection applies them synchronously).
private SqliteConnection GetOpenConnection()
{
if (_disposed)
throw new ObjectDisposedException(nameof(SqliteRedbConnection),
"The scope that owned this connection has ended. Resolve a fresh scoped IRedbService " +
"instead of reusing one from a finished scope or exchange.");
// Same ambient-transaction rule as the async twin.
if (_currentTransaction is not { IsActive: true } && Transaction.Current is { } ambient)
{
_ambientLease ??= AmbientConnectionRegistry.Acquire(ambient, DatabaseKey, SessionSignature, OpenAmbient, BeginAmbientTransaction);
return (SqliteConnection)_ambientLease.Entry.Connection;
}
if (_connection == null)
{
_connection = _dataSource.OpenConnection();
}
else if (_connection.State != System.Data.ConnectionState.Open)
{
_connection.Open();
}
return _connection;
}
///
public T? QueryFirstOrDefault(string sql, params object[] parameters) where T : class, new()
{
using var _guard = EnterCommand();
var conn = GetOpenConnection();
try
{
return QueryFirstOrDefaultCore(conn, sql, parameters);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private T? QueryFirstOrDefaultCore(SqliteConnection conn, string sql, object[] parameters) where T : class, new()
{
using var cmd = CreateCommand(conn, sql, parameters);
using var reader = cmd.ExecuteReader();
return reader.Read() ? new RedbRowMapper().MapRow(reader) : null;
}
///
public List Query(string sql, params object[] parameters) where T : new()
{
using var _guard = EnterCommand();
var conn = GetOpenConnection();
try
{
return QueryCore(conn, sql, parameters);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private List QueryCore(SqliteConnection conn, string sql, object[] parameters) where T : new()
{
using var cmd = CreateCommand(conn, sql, parameters);
using var reader = cmd.ExecuteReader();
var results = new List();
var mapper = new RedbRowMapper();
while (reader.Read())
results.Add(mapper.MapRow(reader));
return results;
}
///
public int Execute(string sql, params object[] parameters)
{
using var _guard = EnterCommand();
var conn = GetOpenConnection();
try
{
using var cmd = CreateCommand(conn, sql, parameters);
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
///
public T? ExecuteScalar(string sql, params object[] parameters)
{
using var _guard = EnterCommand();
var conn = GetOpenConnection();
try
{
return ExecuteScalarCore(conn, sql, parameters);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private T? ExecuteScalarCore(SqliteConnection conn, string sql, object[] parameters)
{
using var cmd = CreateCommand(conn, sql, parameters);
var result = cmd.ExecuteScalar();
if (result == null || result == DBNull.Value)
return default;
return ConvertScalar(result);
}
///
public string? ExecuteJson(string sql, params object[] parameters)
{
using var _guard = EnterCommand();
var conn = GetOpenConnection();
try
{
return ExecuteJsonCore(conn, sql, parameters);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private string? ExecuteJsonCore(SqliteConnection conn, string sql, object[] parameters)
{
using var cmd = CreateCommand(conn, sql, parameters);
var result = cmd.ExecuteScalar();
return result == null || result == DBNull.Value ? null : result.ToString();
}
///
/// Convert a raw SQLite value to T, handling uuid->Guid (a hash BLOB or a TEXT guid),
/// TEXT/ DateTime -> DateTimeOffset, and BLOB -> byte[] (which
/// Convert.ChangeType cannot do), then falling back to ChangeType.
///
private static T ConvertScalar(object value)
{
var targetType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
if (value.GetType() == targetType || targetType.IsAssignableFrom(value.GetType()))
return (T)value;
if (targetType == typeof(Guid))
return (T)(object)SqliteHash.FromDbValue(value);
// Datetimes are stored as REAL Julian day (UTC) → value is a double.
if (targetType == typeof(DateTimeOffset))
return (T)(object)(value is double jdo ? SqliteJulian.FromJulian(jdo)
: value is DateTimeOffset d ? d
: value is DateTime dt ? new DateTimeOffset(dt, TimeSpan.Zero)
: DateTimeOffset.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind));
if (targetType == typeof(DateTime))
return (T)(object)(value is double jdt ? SqliteJulian.FromJulian(jdt).UtcDateTime
: value is DateTime dt3 ? dt3
: value is DateTimeOffset dto3 ? dto3.UtcDateTime
: DateTime.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind));
if (targetType == typeof(DateOnly))
return (T)(object)(value is double jod ? DateOnly.FromDateTime(SqliteJulian.FromJulian(jod).UtcDateTime)
: value is DateTime dt4 ? DateOnly.FromDateTime(dt4)
: DateOnly.Parse(value.ToString()!, System.Globalization.CultureInfo.InvariantCulture));
if (targetType == typeof(byte[]))
return (T)(object)(byte[])value;
return (T)redb.Core.Utils.RedbDecimal.ChangeType(value, targetType);
}
///
/// Execute SQL command (INSERT, UPDATE, DELETE).
///
public Task ExecuteAsync(string sql, params object[] parameters)
=> ExecuteAsync(sql, parameters, CancellationToken.None);
///
public async Task ExecuteAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await ExecuteCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task ExecuteCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
return await cmd.ExecuteNonQueryAsync(cancellationToken);
}
///
/// Execute SQL query and return list of scalar values (first column only).
/// Use for simple queries like SELECT _id FROM ... that return single column.
///
public Task> QueryScalarListAsync(string sql, params object[] parameters)
=> QueryScalarListAsync(sql, parameters, CancellationToken.None);
///
public async Task> QueryScalarListAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await QueryScalarListCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task> QueryScalarListCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
var results = new List();
while (await reader.ReadAsync(cancellationToken))
{
if (reader.IsDBNull(0))
{
results.Add(default!);
}
else
{
results.Add(ConvertScalar(reader.GetValue(0)));
}
}
return results;
}
// === TRANSACTION METHODS ===
///
/// Begin new transaction.
///
public async Task BeginTransactionAsync(System.Data.IsolationLevel? isolationLevel = null, CancellationToken cancellationToken = default)
{
// BR-1: the parameter is accepted for portability. SQLite is a single serial writer and
// BEGIN IMMEDIATE below already takes the write lock at start - every transaction is
// effectively serializable, whatever level the caller names.
_ = isolationLevel;
if (_currentTransaction != null && _currentTransaction.IsActive)
throw new InvalidOperationException("Transaction already active. Commit or rollback first.");
if (Transaction.Current != null)
throw new InvalidOperationException(
"Ambient TransactionScope detected. Cannot create explicit transaction inside TransactionScope. " +
"Use ExecuteAtomicAsync() which respects ambient transactions.");
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
// [Diag-TXLOCK] — capture WHO is about to BEGIN IMMEDIATE and WHAT
// else is currently holding write tx; on BUSY we dump again so the
// operator can see who was racing.
var connHash = GetHashCode();
var ambient = Transaction.Current?.TransactionInformation.LocalIdentifier ?? "";
var caller = DiagEnabled ? CaptureCallerStack(skipFrames: 1) : "";
if (DiagEnabled)
{
Console.WriteLine(
$"[Diag-TXLOCK] BEGIN ENTRY conn=#{connHash} thread={Environment.CurrentManagedThreadId} " +
$"ambientTx={ambient} activeCount={_activeBegins.Count}");
DumpActiveBegins("BEGIN ENTRY (pre-BeginImmediate)");
// Console.WriteLine($"[Diag-TXLOCK] BEGIN CALLER conn=#{connHash}\n{caller}");
}
SqliteTransaction sqliteTx;
try
{
// BEGIN IMMEDIATE (deferred:false) acquires SQLite's single write lock at
// transaction start — the SQLite equivalent of pessimistic locking / the PG
// `FOR UPDATE` intent. Atomicity here is critical and reused widely.
sqliteTx = conn.BeginTransaction(deferred: false);
}
catch (SqliteException ex)
{
if (DiagEnabled)
{
Console.WriteLine(
$"[Diag-TXLOCK] BEGIN FAILED conn=#{connHash} thread={Environment.CurrentManagedThreadId} " +
$"errno={ex.SqliteErrorCode} msg='{ex.Message}'");
DumpActiveBegins("BEGIN FAILED — current holders");
}
throw;
}
_currentTransaction = new SqliteRedbTransaction(sqliteTx, () =>
{
_currentTransaction = null;
if (DiagEnabled)
{
_activeBegins.TryRemove(connHash, out _);
Console.WriteLine(
$"[Diag-TXLOCK] BEGIN RELEASED conn=#{connHash} thread={Environment.CurrentManagedThreadId} " +
$"activeCount={_activeBegins.Count}");
}
});
if (DiagEnabled)
{
_activeBegins[connHash] = new BeginEntry(
connHash, Environment.CurrentManagedThreadId, DateTime.UtcNow, ambient, caller);
Console.WriteLine(
$"[Diag-TXLOCK] BEGIN OK conn=#{connHash} thread={Environment.CurrentManagedThreadId} " +
$"activeCount={_activeBegins.Count}");
}
return _currentTransaction;
}
// ── [Diag-TXLOCK] helpers ──────────────────────────────────────────
private static string CaptureCallerStack(int skipFrames)
{
try
{
var st = new StackTrace(skipFrames + 1, fNeedFileInfo: false);
var frames = st.GetFrames();
if (frames is null) return "";
var top = frames.Take(8).Select(f =>
{
var m = f.GetMethod();
return m is null ? "" : $" at {m.DeclaringType?.FullName}.{m.Name}";
});
return string.Join("\n", top);
}
catch { return ""; }
}
private static void DumpActiveBegins(string label)
{
if (_activeBegins.IsEmpty)
{
// Console.WriteLine($"[Diag-TXLOCK] {label}: ");
return;
}
// Console.WriteLine($"[Diag-TXLOCK] {label}: count={_activeBegins.Count}");
foreach (var (key, e) in _activeBegins)
{
var heldFor = DateTime.UtcNow - e.BeginUtc;
Console.WriteLine(
$" conn=#{key} thread={e.ThreadId} heldFor={heldFor.TotalMilliseconds:N0}ms " +
$"ambientAtBegin={e.AmbientTxId}");
foreach (var line in e.CallerStack.Split('\n').Take(5))
Console.WriteLine($" {line}");
}
}
// === ATOMIC OPERATIONS ===
///
/// Atomic execution under an explicit isolation level (BR-1). An active or ambient transaction
/// wins: operations join it and its level is NOT changed.
///
public async Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func operations, CancellationToken cancellationToken = default)
{
if (IsInTransaction)
{
await operations();
return;
}
await using var tx = await BeginTransactionAsync(isolationLevel, cancellationToken);
try
{
await operations();
await tx.CommitAsync();
}
catch
{
await tx.RollbackAsync();
throw;
}
}
/// Result-returning form of the isolation-level overload (BR-1).
public async Task ExecuteAtomicAsync(System.Data.IsolationLevel isolationLevel, Func> operations, CancellationToken cancellationToken = default)
{
if (IsInTransaction)
return await operations();
await using var tx = await BeginTransactionAsync(isolationLevel, cancellationToken);
try
{
var result = await operations();
await tx.CommitAsync();
return result;
}
catch
{
await tx.RollbackAsync();
throw;
}
}
///
/// Execute operations atomically (SaveChanges replacement).
///
public async Task ExecuteAtomicAsync(Func operations, CancellationToken cancellationToken = default)
{
// EF pattern: if any transaction active (explicit or ambient TransactionScope) — just execute
if (IsInTransaction)
{
await operations();
return;
}
// Otherwise create auto-transaction
await using var tx = await BeginTransactionAsync(cancellationToken: cancellationToken);
try
{
await operations();
await tx.CommitAsync();
}
catch
{
await tx.RollbackAsync();
throw;
}
}
///
/// Execute operations atomically and return result.
///
public async Task ExecuteAtomicAsync(Func> operations, CancellationToken cancellationToken = default)
{
// EF pattern: if any transaction active (explicit or ambient TransactionScope) — just execute
if (IsInTransaction)
{
return await operations();
}
await using var tx = await BeginTransactionAsync(cancellationToken: cancellationToken);
try
{
var result = await operations();
await tx.CommitAsync();
return result;
}
catch
{
await tx.RollbackAsync();
throw;
}
}
// === JSON METHODS ===
///
/// Execute SQL returning JSON (for SQLite functions).
///
public Task ExecuteJsonAsync(string sql, params object[] parameters)
=> ExecuteJsonAsync(sql, parameters, CancellationToken.None);
///
public async Task ExecuteJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await ExecuteJsonCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task ExecuteJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
var result = await cmd.ExecuteScalarAsync(cancellationToken);
if (result == null || result == DBNull.Value)
return null;
return result.ToString();
}
///
/// Execute SQL returning multiple JSON rows.
///
public Task> ExecuteJsonListAsync(string sql, params object[] parameters)
=> ExecuteJsonListAsync(sql, parameters, CancellationToken.None);
///
public async Task> ExecuteJsonListAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await ExecuteJsonListCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task> ExecuteJsonListCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
var results = new List();
while (await reader.ReadAsync(cancellationToken))
{
// Skip NULL values (e.g. get_object_json returns NULL for deleted objects)
if (reader.IsDBNull(0))
continue;
var json = reader.GetString(0);
if (!string.IsNullOrEmpty(json))
results.Add(json);
}
return results;
}
///
/// Execute SQL and serialize the result rows to a JSON array string in C#
/// (column names from the reader). SQLite has no row_to_json/json_agg, so the
/// Pro analytics providers package dynamic-shaped results here instead of in SQL.
/// Returns "[]" when there are no rows.
///
public Task QueryRowsAsJsonAsync(string sql, params object[] parameters)
=> QueryRowsAsJsonAsync(sql, parameters, CancellationToken.None);
/// Cancellable form.
public async Task QueryRowsAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await QueryRowsAsJsonCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task QueryRowsAsJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
var rows = new List>();
while (await reader.ReadAsync(cancellationToken))
{
var row = new Dictionary(reader.FieldCount);
for (int i = 0; i < reader.FieldCount; i++)
row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i);
rows.Add(row);
}
return JsonSerializer.Serialize(rows);
}
///
/// Execute SQL and serialize the FIRST result row to a JSON object string in C#,
/// or null if there are no rows. SQLite analog of "SELECT row_to_json(t) FROM (...) t".
///
public Task QueryFirstRowAsJsonAsync(string sql, params object[] parameters)
=> QueryFirstRowAsJsonAsync(sql, parameters, CancellationToken.None);
/// Cancellable form.
public async Task QueryFirstRowAsJsonAsync(string sql, object[] parameters, CancellationToken cancellationToken)
{
using var _guard = EnterCommand();
var conn = await GetOpenConnectionAsync(cancellationToken);
try
{
return await QueryFirstRowAsJsonCoreAsync(conn, sql, parameters, cancellationToken);
}
catch (Exception ex)
{
RollbackOrphanTransaction(conn, ex);
throw;
}
}
private async Task QueryFirstRowAsJsonCoreAsync(SqliteConnection conn, string sql, object[] parameters, CancellationToken cancellationToken)
{
await using var cmd = CreateCommand(conn, sql, parameters);
await using var reader = await cmd.ExecuteReaderAsync(cancellationToken);
if (!await reader.ReadAsync(cancellationToken))
return null;
var row = new Dictionary(reader.FieldCount);
for (int i = 0; i < reader.FieldCount; i++)
row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i);
return JsonSerializer.Serialize(row);
}
// === DISPOSE ===
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
_disposed = true;
// Teardown takes the SAME exclusion as commands: wait for the in-flight one (new
// entrants bounce with ObjectDisposedException the moment the gate flag is set).
// The budget follows the connection's own Default Timeout (SQLite's command
// timeout). The LIVE object is the source of truth (it can be changed
// programmatically); the string is the fallback for a never-opened connection.
int commandTimeout;
try
{
commandTimeout = _connection?.DefaultTimeout
?? new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder(_dataSource.ConnectionString).DefaultTimeout;
}
catch { commandTimeout = 0; }
await _gate.DisposeAndWaitAsync(CommandGate.BudgetFrom(commandTimeout));
// The physical connection MUST return to the pool even if disposing a broken transaction
// throws (e.g. after a mid-query failure): finally guarantees the return, and the exception
// is NOT swallowed — it propagates so the fault stays observable. The route's ReleaseScopes
// loop is throw-resilient, so a propagated dispose fault won't strand sibling scopes.
try
{
if (_currentTransaction != null)
await _currentTransaction.DisposeAsync();
}
finally
{
_currentTransaction = null;
var conn = _connection;
_connection = null;
if (conn != null)
{
try { ReleaseOrphanTransactionBeforePooling(conn); }
finally { await conn.DisposeAsync(); }
}
}
}
///
/// Synchronous dispose for DI container compatibility.
///
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
try
{
_currentTransaction?.DisposeAsync().AsTask().GetAwaiter().GetResult();
}
finally
{
_currentTransaction = null;
var conn = _connection;
_connection = null;
if (conn != null)
{
try { ReleaseOrphanTransactionBeforePooling(conn); }
finally { conn.Dispose(); }
}
}
}
///
/// Convert @p0, @p1 parameter format to SQLite $1, $2 format.
/// Enables cross-platform SQL compatibility.
///
private static string ConvertParameters(string sql, int paramCount)
{
var result = sql;
// Replace @p0, @p1 with $1, $2 (in reverse order to avoid index shifting)
for (int i = paramCount - 1; i >= 0; i--)
{
result = result.Replace($"@p{i}", $"${i + 1}");
}
return result;
}
}
///
/// Row mapper for converting SqliteDataReader to objects.
/// Supports multiple column name formats:
/// - SQLite table columns: _id, _name, _id_scheme
/// - JSON output: id, name, id_scheme
/// - PascalCase: Id, Name, IdScheme
///
/// Target type.
internal class RedbRowMapper where T : new()
{
// Bound on the first row: one mapper reads one result set, whose columns do not change between rows.
private RedbRowMapping.Slot?[]? _slots;
public T MapRow(SqliteDataReader reader)
{
var obj = new T();
var slots = _slots ??= RedbRowMapping.Bind(reader);
for (int i = 0; i < slots.Length; i++)
{
var slot = slots[i];
if (slot == null)
continue;
var property = slot.Property;
var value = reader.IsDBNull(i) ? null : reader.GetValue(i);
if (value != null)
{
try
{
var targetType = slot.TargetType;
// Datetimes are stored as REAL Julian day (UTC) — value is a double.
if (targetType == typeof(DateTimeOffset))
{
if (value is double jd)
slot.Assign(obj, SqliteJulian.FromJulian(jd));
else if (value is DateTime dt)
slot.Assign(obj, new DateTimeOffset(dt, TimeSpan.Zero));
else if (value is DateTimeOffset dto)
slot.Assign(obj, dto);
else if (value is string sdt)
slot.Assign(obj, DateTimeOffset.Parse(sdt, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind));
continue;
}
if (targetType == typeof(DateTime))
{
if (value is double jd2) slot.Assign(obj, SqliteJulian.FromJulian(jd2).UtcDateTime);
else if (value is DateTime dt2) slot.Assign(obj, dt2);
else if (value is DateTimeOffset dto2) slot.Assign(obj, dto2.UtcDateTime);
else if (value is string sdt2) slot.Assign(obj, DateTime.Parse(sdt2, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind));
continue;
}
if (targetType == typeof(DateOnly))
{
if (value is double jd3) slot.Assign(obj, DateOnly.FromDateTime(SqliteJulian.FromJulian(jd3).UtcDateTime));
else if (value is DateTime dt3) slot.Assign(obj, DateOnly.FromDateTime(dt3));
else if (value is string sdt3) slot.Assign(obj, DateOnly.Parse(sdt3, System.Globalization.CultureInfo.InvariantCulture));
continue;
}
// A hash comes back as BLOB(16), a data guid as TEXT — SqliteHash reads both.
if (targetType == typeof(Guid))
{
slot.Assign(obj, SqliteHash.FromDbValue(value));
continue;
}
// A value already of the property's type is assigned as is (BLOB -> byte[] among them).
if (property.PropertyType.IsInstanceOfType(value))
{
slot.Assign(obj, value);
continue;
}
var convertedValue = redb.Core.Utils.RedbDecimal.ChangeType(value, targetType, System.Globalization.CultureInfo.InvariantCulture);
slot.Assign(obj, convertedValue);
}
catch (Exception ex) when (ex is InvalidCastException or FormatException or OverflowException)
{
// SL-57: two silent catches left the property at its default - the row read as if the
// column were NULL.
throw new InvalidOperationException(
$"Column '{reader.GetName(i)}': the value '{value}' ({value.GetType().Name}) cannot be read as " +
$"{property.PropertyType.Name} ({typeof(T).Name}.{property.Name}).", ex);
}
}
}
return obj;
}
}
}
Path: redb/redb.SQLite/Data/SqliteRedbContext.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/SqliteRedbContext.cs
----
using System;
using Microsoft.Data.Sqlite;
using redb.Core.Data;
namespace redb.SQLite.Data
{
///
/// SQLite implementation of REDB context.
/// Assembles all Sqlite components into single facade.
///
public class SqliteRedbContext : RedbContextBase
{
private readonly SqliteRedbConnection _connection;
private readonly SqliteKeyGenerator _keyGenerator;
private readonly SqliteBulkOperations _bulkOperations;
///
/// Database connection.
///
public override IRedbConnection Db => _connection;
///
/// Key generator with caching.
///
public override IKeyGenerator Keys => _keyGenerator;
///
/// Bulk operations (COPY protocol).
///
protected override IBulkOperations BulkOperations => _bulkOperations;
///
protected override Task QueryRowsAsJsonCoreAsync(string sql, object[] parameters, System.Threading.CancellationToken cancellationToken)
=> _connection.QueryRowsAsJsonAsync(sql, parameters, cancellationToken);
///
/// Sqlite data source (for direct access if needed).
///
public SqliteDataSource DataSource { get; }
///
/// Create SQLite context from data source.
///
/// Sqlite data source (pooled connections).
public SqliteRedbContext(SqliteDataSource dataSource)
{
DataSource = dataSource;
_connection = new SqliteRedbConnection(dataSource);
var domain = redb.Core.Models.Configuration.RedbServiceConfiguration.ComputeCacheDomain(dataSource.ConnectionString);
_keyGenerator = new SqliteKeyGenerator(dataSource, domain,
ambientTransactionAccessor: () => _connection.TryGetAmbientTransaction());
_bulkOperations = new SqliteBulkOperations(_connection);
}
///
/// Create SQLite context from connection string.
///
/// SQLite connection string.
public SqliteRedbContext(string connectionString)
: this(SqliteDataSource.Create(connectionString))
{
}
///
/// Dispose context and all components.
///
public override async ValueTask DisposeAsync()
{
await _connection.DisposeAsync();
// DataSource is shared, don't dispose it here
}
}
}
Path: redb/redb.SQLite/Data/SqliteRedbTransaction.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/SqliteRedbTransaction.cs
----
using Microsoft.Data.Sqlite;
using redb.Core.Data;
using System;
using System.Threading.Tasks;
namespace redb.SQLite.Data
{
///
/// SQLite implementation of IRedbTransaction using Sqlite.
/// Connection-scoped: parent connection automatically uses this transaction.
///
public class SqliteRedbTransaction : IRedbTransaction
{
private readonly SqliteTransaction _transaction;
private readonly Action _onDispose;
private bool _completionReported;
// Reports the outcome once to the callbacks registered for this transaction (cache publication after commit).
private void Complete(bool committed)
{
if (_completionReported) return;
_completionReported = true;
redb.Core.Data.TransactionCompletion.Completed(this, committed);
}
private bool _disposed = false;
///
/// Transaction unique identifier.
///
public Guid TransactionId { get; } = Guid.NewGuid();
///
/// Whether transaction is still active.
///
public bool IsActive { get; private set; } = true;
///
/// Transaction start time.
///
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
///
/// Internal Sqlite transaction (for command assignment).
///
internal SqliteTransaction SqliteTransaction => _transaction;
///
/// Create new transaction wrapper.
///
/// Underlying Sqlite transaction.
/// Callback when transaction is disposed.
public SqliteRedbTransaction(SqliteTransaction transaction, Action onDispose)
{
_transaction = transaction ?? throw new ArgumentNullException(nameof(transaction));
_onDispose = onDispose ?? throw new ArgumentNullException(nameof(onDispose));
}
///
/// Commit all changes.
///
public async Task CommitAsync()
{
if (!IsActive)
throw new InvalidOperationException("Transaction is not active. Already committed or rolled back.");
try
{
await _transaction.CommitAsync();
}
catch (Exception ex)
{
// Commit failed: the underlying sqlite3 handle may still have autocommit=0.
// Speculatively rollback so the pooled SqliteConnection returns clean.
// Both errors are visible via [Diag-TX-LIFECYCLE] so the source is traceable.
// Console.WriteLine($"[Diag-TX-LIFECYCLE] CommitAsync FAILED: {ex.GetType().Name}: {ex.Message}. Attempting speculative rollback.");
Complete(committed: false);
try { await _transaction.RollbackAsync(); }
catch (Exception rbEx)
{
// Console.WriteLine($"[Diag-TX-LIFECYCLE] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty handle (mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire).");
}
IsActive = false;
_onDispose();
throw;
}
Complete(committed: true);
IsActive = false;
// Clear the connection's `_currentTransaction` slot now — any
// command issued between commit and dispose must NOT bind to this
// (now closed) SqliteTransaction. DisposeAsync is idempotent on
// _onDispose (the callback just nulls a field).
_onDispose();
}
///
/// Rollback all changes.
///
public async Task RollbackAsync()
{
if (!IsActive)
throw new InvalidOperationException("Transaction is not active. Already committed or rolled back.");
Complete(committed: false);
try
{
await _transaction.RollbackAsync();
}
catch (Exception ex)
{
// Console.WriteLine($"[Diag-TX-LIFECYCLE] RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Pool may receive a dirty handle (mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire).");
IsActive = false;
_onDispose();
throw;
}
IsActive = false;
_onDispose();
}
///
/// Dispose transaction.
/// If still active - rollback automatically.
///
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
_disposed = true;
Complete(committed: false);
// Auto-rollback if still active. The catch CANNOT throw (Dispose contract),
// so leaks here are mitigated by SqliteDataSource.EnsureCleanTransactionState
// which runs a speculative ROLLBACK on every pooled connection acquire.
if (IsActive)
{
try
{
await _transaction.RollbackAsync();
}
catch (Exception ex)
{
// Console.WriteLine($"[Diag-TX-LIFECYCLE] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. Pool poisoning mitigated by SqliteDataSource.EnsureCleanTransactionState on next acquire.");
}
IsActive = false;
}
// Disposing a broken transaction must never block the connection's cleanup callback:
// _onDispose() clears _currentTransaction on the connection so it can return to the pool.
// finally guarantees that even if _transaction.DisposeAsync() throws — and the exception
// is NOT swallowed, it propagates so the fault stays observable.
try
{
await _transaction.DisposeAsync();
}
finally
{
_onDispose();
}
}
}
}
Path: redb/redb.SQLite/Data/SqliteRegexFunctions.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/SqliteRegexFunctions.cs
----
using System.Text.RegularExpressions;
using Microsoft.Data.Sqlite;
namespace redb.SQLite.Data
{
///
/// Regular expressions for queries, on one connection. SQLite has none of its own - X REGEXP Y calls a user
/// function that nobody registers - so the query builder translates a LINQ Regex.IsMatch or
/// Regex.Replace to these functions, and the expression runs with the .NET semantics it has in memory.
///
///
/// NULL in, NULL out, like the built-ins: a NULL match is neither true nor false, so a row with a NULL value is not
/// selected by the predicate or by its negation. The match timeout is the process default of
/// (REGEX_DEFAULT_MATCH_TIMEOUT ), the same an in-memory match uses.
///
///
internal static class SqliteRegexFunctions
{
internal static void Install(SqliteConnection connection)
{
connection.CreateFunction(
"redb_regexp",
(input, pattern) => input is null || pattern is null
? (long?)null
: Regex.IsMatch(input, pattern) ? 1L : 0L,
isDeterministic: true);
connection.CreateFunction(
"redb_regexp_i",
(input, pattern) => input is null || pattern is null
? (long?)null
: Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) ? 1L : 0L,
isDeterministic: true);
connection.CreateFunction(
"redb_regexp_replace",
(input, pattern, replacement) => input is null || pattern is null || replacement is null
? null
: Regex.Replace(input, pattern, replacement),
isDeterministic: true);
}
}
}
Path: redb/redb.SQLite/Extensions/PropertyInfoExtensions.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/Extensions/PropertyInfoExtensions.cs
----
using System.Reflection;
using System.Text.Json.Serialization;
using redb.Core.Attributes;
namespace redb.SQLite.Extensions
{
///
/// Extensions for working with PropertyInfo
///
internal static class PropertyInfoExtensions
{
///
/// Checks if property should be ignored by REDB
///
/// Property to check
/// true if property should be ignored
public static bool ShouldIgnoreForRedb(this PropertyInfo property)
{
return //property.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Length > 0 ||
property.GetCustomAttributes(typeof(RedbIgnoreAttribute), false).Length > 0;
}
}
}
Path: redb/redb.SQLite/Extensions/RedbServiceExtensions.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/Extensions/RedbServiceExtensions.cs
----
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Models.Security;
using redb.SQLite.Providers;
using redb.Core.Providers;
using redb.Core.Serialization;
namespace redb.SQLite.Extensions
{
///
/// Extension methods for unified REDB registration following EF Core AddDbContext pattern
///
public static class RedbServiceExtensions
{
///
/// Registers REDB with configuration via lambda (main method).
/// Automatically registers all necessary providers and services.
///
/// Service collection
/// Delegate for configuration setup
/// Service collection for method chaining
///
/// services.AddRedb(options => {
/// options.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking;
/// options.EnablePropsCache = true;
/// options.PropsCacheMaxSize = 50000;
/// });
///
[Obsolete("Use services.AddRedb(o => o.UseSqlite(connectionString)) from redb.Core.Extensions")]
public static IServiceCollection AddRedbSqlite(
this IServiceCollection services,
Action? configure = null)
{
var config = new RedbServiceConfiguration();
configure?.Invoke(config); // Validation triggers in setters!
services.AddSingleton(config);
// Auto-register IRedbContext if ConnectionString is provided
if (!string.IsNullOrEmpty(config.ConnectionString))
{
// Factory registration: the container OWNS the data source it creates and
// disposes it on shutdown, releasing the connection pool (an instance
// registration is never disposed by MS DI - the pool would outlive the
// container and keep the database file locked).
services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences));
services.AddScoped(sp =>
new Data.SqliteRedbContext(sp.GetRequiredService()));
}
// Register SecurityContext (required for providers)
services.AddScoped(sp =>
AmbientSecurityContext.GetOrCreateDefault());
// Register ALL providers automatically
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// The user configuration service takes its statements from the dialect
services.AddSingleton();
// Register user configuration service
services.AddScoped();
services.AddScoped();
return services;
}
///
/// Registers REDB with configuration from appsettings.json
///
/// Service collection
/// Application configuration
/// Section name in appsettings.json (default "RedbService")
/// Service collection for method chaining
///
/// In appsettings.json:
/// "RedbService": { "EnablePropsCache": true, "PropsCacheMaxSize": 50000 }
/// services.AddRedb(Configuration);
///
[Obsolete("Use services.AddRedb(o => o.UseSqlite(connectionString)) from redb.Core.Extensions")]
public static IServiceCollection AddRedbSqliteFromConfig(
this IServiceCollection services,
IConfiguration configuration,
string sectionName = "RedbService")
{
var config = configuration.GetSection(sectionName).Get()
?? new RedbServiceConfiguration();
services.AddSingleton(config);
// Auto-register IRedbContext if ConnectionString is provided
if (!string.IsNullOrEmpty(config.ConnectionString))
{
// Factory registration: the container OWNS the data source it creates and
// disposes it on shutdown, releasing the connection pool (an instance
// registration is never disposed by MS DI - the pool would outlive the
// container and keep the database file locked).
services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences));
services.AddScoped(sp =>
new Data.SqliteRedbContext(sp.GetRequiredService()));
}
// Register SecurityContext (required for providers)
services.AddScoped(sp =>
AmbientSecurityContext.GetOrCreateDefault());
// Register providers
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// The user configuration service takes its statements from the dialect
services.AddSingleton();
// Register user configuration service
services.AddScoped();
services.AddScoped();
return services;
}
///
/// Registers REDB with ready configuration instance
///
/// Service collection
/// Ready configuration instance
/// Service collection for method chaining
///
/// var config = PredefinedConfigurations.Production;
/// services.AddRedb(config);
///
public static IServiceCollection AddRedb(
this IServiceCollection services,
RedbServiceConfiguration configuration)
{
services.AddSingleton(configuration);
// Auto-register IRedbContext if ConnectionString is provided
if (!string.IsNullOrEmpty(configuration.ConnectionString))
{
// Factory registration: the container OWNS the data source it creates and
// disposes it on shutdown, releasing the connection pool (an instance
// registration is never disposed by MS DI - the pool would outlive the
// container and keep the database file locked).
services.AddSingleton(_ => Data.SqliteDataSource.Create(configuration.ConnectionString, configuration.StringCollation != null, configuration.EnableLazyReferences));
services.AddScoped(sp =>
new Data.SqliteRedbContext(sp.GetRequiredService()));
}
// Register SecurityContext (required for providers)
services.AddScoped(sp =>
AmbientSecurityContext.GetOrCreateDefault());
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
return services;
}
}
}
Path: redb/redb.SQLite/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using redb.Core;
using redb.Core.Configuration;
using System;
using redb.Core.Models.Configuration;
namespace redb.SQLite.Extensions
{
///
/// Extension methods for registering RedbService in DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Register RedbService with default configuration.
///
[Obsolete("Use services.AddRedb() from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(this IServiceCollection services)
{
services.AddScoped();
services.AddScoped();
return services;
}
///
/// Register RedbService with configuration from IConfiguration.
///
[Obsolete("Use services.AddRedb(configuration) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(
this IServiceCollection services,
IConfiguration configuration,
string sectionName = "RedbService")
{
// Register configuration from appsettings.json
var config = configuration.GetSection(sectionName).Get()
?? new RedbServiceConfiguration();
services.AddSingleton(config);
services.AddScoped();
return services;
}
///
/// Register RedbService with programmatic configuration via Action.
///
[Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(
this IServiceCollection services,
Action configureOptions)
{
var config = new RedbServiceConfiguration();
configureOptions(config);
services.AddSingleton(config);
services.AddScoped();
return services;
}
///
/// Register RedbService with programmatic configuration via Builder.
///
[Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(
this IServiceCollection services,
Action configureBuilder)
{
var builder = new RedbServiceConfigurationBuilder();
configureBuilder(builder);
var config = builder.Build();
services.AddSingleton(config);
services.AddScoped();
return services;
}
///
/// Register RedbService with predefined profile.
///
[Obsolete("Use services.AddRedb(PredefinedConfigurations.GetByName(profile)) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(
this IServiceCollection services,
string profileName)
{
var config = profileName.ToLowerInvariant() switch
{
"development" => PredefinedConfigurations.Development,
"production" => PredefinedConfigurations.Production,
"highperformance" => PredefinedConfigurations.HighPerformance,
"bulkoperations" => PredefinedConfigurations.BulkOperations,
"debug" => PredefinedConfigurations.Debug,
"integrationtesting" => PredefinedConfigurations.IntegrationTesting,
"datamigration" => PredefinedConfigurations.DataMigration,
_ => throw new ArgumentException($"Unknown profile: {profileName}")
};
services.AddSingleton(config);
services.AddScoped();
return services;
}
///
/// Register RedbService with combined configuration (profile + additional settings).
///
[Obsolete("Use services.AddRedb(options => { ... }) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbService(
this IServiceCollection services,
string profileName,
Action additionalConfiguration)
{
var baseConfig = profileName.ToLowerInvariant() switch
{
"development" => PredefinedConfigurations.Development,
"production" => PredefinedConfigurations.Production,
"highperformance" => PredefinedConfigurations.HighPerformance,
"bulkoperations" => PredefinedConfigurations.BulkOperations,
"debug" => PredefinedConfigurations.Debug,
"integrationtesting" => PredefinedConfigurations.IntegrationTesting,
"datamigration" => PredefinedConfigurations.DataMigration,
_ => throw new ArgumentException($"Unknown profile: {profileName}")
};
var builder = new RedbServiceConfigurationBuilder(baseConfig);
additionalConfiguration(builder);
var finalConfig = builder.Build();
services.AddSingleton(finalConfig);
services.AddScoped();
return services;
}
///
/// Register RedbService with configuration validation.
///
[Obsolete("Use services.AddRedb(configuration) - validation now built into configuration properties")]
public static IServiceCollection AddValidatedRedbService(
this IServiceCollection services,
IConfiguration configuration,
bool throwOnValidationError = false,
string sectionName = "RedbService")
{
var config = configuration.GetSection(sectionName).Get()
?? new RedbServiceConfiguration();
// Validate configuration
var validator = new RedbServiceConfigurationValidator();
var validationResult = validator.Validate(null, config);
if (!validationResult.Succeeded && throwOnValidationError)
{
throw new InvalidOperationException($"Configuration validation failed: {validationResult.FailureMessage}");
}
services.AddSingleton(config);
services.AddScoped();
return services;
}
///
/// Register RedbService with configuration change monitoring (hot-reload).
///
[Obsolete("Use services.AddRedb(configuration) from redb.SQLite.Extensions.RedbServiceExtensions")]
public static IServiceCollection AddRedbServiceWithHotReload(
this IServiceCollection services,
IConfiguration configuration,
string sectionName = "RedbService")
{
// For hot-reload use IOptionsMonitor
services.Configure(configuration.GetSection(sectionName));
// Register change monitoring (if available)
// Configuration monitoring is deferred
// services.AddRedbServiceConfigurationMonitoring(configuration);
// Register RedbService with hot-reload support
services.AddScoped(provider =>
{
try
{
var configMonitor = provider.GetService>();
if (configMonitor != null)
{
// TODO: Implement hot-reload support in RedbService
var config = configMonitor.CurrentValue;
return new RedbService(provider);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Config monitor setup failed: {ex.Message}");
}
// Fallback to regular configuration
return new RedbService(provider);
});
return services;
}
}
}
Path: redb/redb.SQLite/Extensions/SqliteOptionsExtensions.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/Extensions/SqliteOptionsExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using redb.Core;
using redb.Core.Data;
using redb.Core.Extensions;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Models.Security;
using redb.Core.Providers;
using redb.Core.Query;
using redb.Core.Serialization;
using redb.Core.Services;
using redb.SQLite.Data;
using redb.SQLite.Providers;
using redb.SQLite.Sql;
namespace redb.SQLite.Extensions;
///
/// SQLite provider extensions for RedbOptionsBuilder.
///
public static class SqliteOptionsExtensions
{
///
/// Configures REDB to use SQLite as the database provider.
/// For Pro version, use AddRedbPro() from redb.SQLite.Pro package.
///
/// The options builder.
/// SQLite connection string. If null, must be set in Configure().
/// The options builder for chaining.
///
/// services.AddRedb(options => options
/// .UseSqlite("Host=localhost;Database=mydb;Username=user;Password=pass")
/// .Configure(c => c.EnablePropsCache = true));
///
public static RedbOptionsBuilder UseSqlite(
this RedbOptionsBuilder builder,
string? connectionString = null)
{
var infrastructure = (IRedbOptionsBuilderInfrastructure)builder;
if (!string.IsNullOrEmpty(connectionString))
infrastructure.Configuration.ConnectionString = connectionString;
infrastructure.SetProviderRegistration((services, config, isPro) =>
{
if (isPro)
throw new InvalidOperationException(
"Pro version requires redb.SQLite.Pro package. Use AddRedbPro() from redb.SQLite.Pro.Extensions.");
RegisterOpenSourceServices(services, config);
});
return builder;
}
///
/// Registers OpenSource SQLite services.
/// Called by UseSqlite() and can be used by Pro version as fallback.
///
public static void RegisterOpenSourceServices(IServiceCollection services, RedbServiceConfiguration config)
{
// Free tier loads the native SQLite extension that hosts the server-side SQL
// functions (get_object_json, pvt_build_*_sql, ...). Honour an explicit override
// (REDB_SQLITE_EXTENSION env / manual NativeExtensionPath) first; otherwise
// auto-locate the binary shipped in this package next to the running app.
// Pro locates it too: it reads objects in C#, but the JSON of an object is get_object_json.
Data.SqliteDataSource.NativeExtensionPath ??= Data.SqliteDataSource.LocatePackagedExtension();
// DataSource and Context
if (!string.IsNullOrEmpty(config.ConnectionString))
{
// Factory registration: the container OWNS the data source it creates and disposes it
// on shutdown, releasing the connection pool (an instance registration is never
// disposed by MS DI - the pool would outlive the container and keep the file locked).
services.AddSingleton(_ => Data.SqliteDataSource.Create(config.ConnectionString, config.StringCollation != null, config.EnableLazyReferences));
services.AddScoped(sp =>
new SqliteRedbContext(sp.GetRequiredService()));
}
// Security
services.AddScoped(sp =>
AmbientSecurityContext.GetOrCreateDefault());
// SQL Dialect
services.AddSingleton();
// Core providers
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// Query providers
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped(sp => sp.GetRequiredService().ListProvider); // one per scope: the service's own
services.AddScoped();
// Background deletion service (singleton + hosted service)
services.AddSingleton();
services.AddSingleton(sp => sp.GetRequiredService());
services.AddHostedService(sp => sp.GetRequiredService());
// Main service
services.AddScoped();
}
}
Path: redb/redb.SQLite/Providers/LazyPropsLoader.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/Providers/LazyPropsLoader.cs
----
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using redb.Core.Caching;
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Exceptions;
using redb.Core.Models.Configuration;
using redb.Core.Providers;
using redb.Core.Query;
using redb.Core.Serialization;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers
{
///
/// OpenSource implementation of lazy Props loading for SQLite.
/// Uses get_object_json SQL function for simple and efficient loading.
/// Pro version uses PropsMaterializer with PVT optimizations.
///
public class LazyPropsLoader : ILazyPropsLoader
{
// get_object_json depth the batch uses when the caller names none (query pages, tree loads).
private const int DefaultBatchDepth = 10;
private readonly ConcurrentDictionary _loadingInProgress = new();
private readonly IRedbContext _context;
private readonly IRedbObjectSerializer _serializer;
private readonly RedbServiceConfiguration _config;
private readonly ISqlDialect _sql;
private readonly GlobalPropsCache _propsCache;
///
public string? CacheDomain => _propsCache.Domain;
///
public redb.Core.Data.IRedbContext? ScopeContext => _context;
private readonly ILogger? _logger;
public LazyPropsLoader(
IRedbContext context,
ISchemeSyncProvider schemeSync,
IRedbObjectSerializer serializer,
RedbServiceConfiguration config,
IListProvider? listProvider = null,
ILogger? logger = null)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_config = config ?? throw new ArgumentNullException(nameof(config));
_propsCache = schemeSync?.PropsCache ?? throw new ArgumentNullException(nameof(schemeSync));
_sql = new Sql.SqliteDialect();
_logger = logger;
}
///
/// Synchronous Props loading (for getter).
///
public TProps? LoadProps(long objectId, long schemeId) where TProps : class, new()
{
if (_config.LazyReferenceAccess == LazyReferenceAccessMode.Throw)
throw new RedbSynchronousLazyLoadException(objectId, schemeId);
// Blocking by design (the getter is synchronous), but never on the caller's context: the load
// runs on the thread pool, so a host with a SynchronizationContext (Blazor Server, WPF, MAUI)
// waits instead of deadlocking on its own continuations (review). The caller blocks meanwhile,
// so the context stays single-threaded; ExecutionContext (the AsyncLocal scope) flows in.
return Task.Run(() => LoadPropsAsync(objectId, schemeId)).GetAwaiter().GetResult();
}
///
/// Async Props loading for single object via get_object_json.
/// Simple and efficient for OpenSource version.
///
public async Task LoadPropsAsync(long objectId, long schemeId, CancellationToken cancellationToken = default) where TProps : class, new()
{
if (_context.IsDisposed)
throw new RedbLazyLoadScopeEndedException(objectId, schemeId);
// 1. Check cache first
if (_config.EnablePropsCache && _propsCache.Instance != null)
{
var hashes = await _context.QueryScalarListAsync(
_sql.LazyLoader_SelectObjectHash(), new object[] { objectId }, cancellationToken);
if (hashes.Count > 0)
{
var hash = hashes[0];
var cached = _propsCache.Get(objectId, hash);
if (cached != null)
{
var propsFromCache = cached.GetPropsDirectly();
if (propsFromCache != null)
return propsFromCache;
}
}
}
// 2. Load via get_object_json — ONE query, simple!
var jsonResults = await _context.QueryScalarListAsync(
_sql.LazyLoader_GetObjectJson(), new object[] { objectId, 1 }, cancellationToken); // V4 (L.3): the reloaded object's own references are stubs again (L.3): the reloaded object's own references are stubs again
var json = jsonResults.FirstOrDefault();
if (string.IsNullOrEmpty(json))
return null; // V4 (L.3): a reference whose target left for the trash reloads as null Props, not an exception
// 3. Deserialize
var obj = _serializer.Deserialize(json);
redb.Core.Utils.LazyReferenceInstaller.Install(obj, this); // V4 (L.3): nested stubs get their loader
// 4. Cache the result
if (_config.EnablePropsCache && obj.hash.HasValue)
{
redb.Core.Caching.CachePublication.AfterCommit(_context, () => _propsCache.Set(obj));
}
// Raw access instead of the getter: for an object with properties:null (values wiped by a
// race, or a bare object) Install has attached the loader to the root itself, so the Props
// getter would start a new load - endless recursion eating a pool thread per turn.
return obj.GetPropsDirectly();
}
///
/// BULK Props loading for multiple objects via get_object_json batch.
/// Uses unnest for efficient batch loading.
///
public async Task LoadPropsForManyAsync(List> objects, int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new()
{
var depth = propsDepth ?? DefaultBatchDepth;
if (objects.Count == 0) return;
var requested = objects;
// Protection from infinite recursion
var uniqueIds = objects.Select(o => o.id).Distinct().ToList();
var alreadyLoading = uniqueIds.Where(id => _loadingInProgress.ContainsKey(id)).ToList();
if (alreadyLoading.Any())
{
objects = objects.Where(o => !alreadyLoading.Contains(o.id)).ToList();
uniqueIds = uniqueIds.Except(alreadyLoading).ToList();
if (objects.Count == 0) return;
}
foreach (var id in uniqueIds)
_loadingInProgress.TryAdd(id, 0);
try
{
HashSet needToLoad;
Dictionary> fromCache;
// 1. Check cache
if (_config.EnablePropsCache && _propsCache.Instance != null)
{
var objectsData = objects
.Where(o => o.hash.HasValue)
.Select(o => (o.id, o.hash!.Value))
.ToList();
needToLoad = _propsCache.FilterNeedToLoad(objectsData, out fromCache);
// An object without a hash cannot be matched by the cache: it loads from the database, never dropped.
foreach (var obj in objects)
if (!obj.hash.HasValue)
needToLoad.Add(obj.id);
foreach (var obj in objects)
{
if (fromCache.TryGetValue(obj.id, out var cachedObj))
{
obj.Props = cachedObj.Props;
obj._propsLoaded = true;
obj._lazyLoader = null;
}
}
}
else
{
needToLoad = objects.Select(o => o.id).ToHashSet();
fromCache = new Dictionary>();
}
// 2. Load from DB via get_object_json batch
if (needToLoad.Count > 0)
{
var idsToLoad = needToLoad.ToArray();
// Batch query via unnest + get_object_json
var results = await _context.QueryAsync(
_sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsToLoad, depth }, cancellationToken);
var jsonById = results.ToDictionary(r => r.Id, r => r.JsonData);
foreach (var obj in objects.Where(o => needToLoad.Contains(o.id)))
{
if (jsonById.TryGetValue(obj.id, out var json) && !string.IsNullOrEmpty(json))
{
try
{
var loaded = _serializer.Deserialize(json);
// Copy Props from loaded object
obj.Props = loaded.Props;
obj._propsLoaded = true;
obj._lazyLoader = null;
redb.Core.Utils.LazyReferenceInstaller.Install(obj, this); // V4 (L.3)
// Cache
if (_config.EnablePropsCache && obj.hash.HasValue)
{
redb.Core.Caching.CachePublication.AfterCommit(_context, () => _propsCache.Set(obj));
}
}
catch (Exception)
{
// Skip failed deserialization, leave Props as default
}
}
}
// get_object_json is null only for an object that is gone: deleted after the query found it. It
// leaves the list instead of being handed out without Props; the page is shorter by it.
requested.RemoveAll(o => needToLoad.Contains(o.id) && !(jsonById.TryGetValue(o.id, out var j) && !string.IsNullOrEmpty(j)));
}
}
finally
{
foreach (var id in uniqueIds)
_loadingInProgress.TryRemove(id, out _);
}
}
///
/// BULK Props loading with projection filter (for Select projections).
/// In OpenSource version, projection is ignored — full objects loaded via get_object_json.
///
public Task LoadPropsForManyAsync(
List> objects,
HashSet? projectedStructureIds, CancellationToken cancellationToken = default) where TProps : class, new()
{
// OpenSource: ignore projection, load full objects
return LoadPropsForManyAsync(objects, propsDepth: null);
}
///
/// BULK Props loading at the default batch depth; the depth form above is the core.
/// A stub reload passes 1 (transitive laziness), query pages their PropsDepth.
///
public Task LoadPropsForManyAsync(List> objects, CancellationToken cancellationToken = default) where TProps : class, new()
=> LoadPropsForManyAsync(objects, propsDepth: null);
///
/// BULK Props loading with projection filter and custom depth.
/// In OpenSource version the projection is ignored (full objects); the depth is honoured.
///
public Task LoadPropsForManyAsync(
List> objects,
HashSet? projectedStructureIds,
int? propsDepth, CancellationToken cancellationToken = default) where TProps : class, new()
{
// OpenSource: ignore projection; the depth is honoured
return LoadPropsForManyAsync(objects, propsDepth);
}
///
/// BULK loading for polymorphic objects (different schemes).
/// Each object is deserialized to its own type based on scheme_id.
///
public async Task LoadPropsForManyPolymorphicAsync(List objects, CancellationToken cancellationToken = default)
{
if (objects.Count == 0) return;
var uniqueIds = objects.Select(o => o.Id).Distinct().ToList();
var alreadyLoading = uniqueIds.Where(id => _loadingInProgress.ContainsKey(id)).ToList();
if (alreadyLoading.Any())
{
objects = objects.Where(o => !alreadyLoading.Contains(o.Id)).ToList();
uniqueIds = uniqueIds.Except(alreadyLoading).ToList();
if (objects.Count == 0) return;
}
foreach (var id in uniqueIds)
_loadingInProgress.TryAdd(id, 0);
try
{
var idsToLoad = uniqueIds.ToArray();
var depth = DefaultBatchDepth;
// Batch query
var results = await _context.QueryAsync(
_sql.LazyLoader_GetObjectJsonBatch(), new object[] { idsToLoad, depth }, cancellationToken);
var jsonById = results.ToDictionary(r => r.Id, r => r.JsonData);
foreach (var obj in objects)
{
if (jsonById.TryGetValue(obj.Id, out var json) && !string.IsNullOrEmpty(json))
{
try
{
// Get Props type from object's generic parameter (the type or its RedbObject base)
var objType = obj.GetType();
var genericObjType = redb.Core.Utils.RedbObjectTypes.GenericOf(objType);
if (genericObjType != null)
{
var propsType = genericObjType.GetGenericArguments()[0];
var loaded = _serializer.DeserializeDynamic(json, propsType);
// Copy Props via reflection
var propsProperty = objType.GetProperty("Props");
var loadedProps = loaded.GetType().GetProperty("Props")?.GetValue(loaded);
propsProperty?.SetValue(obj, loadedProps);
// Mark as loaded
var loadedField = objType.GetField("_propsLoaded");
loadedField?.SetValue(obj, true);
var loaderField = objType.GetField("_lazyLoader");
loaderField?.SetValue(obj, null);
}
}
catch (Exception)
{
// Skip failed deserialization
}
}
}
}
finally
{
foreach (var id in uniqueIds)
_loadingInProgress.TryRemove(id, out _);
}
}
}
///
/// DTO for batch get_object_json results.
///
internal class ObjectJsonResult
{
public long Id { get; set; }
public string JsonData { get; set; } = string.Empty;
}
}
Path: redb/redb.SQLite/Providers/SqliteListProvider.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/Providers/SqliteListProvider.cs
----
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Providers;
using redb.Core.Providers.Base;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers
{
///
/// SQLite implementation of IListProvider.
/// Inherits all logic from ListProviderBase, provides SQLite-specific SQL via SqliteDialect.
///
public class SqliteListProvider : ListProviderBase
{
///
/// Creates SQLite list provider with default SqliteDialect.
///
/// Database context for executing queries
/// Service configuration
/// Scheme sync provider (for accessing domain-bound caches)
/// Optional logger for diagnostics
public SqliteListProvider(
IRedbContext context,
RedbServiceConfiguration configuration,
ISchemeSyncProvider schemeSync,
ILogger? logger = null)
: base(context, configuration, new SqliteDialect(), schemeSync, logger)
{
}
}
}
Path: redb/redb.SQLite/Providers/SqliteMaintenanceProvider.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/Providers/SqliteMaintenanceProvider.cs
----
using redb.Core.Data;
using redb.Core.Providers.Base;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers
{
///
/// SQLite maintenance provider. All logic lives in the base; this class only wires the
/// dialect in (same shape as SqliteValidationProvider).
///
public class SqliteMaintenanceProvider : MaintenanceProviderBase
{
public SqliteMaintenanceProvider(IRedbContext context, int analysisLimit, ILogger? logger = null)
: base(context, new SqliteDialect(), analysisLimit, logger)
{
}
}
}
Path: redb/redb.SQLite/Providers/SqliteObjectStorageProvider.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/Providers/SqliteObjectStorageProvider.cs
----
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Providers;
using redb.Core.Providers.Base;
using redb.Core.Query;
using redb.Core.Serialization;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers
{
///
/// SQLite implementation of ObjectStorageProvider.
/// Inherits all business logic from ObjectStorageProviderBase, provides SQLite-specific LazyPropsLoader.
///
public class SqliteObjectStorageProvider : ObjectStorageProviderBase
{
///
/// Creates a new SqliteObjectStorageProvider instance.
///
public SqliteObjectStorageProvider(
IRedbContext context,
IRedbObjectSerializer serializer,
IPermissionProvider permissionProvider,
IRedbSecurityContext securityContext,
ISchemeSyncProvider schemeSync,
RedbServiceConfiguration configuration,
IListProvider? listProvider = null,
ILogger? logger = null,
redb.Core.Interception.RedbSaveInterceptorPipeline? saveInterceptors = null)
: base(context, serializer, permissionProvider, securityContext,
schemeSync, configuration, new SqliteDialect(), listProvider, logger, saveInterceptors)
{
}
///
/// Creates SQLite-specific LazyPropsLoader for lazy property loading.
///
protected override ILazyPropsLoader CreateLazyPropsLoader()
{
return new LazyPropsLoader(Context, SchemeSyncProvider, Serializer, Configuration, ListProvider, Logger);
}
}
}
Path: redb/redb.SQLite/Providers/SqlitePermissionProvider.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/Providers/SqlitePermissionProvider.cs
----
using redb.Core.Data;
using redb.Core.Models.Contracts;
using redb.Core.Providers.Base;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers;
///
/// SQLite implementation of permission provider.
/// Inherits all business logic from PermissionProviderBase.
/// Only provides SQLite-specific SQL dialect.
///
/// IMPORTANT: Uses SQLite function get_user_permissions_for_object()
/// for efficient recursive permission calculation.
///
/// Usage:
/// services.AddScoped<IPermissionProvider, SqlitePermissionProvider>();
///
public class SqlitePermissionProvider : PermissionProviderBase
{
///
/// Creates a new SQLite permission provider.
///
/// Database context for executing queries
/// Security context for authorization
/// Optional logger for diagnostics
public SqlitePermissionProvider(
IRedbContext context,
IRedbSecurityContext securityContext,
ILogger? logger = null)
: base(context, securityContext, new SqliteDialect(), logger)
{
}
// All business logic is inherited from PermissionProviderBase.
// SQLite-specific SQL is provided by SqliteDialect.
// The critical method Permissions_GetEffectiveForObject() uses
// SQLite function get_user_permissions_for_object() for efficient
// recursive permission calculation with inheritance.
}
Path: redb/redb.SQLite/Providers/SqliteQueryableProvider.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/Providers/SqliteQueryableProvider.cs
----
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Models.Contracts;
using redb.Core.Models.Security;
using redb.Core.Providers;
using redb.Core.Providers.Base;
using redb.Core.Query;
using redb.Core.Query.Base;
using redb.Core.Query.QueryExpressions;
using redb.Core.Serialization;
using redb.SQLite.Query;
using redb.Core.Query.Parsing;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
namespace redb.SQLite.Providers
{
///
/// SQLite implementation of IQueryableProvider.
/// Inherits all logic from QueryableProviderBase, provides SQLite-specific query providers.
///
public class SqliteQueryableProvider : QueryableProviderBase
{
public SqliteQueryableProvider(
IRedbContext context,
IRedbObjectSerializer serializer,
ISchemeSyncProvider schemeSync,
IRedbSecurityContext securityContext,
ILazyPropsLoader? lazyPropsLoader = null,
RedbServiceConfiguration? configuration = null,
string? cacheDomain = null,
ILogger? logger = null)
: base(context, serializer, schemeSync, securityContext, lazyPropsLoader, configuration, cacheDomain, logger)
{
}
protected override IRedbQueryable CreateQuery(long schemeId, long? userId, bool checkPermissions)
{
var queryProvider = new SqliteQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, SchemeSync);
return queryProvider.CreateQuery(schemeId, userId, checkPermissions);
}
protected override IRedbQueryable CreateTreeQuery(
long schemeId, long? userId, bool checkPermissions, long? rootObjectId, int? maxDepth)
{
var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync);
return treeQueryProvider.CreateTreeQuery(schemeId, userId, checkPermissions, rootObjectId, maxDepth);
}
protected override IRedbQueryable CreateEmptyTreeQuery(long schemeId, long? userId, bool checkPermissions)
{
var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync);
var emptyTreeQuery = treeQueryProvider.CreateTreeQuery(schemeId, userId, checkPermissions);
return emptyTreeQuery.Where(x => false);
}
protected override IRedbQueryable CreateMultiRootTreeQuery(
long schemeId, long? userId, bool checkPermissions, List rootObjects, int? maxDepth)
{
var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync);
var parentIds = rootObjects.Select(obj => obj.Id).ToArray();
var multiRootContext = new TreeQueryContext(schemeId, userId, checkPermissions, null, maxDepth)
{
ParentIds = parentIds
};
var filterParser = new FilterExpressionParser();
var orderingParser = new OrderingExpressionParser();
return new SqliteTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser);
}
protected override IRedbQueryable CreateMultiRootTreeQueryByIds(
long schemeId, long? userId, bool checkPermissions, IEnumerable rootObjectIds, int? maxDepth)
{
var treeQueryProvider = new SqliteTreeQueryProvider(Context, Serializer, LazyPropsLoader, Configuration, Logger, cacheDomain: CacheDomain, schemeSync: SchemeSync);
var parentIds = rootObjectIds.ToArray();
var multiRootContext = new TreeQueryContext(schemeId, userId, checkPermissions, null, maxDepth)
{
ParentIds = parentIds
};
var filterParser = new FilterExpressionParser();
var orderingParser = new OrderingExpressionParser();
return new SqliteTreeQueryable(treeQueryProvider, multiRootContext, filterParser, orderingParser);
}
}
}
Path: redb/redb.SQLite/Providers/SqliteRoleProvider.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/Providers/SqliteRoleProvider.cs
----
using redb.Core.Data;
using redb.Core.Models.Contracts;
using redb.Core.Providers.Base;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers;
///
/// SQLite implementation of role provider.
/// Inherits all business logic from RoleProviderBase.
/// Only provides SQLite-specific SQL dialect.
///
/// Usage:
/// services.AddScoped<IRoleProvider, SqliteRoleProvider>();
///
public class SqliteRoleProvider : RoleProviderBase
{
///
/// Creates a new SQLite role provider.
///
/// Database context for executing queries
/// Security context for authorization
/// Optional logger for diagnostics
public SqliteRoleProvider(
IRedbContext context,
IRedbSecurityContext securityContext,
ILogger? logger = null)
: base(context, securityContext, new SqliteDialect(), logger)
{
}
// All business logic is inherited from RoleProviderBase.
// SQLite-specific SQL is provided by SqliteDialect.
// Override virtual methods here for SQLite-specific optimizations if needed.
// For example, using RETURNING clause for insert operations.
}
Path: redb/redb.SQLite/Providers/SqliteSchemeSyncProvider.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/Providers/SqliteSchemeSyncProvider.cs
----
using System.Text.Json;
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Providers;
using redb.Core.Providers.Base;
using redb.SQLite.Sql;
using Microsoft.Extensions.Logging;
namespace redb.SQLite.Providers;
///
/// SQLite implementation of scheme synchronization provider.
/// Inherits all logic from SchemeSyncProviderBase, provides SQLite-specific SQL via SqliteDialect.
///
public class SqliteSchemeSyncProvider : SchemeSyncProviderBase
{
///
/// Creates SQLite scheme sync provider with default SqliteDialect.
///
public SqliteSchemeSyncProvider(
IRedbContext context,
RedbServiceConfiguration? configuration = null,
string? cacheDomain = null,
ILogger? logger = null)
: base(context, new SqliteDialect(), configuration, cacheDomain, logger)
{
}
///
/// Gets structure tree as JsonElement (for API compatibility).
///
public new async Task GetStructureTreeJsonAsync(long schemeId)
{
var result = await base.GetStructureTreeJsonAsync(schemeId);
if (string.IsNullOrEmpty(result))
return JsonSerializer.SerializeToElement("[]");
return JsonSerializer.SerializeToElement(result);
}
///
/// SQLite type migration for an existing structure whose property type changed. The Postgres/MSSQL
/// path runs a stored function (migrate_structure_type ); SQLite has no stored functions, so the
/// equivalent runs here as plain SQL. Fixes GitHub #5, where the base path emitted
/// SELECT * FROM migrate_structure_type(...) and failed with
/// no such table: migrate_structure_type , so InitializeAsync never came up.
///
public override async Task MigrateStructureTypeAsync(
long structureId, string oldTypeName, string newTypeName, bool dryRun = false, CancellationToken cancellationToken = default)
{
var source = GetValueColumn(oldTypeName);
var target = GetValueColumn(newTypeName);
// No scalar value-column mapping on one side (e.g. a nested Class property): there is nothing to
// move in _values here; let the caller update _id_type. Mirrors the PG function returning a benign
// result rather than throwing.
if (source == null || target == null)
return new TypeMigrationResult { Errors = $"No value-column mapping for '{oldTypeName}' -> '{newTypeName}'" };
// Same storage column (Int -> Long both _Long; DateTime -> DateOnly both _DateTimeOffset;
// String -> MimeType both _String): values already sit in the right column, only _id_type changes.
if (string.Equals(source, target, StringComparison.OrdinalIgnoreCase))
return new TypeMigrationResult();
// Rows that actually hold a value under the old column for this structure.
var affected = (int)(await Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM _values WHERE _id_structure = $1 AND {source} IS NOT NULL", new object[] { structureId }, cancellationToken) ?? 0);
if (affected == 0 || dryRun)
return new TypeMigrationResult { AffectedRows = affected };
// There IS data to move across storage columns. Which of those moves is safe is decided by an
// explicit matrix, mirroring the pairs PostgreSQL's migrate_structure_type() supports. A blanket
// refusal used to stand here; it was written when the alternative was a cryptic "no such table"
// (GitHub #5) and it swept up conversions that are trivially safe — Boolean and Long are both
// INTEGER columns, so bool -> int is a plain copy.
var conversion = BuildConversion(source, target);
if (conversion == null)
{
// Reported as a result rather than thrown, which is how PostgreSQL and MSSQL report the same
// refusal. The scheme-sync path turns any failing result into RedbTypeMigrationException, so
// the caller that matters still gets an exception — the same one on all three providers.
return new TypeMigrationResult
{
AffectedRows = affected,
SuccessCount = 0,
ErrorCount = affected,
Errors =
$"SQLite: cannot auto-migrate structure {structureId} from '{oldTypeName}' to '{newTypeName}' — " +
$"{affected} value(s) live in column {source} and moving them to {target} is not a safe automatic " +
$"conversion. Remove and re-add the property (dropping its values), or migrate the data manually " +
$"before changing the type."
};
}
// Rows the conversion can actually take. For text sources this is narrower than `affected`:
// an unparseable string must stay where it is rather than become CAST's silent 0.
var convertible = (int)(await Context.ExecuteScalarAsync(
$"SELECT CAST(COUNT(*) AS BIGINT) FROM _values WHERE _id_structure = $1 " +
$"AND {source} IS NOT NULL AND {conversion.Guard}", new object[] { structureId }, cancellationToken) ?? 0);
await Context.ExecuteAsync(
$"UPDATE _values SET {target} = {conversion.Expression}, {source} = NULL, _unique = NULL " +
$"WHERE _id_structure = $1 AND {source} IS NOT NULL AND {conversion.Guard}", new object[] { structureId }, cancellationToken);
return new TypeMigrationResult
{
AffectedRows = affected,
SuccessCount = convertible,
ErrorCount = affected - convertible,
Errors = convertible == affected
? null
: $"SQLite: {affected - convertible} of {affected} value(s) in {source} could not be read as " +
$"'{newTypeName}' and were left in place; {convertible} were moved to {target}."
};
}
/// A conversion: the value expression for the target column, and the rows it applies to.
private sealed record Conversion(string Expression, string Guard);
///
/// Cross-column conversions SQLite performs, keyed by storage column pair. Mirrors the matrix in
/// PostgreSQL's migrate_structure_type() so a type change behaves the same on every provider.
///
///
///