Path: redb/redb.Postgres/Data/NpgsqlRedbTransaction.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.Postgres/Data/NpgsqlRedbTransaction.cs
----
using Npgsql;
using redb.Core.Data;
using System;
using System.Threading.Tasks;
namespace redb.Postgres.Data
{
///
/// PostgreSQL implementation of IRedbTransaction using Npgsql.
/// Connection-scoped: parent connection automatically uses this transaction.
///
public class NpgsqlRedbTransaction : IRedbTransaction
{
private readonly NpgsqlTransaction _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 Npgsql transaction (for command assignment).
///
internal NpgsqlTransaction NpgsqlTransaction => _transaction;
///
/// Create new transaction wrapper.
///
/// Underlying Npgsql transaction.
/// Callback when transaction is disposed.
public NpgsqlRedbTransaction(NpgsqlTransaction 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: Npgsql's NpgsqlConnection still holds a reference to
// _transaction. Npgsql's pool reset (DISCARD ALL on acquire) usually
// hides leaks of this shape, but the semantics should not depend on
// pool-driver tolerance — speculatively rollback so the connection
// returns clean, then re-throw so the caller still sees the original
// exception. Both attempts are logged via [Diag-TX-LIFECYCLE-PG] so a
// failure shape never goes silent.
// Console.WriteLine($"[Diag-TX-LIFECYCLE-PG] 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-PG] Speculative rollback after failed commit ALSO FAILED: {rbEx.GetType().Name}: {rbEx.Message}. Pool may receive a dirty NpgsqlConnection (Npgsql's DISCARD ALL on next acquire is the only remaining mitigation).");
}
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 (Npgsql 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);
try
{
await _transaction.RollbackAsync();
}
catch (ObjectDisposedException)
{
// The connector broke mid-command (e.g. a COPY torn down by a cancellation token)
// and Npgsql disposed the transaction with it - the server has already rolled the
// transaction back on disconnect. Treat the rollback as done: rethrowing here would
// mask the original failure (the OCE) with a secondary ObjectDisposedException.
IsActive = false;
_onDispose();
}
catch (Exception ex)
{
// Console.WriteLine( RollbackAsync FAILED: {ex.GetType().Name}: {ex.Message}. Npgsql's DISCARD ALL on next pool acquire is the only mitigation if the underlying state is dirty.");
IsActive = false;
_onDispose();
throw;
}
IsActive = false;
_onDispose();
}
///
/// Dispose transaction.
/// If still active - rollback automatically. The catch CANNOT throw (Dispose contract),
/// so a leaked NpgsqlConnection (autocommit=off at the driver layer) is mitigated by
/// Npgsql's built-in DISCARD ALL on next pool acquire.
///
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
_disposed = true;
Complete(committed: false);
// Auto-rollback if still active
if (IsActive)
{
try
{
await _transaction.RollbackAsync();
}
catch (Exception ex)
{
// Console.WriteLine($"[Diag-TX-LIFECYCLE-PG] DisposeAsync auto-rollback FAILED: {ex.GetType().Name}: {ex.Message}. Pool poisoning mitigated by Npgsql's DISCARD ALL 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();
}
}
}
}