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