Path: redb/redb.MSSql/Data/SqlRedbTransaction.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.MSSql/Data/SqlRedbTransaction.cs ---- using Microsoft.Data.SqlClient; using redb.Core.Data; namespace redb.MSSql.Data; /// /// MS SQL Server implementation of IRedbTransaction using SqlTransaction. /// Connection-scoped: parent connection automatically uses this transaction. /// public class SqlRedbTransaction : IRedbTransaction { private readonly SqlTransaction _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; /// /// 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 SqlTransaction (for command assignment). /// internal SqlTransaction SqlTransaction => _transaction; /// /// The server ended the transaction while we still hold it open: SqlClient zombies a transaction the server rolled /// back (command timeout, deadlock victim 1205, an error that dooms it, a broken connection) and its /// then reads null. Read only while /// is true; after our own Commit or Rollback the driver reads the same, and decides. /// private bool EndedByServer => _transaction.Connection is null; /// /// Create new transaction wrapper. /// /// Underlying SqlTransaction. /// Callback when transaction is disposed. public SqlRedbTransaction(SqlTransaction 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: SqlConnection._currentTransaction may still be set. // Try speculative rollback so the connection returns to the pool clean; // otherwise the next caller's BeginTransaction fails with // "SqlConnection does not support parallel transactions". // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] 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-MSSQL] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty SqlConnection (next BeginTransaction will throw 'parallel transactions')."); } IsActive = false; _onDispose(); throw; } Complete(committed: true); IsActive = false; // Clear the connection's `_currentTransaction` slot now so commands // issued between commit and dispose run against the autocommit // connection (Microsoft.Data.SqlClient is more tolerant of // cmd.Transaction=closedTx than Microsoft.Data.Sqlite, but the // semantics should not depend on driver tolerance). _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); if (EndedByServer) { // The server already rolled the transaction back (timeout, deadlock victim, dooming error): the rollback // asked for has happened. Our own Commit or Rollback clears IsActive first, so a misuse still throws above. IsActive = false; _onDispose(); return; } try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Pool may receive a dirty SqlConnection (next BeginTransaction will throw 'parallel transactions')."); IsActive = false; _onDispose(); throw; } IsActive = false; _onDispose(); } /// /// Dispose transaction. /// If still active - rollback automatically. The catch CANNOT throw (Dispose contract); a /// connection that reaches the pool with its transaction still open is rolled back by the /// SqlClient pool itself, which resets the session before handing the connection out again. /// public async ValueTask DisposeAsync() { if (_disposed) return; _disposed = true; Complete(committed: false); // Auto-rollback if still active; nothing to roll back when the server has ended the transaction already if (IsActive && EndedByServer) { IsActive = false; } else if (IsActive) { try { await _transaction.RollbackAsync(); } catch (Exception ex) { // Console.WriteLine($"[Diag-TX-LIFECYCLE-MSSQL] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. The SqlClient pool rolls the session back before its next hand-out."); } 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(); } } }