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; } } }