Path: redb/redb.Tests.Integration/Tests/Base/ConnectionLeaseTestsBase.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.Tests.Integration/Tests/Base/ConnectionLeaseTestsBase.cs
----
using System.Data.Common;
using System.Transactions;
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Data;
using redb.Tests.Integration.Helpers;
using redb.Tests.Integration.Models;
namespace redb.Tests.Integration.Tests.Base;
///
/// : the caller's own command on the connection redb works on, in the
/// transaction redb's commands run in. A Route .Transacted() block with a SQL step and a redb save into the same
/// database must hold ONE connection: a second one makes the transaction distributed (SQL Server refuses or promotes,
/// PostgreSQL needs prepared transactions) or, on SQLite, waits for the write lock the scope's connection holds.
/// Verification always goes through a fresh DI scope outside any transaction.
///
public abstract class ConnectionLeaseTestsBase : IAsyncLifetime
{
private const string NamePrefix = "conn-lease-";
private readonly IServiceProvider _services;
// Free and Pro collections of one provider share a database and may run at the same time: every test
// removes only the tags it created, never a whole prefix.
private readonly List _tags = new();
protected ConnectionLeaseTestsBase(IServiceProvider services) => _services = services;
/// Idempotent DDL of the probe table connection_lease_rows (tag) in the provider's dialect.
protected abstract string CreateProbeTableSql { get; }
///
/// Whether a lease inside a carries a transaction object: true where the driver
/// cannot enlist and redb runs its own transaction on the scope's connection (SQLite).
///
protected abstract bool AmbientLeaseCarriesTransaction { get; }
public async Task InitializeAsync()
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await redb.SyncSchemeAsync();
await redb.Context.ExecuteAsync(CreateProbeTableSql);
}
public async Task DisposeAsync()
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
foreach (var tag in _tags)
{
await redb.Context.ExecuteAsync($"DELETE FROM _objects WHERE _name LIKE '{tag}%'");
await redb.Context.ExecuteAsync($"DELETE FROM connection_lease_rows WHERE tag LIKE '{tag}%'");
}
}
private static TransactionScope NewScope() => new(TransactionScopeAsyncFlowOption.Enabled);
private string NewTag()
{
var tag = NamePrefix + Guid.NewGuid().ToString("N")[..10];
_tags.Add(tag);
return tag;
}
// The tag is generated here (prefix and hex digits), so the literal is safe and the statement needs no
// parameter syntax of a particular driver.
private static async Task InsertThroughLeaseAsync(RedbConnectionLease lease, string tag)
{
await using DbCommand command = lease.CreateCommand();
command.CommandText = $"INSERT INTO connection_lease_rows (tag) VALUES ('{tag}')";
(await command.ExecuteNonQueryAsync()).Should().Be(1);
}
private async Task<(long Objects, long Rows)> CountCommittedAsync(string tag)
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var objects = await redb.Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM _objects WHERE _name LIKE '{tag}%'");
var rows = await redb.Context.ExecuteScalarAsync(
$"SELECT COUNT(*) FROM connection_lease_rows WHERE tag LIKE '{tag}%'");
return (objects, rows);
}
[Fact]
public async Task TransactionScope_LeaseAndSave_CommitTogether_OnOneConnection()
{
var tag = NewTag();
using (var tx = NewScope())
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await using (var lease = await redb.Context.Db.LeaseAsync())
{
(lease.Transaction != null).Should().Be(AmbientLeaseCarriesTransaction);
await InsertThroughLeaseAsync(lease, tag);
}
await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 1m));
Transaction.Current!.TransactionInformation.DistributedIdentifier.Should().Be(Guid.Empty,
"the lease and the save share the scope's one connection, so the transaction never becomes distributed");
tx.Complete();
}
(await CountCommittedAsync(tag)).Should().Be((1L, 1L),
"the leased command and the redb save commit together with the scope");
}
[Fact]
public async Task TransactionScope_LeaseAndSave_RollBackTogether()
{
var tag = NewTag();
using (NewScope())
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await using (var lease = await redb.Context.Db.LeaseAsync())
await InsertThroughLeaseAsync(lease, tag);
await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 2m));
// not completed
}
(await CountCommittedAsync(tag)).Should().Be((0L, 0L),
"an abandoned scope takes back the leased command's row and the redb object alike");
}
[Fact]
public async Task ExplicitTransaction_LeaseCarriesIt_CommitAndRollback()
{
var committed = NewTag();
var rolledBack = NewTag();
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await using (var tx = await redb.Context.BeginTransactionAsync())
{
await using (var lease = await redb.Context.Db.LeaseAsync())
{
lease.Transaction.Should().NotBeNull("commands on a connection with an explicit transaction are bound to it");
await InsertThroughLeaseAsync(lease, committed);
}
await redb.SaveAsync(TestDataFactory.CreateSimple(committed, 3m));
await tx.CommitAsync();
}
await using (var tx = await redb.Context.BeginTransactionAsync())
{
await using (var lease = await redb.Context.Db.LeaseAsync())
await InsertThroughLeaseAsync(lease, rolledBack);
await redb.SaveAsync(TestDataFactory.CreateSimple(rolledBack, 4m));
await tx.RollbackAsync();
}
(await CountCommittedAsync(committed)).Should().Be((1L, 1L), "the commit takes both");
(await CountCommittedAsync(rolledBack)).Should().Be((0L, 0L), "the rollback takes back both");
}
[Fact]
public async Task NoTransaction_LeasedCommandAutocommits()
{
var tag = NewTag();
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await using (var lease = await redb.Context.Db.LeaseAsync())
{
lease.Transaction.Should().BeNull("no transaction is active");
await InsertThroughLeaseAsync(lease, tag);
}
(await CountCommittedAsync(tag)).Rows.Should().Be(1L, "without a transaction the command commits on its own");
}
[Fact]
public async Task WhileLeaseIsHeld_RedbOnTheConnectionAndInTheScope_IsRefused_ThenWorksAfterRelease()
{
var tag = NewTag();
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
await using (await redb.Context.Db.LeaseAsync())
{
var sameConnection = async () => await redb.Context.ExecuteScalarAsync("SELECT 1");
await sameConnection.Should().ThrowAsync(
"the lease holds the connection's command gate, as a redb command does");
}
(await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L, "the release gives the gate back");
using (var tx = NewScope())
{
await using var other = _services.CreateAsyncScope();
var otherRedb = other.ServiceProvider.GetRequiredService();
await using (var lease = await redb.Context.Db.LeaseAsync())
{
var otherScope = async () => await otherRedb.Context.ExecuteScalarAsync("SELECT 1");
await otherScope.Should().ThrowAsync(
"inside a TransactionScope every DI scope of the database shares the scope's connection and its gate");
await InsertThroughLeaseAsync(lease, tag);
}
await otherRedb.SaveAsync(TestDataFactory.CreateSimple(tag, 5m));
tx.Complete();
}
(await CountCommittedAsync(tag)).Should().Be((1L, 1L));
}
[Fact]
public async Task HolderThrowsInsideAwaitUsing_GatesAreReleased_AndTheScopeRollsBackWhole()
{
var tag = NewTag();
using (NewScope())
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var holder = async () =>
{
await using var lease = await redb.Context.Db.LeaseAsync();
await InsertThroughLeaseAsync(lease, tag);
throw new ApplicationException("the holder failed");
};
await holder.Should().ThrowAsync();
await redb.SaveAsync(TestDataFactory.CreateSimple(tag, 6m));
// not completed: the step failed
}
(await CountCommittedAsync(tag)).Should().Be((0L, 0L));
}
[Fact]
public async Task HolderClosedTheConnection_ReleaseThrows_AndTheNextCommandStillRuns()
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
var lease = await redb.Context.Db.LeaseAsync();
await lease.Connection.CloseAsync();
var release = async () => await lease.DisposeAsync();
await release.Should().ThrowAsync().WithMessage("*not open*");
(await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L,
"the release left the gate although it reported the closed connection");
}
[Fact]
public async Task LeaseAfterTheAmbientTransactionEnded_IsRefused_AndLeavesNoGateBehind()
{
await using var scope = _services.CreateAsyncScope();
var redb = scope.ServiceProvider.GetRequiredService();
using (NewScope())
{
Transaction.Current!.Rollback();
var lease = async () => await redb.Context.Db.LeaseAsync();
await lease.Should().ThrowAsync(
"a connection taken for a transaction that already ended would run outside it");
}
(await redb.Context.ExecuteScalarAsync("SELECT 1")).Should().Be(1L,
"the refused lease did not keep the connection's gate");
}
}