Bundle: redb-route / tests/redb.Route.Tests.Sql (tests.redb.Route.Tests.Sql.txt), 154 files
Snapshot: 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-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchCancellationTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchCancellationTests.cs
----
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
/// Cancellation during a batch ends the batch; it is never an item error to collect and move past.
public sealed class BatchCancellationTests
{
[Fact]
public async Task Batch_Cancellation_IsNotRecordedAsItemError()
{
using var cts = new CancellationTokenSource();
// A provider with savepoints: continue mode needs them, and the subject here is cancellation, not their absence.
var connection = new FakeBatchConnection
{
Savepoints = SavepointBehavior.Works,
OnExecute = (index, ct) =>
{
ct.ThrowIfCancellationRequested();
if (index == 1)
{
// The host shuts down while the second item is on the wire.
cts.Cancel();
throw new OperationCanceledException(cts.Token);
}
return 1;
},
};
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection),
"INSERT INTO t (id) VALUES (:#id)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
["breakBatchOnError"] = "false",
});
var producer = endpoint.CreateProducer();
var items = new List>
{
new() { ["id"] = 1 },
new() { ["id"] = 2 },
new() { ["id"] = 3 },
};
var exchange = new Exchange(new Message(items));
var act = () => producer.Process(exchange, cts.Token);
await act.Should().ThrowAsync();
connection.Executions.Should().Be(2, "no item may be attempted after the batch was cancelled");
exchange.In.Headers.Should().NotContainKey(SqlHeaders.Error, "a cancellation is not an item error");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchEmptySourceTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchEmptySourceTests.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
/// An empty batch source writes nothing and reports zero, as Camel's empty executeBatch() does.
public sealed class BatchEmptySourceTests
{
[Fact]
public async Task Batch_EmptyList_ExecutesNothing()
{
var connection = new FakeBatchConnection();
var factory = new FixedConnectionFactory(connection);
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, "INSERT INTO t (id, val) VALUES (:#id, :#val)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
});
var exchange = new Exchange(new Message(new List>()));
await endpoint.CreateProducer().Process(exchange, CancellationToken.None);
factory.Requests.Should().Be(0, "an empty batch needs no connection");
connection.Executions.Should().Be(0, "an empty batch must not run the statement once with NULL parameters");
Convert.ToInt32(exchange.In.Headers["redbSql.updateCount"]).Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchErrorModeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchErrorModeTests.cs
----
using System.Collections;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Error modes of the batch, decided 2026-09-14 with Apache Camel as the reference: breaking on the first error is the
/// default and rethrows the provider's own exception; continuing past an error is only done under a savepoint per item,
/// refused before any write where savepoints cannot work, and stopped the moment the transaction is found dead.
///
///
/// Headers and exception data are addressed by their literal names: the constants arrive with the behaviour (wave 17.1),
/// and these tests are written against the code before it.
///
public sealed class BatchErrorModeTests
{
private const string Sql = "INSERT INTO t (id) VALUES (:#id)";
[Fact]
public async Task Batch_DefaultMode_BreaksOnFirstError()
{
var connection = new FakeBatchConnection { OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: null);
var exchange = new Exchange(new Message(Items(3)));
var act = () => producer.Process(exchange, CancellationToken.None);
await act.Should().ThrowAsync("without an explicit mode a failing item fails the whole batch");
connection.Executions.Should().Be(2, "nothing runs after the failing item");
connection.Transaction!.RolledBack.Should().BeTrue();
}
[Fact]
public async Task BreakOnError_ThrowsProviderExceptionUnwrapped()
{
var connection = new FakeBatchConnection { OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: true);
var exchange = new Exchange(new Message(Items(3)));
// Outcome.Of, not ThrowAsync: AwesomeAssertions looks inside AggregateException, which would hide the wrapping.
var thrown = await Outcome.Of(() => producer.Process(exchange, CancellationToken.None));
thrown.Should().BeOfType(
"the provider's exception reaches the route as is, so OnException matches it");
thrown!.Data["redbSql.batchFailedIndex"].Should().Be(1);
}
[Fact]
public async Task BreakOnError_ReportsTheStrategyInTheHeaderToo()
{
var connection = new FakeBatchConnection { OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: true);
var exchange = new Exchange(new Message(Items(3)));
var thrown = await Outcome.Of(() => producer.Process(exchange, CancellationToken.None));
thrown.Should().NotBeNull();
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("Commands",
"an OnException handler reads the failed index by the strategy: a DbBatch index may be the start of a chunk");
}
[Fact]
public async Task BreakOnError_RetriedOnTheSameExchange_ClearsTheFailureHeaders()
{
await using var context = new RouteContext();
var exchange = new Exchange(new Message(Items(3)));
var failing = CreateProducer(context, new FakeBatchConnection { OnExecute = FailAt(1) }, breakOnError: true);
(await Outcome.Of(() => failing.Process(exchange, CancellationToken.None))).Should().NotBeNull();
exchange.In.Headers.Should().ContainKey("redbSql.batchFailedIndex");
// The route's redelivery runs the same exchange again, this time without the error.
var succeeding = CreateProducer(context, new FakeBatchConnection(), breakOnError: true);
var retry = await Outcome.Of(() => succeeding.Process(exchange, CancellationToken.None));
retry.Should().BeNull(Outcome.Describe(retry));
exchange.In.Headers.Should().NotContainKey("redbSql.batchFailedIndex",
"the failure of the first attempt is not a result of the attempt that succeeded");
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("Commands");
}
[Fact]
public async Task BatchContinue_CleanRunAfterErrors_ClearsTheErrorHeaders()
{
await using var context = new RouteContext();
var exchange = new Exchange(new Message(Items(3)));
var first = CreateProducer(context, new FakeBatchConnection { Savepoints = SavepointBehavior.Works, OnExecute = FailAt(1) }, breakOnError: false);
(await Outcome.Of(() => first.Process(exchange, CancellationToken.None))).Should().BeNull();
exchange.In.Headers.Should().ContainKey("redbSql.batchErrors").And.ContainKey("redbSql.error");
var second = CreateProducer(context, new FakeBatchConnection { Savepoints = SavepointBehavior.Works }, breakOnError: false);
var clean = await Outcome.Of(() => second.Process(exchange, CancellationToken.None));
clean.Should().BeNull(Outcome.Describe(clean));
exchange.In.Headers.Should().NotContainKey("redbSql.batchErrors", "no item of this run failed");
exchange.In.Headers.Should().NotContainKey("redbSql.error", "the errors of an earlier step do not describe this one");
}
[Fact]
public async Task BatchContinue_SavepointsUnavailable_FailsBeforeFirstWrite()
{
var connection = new FakeBatchConnection { Savepoints = SavepointBehavior.Unsupported, OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: false);
var exchange = new Exchange(new Message(Items(3)));
var act = () => producer.Process(exchange, CancellationToken.None);
await act.Should().ThrowAsync("continuing past an error cannot be honest without savepoints");
connection.Executions.Should().Be(0, "the refusal comes before anything is written");
}
[Fact]
public async Task BatchContinue_StatementLevelError_ContinuesAndReportsItemErrors()
{
var connection = new FakeBatchConnection { Savepoints = SavepointBehavior.Works, OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: false);
var exchange = new Exchange(new Message(Items(3)));
await producer.Process(exchange, CancellationToken.None);
connection.Executions.Should().Be(3);
connection.Transaction!.SavepointLog.Should().Contain(entry => entry.StartsWith("rollback:"),
"the failed item is undone to its savepoint, the others stay");
connection.Transaction.Committed.Should().BeTrue();
exchange.In.Headers.Should().ContainKey("redbSql.batchErrors");
var errors = ((IEnumerable)exchange.In.Headers["redbSql.batchErrors"]!).Cast().ToList();
errors.Should().ContainSingle();
errors[0].GetType().GetProperty("Index")!.GetValue(errors[0]).Should().Be(1);
}
[Fact]
public async Task BatchContinue_TransactionDeadAfterItemError_NoFurtherCommands()
{
var connection = new FakeBatchConnection { Savepoints = SavepointBehavior.RollbackToSavepointFails, OnExecute = FailAt(1) };
await using var context = new RouteContext();
var producer = CreateProducer(context, connection, breakOnError: false);
var exchange = new Exchange(new Message(Items(3)));
var thrown = await Outcome.Of(() => producer.Process(exchange, CancellationToken.None));
thrown.Should().BeOfType("the item's own error ends a batch whose transaction is gone");
connection.Executions.Should().Be(2,
"after a failed rollback to the savepoint no statement may be sent — SQL Server would run it in autocommit");
}
private static Func FailAt(int failingIndex) => (index, _) =>
index == failingIndex ? throw new FakeDbException($"fake: item {index} violates a constraint") : 1;
private static IProducer CreateProducer(RouteContext context, FakeBatchConnection connection, bool? breakOnError)
{
var parameters = new Dictionary
{
["outputType"] = "None",
["batchSize"] = "10",
};
if (breakOnError is { } mode)
parameters["breakBatchOnError"] = mode ? "true" : "false";
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), Sql, parameters);
return endpoint.CreateProducer();
}
private static List> Items(int count) =>
Enumerable.Range(1, count).Select(i => new Dictionary { ["id"] = i }).ToList();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemBinderTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemBinderTests.cs
----
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json;
using System.Text.Json.Nodes;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Where a batch item's parameter values come from: the order of the sources, name matching for each item shape, JSON
/// values, items that are exchanges, and when an expression context is created.
///
public sealed class BatchItemBinderTests : IDisposable
{
private readonly SqliteTestHelper _db = new();
public BatchItemBinderTests() => _db.Execute(
"CREATE TABLE bound (id INTEGER NOT NULL, val TEXT NULL, tenant TEXT NULL, i INTEGER NULL, d REAL NULL, b INTEGER NULL, g REAL NULL)");
public void Dispose() => _db.Dispose();
// ── Order of sources ────────────────────────────────────────────────────
[Fact]
public async Task Binder_ExplicitConstant_WinsOverItemValue()
{
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(DictionaryItems()),
new() { ["param.val"] = "constant" });
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("val").Should().Equal(new object?[] { "constant", "constant" }, "an explicit param.* is the first source");
}
[Fact]
public async Task Binder_ParentHeader_UsedWhenItemHasNoKey()
{
var carrier = Carrier(new List> { new() { ["id"] = 1 }, new() { ["id"] = 2 } });
carrier.In.Headers["val"] = "from-header";
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", carrier);
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("val").Should().Equal(new object?[] { "from-header", "from-header" },
"the carrying exchange's header is the source after the item's own keys");
}
// ── Dictionary items ────────────────────────────────────────────────────
[Fact]
public async Task Binder_DictionaryKey_CaseInsensitiveFallback()
{
var items = new List> { new() { ["ID"] = 1, ["Val"] = "a" } };
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows("id", "val").Should().Equal("1|a");
}
[Fact]
public async Task Binder_DictionaryKeysDifferingOnlyByCase_ExactKeyWins()
{
var items = new List> { new() { ["id"] = 1, ["val"] = "exact", ["VAL"] = "other" } };
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("val").Should().Equal(new object?[] { "exact" }, "a key that matches the placeholder exactly is taken as is");
}
[Fact]
public async Task Binder_DictionaryKeysDifferingOnlyByCase_NoExactKey_IsNotGuessed()
{
var items = new List> { new() { ["id"] = 1, ["Val"] = "x", ["VAL"] = "y" } };
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(items));
thrown.Should().BeOfType(Outcome.Describe(thrown))
.Which.Message.Should().Contain("item 0").And.Contain(":#val");
Column("val").Should().BeEmpty("two keys differing only by case do not name one value");
}
// ── POCO items ──────────────────────────────────────────────────────────
[Fact]
public async Task Binder_Poco_ColumnAttributeAndSnakeCase()
{
var items = new List
{
new() { Id = 1, Value = "a", TenantCode = "t1" },
new() { Id = 2, Value = "b", TenantCode = null },
};
var thrown = await RunAsync("INSERT INTO bound (id, val, tenant) VALUES (:#id, :#item_value, :#tenant_code)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows("id", "val", "tenant").Should().Equal("1|a|t1", "2|b|");
}
// ── JSON items ──────────────────────────────────────────────────────────
[Fact]
public async Task Binder_JsonElement_ScalarKinds()
{
const string json = """[{"id":1,"val":"text","i":42,"d":1.5,"b":true,"g":1e300,"tenant":null}]""";
var items = JsonSerializer.Deserialize>(json)!;
var thrown = await RunAsync(
"INSERT INTO bound (id, val, i, d, b, g, tenant) VALUES (:#id, :#val, :#i, :#d, :#b, :#g, :#tenant)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
var row = _db.Query("SELECT id, val, i, d, b, g, tenant FROM bound").Should().ContainSingle().Subject;
row["id"].Should().Be(1L);
row["val"].Should().Be("text");
row["i"].Should().Be(42L);
row["d"].Should().Be(1.5);
row["b"].Should().Be(1L);
row["g"].Should().Be(1e300);
row["tenant"].Should().BeNull();
}
[Fact]
public async Task Binder_JsonElement_EmptyString_IsDbNull()
{
var items = JsonSerializer.Deserialize>("""[{"id":1,"val":""}]""")!;
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("val").Should().Equal(new object?[] { null }, "an empty JSON string is NULL, like an empty string anywhere else");
}
[Fact]
public async Task Binder_JsonElement_ObjectAndArrayValues_AreRawText()
{
const string json = """[{"id":1,"val":{"a":1,"b":[true,null]},"tenant":[1,"x"]}]""";
var items = JsonSerializer.Deserialize>(json)!;
var thrown = await RunAsync("INSERT INTO bound (id, val, tenant) VALUES (:#id, :#val, :#tenant)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows("val", "tenant").Should().Equal("""{"a":1,"b":[true,null]}|[1,"x"]""");
}
[Fact]
public async Task Binder_JsonObjectItems_BindScalars()
{
var items = JsonNode.Parse("""[{"id":1,"val":"a","i":7},{"id":2,"val":null,"i":8}]""")!
.AsArray().Select(node => node!.AsObject()).ToList();
var thrown = await RunAsync("INSERT INTO bound (id, val, i) VALUES (:#id, :#val, :#i)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows("id", "val", "i").Should().Equal("1|a|7", "2||8");
}
// ── Exchange items ──────────────────────────────────────────────────────
[Fact]
public async Task Binder_ExchangeItem_UsesOwnHeadersNotParent()
{
var carrier = Carrier(new List { ItemExchange(1, "a"), ItemExchange(2, "b") });
carrier.In.Headers["id"] = 99;
carrier.In.Headers["val"] = "parent";
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", carrier);
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows("id", "val").Should().Equal("1|a", "2|b");
}
[Fact]
public async Task Binder_ExchangeItem_ExpressionEvaluatedOnItem()
{
var carrier = Carrier(new List { ItemExchange(1, "a", label: "L1"), ItemExchange(2, "b", label: "L2") });
carrier.In.Headers["label"] = "parent";
var thrown = await RunAsync("INSERT INTO bound (id, val, tenant) VALUES (:#id, :#val, :#tenant)", carrier,
new() { ["param.tenant"] = "${header.label}" });
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("tenant").Should().Equal(new object?[] { "L1", "L2" }, "an item exchange evaluates param.* on itself");
}
// ── Normalisation and expression context ───────────────────────────────
[Fact]
public async Task Binder_EmptyString_IsDbNull_SameAsSinglePath()
{
var items = new List> { new() { ["id"] = 1, ["val"] = "" } };
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", Carrier(items));
thrown.Should().BeNull(Outcome.Describe(thrown));
Column("val").Should().Equal(new object?[] { null });
}
[Fact]
public async Task Binder_NoTemplates_CreatesNoChildExchange()
{
var carrier = new CountingExchange(Carrier(DictionaryItems()));
var thrown = await RunAsync("INSERT INTO bound (id, val) VALUES (:#id, :#val)", carrier);
thrown.Should().BeNull(Outcome.Describe(thrown));
carrier.LinkedChildren.Should().Be(0, "without ${...} in param.* nothing needs an expression context");
Column("val").Should().Equal(new object?[] { "a", "b" });
}
[Fact]
public async Task Binder_Templates_EvaluatedInLinkedChildOfCarryingExchange()
{
var carrier = new CountingExchange(Carrier(DictionaryItems()));
carrier.Properties["tenant"] = "t1";
var thrown = await RunAsync("INSERT INTO bound (id, val, tenant) VALUES (:#id, :#val, :#tenant)", carrier,
new() { ["param.tenant"] = "${property.tenant}" });
thrown.Should().BeNull(Outcome.Describe(thrown));
carrier.LinkedChildren.Should().Be(2, "each item is evaluated in a linked child of the carrying exchange");
Column("tenant").Should().Equal(new object?[] { "t1", "t1" });
}
public sealed class PocoItem
{
public int Id { get; set; }
[Column("item_value")]
public string? Value { get; set; }
public string? TenantCode { get; set; }
}
// ── Helpers ─────────────────────────────────────────────────────────────
private static Exchange Carrier(object items) => new(new Message(items));
private static List> DictionaryItems() =>
[
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 2, ["val"] = "b" },
];
private static IExchange ItemExchange(int id, string val, string? label = null)
{
var exchange = new Exchange(new Message($"event-{id}"));
exchange.In.Headers["id"] = id;
exchange.In.Headers["val"] = val;
if (label is not null)
exchange.In.Headers["label"] = label;
return exchange;
}
private async Task RunAsync(string sql, IExchange carrier, Dictionary? options = null)
{
var parameters = new Dictionary { ["outputType"] = "None", ["batchSize"] = "10" };
if (options is not null)
foreach (var (key, value) in options)
parameters[key] = value;
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), sql, parameters);
return await Outcome.Of(() => endpoint.CreateProducer().Process(carrier, CancellationToken.None));
}
private List Column(string name) =>
_db.Query($"SELECT {name} FROM bound ORDER BY id").Select(r => r[name]).ToList();
private List Rows(params string[] columns) =>
_db.Query($"SELECT {string.Join(", ", columns)} FROM bound ORDER BY id")
.Select(r => string.Join("|", columns.Select(c => r[c])))
.ToList();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemExpressionTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemExpressionTests.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
/// Explicit param.* expressions evaluated per batch item, and the order of value sources.
public sealed class BatchItemExpressionTests : IDisposable
{
private readonly SqliteTestHelper _db = new();
public BatchItemExpressionTests() =>
_db.Execute("CREATE TABLE tenant_items (id INTEGER NOT NULL, val TEXT NOT NULL, tenant TEXT NULL)");
public void Dispose() => _db.Dispose();
[Fact]
public async Task Batch_ItemExpression_SeesExchangeProperties()
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
"INSERT INTO tenant_items (id, val, tenant) VALUES (:#id, :#val, :#tenant)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
["param.tenant"] = "${property.tenant}",
});
var exchange = new Exchange(new Message(Items()));
exchange.Properties["tenant"] = "t1";
await endpoint.CreateProducer().Process(exchange, CancellationToken.None);
_db.Query("SELECT tenant FROM tenant_items ORDER BY id").Select(r => r["tenant"])
.Should().Equal(new object?[] { "t1", "t1" }, "an item's expression runs in the context of the exchange that carries the batch");
}
[Fact]
public async Task Batch_ItemsDoNotInheritParentHeaderValues_WhenItemHasKey()
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
"INSERT INTO tenant_items (id, val) VALUES (:#id, :#val)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
});
var exchange = new Exchange(new Message(Items()));
exchange.In.Headers["val"] = "parent";
await endpoint.CreateProducer().Process(exchange, CancellationToken.None);
_db.Query("SELECT val FROM tenant_items ORDER BY id").Select(r => r["val"])
.Should().Equal(new object?[] { "a", "b" }, "an item's own value wins over the carrying exchange's header");
}
private static List> Items() =>
[
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 2, ["val"] = "b" },
];
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemFrameworkTypeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemFrameworkTypeTests.cs
----
using System.Text.Json;
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Batch items whose type comes from .NET itself are not POCOs: their properties are not record fields. An XML node carries no
/// named values, as in Apache Camel — its values are bound with xpath expressions; a JSON document is read as its JSON.
///
public sealed class BatchItemFrameworkTypeTests : IDisposable
{
private readonly SqliteTestHelper _db = new();
public BatchItemFrameworkTypeTests() => _db.Execute("CREATE TABLE framework_items (id INTEGER NULL, val TEXT NULL)");
public void Dispose() => _db.Dispose();
[Fact]
public async Task Binder_XElementItems_NamedPlaceholder_FailsWithXPathHint()
{
var items = new List { XElement.Parse("""n1 text
""") };
var thrown = await RunAsync("INSERT INTO framework_items (id, val) VALUES (:#id, :#value)", items,
new() { ["param.id"] = "1" });
thrown.Should().BeOfType(
$"XElement.Value is not a field named 'value' ({Outcome.Describe(thrown)}, rows: {string.Join(", ", Rows())})")
.Which.Message.Should().Contain("item 0").And.Contain(":#value").And.Contain("xpath");
Rows().Should().BeEmpty();
}
[Fact]
public async Task Binder_XElementItems_BindWithXPathExpressions()
{
var items = new List
{
XElement.Parse("""n1
"""),
XElement.Parse("""n2
"""),
};
var thrown = await RunAsync("INSERT INTO framework_items (id, val) VALUES (:#id, :#val)", items, new()
{
["param.id"] = "${xpath('@id')}",
["param.val"] = "${xpath('name')}",
});
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows().Should().Equal("1|n1", "2|n2");
}
[Fact]
public async Task Binder_JsonDocumentItems_BindByKeys()
{
using var first = JsonDocument.Parse("""{"id":1,"val":"a"}""");
using var second = JsonDocument.Parse("""{"id":2,"val":null}""");
var thrown = await RunAsync("INSERT INTO framework_items (id, val) VALUES (:#id, :#val)", new List { first, second });
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows().Should().Equal("1|a", "2|");
}
[Fact]
public async Task Binder_FrameworkObjectItem_HasNoNamedValues()
{
var items = new List { new Uri("https://h.example:8443/p") };
var thrown = await RunAsync("INSERT INTO framework_items (id, val) VALUES (:#port, :#host)", items);
thrown.Should().BeOfType(
$"Uri.Port and Uri.Host are not record fields ({Outcome.Describe(thrown)}, rows: {string.Join(", ", Rows())})")
.Which.Message.Should().Contain("item 0").And.Contain(":#port");
Rows().Should().BeEmpty();
}
[Fact]
public async Task Binder_AnonymousTypeItems_BindByProperty()
{
var items = new List { new { id = 1, val = "a" }, new { id = 2, val = (string?)null } };
var thrown = await RunAsync("INSERT INTO framework_items (id, val) VALUES (:#id, :#val)", items);
thrown.Should().BeNull(Outcome.Describe(thrown));
Rows().Should().Equal("1|a", "2|");
}
private async Task RunAsync(string sql, object items, Dictionary? options = null)
{
var parameters = new Dictionary { ["outputType"] = "None", ["batchSize"] = "10" };
if (options is not null)
foreach (var (key, value) in options)
parameters[key] = value;
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), sql, parameters);
IExchange carrier = new Exchange(new Message(items));
return await Outcome.Of(() => endpoint.CreateProducer().Process(carrier, CancellationToken.None));
}
private List Rows() =>
_db.Query("SELECT id, val FROM framework_items ORDER BY id").Select(r => $"{r["id"]}|{r["val"]}").ToList();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemShapeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchItemShapeTests.cs
----
using System.Text.Json;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Batch items in the shapes routes actually produce: CSV maps with string values, POCO lists, JSON arrays. Each
/// item's values must reach the statement's parameters.
///
public sealed class BatchItemShapeTests : IDisposable
{
private const string Json = """[{"id":1,"val":"a"},{"id":2,"val":"b"}]""";
private readonly SqliteTestHelper _db = new();
public BatchItemShapeTests() => _db.Execute("CREATE TABLE items (id INTEGER NOT NULL, val TEXT NOT NULL)");
public void Dispose() => _db.Dispose();
[Fact]
public async Task Batch_StringDictionaryItems_BindByKey()
{
var items = new List>
{
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "2", ["val"] = "b" },
};
var exchange = await RunBatchAsync(items);
AssertRows(exchange, "1|a", "2|b");
}
[Fact]
public async Task Batch_PocoItems_BindByProperty()
{
var items = new List
{
new() { Id = 1, Val = "a" },
new() { Id = 2, Val = "b" },
};
var exchange = await RunBatchAsync(items);
AssertRows(exchange, "1|a", "2|b");
}
[Fact]
public async Task Batch_JsonElementItems_BindScalars()
{
var items = JsonSerializer.Deserialize>(Json)!;
var exchange = await RunBatchAsync(items);
AssertRows(exchange, "1|a", "2|b");
}
[Fact]
public async Task Batch_JsonElementValuesInDictionaryItems_BindScalars()
{
// What a JSON unmarshal to object-valued maps produces: every value is a JsonElement.
var items = JsonSerializer.Deserialize>>(Json)!;
var exchange = await RunBatchAsync(items);
AssertRows(exchange, "1|a", "2|b");
}
[Fact]
public async Task Batch_UnknownItemShape_WithoutParams_FailsWithIndex()
{
// Scalar items carry no named values; Camel fails an unresolved named parameter instead of binding NULL.
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
"INSERT INTO items (id, val) VALUES (:#id, :#val)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
["breakBatchOnError"] = "true",
});
var exchange = new Exchange(new Message(new List { "a", "b" }));
var act = () => endpoint.CreateProducer().Process(exchange, CancellationToken.None);
await act.Should().ThrowAsync().WithMessage("*item 0*");
}
public sealed class ShapeItem
{
public int Id { get; set; }
public string Val { get; set; } = "";
}
private async Task RunBatchAsync(object body)
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
"INSERT INTO items (id, val) VALUES (:#id, :#val)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
["breakBatchOnError"] = "false",
});
var exchange = new Exchange(new Message(body));
await endpoint.CreateProducer().Process(exchange, CancellationToken.None);
return exchange;
}
private void AssertRows(Exchange exchange, params string[] expected)
{
var rows = _db.Query("SELECT id, val FROM items ORDER BY id")
.Select(r => $"{r["id"]}|{r["val"]}")
.ToList();
var error = exchange.In.Headers.TryGetValue(SqlHeaders.Error, out var e) ? e : "none";
rows.Should().Equal(expected, $"every item's values must be bound (error header: {error})");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchOptionsValidationTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchOptionsValidationTests.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Options that cannot take effect fail when the endpoint is created (decision 5-a, connector only). Today a
/// ${...} value for a numeric option is silently dropped and the option keeps its default — for
/// batchSize that turns batching off and sends the whole list to a single statement.
///
public sealed class BatchOptionsValidationTests
{
[Theory]
[InlineData("batchSize")]
[InlineData("commandTimeout")]
[InlineData("maxMessagesPerPoll")]
public async Task KnownOption_UnconvertibleValue_FailsAtEndpointCreation(string option)
{
await using var context = new RouteContext();
var act = () => SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(new FakeBatchConnection()),
"INSERT INTO t (id) VALUES (:#id)", new() { [option] = "${header.n}" });
act.Should().Throw().WithMessage($"*{option}*");
}
[Fact]
public async Task Batch_NegativeBatchSize_FailsAtEndpointCreation()
{
await using var context = new RouteContext();
var act = () => SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(new FakeBatchConnection()),
"INSERT INTO t (id) VALUES (:#id)", new() { ["batchSize"] = "-1" });
act.Should().Throw().WithMessage("*BatchSize*");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchResultsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchResultsTests.cs
----
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Sql.Mapping;
using redb.Route.Telemetry;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// What a batch reports besides the rows it wrote: the rows its statements return (RETURNING / OUTPUT ) in
/// redbSql.generatedKeys — in item order, the body left alone, as Apache Camel's CamelSqlGeneratedKeyRows — and
/// the batch tags on the sql.execute span. Spans are picked by the endpoint marker, never by position: the in-memory
/// exporter listens to the process-wide activity source.
///
public sealed class BatchResultsTests : IDisposable
{
private const string Insert = "INSERT INTO t (id) VALUES (:#id)";
private readonly SqliteTestHelper _db = new();
public void Dispose() => _db.Dispose();
// ── Generated keys ──────────────────────────────────────────────
[Fact]
public async Task GeneratedKeys_DbBatch_OrderMatchesItems()
{
var connection = new FakeBatchConnection { SupportsBatch = true, OnExecuteBatchReader = (_, batch) => KeyResults(batch) };
var items = Items(5);
var (exchange, thrown) = await RunFakeAsync(connection, items, batchSize: 2, outputType: "SelectList");
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.BatchSizes.Should().Equal(2, 2, 1);
exchange.In.Headers.Should().ContainKey(SqlHeaders.GeneratedKeys);
exchange.In.Headers[SqlHeaders.GeneratedKeys].Should().BeAssignableTo>>()
.Which.Select(k => k["key"]).Should().Equal(new object?[] { 0L, 10L, 20L, 30L, 40L }, "keys follow the items across chunks");
exchange.In.Headers["redbSql.generatedKeysRowCount"].Should().Be(5);
exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(5, "the rows affected are summed over every command of the batch");
exchange.In.Body.Should().BeSameAs(items, "the returned rows go to a header; the body is left alone");
}
/// Its Key cannot hold the keys the fake returns (10, 20, …): a configuration error, not an item's.
public sealed class NarrowKeyRow
{
public bool Key { get; set; }
}
[Fact]
public async Task GeneratedKeys_MappingError_IsAConfigurationErrorNotAChunkFailure()
{
var connection = new FakeBatchConnection { SupportsBatch = true, OnExecuteBatchReader = (_, batch) => KeyResults(batch) };
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), Insert, new()
{
["outputType"] = "SelectList",
["outputClass"] = typeof(NarrowKeyRow).AssemblyQualifiedName!,
["batchSize"] = "2",
});
var exchange = new Exchange(new Message(Items(3)));
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
thrown.Should().BeOfType(Outcome.Describe(thrown))
.Which.Message.Should().Contain("Key", "the mapping error reaches the route as itself");
thrown!.Data.Contains("redbSql.batchFailedChunk").Should().BeFalse("no statement failed; the driver has nothing to name");
exchange.In.Headers.Should().NotContainKey(SqlHeaders.BatchFailedIndex, "a mapping error is not an item's failure");
connection.Transaction!.RolledBack.Should().BeTrue();
}
[Fact]
public async Task GeneratedKeys_OutputTypeAuto_InsertCollectsNothing()
{
var connection = new FakeBatchConnection { SupportsBatch = true };
var (exchange, thrown) = await RunFakeAsync(connection, Items(3), batchSize: 10, outputType: "Auto");
thrown.Should().BeNull(Outcome.Describe(thrown));
exchange.In.Headers.Should().NotContainKey(SqlHeaders.GeneratedKeys,
"Auto makes an INSERT a statement without rows; outputType is set explicitly to collect RETURNING / OUTPUT rows");
exchange.In.Headers.Should().NotContainKey("redbSql.generatedKeysRowCount");
}
// ── Telemetry ───────────────────────────────────────────────────
[Fact]
public async Task Telemetry_SuccessfulBatch_TagsSizeAndStrategy()
{
_db.Execute("CREATE TABLE tel_items (id INTEGER PRIMARY KEY)");
var marker = $"batch-telemetry-{Guid.NewGuid():N}";
var span = await CaptureSpanAsync(marker, async () =>
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
$"INSERT INTO tel_items (id) VALUES (:#id) /* {marker} */", new() { ["batchSize"] = "10" });
return await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message(Items(3))), CancellationToken.None));
});
span.GetTagItem("db.operation.batch.size").Should().Be(3, "the OpenTelemetry database convention's batch size");
span.GetTagItem("redb.sql.batch.strategy").Should().Be("Commands");
span.GetTagItem("redb.sql.batch.chunks").Should().BeNull("only a DbBatch has round trips to count");
span.GetTagItem("redb.sql.batch.failed_index").Should().BeNull();
}
[Fact]
public async Task Telemetry_SingleItemBatch_NoBatchSizeTag()
{
_db.Execute("CREATE TABLE tel_one (id INTEGER PRIMARY KEY)");
var marker = $"batch-telemetry-{Guid.NewGuid():N}";
var span = await CaptureSpanAsync(marker, async () =>
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(),
$"INSERT INTO tel_one (id) VALUES (:#id) /* {marker} */", new() { ["batchSize"] = "10" });
return await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message(Items(1))), CancellationToken.None));
});
span.GetTagItem("redb.sql.batch.strategy").Should().Be("Commands");
span.GetTagItem("db.operation.batch.size").Should().BeNull("the convention counts a batch only from two operations");
}
[Fact]
public async Task Telemetry_FailedDbBatch_TagsFailedIndex()
{
var marker = $"batch-telemetry-{Guid.NewGuid():N}";
var connection = new FakeBatchConnection
{
SupportsBatch = true,
OnExecuteBatch = (index, batch) => index == 1
? throw new FakeDbException("duplicate key", batch.BatchCommands[1])
: batch.BatchCommands.Count,
};
var span = await CaptureSpanAsync(marker, async () =>
{
var (_, thrown) = await RunFakeAsync(connection, Items(10), batchSize: 3, outputType: "None", marker);
thrown.Should().BeOfType(Outcome.Describe(thrown));
return null;
});
span.GetTagItem("redb.sql.batch.failed_index").Should().Be(4, "the second command of the second chunk is item 4");
span.GetTagItem("redb.sql.batch.strategy").Should().Be("DbBatch");
}
// ── Helpers ─────────────────────────────────────────────────────
private static List> Items(int count) =>
Enumerable.Range(0, count).Select(i => new Dictionary { ["id"] = i }).ToList();
/// One result set per command of the batch: a single row whose key is ten times the command's id.
private static DbDataReader KeyResults(FakeDbBatch batch)
{
var tables = batch.BatchCommands.Cast().Select(command =>
{
var table = new DataTable();
table.Columns.Add("key", typeof(long));
table.Rows.Add(Convert.ToInt64(command.Parameters["id"].Value) * 10);
return table;
}).ToArray();
return new DataTableReader(tables);
}
private static async Task<(Exchange Exchange, Exception? Thrown)> RunFakeAsync(
FakeBatchConnection connection, List> items, int batchSize, string outputType, string? marker = null)
{
await using var context = new RouteContext();
var sql = marker is null ? Insert : $"{Insert} /* {marker} */";
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), sql, new()
{
["outputType"] = outputType,
["batchSize"] = batchSize.ToString(),
});
var exchange = new Exchange(new Message(items));
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
return (exchange, thrown);
}
private static async Task CaptureSpanAsync(string marker, Func> run)
{
var activities = new List();
using (var tracer = Sdk.CreateTracerProviderBuilder()
.AddSource(RouteActivitySource.SourceName)
.AddInMemoryExporter(activities)
.Build()!)
{
var thrown = await run();
thrown.Should().BeNull(Outcome.Describe(thrown));
tracer.ForceFlush(1000);
}
return activities.Should().ContainSingle(a => HasMarker(a, marker)).Which;
}
private static bool HasMarker(Activity activity, string marker) =>
activity.GetTagItem("redb.route.endpoint") is string endpoint && endpoint.Contains(marker, StringComparison.Ordinal);
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchRollbackTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchRollbackTests.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
/// What surrounds a failed batch: the rollback, and the resources the batch held.
public sealed class BatchRollbackTests
{
[Fact]
public async Task Break_RollbackFails_OriginalExceptionIsThrown()
{
var connection = new FakeBatchConnection
{
FailRollback = true,
OnExecute = (index, _) => index == 1 ? throw new FakeDbException("fake: item 1 violates a constraint") : 1,
};
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection),
"INSERT INTO t (id) VALUES (:#id)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
["breakBatchOnError"] = "true",
});
var exchange = new Exchange(new Message(new List>
{
new() { ["id"] = 1 },
new() { ["id"] = 2 },
}));
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
thrown.Should().BeOfType("a failing rollback is logged; the error that ended the batch is what the route sees");
}
[Fact]
public async Task Cancellation_DuringItem_PropagatesAndDisposesTransaction()
{
using var cts = new CancellationTokenSource();
var connection = new FakeBatchConnection
{
OnExecute = (index, ct) =>
{
ct.ThrowIfCancellationRequested();
if (index == 1)
{
cts.Cancel();
throw new OperationCanceledException(cts.Token);
}
return 1;
},
};
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection),
"INSERT INTO t (id) VALUES (:#id)", new()
{
["outputType"] = "None",
["batchSize"] = "10",
});
var exchange = new Exchange(new Message(new List>
{
new() { ["id"] = 1 },
new() { ["id"] = 2 },
new() { ["id"] = 3 },
}));
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, cts.Token));
thrown.Should().BeAssignableTo();
connection.Executions.Should().Be(2, "nothing is sent after the cancelled item");
connection.Transaction!.Committed.Should().BeFalse();
connection.Transaction.IsDisposed.Should().BeTrue("a cancelled batch still releases its transaction");
connection.IsDisposed.Should().BeTrue("and returns its connection");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchRouteErrorHandlingTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchRouteErrorHandlingTests.cs
----
using System.Data.Common;
using redb.Route.Core;
using redb.Route.Sql;
namespace redb.Route.Tests.Sql.Batch;
///
/// A failed batch inside a route: the route's OnException<DbException> must match it. Handlers are found by the
/// thrown exception's type and its base types, so this holds only if the provider's exception reaches the route unwrapped.
///
public sealed class BatchRouteErrorHandlingTests : IAsyncLifetime
{
private readonly SqliteTestHelper _db = new();
private readonly RouteContext _context = new();
public BatchRouteErrorHandlingTests() =>
_db.Execute("CREATE TABLE route_items (id INTEGER PRIMARY KEY, val TEXT NOT NULL)");
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await _context.DisposeAsync();
_db.Dispose();
}
[Fact]
public async Task Break_OnExceptionDbException_HandlerRuns()
{
Exception? handled = null;
_context.AddComponent(new SqlComponent());
_context.AddToRegistry("main", _db.CreateFactory());
_context.AddRoutes(r =>
{
r.From("direct://sql-batch-errors")
.OnException()
.Handled()
.Process(e => handled = e.Exception)
.EndOnException()
.To("sql:INSERT INTO route_items (id, val) VALUES (:#id, :#val)?dataSource=main&batchSize=10&outputType=None");
});
await _context.Start();
var producer = _context.GetEndpoint("direct://sql-batch-errors").CreateProducer();
await producer.Start();
var items = new List>
{
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 1, ["val"] = "dup" },
};
var escaped = await Record.ExceptionAsync(() => producer.Process(new Exchange(new Message(items))));
handled.Should().BeAssignableTo(
$"the route's OnException handles the failed batch (escaped the route: {escaped?.GetType().Name ?? "nothing"})");
Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM route_items")).Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchSourceTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchSourceTests.cs
----
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// Which message bodies are batch sources, and how a streamed source is read: at most one chunk ahead of the writes, no
/// connection for an empty stream, the source's own failure ending the batch.
///
public sealed class BatchSourceTests : IDisposable
{
private const string Insert = "INSERT INTO source_log (val) VALUES (:#val)";
private readonly SqliteTestHelper _db = new();
public BatchSourceTests() => _db.Execute("CREATE TABLE source_log (val TEXT)");
public void Dispose() => _db.Dispose();
[Fact]
public async Task Batch_ByteArrayBody_IsNotExpandedIntoItems()
{
var exchange = new Exchange(new Message(new byte[] { 1, 2, 3 }));
exchange.In.Headers["val"] = "h";
await ProduceAsync(exchange);
Values().Should().Equal(new object?[] { "h" }, "a byte[] body is one value, not a list of batch items");
}
public static TheoryData ByteAndCharSequences() => new()
{
new ArraySegment([1, 2, 3]),
new List { 1, 2, 3 },
new[] { 'a', 'b', 'c' },
new ReadOnlyMemory([1, 2, 3]),
};
[Theory]
[MemberData(nameof(ByteAndCharSequences))]
public async Task Batch_ByteOrCharSequenceBody_IsNotExpandedIntoItems(object body)
{
var exchange = new Exchange(new Message(body));
exchange.In.Headers["val"] = "h";
var thrown = await ProduceAsync(exchange);
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "h" }, $"a {body.GetType().Name} is one value like a byte[], not a list of batch items");
}
// ── Bodies that are batch sources ───────────────────────────────────────
[Fact]
public async Task Source_EnumerableNotList_IsBatched()
{
var body = Enumerable.Range(1, 3).Select(i => new Dictionary { ["val"] = "v" + i });
var thrown = await ProduceAsync(new Exchange(new Message(body)));
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "v1", "v2", "v3" }, "a lazy sequence is a batch source like a list");
}
[Fact]
public async Task Source_AsyncEnumerableOfReferenceType_IsBatched()
{
var source = new CountingAsyncSource>(
[new() { ["val"] = "a" }, new() { ["val"] = "b" }, new() { ["val"] = "c" }]);
var thrown = await ProduceAsync(new Exchange(new Message(source)));
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "a", "b", "c" });
source.Disposed.Should().BeTrue("the connector disposes the enumerator it opened");
}
[Fact]
public async Task Source_JsonElementArray_IsBatched()
{
using var document = JsonDocument.Parse("""[{"val":"a"},{"val":"b"}]""");
var thrown = await ProduceAsync(new Exchange(new Message(document.RootElement.Clone())));
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "a", "b" }, "unmarshalling a JSON array to object gives a JsonElement array");
}
[Fact]
public async Task Source_JsonDocumentArray_IsBatched()
{
using var document = JsonDocument.Parse("""[{"val":"a"},{"val":"b"}]""");
var thrown = await ProduceAsync(new Exchange(new Message(document)));
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "a", "b" });
}
[Fact]
public async Task Source_JsonArray_IsBatched()
{
var array = JsonNode.Parse("""[{"val":"a"},{"val":"b"}]""")!.AsArray();
var thrown = await ProduceAsync(new Exchange(new Message(array)));
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "a", "b" });
}
// ── Bodies that stay a single statement ────────────────────────────────
[Fact]
public async Task Source_AsyncEnumerableOfValueType_UsesSingleStatementPath()
{
var source = new CountingAsyncSource([1, 2, 3]);
var exchange = new Exchange(new Message(source));
exchange.In.Headers["val"] = "h";
var thrown = await ProduceAsync(exchange);
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { "h" }, "IAsyncEnumerable is not IAsyncEnumerable: covariance needs reference types");
source.ItemsRead.Should().Be(0);
}
[Fact]
public async Task Source_StringDictionaryJsonObjectXmlDocument_NotBatched()
{
var xml = new XmlDocument();
xml.LoadXml("|
|
");
var bodies = new object[]
{
"text",
new Dictionary { ["val"] = "dictionary" },
JsonNode.Parse("""{"val":"json-object"}""")!.AsObject(),
xml,
};
foreach (var body in bodies)
{
var exchange = new Exchange(new Message(body));
exchange.In.Headers.TryAdd("val", "header");
if (body is IDictionary or JsonObject)
exchange.In.Headers.Remove("val");
var thrown = await ProduceAsync(exchange);
thrown.Should().BeNull($"{body.GetType().Name}: {Outcome.Describe(thrown)}");
}
Values().Should().Equal(new object?[] { "header", "dictionary", "json-object", "header" },
"a string, a map and an XML document are each one value: one statement per body");
}
// ── Streaming ───────────────────────────────────────────────────────────
[Fact]
public async Task Stream_EmptyAsyncSource_OpensNoConnection()
{
var connection = new FakeBatchConnection();
var factory = new FixedConnectionFactory(connection);
var exchange = new Exchange(new Message(new CountingAsyncSource>([])));
var thrown = await ProduceOnFakeAsync(factory, exchange, batchSize: 10);
thrown.Should().BeNull(Outcome.Describe(thrown));
factory.Requests.Should().Be(0, "an empty stream writes nothing, so no connection is opened");
exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(0);
}
[Fact]
public async Task Stream_DbBatch_ReadsAtMostOneChunkAheadOfWrites()
{
var source = new CountingAsyncSource>(Items(10));
var readAtEachRoundTrip = new List();
var connection = new FakeBatchConnection
{
SupportsBatch = true,
OnExecuteBatch = (_, batch) =>
{
readAtEachRoundTrip.Add(source.ItemsRead);
return batch.BatchCommands.Count;
},
};
var thrown = await ProduceOnFakeAsync(new FixedConnectionFactory(connection), new Exchange(new Message(source)), batchSize: 3);
thrown.Should().BeNull(Outcome.Describe(thrown));
readAtEachRoundTrip.Should().Equal(new[] { 3, 6, 9, 10 }, "a chunk is read, then written, before the next one is read");
}
[Fact]
public async Task Stream_Commands_ReadsOneItemAheadOfWrites()
{
var source = new CountingAsyncSource>(Items(4));
var readAtEachStatement = new List();
var connection = new FakeBatchConnection
{
OnExecute = (_, _) =>
{
readAtEachStatement.Add(source.ItemsRead);
return 1;
},
};
var thrown = await ProduceOnFakeAsync(new FixedConnectionFactory(connection), new Exchange(new Message(source)), batchSize: 3);
thrown.Should().BeNull(Outcome.Describe(thrown));
readAtEachStatement.Should().Equal(1, 2, 3, 4);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Stream_SourceThrows_RollsBackAndRethrowsSourceException(bool breakOnError)
{
var source = new CountingAsyncSource>(Items(10), failAfter: 4);
var connection = new FakeBatchConnection { Savepoints = SavepointBehavior.Works };
var exchange = new Exchange(new Message(source));
var thrown = await ProduceOnFakeAsync(new FixedConnectionFactory(connection), exchange, batchSize: 3, breakOnError);
thrown.Should().BeOfType("the source's own failure ends the batch in either mode");
thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(4, "four items were read before the source failed");
connection.Transaction!.Committed.Should().BeFalse();
connection.Transaction.RolledBack.Should().BeTrue();
source.Disposed.Should().BeTrue();
}
[Fact]
public async Task Stream_SourceThrowsAfterCancellation_IsNotReportedAsASourceFailure()
{
using var cts = new CancellationTokenSource();
// A streamed source whose driver answers the stop with its own exception (SQL Server: "Operation cancelled by user").
var source = new CancelThenThrowSource(cts);
var connection = new FakeBatchConnection();
var exchange = new Exchange(new Message(source));
var thrown = await ProduceOnFakeAsync(new FixedConnectionFactory(connection), exchange, batchSize: 3, ct: cts.Token);
thrown.Should().BeOfType(Outcome.Describe(thrown));
thrown!.Data.Contains(SqlHeaders.BatchFailedIndex).Should().BeFalse("under a cancellation the writers do not report an item, and neither does the source");
exchange.In.Headers.Should().NotContainKey(SqlHeaders.BatchFailedIndex);
connection.Transaction!.RolledBack.Should().BeTrue();
}
/// Yields one item; on the next read cancels the token and throws as a driver would.
private sealed class CancelThenThrowSource(CancellationTokenSource cts) : IAsyncEnumerable>
{
public IAsyncEnumerator> GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
new Enumerator(cts);
private sealed class Enumerator(CancellationTokenSource cts) : IAsyncEnumerator>
{
private int _reads;
public Dictionary Current { get; } = new() { ["val"] = "v0" };
public ValueTask MoveNextAsync()
{
if (_reads++ == 0)
return ValueTask.FromResult(true);
cts.Cancel();
throw new FakeSourceException("fake: the source was interrupted by the stop");
}
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
[Fact]
public async Task Stream_Cancellation_DisposesEnumerator()
{
using var cts = new CancellationTokenSource();
var source = new CountingAsyncSource>(Items(10));
var connection = new FakeBatchConnection
{
OnExecute = (index, _) =>
{
if (index == 1)
{
cts.Cancel();
throw new OperationCanceledException(cts.Token);
}
return 1;
},
};
var thrown = await ProduceOnFakeAsync(new FixedConnectionFactory(connection), new Exchange(new Message(source)),
batchSize: 3, ct: cts.Token);
thrown.Should().BeAssignableTo(Outcome.Describe(thrown));
source.Disposed.Should().BeTrue("the enumerator is released when the batch is cancelled");
}
// ── Helpers ─────────────────────────────────────────────────────────────
private static List> Items(int count) =>
Enumerable.Range(0, count).Select(i => new Dictionary { ["val"] = "v" + i }).ToList();
private async Task ProduceAsync(Exchange exchange)
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), Insert, new()
{
["outputType"] = "None",
["batchSize"] = "10",
});
return await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
}
private static async Task ProduceOnFakeAsync(
FixedConnectionFactory factory, Exchange exchange, int batchSize, bool breakOnError = true, CancellationToken ct = default)
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, Insert, new()
{
["outputType"] = "None",
["batchSize"] = batchSize.ToString(),
["breakBatchOnError"] = breakOnError ? "true" : "false",
});
return await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, ct));
}
private List Values() => _db.Query("SELECT val FROM source_log ORDER BY rowid").Select(r => r["val"]).ToList();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchStrategyTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchStrategyTests.cs
----
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.Batch.Fakes;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// How a batch goes over the wire. Breaking on the first error on a connection that can create a DbBatch : chunks of
/// batchSize statements, one round trip each. Otherwise one command whose parameters are reused for every item. There
/// is no option to choose: as in Apache Camel, the driver's capability decides.
///
public sealed class BatchStrategyTests
{
private const string Insert = "INSERT INTO t (id) VALUES (:#id)";
[Fact]
public async Task DbBatch_ChunksByBatchSize()
{
var sentIds = new List();
var connection = new FakeBatchConnection
{
SupportsBatch = true,
OnExecuteBatch = (_, batch) =>
{
sentIds.AddRange(batch.BatchCommands.Select(c => c.Parameters["id"].Value));
return batch.BatchCommands.Count;
},
};
var (exchange, thrown) = await RunAsync(connection, Items(10), batchSize: 3);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.BatchSizes.Should().Equal(new[] { 3, 3, 3, 1 }, "batchSize is the number of statements in one round trip");
connection.Executions.Should().Be(0, "no item runs as a command of its own");
sentIds.Should().Equal(Enumerable.Range(0, 10).Cast(), "every item keeps its own values, in order");
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("DbBatch");
exchange.In.Headers["redbSql.batchChunkCount"].Should().Be(4);
exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(10);
connection.Transaction!.Committed.Should().BeTrue("all chunks share one transaction");
}
[Fact]
public async Task DbBatch_FailedCommand_MapsToItemIndex()
{
var connection = new FakeBatchConnection
{
SupportsBatch = true,
OnExecuteBatch = (index, batch) => index == 1
? throw new FakeDbException("duplicate key", batch.BatchCommands[1])
: batch.BatchCommands.Count,
};
var (exchange, thrown) = await RunAsync(connection, Items(10), batchSize: 3);
thrown.Should().BeOfType(Outcome.Describe(thrown));
thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(4, "the second command of the second chunk is item 4");
exchange.In.Headers[SqlHeaders.BatchFailedIndex].Should().Be(4);
connection.BatchSizes.Should().Equal(new[] { 3, 3 }, "nothing is sent after the failed chunk");
connection.Transaction!.RolledBack.Should().BeTrue();
}
[Fact]
public async Task DbBatch_ProviderWithoutBatchCommand_ReportsChunkStartAndRange()
{
var connection = new FakeBatchConnection
{
SupportsBatch = true,
OnExecuteBatch = (index, batch) => index == 1 ? throw new FakeDbException("failed") : batch.BatchCommands.Count,
};
var (_, thrown) = await RunAsync(connection, Items(10), batchSize: 3);
thrown.Should().BeOfType(Outcome.Describe(thrown));
thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(3, "without the failed command only the chunk is known: its first item");
thrown.Data["redbSql.batchFailedChunk"].Should().Be("3..5");
}
[Fact]
public async Task DbBatch_UsesBatchCommandCreateParameter_WhenAvailable()
{
var connection = new FakeBatchConnection { SupportsBatch = true, BatchCommandsCanCreateParameter = true };
var (_, thrown) = await RunAsync(connection, Items(4), batchSize: 10);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.BatchParametersCreated.Should().Be(4);
connection.CommandsCreated.Should().Be(0);
connection.BatchSizes.Should().Equal(4);
}
[Fact]
public async Task DbBatch_BatchCommandCannotCreateParameter_OneCommandMakesThem()
{
var connection = new FakeBatchConnection { SupportsBatch = true, BatchCommandsCanCreateParameter = false };
var (_, thrown) = await RunAsync(connection, Items(4), batchSize: 10);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.BatchParametersCreated.Should().Be(0);
connection.CommandsCreated.Should().Be(1, "one command serves as the parameter factory for the whole batch");
connection.Executions.Should().Be(0);
connection.BatchSizes.Should().Equal(4);
}
[Fact]
public async Task Commands_OneCommandAndParameterSetForWholeBatch()
{
var connection = new FakeBatchConnection();
var (exchange, thrown) = await RunAsync(connection, Items(5), batchSize: 10);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.CommandsCreated.Should().Be(1, "the statement is parsed once and its parameters reused for every item");
connection.Executions.Should().Be(5);
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("Commands");
exchange.In.Headers.Should().NotContainKey("redbSql.batchChunkCount");
}
[Fact]
public async Task Savepoints_OneCommandForWholeBatch()
{
var connection = new FakeBatchConnection { Savepoints = SavepointBehavior.Works };
var (exchange, thrown) = await RunAsync(connection, Items(3), batchSize: 10, breakOnError: false);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.CommandsCreated.Should().Be(1);
connection.Executions.Should().Be(3);
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("Savepoints");
}
[Fact]
public async Task Strategy_Continue_AlwaysSavepoints_EvenWhenBatchCapable()
{
var connection = new FakeBatchConnection { SupportsBatch = true, Savepoints = SavepointBehavior.Works };
var (exchange, thrown) = await RunAsync(connection, Items(3), batchSize: 10, breakOnError: false);
thrown.Should().BeNull(Outcome.Describe(thrown));
connection.BatchSizes.Should().BeEmpty("a DbBatch cannot go on past a failed command");
connection.Executions.Should().Be(3);
exchange.In.Headers["redbSql.batchStrategy"].Should().Be("Savepoints");
}
private static List> Items(int count) =>
Enumerable.Range(0, count).Select(i => new Dictionary { ["id"] = i }).ToList();
private static async Task<(Exchange Exchange, Exception? Thrown)> RunAsync(
FakeBatchConnection connection, List> items, int batchSize, bool breakOnError = true)
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), Insert, new()
{
["outputType"] = "None",
["batchSize"] = batchSize.ToString(),
["breakBatchOnError"] = breakOnError ? "true" : "false",
});
var exchange = new Exchange(new Message(items));
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
return (exchange, thrown);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/BatchStrictBindingTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/BatchStrictBindingTests.cs
----
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.Batch;
///
/// A placeholder with no value anywhere is an error, as in Apache Camel ("Cannot find key ... to use when setting named
/// parameter"); a key that is present with a null value binds NULL.
///
public sealed class BatchStrictBindingTests : IDisposable
{
private const string Insert = "INSERT INTO strict_items (id, val) VALUES (:#id, :#val)";
private readonly SqliteTestHelper _db = new();
public BatchStrictBindingTests() => _db.Execute("CREATE TABLE strict_items (id INTEGER NOT NULL, val TEXT NULL)");
public void Dispose() => _db.Dispose();
[Fact]
public async Task Batch_MissingKey_BreakMode_FailsWithItemIndexAndParameterName()
{
var carrier = Carrier(new Dictionary { ["id"] = 1, ["val"] = "a" }, new Dictionary { ["id"] = 2 });
var thrown = await RunAsync(carrier, breakOnError: true);
thrown.Should().BeOfType(Outcome.Describe(thrown));
thrown!.Message.Should().Contain("item 1").And.Contain(":#val");
thrown.Data[SqlHeaders.BatchFailedIndex].Should().Be(1);
Ids().Should().BeEmpty("the batch breaks on that item and rolls back");
}
[Fact]
public async Task Batch_MissingKey_ContinueMode_ReportedAsItemError()
{
var carrier = Carrier(new Dictionary { ["id"] = 1, ["val"] = "a" }, new Dictionary { ["id"] = 2 }, new Dictionary { ["id"] = 3, ["val"] = "c" });
var thrown = await RunAsync(carrier, breakOnError: false);
thrown.Should().BeNull(Outcome.Describe(thrown));
Ids().Should().Equal(new object?[] { 1L, 3L }, "the item without a value is skipped, the others commit");
carrier.In.Headers.Should().ContainKey(SqlHeaders.BatchErrors);
var errors = carrier.In.Headers[SqlHeaders.BatchErrors].Should().BeAssignableTo>().Subject;
errors.Should().ContainSingle().Which.Index.Should().Be(1);
errors[0].Message.Should().Contain(":#val");
}
[Fact]
public async Task Batch_KeyWithNullValue_BindsNull()
{
var carrier = Carrier(new Dictionary { ["id"] = 1, ["val"] = null });
var thrown = await RunAsync(carrier);
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { null }, "a key that is present binds its value, null included");
}
[Fact]
public async Task Batch_ExplicitTemplateEvaluatingToNull_BindsNull()
{
var carrier = Carrier(new Dictionary { ["id"] = 1 });
var thrown = await RunAsync(carrier, options: new() { ["param.val"] = "${header.missing}" });
thrown.Should().BeNull(Outcome.Describe(thrown));
Values().Should().Equal(new object?[] { null }, "an explicit param.* always has a value, even when it evaluates to null");
}
[Fact]
public async Task Batch_ScalarItems_AllNamesResolvedElsewhere_Bind()
{
var carrier = new Exchange(new Message(new List { 1, 2 }));
carrier.In.Headers["val"] = "h";
var thrown = await RunAsync(carrier, options: new() { ["param.id"] = "${body}" });
thrown.Should().BeNull(Outcome.Describe(thrown));
Ids().Should().Equal(new object?[] { 1L, 2L });
Values().Should().Equal(new object?[] { "h", "h" }, "a scalar item carries no names, the header still provides one");
}
private static Exchange Carrier(params Dictionary[] items) => new(new Message(items.ToList()));
private async Task RunAsync(Exchange carrier, bool? breakOnError = null, Dictionary? options = null)
{
var parameters = new Dictionary { ["outputType"] = "None", ["batchSize"] = "10" };
if (breakOnError is { } mode)
parameters["breakBatchOnError"] = mode ? "true" : "false";
if (options is not null)
foreach (var (key, value) in options)
parameters[key] = value;
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), Insert, parameters);
return await Outcome.Of(() => endpoint.CreateProducer().Process(carrier, CancellationToken.None));
}
private List Ids() => _db.Query("SELECT id FROM strict_items ORDER BY id").Select(r => r["id"]).ToList();
private List Values() => _db.Query("SELECT val FROM strict_items ORDER BY id").Select(r => r["val"]).ToList();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/CountingAsyncSource.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/CountingAsyncSource.cs
----
namespace redb.Route.Tests.Sql.Batch.Fakes;
///
/// An asynchronous batch source that counts what the connector read from it, can fail after a given number of items, and
/// records whether its enumerator was disposed.
///
internal sealed class CountingAsyncSource : IAsyncEnumerable
{
private readonly IReadOnlyList _items;
private readonly int? _failAfter;
public CountingAsyncSource(IReadOnlyList items, int? failAfter = null)
{
_items = items;
_failAfter = failAfter;
}
/// Items handed out so far.
public int ItemsRead { get; private set; }
/// The enumerator was disposed.
public bool Disposed { get; private set; }
public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
new Enumerator(this, cancellationToken);
private sealed class Enumerator(CountingAsyncSource source, CancellationToken ct) : IAsyncEnumerator
{
private int _index = -1;
public T Current => source._items[_index];
public ValueTask MoveNextAsync()
{
ct.ThrowIfCancellationRequested();
if (source._failAfter is { } failAfter && _index + 1 == failAfter)
throw new FakeSourceException($"fake: the source failed after {failAfter} items");
if (_index + 1 >= source._items.Count)
return ValueTask.FromResult(false);
_index++;
source.ItemsRead++;
return ValueTask.FromResult(true);
}
public ValueTask DisposeAsync()
{
source.Disposed = true;
return ValueTask.CompletedTask;
}
}
}
/// A failure of the batch source itself, not of an item's statement.
internal sealed class FakeSourceException(string message) : Exception(message);
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/CountingExchange.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/CountingExchange.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Tests.Sql.Batch.Fakes;
/// An exchange that delegates to a real one and counts the linked children created from it.
internal sealed class CountingExchange(Exchange inner) : IExchange
{
/// Calls of .
public int LinkedChildren { get; private set; }
public IMessage In { get => inner.In; set => inner.In = value; }
public IMessage? Out { get => inner.Out; set => inner.Out = value; }
public ExchangePattern Pattern { get => inner.Pattern; set => inner.Pattern = value; }
public IDictionary Properties => inner.Properties;
public Exception? Exception { get => inner.Exception; set => inner.Exception = value; }
public bool ExceptionHandled { get => inner.ExceptionHandled; set => inner.ExceptionHandled = value; }
public string? RouteId { get => inner.RouteId; set => inner.RouteId = value; }
public IRouteContext? Context => ((IExchange)inner).Context;
public IServiceProvider? ServiceProvider => ((IExchange)inner).ServiceProvider;
public string ExchangeId => inner.ExchangeId;
public bool IsStopped => inner.IsStopped;
public T? GetProperty(string key) => inner.GetProperty(key);
public void Stop() => inner.Stop();
public IExchange Clone() => inner.Clone();
public IExchange Snapshot() => inner.Snapshot();
public IExchange CreateLinkedChild(IMessage message)
{
LinkedChildren++;
return inner.CreateLinkedChild(message);
}
public ValueTask DisposeAsync() => ((IAsyncDisposable)inner).DisposeAsync();
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchCommand.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchCommand.cs
----
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Data.Sqlite;
namespace redb.Route.Tests.Sql.Batch.Fakes;
///
/// Command of : executions go to the connection's script. Parameters live in a real
/// SQLite parameter collection, so the connector's binding code runs unchanged.
///
internal sealed class FakeBatchCommand : DbCommand
{
private readonly FakeBatchConnection _connection;
private readonly SqliteCommand _parameterHost = new();
private string _commandText = "";
public FakeBatchCommand(FakeBatchConnection connection)
{
_connection = connection;
DbConnection = connection;
}
[AllowNull]
public override string CommandText
{
get => _commandText;
set => _commandText = value ?? "";
}
public override int CommandTimeout { get; set; }
public override CommandType CommandType { get; set; }
public override bool DesignTimeVisible { get; set; }
public override UpdateRowSource UpdatedRowSource { get; set; }
protected override DbConnection? DbConnection { get; set; }
protected override DbParameterCollection DbParameterCollection => _parameterHost.Parameters;
protected override DbTransaction? DbTransaction { get; set; }
public override void Cancel() { }
public override void Prepare() { }
public override int ExecuteNonQuery() => _connection.Execute(CommandText, CancellationToken.None);
public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken)
{
try
{
return Task.FromResult(_connection.Execute(CommandText, cancellationToken));
}
catch (Exception ex)
{
// Surface the scripted failure the way an async provider does: through the task.
return Task.FromException(ex);
}
}
public override object? ExecuteScalar() => _connection.Execute(CommandText, CancellationToken.None);
protected override DbParameter CreateDbParameter() => new SqliteParameter();
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) =>
throw new NotSupportedException("The fake batch connection only executes non-queries.");
protected override void Dispose(bool disposing)
{
if (disposing)
_parameterHost.Dispose();
base.Dispose(disposing);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchConnection.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchConnection.cs
----
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
namespace redb.Route.Tests.Sql.Batch.Fakes;
///
/// A connection whose command executions are scripted per execution index, and which counts what the connector
/// asks of it. Lets batch algorithms be tested at the exact point where a real provider would fail or be cancelled.
///
internal sealed class FakeBatchConnection : DbConnection
{
private string _connectionString = "";
private int _executions;
/// Called for every execution with its zero-based index; returns rows affected or throws.
public Func? OnExecute { get; init; }
/// How the connection's transactions answer savepoint calls.
public SavepointBehavior Savepoints { get; init; } = SavepointBehavior.Unsupported;
/// Rolling back a transaction of this connection throws.
public bool FailRollback { get; init; }
/// The connection was disposed.
public bool IsDisposed { get; private set; }
/// Commands created through .
public int CommandsCreated { get; private set; }
/// Statements executed, successful or not.
public int Executions => _executions;
/// The last transaction begun on this connection.
public FakeBatchTransaction? Transaction { get; private set; }
/// The connection can create a ( ).
public bool SupportsBatch { get; init; }
/// Batch commands create their own parameters ( ).
public bool BatchCommandsCanCreateParameter { get; init; } = true;
/// Called for every batch execution with its zero-based index and the batch; returns rows affected or throws.
public Func? OnExecuteBatch { get; init; }
/// Number of commands in each executed batch, in order.
public List BatchSizes { get; } = [];
/// Parameters created through .
public int BatchParametersCreated { get; internal set; }
public override bool CanCreateBatch => SupportsBatch;
protected override DbBatch CreateDbBatch() =>
SupportsBatch ? new FakeDbBatch(this) : throw new NotSupportedException("fake: this connection has no DbBatch");
internal int ExecuteBatch(FakeDbBatch batch, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var index = BatchSizes.Count;
BatchSizes.Add(batch.BatchCommands.Count);
return OnExecuteBatch?.Invoke(index, batch) ?? batch.BatchCommands.Count;
}
///
/// Called for every batch executed for its rows, with its zero-based index and the batch; returns a reader over one
/// result set per command, or throws.
///
public Func? OnExecuteBatchReader { get; init; }
internal DbDataReader ExecuteBatchReader(FakeDbBatch batch, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var index = BatchSizes.Count;
BatchSizes.Add(batch.BatchCommands.Count);
return OnExecuteBatchReader?.Invoke(index, batch)
?? throw new NotSupportedException("fake: no OnExecuteBatchReader script for a batch executed for its rows");
}
[AllowNull]
public override string ConnectionString
{
get => _connectionString;
set => _connectionString = value ?? "";
}
public override string Database => "fake";
public override string DataSource => "fake";
public override string ServerVersion => "0";
public override ConnectionState State => ConnectionState.Open;
public override void ChangeDatabase(string databaseName) { }
public override void Close() { }
public override void Open() { }
/// The text of every command execution, in order.
public List ExecutedCommandTexts { get; } = [];
internal int Execute(string commandText, CancellationToken ct)
{
ExecutedCommandTexts.Add(commandText);
var index = _executions++;
return OnExecute?.Invoke(index, ct) ?? 1;
}
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) =>
Transaction = new FakeBatchTransaction(this, isolationLevel);
protected override DbCommand CreateDbCommand()
{
CommandsCreated++;
return new FakeBatchCommand(this);
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchTransaction.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeBatchTransaction.cs
----
using System.Data;
using System.Data.Common;
namespace redb.Route.Tests.Sql.Batch.Fakes;
///
/// Transaction of ; records how it ended and every savepoint call. Like SqlClient it
/// never claims ; whether savepoints work is set on the connection.
///
internal sealed class FakeBatchTransaction(FakeBatchConnection connection, IsolationLevel isolationLevel) : DbTransaction
{
public bool Committed { get; private set; }
public bool RolledBack { get; private set; }
public bool IsDisposed { get; private set; }
/// Savepoint calls in order: save:name , release:name , rollback:name .
public List SavepointLog { get; } = [];
public override IsolationLevel IsolationLevel => isolationLevel;
protected override DbConnection DbConnection => connection;
public override void Commit() => Committed = true;
public override void Rollback()
{
if (connection.FailRollback)
throw new InvalidOperationException("fake: rollback failed, the server already ended the transaction");
RolledBack = true;
}
public override void Save(string savepointName)
{
if (connection.Savepoints == SavepointBehavior.Unsupported)
throw new NotSupportedException("fake: this provider has no savepoints");
SavepointLog.Add("save:" + savepointName);
}
public override void Release(string savepointName)
{
if (connection.Savepoints == SavepointBehavior.Unsupported)
throw new NotSupportedException("fake: this provider has no savepoints");
SavepointLog.Add("release:" + savepointName);
}
public override void Rollback(string savepointName)
{
switch (connection.Savepoints)
{
case SavepointBehavior.Unsupported:
throw new NotSupportedException("fake: this provider has no savepoints");
case SavepointBehavior.RollbackToSavepointFails:
SavepointLog.Add("rollback-failed:" + savepointName);
throw new InvalidOperationException("fake: the server transaction has already ended");
default:
SavepointLog.Add("rollback:" + savepointName);
break;
}
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeDbBatch.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeDbBatch.cs
----
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Data.Sqlite;
namespace redb.Route.Tests.Sql.Batch.Fakes;
///
/// of : one execution is one round trip, handed to the connection's
/// batch script with the commands it carries.
///
internal sealed class FakeDbBatch(FakeBatchConnection connection) : DbBatch
{
private readonly FakeDbBatchCommandCollection _commands = new();
public override int Timeout { get; set; }
protected override DbBatchCommandCollection DbBatchCommands => _commands;
protected override DbConnection? DbConnection { get; set; } = connection;
protected override DbTransaction? DbTransaction { get; set; }
public override int ExecuteNonQuery() => connection.ExecuteBatch(this, CancellationToken.None);
public override Task ExecuteNonQueryAsync(CancellationToken cancellationToken = default)
{
try
{
return Task.FromResult(connection.ExecuteBatch(this, cancellationToken));
}
catch (Exception ex)
{
// Surface the scripted failure the way an async provider does: through the task.
return Task.FromException(ex);
}
}
public override object? ExecuteScalar() => throw new NotSupportedException("The fake batch only executes non-queries.");
public override Task ExecuteScalarAsync(CancellationToken cancellationToken = default) =>
throw new NotSupportedException("The fake batch only executes non-queries.");
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) =>
connection.ExecuteBatchReader(this, CancellationToken.None);
protected override Task ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
{
try
{
return Task.FromResult(connection.ExecuteBatchReader(this, cancellationToken));
}
catch (Exception ex)
{
// Surface the scripted failure the way an async provider does: through the task.
return Task.FromException(ex);
}
}
public override void Prepare() { }
public override Task PrepareAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public override void Cancel() { }
protected override DbBatchCommand CreateDbBatchCommand() => new FakeDbBatchCommand(connection);
}
/// Command of ; parameters live in a real SQLite collection.
internal sealed class FakeDbBatchCommand(FakeBatchConnection connection) : DbBatchCommand
{
private readonly SqliteCommand _parameterHost = new();
private string _commandText = "";
[AllowNull]
public override string CommandText
{
get => _commandText;
set => _commandText = value ?? "";
}
public override CommandType CommandType { get; set; }
public override int RecordsAffected => 1;
protected override DbParameterCollection DbParameterCollection => _parameterHost.Parameters;
public override bool CanCreateParameter => connection.BatchCommandsCanCreateParameter;
public override DbParameter CreateParameter()
{
connection.BatchParametersCreated++;
return new SqliteParameter();
}
}
/// Plain list of batch commands.
internal sealed class FakeDbBatchCommandCollection : DbBatchCommandCollection
{
private readonly List _commands = [];
public override int Count => _commands.Count;
public override bool IsReadOnly => false;
public override void Add(DbBatchCommand item) => _commands.Add(item);
public override void Clear() => _commands.Clear();
public override bool Contains(DbBatchCommand item) => _commands.Contains(item);
public override void CopyTo(DbBatchCommand[] array, int arrayIndex) => _commands.CopyTo(array, arrayIndex);
public override IEnumerator GetEnumerator() => _commands.GetEnumerator();
public override int IndexOf(DbBatchCommand item) => _commands.IndexOf(item);
public override void Insert(int index, DbBatchCommand item) => _commands.Insert(index, item);
public override bool Remove(DbBatchCommand item) => _commands.Remove(item);
public override void RemoveAt(int index) => _commands.RemoveAt(index);
protected override DbBatchCommand GetBatchCommand(int index) => _commands[index];
protected override void SetBatchCommand(int index, DbBatchCommand batchCommand) => _commands[index] = batchCommand;
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeDbException.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FakeDbException.cs
----
using System.Data.Common;
namespace redb.Route.Tests.Sql.Batch.Fakes;
/// A provider error raised by the fake connection's script; may name the batch command that failed.
internal sealed class FakeDbException(string message, DbBatchCommand? batchCommand = null) : DbException(message)
{
protected override DbBatchCommand? DbBatchCommand => batchCommand;
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FixedConnectionFactory.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/FixedConnectionFactory.cs
----
using System.Data.Common;
using redb.Route.Sql.Connection;
namespace redb.Route.Tests.Sql.Batch.Fakes;
/// Hands out one prepared connection instance and counts the requests.
internal sealed class FixedConnectionFactory(DbConnection connection) : ISqlConnectionFactory
{
/// How many times a connection was requested.
public int Requests { get; private set; }
public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default)
{
Requests++;
return Task.FromResult(connection);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/SavepointBehavior.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/Fakes/SavepointBehavior.cs
----
namespace redb.Route.Tests.Sql.Batch.Fakes;
/// How the fake transaction answers savepoint calls.
internal enum SavepointBehavior
{
/// The base behaviour: Save throws .
Unsupported,
/// Save, release and rollback-to-savepoint succeed.
Works,
/// Save succeeds; rolling back to the savepoint fails — the server already ended the transaction.
RollbackToSavepointFails,
}
Path: redb-route/tests/redb.Route.Tests.Sql/Batch/SqlParameterPlanTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/Batch/SqlParameterPlanTests.cs
----
using redb.Route.Sql;
namespace redb.Route.Tests.Sql.Batch;
/// The parameter plan of a statement: its :#name placeholders, the explicit values they use, and the text sent to the provider.
public sealed class SqlParameterPlanTests
{
[Fact]
public void Plan_NamesAndExplicitParams_Classified()
{
var plan = SqlParameterPlan.Create("INSERT INTO t (a, b, c) VALUES (:#a, :#b, :#c)",
new Dictionary(StringComparer.OrdinalIgnoreCase)
{
["a"] = "constant",
["B"] = "${header.b}",
["unused"] = "x",
});
plan.Names.Should().Equal("a", "b", "c");
plan.HasExpressions.Should().BeTrue();
plan.TryGetExplicit("a", out var constant).Should().BeTrue();
constant.IsExpression.Should().BeFalse();
constant.Resolve(null).Should().Be("constant");
plan.TryGetExplicit("b", out var expression).Should().BeTrue("explicit names match placeholders ignoring case");
expression.IsExpression.Should().BeTrue();
plan.TryGetExplicit("c", out _).Should().BeFalse();
plan.TryGetExplicit("unused", out _).Should().BeFalse("a param.* the statement does not use is not part of the plan");
}
[Fact]
public void Plan_RepeatedNameInAnotherCase_IsOneParameterInTheTextToo()
{
var plan = SqlParameterPlan.Create("UPDATE t SET a = :#Id WHERE id = :#id",
new Dictionary(StringComparer.OrdinalIgnoreCase));
plan.Names.Should().Equal("Id");
plan.Slots.Should().Equal(0);
plan.Sql.Should().Be("UPDATE t SET a = @Id WHERE id = @Id",
"a provider that binds names case-sensitively (SQLite) must see the one name the parameter has");
}
[Fact]
public void Plan_TextForTheProvider_UsesItsOwnPlaceholders()
{
var plan = SqlParameterPlan.Create("UPDATE t SET a = :#a, note = ':#a' WHERE id = @id",
new Dictionary(StringComparer.OrdinalIgnoreCase));
plan.Sql.Should().Be("UPDATE t SET a = @a, note = ':#a' WHERE id = @id",
"only the placeholder is rewritten; a literal and the database's own @id stay as written");
plan.Names.Should().Equal("a");
}
[Theory]
[InlineData(SqlPlaceholderStyle.At, "a = @x OR b = @y OR c = @x", new[] { 0, 1 })]
[InlineData(SqlPlaceholderStyle.Colon, "a = :x OR b = :y OR c = :x", new[] { 0, 1, 0 })]
[InlineData(SqlPlaceholderStyle.Question, "a = ? OR b = ? OR c = ?", new[] { 0, 1, 0 })]
public void Plan_Style_TextAndOneParameterPerNameOrOccurrence(SqlPlaceholderStyle style, string expectedSql, int[] expectedSlots)
{
const string sql = "a = :#x OR b = :#y OR c = :#x";
var plan = SqlParameterPlan.Create(sql, new Dictionary(StringComparer.OrdinalIgnoreCase), style);
plan.SourceSql.Should().Be(sql);
plan.Sql.Should().Be(expectedSql);
plan.Names.Should().Equal("x", "y");
plan.Slots.Should().Equal(expectedSlots, "@name binds by name; :name and ? take a parameter for every occurrence");
}
[Fact]
public void Plan_ConstantsOnly_HasNoExpressions_AndEmptyConstantIsNull()
{
var plan = SqlParameterPlan.Create("UPDATE t SET a = :#a",
new Dictionary(StringComparer.OrdinalIgnoreCase) { ["a"] = "" });
plan.HasExpressions.Should().BeFalse();
plan.TryGetExplicit("a", out var empty).Should().BeTrue();
empty.Resolve(null).Should().Be(DBNull.Value);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/ColumnNameMatcherTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/ColumnNameMatcherTests.cs
----
using System.ComponentModel.DataAnnotations.Schema;
using redb.Route.Sql.Mapping;
namespace redb.Route.Tests.Sql;
///
/// The name rule shared by row mapping and batch item binding, pinned as a grid: the rule moved out of
/// unchanged.
///
public sealed class ColumnNameMatcherTests
{
[Theory]
[InlineData("UserId", "UserId")]
[InlineData("userid", "UserId")]
[InlineData("USERID", "UserId")]
[InlineData("user_id", "UserId")]
[InlineData("full_name", "Name")]
[InlineData("FULL_NAME", "Name")]
[InlineData("name", "Name")]
[InlineData("email", "Email")]
[InlineData("email_raw", "email_raw")]
[InlineData("missing", null)]
[InlineData("_", null)]
public void ColumnNameMatcher_SameRuleAsRowMapping(string name, string? expected)
{
var found = ColumnNameMatcher.Find(typeof(Target).GetProperties(), name);
(found?.Name).Should().Be(expected);
}
private sealed class Target
{
public int UserId { get; set; }
[Column("full_name")]
public string? Name { get; set; }
public string? Email { get; set; }
// ReSharper disable once InconsistentNaming — a property named like a column
public string? email_raw { get; set; }
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/AmbientTransactionBatchTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/AmbientTransactionBatchTestsBase.cs
----
using System.Transactions;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The batch inside a route-level transaction (.Transacted() — an ambient ). There is no
/// local transaction to take savepoints on, so continuing past an error cannot be honest and is refused before any write.
/// Runs on providers that enlist in System.Transactions.
///
public abstract class AmbientTransactionBatchTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task BatchContinue_UnderTransactionScope_FailsBeforeFirstWrite()
{
Exception? thrown;
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
(_, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: false);
// A route completes its transaction when the pipeline did not fail.
if (thrown is null)
scope.Complete();
}
thrown.Should().BeOfType(
$"continue mode needs a local transaction with savepoints, but the batch threw {Outcome.Describe(thrown)}");
(await Db.ReadIdsAsync()).Should().BeEmpty("the refusal comes before anything is written");
}
[Fact]
public async Task BatchBreak_UnderTransactionScopeNotCompleted_LeavesNoRows()
{
var items = new List>
{
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 2, ["val"] = "b" },
new() { ["id"] = 3, ["val"] = "c" },
};
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
var (_, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), items, breakOnError: true);
thrown.Should().BeNull($"the batch itself succeeds ({Outcome.Describe(thrown)})");
// A step after the SQL endpoint fails: the route does not complete its transaction.
}
(await Db.ReadIdsAsync()).Should().BeEmpty("the batch wrote inside the route's transaction, which rolled back");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchBindingE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchBindingE2ETestsBase.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Aggregation;
using redb.Route.Core;
using redb.Route.DataFormats.Csv;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// Batch items in the shapes real routes produce — CSV rows, JSON objects, POCOs, aggregated exchanges — written to a real
/// database: every source record must arrive with its own values.
///
public abstract class BatchBindingE2ETestsBase : IAsyncLifetime
{
private const string EntryUri = "direct://batch-binding";
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task CsvWithHeader_ToBatch_AllRowsPersisted()
{
const string csv = "id,val,n\n1,a,10\n2,b,\n3,,30\n";
// CSV values are text, and PostgreSQL does not convert a text parameter to an integer column: the statement casts.
var sql = $"INSERT INTO {Db.Table} (id, val, n) VALUES (CAST(:#id AS int), :#val, CAST(:#n AS bigint))";
await RunRouteAsync(route => route.UnmarshalCsv>>().To(BatchUri(sql)), csv);
(await ReadRowsAsync()).Should().Equal("1|a|10", "2|b|", "3||30");
}
[Fact]
public async Task JsonArray_ToBatch_AllRowsPersisted()
{
const string json = """[{"id":1,"val":"a","n":10},{"id":2,"val":"b","n":null},{"id":3,"val":null,"n":9007199254740993}]""";
var sql = $"INSERT INTO {Db.Table} (id, val, n) VALUES (:#id, :#val, :#n)";
await RunRouteAsync(route => route.Unmarshal>>("application/json").To(BatchUri(sql)), json);
(await ReadRowsAsync()).Should().Equal("1|a|10", "2|b|", "3||9007199254740993");
}
[Fact]
public async Task JsonArrayUnmarshalledToObject_ToBatch_AllRowsPersisted()
{
const string json = """[{"id":1,"val":"a","n":10},{"id":2,"val":"b","n":null},{"id":3,"val":null,"n":30}]""";
var sql = $"INSERT INTO {Db.Table} (id, val, n) VALUES (:#id, :#val, :#n)";
// Unmarshal to object gives one JsonElement array: a batch source since 17.4 (decision 18).
await RunRouteAsync(route => route.Unmarshal("application/json").To(BatchUri(sql)), json);
(await ReadRowsAsync()).Should().Equal("1|a|10", "2|b|", "3||30");
}
[Fact]
public async Task PocoList_ToBatch_AllRowsPersisted()
{
var items = new List
{
new() { Id = 1, Val = "a", N = 10 },
new() { Id = 2, Val = "b" },
new() { Id = 3, N = 30 },
};
var (_, thrown) = await SqlBatchRun.RunAsync(Db, $"INSERT INTO {Db.Table} (id, val, n) VALUES (:#id, :#val, :#n)", items, breakOnError: null);
thrown.Should().BeNull(Outcome.Describe(thrown));
(await ReadRowsAsync()).Should().Equal("1|a|10", "2|b|", "3||30");
}
[Fact]
public async Task AggregateGroupedExchange_ParamsFromHeaders_ToBatch()
{
const int size = 50;
var sql = $"INSERT INTO {Db.Table} (id, val) VALUES (:#id, :#val)";
await using var context = CreateContext();
context.AddRoutes(r => r.From(EntryUri)
.Aggregate(_ => "all", AggregationStrategies.GroupedExchange(), agg => agg.In.Body is List { Count: >= size })
.To(BatchUri(sql, "¶m.val=${header.auditVal}"))
.EndAggregate());
await context.Start();
var producer = context.GetEndpoint(EntryUri).CreateProducer();
await producer.Start();
for (var i = 1; i <= size; i++)
{
var exchange = new Exchange(new Message($"event-{i}"));
exchange.In.Headers["id"] = i;
exchange.In.Headers["auditVal"] = $"v{i}";
await producer.Process(exchange);
}
var rows = await WaitForRowsAsync(size);
rows.Should().Equal(Enumerable.Range(1, size).Select(i => $"{i}|v{i}|"),
"every aggregated message is one item, bound from its own headers");
}
public sealed class BindingRow
{
public int Id { get; set; }
public string? Val { get; set; }
public long? N { get; set; }
}
// ── Helpers ─────────────────────────────────────────────────────────────
private static string BatchUri(string sql, string extra = "") =>
$"sql:{sql}?dataSource={SqlEndpointHarness.DataSourceName}&batchSize=500&outputType=None{extra}";
private RouteContext CreateContext()
{
var context = new RouteContext();
context.AddComponent(new SqlComponent());
context.AddToRegistry(SqlEndpointHarness.DataSourceName, Db.CreateConnectionFactory());
return context;
}
private async Task RunRouteAsync(Func build, object body)
{
await using var context = CreateContext();
context.AddRoutes(r => build(r.From(EntryUri)));
await context.Start();
var producer = context.GetEndpoint(EntryUri).CreateProducer();
await producer.Start();
await producer.Process(new Exchange(new Message(body)));
}
private async Task> ReadRowsAsync()
{
var rows = await Db.QueryAsync($"SELECT id, val, n FROM {Db.Table} ORDER BY id");
return rows.Select(r => $"{Convert.ToInt64(r[0])}|{r[1]}|{(r[2] is null ? "" : Convert.ToInt64(r[2]).ToString())}").ToList();
}
private async Task> WaitForRowsAsync(int count)
{
var stopwatch = Stopwatch.StartNew();
while (true)
{
var rows = await ReadRowsAsync();
if (rows.Count >= count || stopwatch.Elapsed > TimeSpan.FromSeconds(10))
return rows;
await Task.Delay(100);
}
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchEngineE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchEngineE2ETestsBase.cs
----
using System.Data.Common;
using System.Diagnostics;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The batch engine against a real database: large batches arrive whole, the strategy follows the driver's capability
/// (DbBatch where the connection can create one), a failure deep in the batch leaves nothing and names the item.
/// The large batch logs its time: a measurement for the wave report, not an assertion.
///
public abstract class BatchEngineE2ETestsBase(ITestOutputHelper output) : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
private string Insert => $"INSERT INTO {Db.Table} (id, val, n) VALUES (:#id, :#val, :#n)";
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task LargeBatch_AllPersisted_StrategyByDriverCapability()
{
const int count = 10_000;
var items = Enumerable.Range(1, count)
.Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i, ["n"] = (long)i })
.ToList();
var stopwatch = Stopwatch.StartNew();
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Insert, items, breakOnError: null, batchSize: 500);
stopwatch.Stop();
var strategy = exchange.In.Headers.TryGetValue(SqlHeaders.BatchStrategy, out var s) ? s : "none";
output.WriteLine($"[batch-measure] {Provider.Name}: {count} rows, batchSize=500, strategy={strategy}, {stopwatch.ElapsedMilliseconds} ms");
thrown.Should().BeNull(Outcome.Describe(thrown));
Convert.ToInt32((await Db.QueryAsync($"SELECT COUNT(*) FROM {Db.Table}"))[0][0]).Should().Be(count);
Convert.ToInt32(exchange.In.Headers[SqlHeaders.UpdateCount]).Should().Be(count);
if (Provider.CanCreateBatch)
{
strategy.Should().Be("DbBatch", "the connection can create a DbBatch and the batch breaks on the first error");
exchange.In.Headers["redbSql.batchChunkCount"].Should().Be(20, "10 000 statements in round trips of 500");
}
else
{
strategy.Should().Be("Commands");
exchange.In.Headers.Should().NotContainKey("redbSql.batchChunkCount");
}
}
[Fact]
public async Task FailureInLaterChunk_NoRowsAndExactIndex()
{
var items = Enumerable.Range(1, 1200)
.Select(i => new Dictionary { ["id"] = i == 701 ? 1 : i, ["val"] = "v" + i, ["n"] = null })
.ToList();
var (_, thrown) = await SqlBatchRun.RunAsync(Db, Insert, items, breakOnError: true, batchSize: 500);
thrown.Should().BeAssignableTo(Outcome.Describe(thrown));
thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(700, "item 700 repeats the key of item 0");
(await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls every chunk back");
}
[Fact]
public async Task NullsAndMixedClrTypes_Persisted()
{
var items = new List>
{
new() { ["id"] = 1, ["val"] = "a", ["n"] = 1 },
new() { ["id"] = 2, ["val"] = null, ["n"] = 2L },
new() { ["id"] = 3, ["val"] = "ccc", ["n"] = null },
};
var (_, thrown) = await SqlBatchRun.RunAsync(Db, Insert, items, breakOnError: null);
thrown.Should().BeNull(Outcome.Describe(thrown));
var rows = await Db.QueryAsync($"SELECT id, val, n FROM {Db.Table} ORDER BY id");
rows.Select(r => $"{Convert.ToInt64(r[0])}|{r[1]}|{(r[2] is null ? "" : Convert.ToInt64(r[2]).ToString())}")
.Should().Equal("1|a|1", "2||2", "3|ccc|");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchFailureSemanticsTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchFailureSemanticsTestsBase.cs
----
using System.Data.Common;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The connector's batch against a real database: whatever the error mode, the outcome the route sees must match
/// what is persisted. A successful exchange reports exactly the rows written; a failed exchange leaves nothing
/// behind; a failure surfaces the provider's own error.
///
public abstract class BatchFailureSemanticsTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task Batch_ReportedCount_EqualsPersistedRows()
{
var (exchange, thrown) = await RunBatchAsync(Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: false);
await AssertOutcomeMatchesDatabaseAsync(exchange, thrown);
}
[Fact]
public async Task Batch_TransactionKillingError_WritesNothingOutsideTransaction()
{
var (exchange, thrown) = await RunBatchAsync(
Provider.TransactionKillingBatchSql(Db.Table), Provider.TransactionKillingItems(), breakOnError: false);
await AssertOutcomeMatchesDatabaseAsync(exchange, thrown);
}
[Fact]
public async Task BreakOnError_DoomedTransaction_ThrowsOriginalError()
{
var (_, thrown) = await RunBatchAsync(
Provider.TransactionKillingBatchSql(Db.Table), Provider.TransactionKillingItems(), breakOnError: true);
thrown.Should().NotBeNull("the middle item fails and the batch breaks on the first error");
var providerError = thrown as DbException
?? (thrown as AggregateException)?.InnerExceptions.OfType().FirstOrDefault();
providerError.Should().NotBeNull(
$"the failing item's provider error must reach the route, but the batch threw {Outcome.Describe(thrown)}");
(await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls everything back");
}
// ── Decided error modes (17.0b, reference: Apache Camel) ─────────────────
[Fact]
public async Task BreakOnError_DuplicateKey_ThrowsProviderExceptionUnwrapped()
{
var (_, thrown) = await RunBatchAsync(Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: true);
thrown.Should().BeAssignableTo(
$"the provider's exception reaches the route as is, as in Camel, but the batch threw {Outcome.Describe(thrown)}");
(await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls everything back");
}
[Fact]
public async Task BatchContinue_DuplicateKey_CommitsOthersOrFailsCleanly()
{
var (exchange, thrown) = await RunBatchAsync(Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: false);
var persisted = await Db.ReadIdsAsync();
if (Provider.DuplicateKeyDestroysTransaction)
{
thrown.Should().BeAssignableTo(
$"the error ended the transaction, so the batch fails with the item's own error, but it threw {Outcome.Describe(thrown)}");
persisted.Should().BeEmpty();
return;
}
thrown.Should().BeNull($"a statement-level error is undone to its savepoint and the batch goes on ({Outcome.Describe(thrown)})");
persisted.Should().Equal(new[] { 1, 3 }, "the items around the failed one are committed");
SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(new[] { 1 }, "the failed item is reported by its index");
}
// ── Helpers ─────────────────────────────────────────────────────────────
private Task<(Exchange Exchange, Exception? Thrown)> RunBatchAsync(
string sql, List> items, bool breakOnError) =>
SqlBatchRun.RunAsync(Db, sql, items, breakOnError);
private async Task AssertOutcomeMatchesDatabaseAsync(Exchange exchange, Exception? thrown)
{
var persisted = await Db.ReadIdsAsync();
var rows = "[" + string.Join(",", persisted) + "]";
if (thrown is not null)
{
persisted.Should().BeEmpty(
$"a batch that fails must leave nothing behind, but rows {rows} were written although it threw {Outcome.Describe(thrown)}");
return;
}
Convert.ToInt32(exchange.In.Headers[SqlHeaders.RowCount]).Should().Be(persisted.Length,
$"the batch reported success, so its row count must match what is persisted (rows {rows}, " +
$"error header: {(exchange.In.Headers.TryGetValue(SqlHeaders.Error, out var error) ? error : "none")})");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchResultsE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchResultsE2ETestsBase.cs
----
using System.Collections;
using redb.Route.Sql;
using redb.Route.Sql.Mapping;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The rows a batch's statements return (INSERT … RETURNING on PostgreSQL and SQLite, OUTPUT inserted.* on SQL
/// Server) reach redbSql.generatedKeys in item order — across DbBatch chunks too — while the body stays the
/// list that was written. A failed item of a batch that goes on returns no keys.
///
public abstract class BatchResultsE2ETestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
public sealed class KeyRow
{
public int Id { get; set; }
}
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task ReturningKeys_CollectedInItemOrder_AcrossChunks()
{
var items = Enumerable.Range(11, 5).Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i }).ToList();
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.ReturningInsertSql(Db.Table), items, breakOnError: null,
batchSize: 2, new() { ["outputType"] = "SelectList" });
thrown.Should().BeNull(Outcome.Describe(thrown));
KeyIds(exchange).Should().Equal(new[] { 11, 12, 13, 14, 15 }, "keys follow the items, chunk after chunk");
exchange.In.Headers["redbSql.generatedKeysRowCount"].Should().Be(5);
Convert.ToInt32(exchange.In.Headers[SqlHeaders.UpdateCount]).Should().Be(5);
exchange.In.Body.Should().BeSameAs(items, "the returned rows go to a header; the body is left alone");
(await Db.ReadIdsAsync()).Should().Equal(11, 12, 13, 14, 15);
}
/// Its Id cannot hold an integer key: a configuration error, the same for every item.
public sealed class NarrowKeyRow
{
public bool Id { get; set; }
}
[Fact]
public async Task ReturningKeys_MappingError_EndsTheBatchInContinueModeToo()
{
var items = new List> { new() { ["id"] = 31, ["val"] = "a" }, new() { ["id"] = 32, ["val"] = "b" } };
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.ReturningInsertSql(Db.Table), items, breakOnError: false,
batchSize: 10, new() { ["outputType"] = "SelectList", ["outputClass"] = typeof(NarrowKeyRow).AssemblyQualifiedName! });
thrown.Should().BeOfType("a key that cannot be mapped is the endpoint's configuration, not an item's " +
"failure to undo and go past: " + Outcome.Describe(thrown));
exchange.In.Headers.Should().NotContainKey(SqlHeaders.BatchErrors);
(await Db.ReadIdsAsync()).Should().BeEmpty("the batch rolled back");
}
[Fact]
public async Task ReturningKeys_OutputClass_TypedList()
{
var items = new List> { new() { ["id"] = 21, ["val"] = "a" }, new() { ["id"] = 22, ["val"] = "b" } };
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.ReturningInsertSql(Db.Table), items, breakOnError: null,
batchSize: 10, new() { ["outputType"] = "SelectList", ["outputClass"] = typeof(KeyRow).AssemblyQualifiedName! });
thrown.Should().BeNull(Outcome.Describe(thrown));
exchange.In.Headers.Should().ContainKey(SqlHeaders.GeneratedKeys);
exchange.In.Headers[SqlHeaders.GeneratedKeys].Should().BeAssignableTo>()
.Which.Select(k => k.Id).Should().Equal(21, 22);
}
[Fact]
public async Task Continue_FailedItemReturnsNoKeys()
{
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.ReturningInsertSql(Db.Table), Provider.DuplicateKeyItems(),
breakOnError: false, batchSize: 10, new() { ["outputType"] = "SelectList" });
if (Provider.DuplicateKeyDestroysTransaction)
{
thrown.Should().NotBeNull("the duplicate key ends the transaction on this provider, so the batch stops");
return;
}
thrown.Should().BeNull(Outcome.Describe(thrown));
SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1);
KeyIds(exchange).Should().Equal(new[] { 1, 3 }, "the item undone to its savepoint returned no key");
exchange.In.Headers["redbSql.generatedKeysRowCount"].Should().Be(2);
}
[Fact]
public async Task PlainInsert_AutoOutputType_NoKeysHeader()
{
var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems().Take(1).ToList(),
breakOnError: null, batchSize: 10, new() { ["outputType"] = "Auto" });
thrown.Should().BeNull(Outcome.Describe(thrown));
exchange.In.Headers.Should().NotContainKey(SqlHeaders.GeneratedKeys);
}
private static List KeyIds(redb.Route.Core.Exchange exchange)
{
exchange.In.Headers.Should().ContainKey(SqlHeaders.GeneratedKeys, "RETURNING / OUTPUT rows are collected with outputType=SelectList");
return exchange.In.Headers[SqlHeaders.GeneratedKeys].Should().BeAssignableTo().Subject
.Cast>()
.Select(row => Convert.ToInt32(row.Values.First()))
.ToList();
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchStreamingE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/BatchStreamingE2ETestsBase.cs
----
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// A streamed query feeding a batch in the same database: outputType=StreamList hands the next endpoint an
/// IAsyncEnumerable that holds a reader and its connection; the batch reads it chunk by chunk and must release that
/// connection when it is done. Not for SQLite: a reader and a writer on the same file block each other.
///
public abstract class BatchStreamingE2ETestsBase : IAsyncLifetime
{
private const int Rows = 20_000;
private SqlE2EDatabase? _source;
private SqlE2EDatabase? _target;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Source => _source ?? throw new InvalidOperationException("The tables are created in InitializeAsync.");
private SqlE2EDatabase Target => _target ?? throw new InvalidOperationException("The tables are created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_source = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
_target = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
}
///
public async Task DisposeAsync()
{
try
{
if (_source is not null)
await _source.DisposeAsync();
}
finally
{
try
{
if (_target is not null)
await _target.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
}
[Fact]
public async Task StreamList_ToBatch_SameDatabase_AllCopiedAndSourceConnectionReleased()
{
var seed = Enumerable.Range(1, Rows)
.Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i, ["n"] = (long)i })
.ToList();
var (_, seedError) = await SqlBatchRun.RunAsync(Source, $"INSERT INTO {Source.Table} (id, val, n) VALUES (:#id, :#val, :#n)",
seed, breakOnError: null, batchSize: 1000);
seedError.Should().BeNull(Outcome.Describe(seedError));
var factory = Source.CreateConnectionFactory();
await using var context = new RouteContext();
context.AddComponent(new SqlComponent());
context.AddToRegistry(SqlEndpointHarness.DataSourceName, factory);
context.AddRoutes(r => r.From("direct://copy")
.To($"sql:SELECT id, val, n FROM {Source.Table} ORDER BY id?dataSource={SqlEndpointHarness.DataSourceName}&outputType=StreamList")
.To($"sql:INSERT INTO {Target.Table} (id, val, n) VALUES (:#id, :#val, :#n)?dataSource={SqlEndpointHarness.DataSourceName}&batchSize=1000&outputType=None"));
await context.Start();
var producer = context.GetEndpoint("direct://copy").CreateProducer();
await producer.Start();
var exchange = new Exchange(new Message("copy"));
var thrown = await Outcome.Of(() => producer.Process(exchange));
thrown.Should().BeNull(Outcome.Describe(thrown));
Convert.ToInt32((await Target.QueryAsync($"SELECT COUNT(*) FROM {Target.Table}"))[0][0]).Should().Be(Rows);
exchange.In.Headers[SqlHeaders.BatchItemCount].Should().Be(Rows);
factory.OpenConnections.Should().Be(0,
"the batch consumed the streamed result to its end, which closes the reader's connection, and its own connection is disposed");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/DbBatchSemanticsTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/DbBatchSemanticsTestsBase.cs
----
using System.Data.Common;
using System.Transactions;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// Characterization of on providers that implement it: the failed command is identified,
/// a failed batch rolled back leaves nothing (including under an ambient ), parameter
/// values need no explicit types, and statements returning rows deliver every result set.
///
public abstract class DbBatchSemanticsTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task DbBatch_DuplicateKey_ReportsFailedCommandIndex()
{
await using var connection = await Db.OpenAsync();
await using var tx = await connection.BeginTransactionAsync();
await using var batch = CreateBatch(connection, tx, DuplicateKeyStatements());
var error = await Outcome.Of(() => batch.ExecuteNonQueryAsync());
var dbError = error.Should().BeAssignableTo().Which;
dbError.BatchCommand.Should().NotBeNull("the provider identifies the failed command");
batch.BatchCommands.IndexOf(dbError.BatchCommand!).Should().Be(1);
}
[Fact]
public async Task DbBatch_DuplicateKeyThenRollback_LeavesNoRows() =>
await AssertFailedBatchRollbackLeavesNoRowsAsync(DuplicateKeyStatements());
[Fact]
public async Task DbBatch_TransactionKillingErrorThenRollback_LeavesNoRows() =>
await AssertFailedBatchRollbackLeavesNoRowsAsync(
Provider.InsertLiteral(Db.Table, 1, "a"),
Provider.TransactionKillingLiteral(Db.Table),
Provider.InsertLiteral(Db.Table, 3, "c"));
[Fact]
public async Task DbBatchUnderTransactionScope_ErrorWithoutComplete_LeavesNoRows()
{
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await using var connection = await Db.OpenAsync();
await using var batch = CreateBatch(connection, null, DuplicateKeyStatements());
var error = await Outcome.Of(() => batch.ExecuteNonQueryAsync());
error.Should().BeAssignableTo();
}
(await Db.ReadIdsAsync()).Should().BeEmpty("the scope was not completed");
}
[Fact]
public async Task DbBatch_NullsAndMixedClrTypes_Persisted()
{
await using var nullable = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
await using (var connection = await nullable.OpenAsync())
await using (var tx = await connection.BeginTransactionAsync())
await using (var batch = connection.CreateBatch())
{
batch.Transaction = tx;
foreach (var (id, val, n) in new (object, object, object)[] { (1, "a", 1), (2, DBNull.Value, 2L), (3, "ccc", DBNull.Value) })
{
var command = batch.CreateBatchCommand();
command.CommandText = $"INSERT INTO {nullable.Table} (id, val, n) VALUES (@id, @val, @n)";
command.CanCreateParameter.Should().BeTrue();
AddParameter(command, "id", id);
AddParameter(command, "val", val);
AddParameter(command, "n", n);
batch.BatchCommands.Add(command);
}
(await batch.ExecuteNonQueryAsync()).Should().Be(3);
await tx.CommitAsync();
}
var rows = await nullable.QueryAsync($"SELECT id, val, n FROM {nullable.Table} ORDER BY id");
rows.Select(r => string.Join("|", r.Select(v => v?.ToString() ?? "null")))
.Should().Equal("1|a|1", "2|null|2", "3|ccc|null");
}
[Fact]
public async Task DbBatch_ReturningStatements_KeysFromEveryResultAndRecordsAffectedPerCommand()
{
var ids = new List();
int[] recordsAffected;
await using (var connection = await Db.OpenAsync())
await using (var batch = connection.CreateBatch())
{
foreach (var id in new[] { 30, 31 })
{
var command = batch.CreateBatchCommand();
command.CommandText = Provider.NativeReturningInsertSql(Db.Table);
AddParameter(command, "id", id);
AddParameter(command, "val", "k");
batch.BatchCommands.Add(command);
}
await using (var reader = await batch.ExecuteReaderAsync())
{
do
{
while (await reader.ReadAsync())
ids.Add(Convert.ToInt32(reader.GetValue(0)));
}
while (await reader.NextResultAsync());
}
recordsAffected = batch.BatchCommands.Select(c => c.RecordsAffected).ToArray();
}
ids.Should().Equal(30, 31);
recordsAffected.Should().Equal(1, 1);
}
// ── Helpers ─────────────────────────────────────────────────────────────
private string[] DuplicateKeyStatements() =>
[
Provider.InsertLiteral(Db.Table, 1, "a"),
Provider.InsertLiteral(Db.Table, 1, "dup"),
Provider.InsertLiteral(Db.Table, 3, "c"),
];
private async Task AssertFailedBatchRollbackLeavesNoRowsAsync(params string[] statements)
{
await using (var connection = await Db.OpenAsync())
await using (var tx = await connection.BeginTransactionAsync())
await using (var batch = CreateBatch(connection, tx, statements))
{
var error = await Outcome.Of(() => batch.ExecuteNonQueryAsync());
error.Should().BeAssignableTo();
var rollback = await Outcome.Of(() => tx.RollbackAsync());
rollback.Should().BeNull($"rolling back a failed batch works on this provider ({Outcome.Describe(rollback)})");
}
(await Db.ReadIdsAsync()).Should().BeEmpty("no command of a failed, rolled-back batch may survive");
}
private static DbBatch CreateBatch(DbConnection connection, DbTransaction? transaction, params string[] statements)
{
var batch = connection.CreateBatch();
batch.Transaction = transaction;
foreach (var statement in statements)
{
var command = batch.CreateBatchCommand();
command.CommandText = statement;
batch.BatchCommands.Add(command);
}
return batch;
}
private static void AddParameter(DbBatchCommand command, string name, object? value)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.Value = value;
command.Parameters.Add(parameter);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/ParameterSyntaxE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/ParameterSyntaxE2ETestsBase.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// On a real server, :#name is the only placeholder: an @ inside a string literal reaches the table as written.
///
public abstract class ParameterSyntaxE2ETestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
/// The database of the test, created in .
protected SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task LiteralContainingAt_PersistedAsWritten()
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(),
$"INSERT INTO {Db.Table} (id, val) VALUES (:#id, 'user@example.com')", new() { ["outputType"] = "None" });
var exchange = new Exchange(new Message());
exchange.In.Headers["id"] = 5;
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
thrown.Should().BeNull(Outcome.Describe(thrown));
var rows = await Db.QueryAsync($"SELECT id, val FROM {Db.Table}");
rows.Should().ContainSingle();
Convert.ToInt32(rows[0][0]).Should().Be(5);
rows[0][1].Should().Be("user@example.com");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PocoMappingE2ETestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PocoMappingE2ETestsBase.cs
----
using redb.Route.Sql.Mapping;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// Mapping driver types into POCO properties on a real server: dates and times arrive as , and only a
/// value that carries its offset or is UTC may become a ; a timestamp without a time zone is an
/// error that says what to do instead.
///
public abstract class PocoMappingE2ETestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
/// One column at : the instant 2024-01-02 03:04:05 +03:00, in the server's type that keeps the time zone.
protected abstract string ZonedTimestampSql { get; }
/// One column at : 2024-01-02 03:04:05 in the server's timestamp type without a time zone.
protected abstract string UnzonedTimestampSql { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The database is checked in InitializeAsync.");
public enum Kind { None = 0, First = 1, Second = 2 }
public sealed class Target
{
public DateTimeOffset At { get; set; }
public DateOnly Day { get; set; }
public Kind Kind { get; set; }
}
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task ZonedTimestamp_IntoDateTimeOffset_KeepsTheInstant()
{
var (target, thrown) = await MapAsync(ZonedTimestampSql);
thrown.Should().BeNull(Outcome.Describe(thrown));
target!.At.UtcDateTime.Should().Be(new DateTime(2024, 1, 2, 0, 4, 5, DateTimeKind.Utc));
}
[Fact]
public async Task UnzonedTimestamp_IntoDateTimeOffset_FailsWithHint()
{
var (_, thrown) = await MapAsync(UnzonedTimestampSql);
thrown.Should().BeAssignableTo(Outcome.Describe(thrown))
.Which.Message.Should().Contain("at").And.Contain("At").And.Contain("DateTime",
"the message tells to map a timestamp without a time zone to a DateTime property");
}
[Fact]
public async Task DateColumn_IntoDateOnly_Mapped()
{
var (target, thrown) = await MapAsync("SELECT CAST('2024-01-02' AS date) AS day");
thrown.Should().BeNull(Outcome.Describe(thrown));
target!.Day.Should().Be(new DateOnly(2024, 1, 2));
}
[Fact]
public async Task IntegerColumn_IntoEnum_Mapped()
{
var (target, thrown) = await MapAsync("SELECT 2 AS kind");
thrown.Should().BeNull(Outcome.Describe(thrown));
target!.Kind.Should().Be(Kind.Second);
}
private async Task<(Target? Target, Exception? Thrown)> MapAsync(string sql)
{
await using var connection = await Db.OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = sql;
await using var reader = await command.ExecuteReaderAsync();
(await reader.ReadAsync()).Should().BeTrue();
Target? target = null;
var thrown = await Outcome.Of(() =>
{
target = new PocoRowMapper().Map(reader);
return Task.CompletedTask;
});
return (target, thrown);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollFailureAfterRollbackTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollFailureAfterRollbackTestsBase.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// A transacted poll (transacted=true ) with onFailureAfterRollback=true on a real provider: each row runs under a
/// savepoint, so a failed row is undone alone, keeps its onFailure mark and the rows around it commit in the same
/// poll. Without the option the whole poll rolls back, as in Apache Camel. SQL Server is the case that matters: SqlClient
/// reports no savepoint support and has it.
///
public abstract class PollFailureAfterRollbackTestsBase(ITestOutputHelper output) : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_db = await SqlE2EDatabase.CreateAsync(Provider);
for (var id = 1; id <= 3; id++)
await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "new"));
}
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
private async Task PollAsync(bool afterRollback)
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var parameters = new Dictionary
{
["mode"] = "Poll",
["transacted"] = "true",
["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id",
["onFailure"] = $"UPDATE {Db.Table} SET val = 'failed' WHERE id = :#id",
["delay"] = "100",
["repeatCount"] = "1",
};
if (afterRollback)
parameters["onFailureAfterRollback"] = "true";
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory,
$"SELECT id, val FROM {Db.Table} WHERE val = 'new' ORDER BY id", parameters);
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(ci => Convert.ToInt64(ci.Arg().In.Headers["id"]) == 2
? Task.FromException(new InvalidOperationException("row 2 is bad"))
: Task.CompletedTask);
var consumer = (SqlConsumer)endpoint.CreateConsumer(processor);
var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None));
var rows = await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id");
var values = string.Join(",", rows.Select(r => r[0]));
output.WriteLine($"[probe] {Provider.Name}: transacted poll, afterRollback={afterRollback}: poll={Outcome.Describe(thrown)}, rows={values}, open={factory.OpenConnections}");
thrown.Should().BeNull(Outcome.Describe(thrown));
factory.OpenConnections.Should().Be(0);
return values;
}
[Fact]
public async Task OnFailureAfterRollback_MarksTheFailedRow_AndCommitsTheOthers()
{
(await PollAsync(afterRollback: true)).Should().Be("done,failed,done");
}
[Fact]
public async Task ByDefault_TheWholePollRollsBack()
{
(await PollAsync(afterRollback: false)).Should().Be("new,new,new");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollListDeliveryTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollListDeliveryTestsBase.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// A streaming poll delivered as one list (outputType=StreamList , pollDelivery=List , Apache Camel
/// useIterator=false with a result set iterator): the route reads the rows from the open reader; onSuccess runs
/// once, after the reader is closed, so it shares the consumer transaction on every driver.
///
public abstract class PollListDeliveryTestsBase(ITestOutputHelper output) : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_db = await SqlE2EDatabase.CreateAsync(Provider);
for (var id = 1; id <= 3; id++)
await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "new"));
}
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task StreamListAsList_Transacted_OnSuccessOnceAfterReaderClosed()
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, $"SELECT id, val FROM {Db.Table} ORDER BY id", new()
{
["mode"] = "Poll",
["outputType"] = "StreamList",
["pollDelivery"] = "List",
["transacted"] = "true",
["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done'",
["delay"] = "100",
["repeatCount"] = "1",
});
var exchanges = 0;
var rowsRead = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(async ci =>
{
exchanges++;
if (ci.Arg().In.Body is IAsyncEnumerable> stream)
await foreach (var _ in stream)
rowsRead++;
});
var consumer = (SqlConsumer)endpoint.CreateConsumer(processor);
var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None));
var values = string.Join(",", (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]));
output.WriteLine($"[probe] {Provider.Name}: StreamList as one list, transacted: poll={Outcome.Describe(thrown)}, " +
$"exchanges={exchanges}, rows read={rowsRead}, rows={values}, open={factory.OpenConnections}");
thrown.Should().BeNull(Outcome.Describe(thrown));
exchanges.Should().Be(1, "the whole poll is one exchange");
rowsRead.Should().Be(3, "the route reads the rows from the stream");
values.Should().Be("done,done,done", "onSuccess ran once, after the reader was closed, in the consumer transaction");
factory.OpenConnections.Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollStreamLifecycleTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollStreamLifecycleTestsBase.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The poll consumer with outputType=StreamList , outside a transaction, keeps its reader open while it processes each
/// row. As in Apache Camel (onConsume through the data source), onSuccess / onFailure then run on a
/// connection of their own, so a driver that allows one active command per connection still marks every row. Not for SQLite:
/// in its default journal mode the open reader blocks a write on another connection — the documented cost of that rule.
///
public abstract class PollStreamLifecycleTestsBase(ITestOutputHelper output) : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_db = await SqlE2EDatabase.CreateAsync(Provider);
for (var id = 1; id <= 3; id++)
await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "new"));
}
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task PollStream_OnSuccess_MarksEveryProcessedRow()
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, $"SELECT id, val FROM {Db.Table} ORDER BY id", new()
{
["mode"] = "Poll",
["outputType"] = "StreamList",
["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id",
["delay"] = "100",
["repeatCount"] = "1",
});
var processed = 0;
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(Task.CompletedTask)
.AndDoes(_ => processed++);
var consumer = (SqlConsumer)endpoint.CreateConsumer(processor);
var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None));
var rows = await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id");
var values = string.Join(",", rows.Select(r => r[0]));
output.WriteLine($"[probe] {Provider.Name}: poll StreamList + onSuccess: poll={Outcome.Describe(thrown)}, processed={processed}, rows={values}, open={factory.OpenConnections}");
thrown.Should().BeNull(Outcome.Describe(thrown));
processed.Should().Be(3);
values.Should().Be("done,done,done", "onSuccess must mark every processed row; a row left unmarked is polled and processed again");
factory.OpenConnections.Should().Be(0);
}
[Fact]
public async Task PollStream_OnFailure_RecordsEveryFailedRow_OnPrimaryConnection()
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, $"SELECT id, val FROM {Db.Table} ORDER BY id", new()
{
["mode"] = "Poll",
["outputType"] = "StreamList",
["onFailure"] = $"UPDATE {Db.Table} SET val = 'failed' WHERE id = :#id",
["delay"] = "100",
["repeatCount"] = "1",
});
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any())
.Returns(_ => throw new InvalidOperationException("route failed"));
var consumer = (SqlConsumer)endpoint.CreateConsumer(processor);
var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None));
var values = string.Join(",", (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]));
output.WriteLine($"[probe] {Provider.Name}: poll StreamList + onFailure: poll={Outcome.Describe(thrown)}, rows={values}, " +
$"readOnly requests={string.Join(",", factory.ReadOnlyRequests)}, open={factory.OpenConnections}");
thrown.Should().BeNull(Outcome.Describe(thrown));
values.Should().Be("failed,failed,failed", "onFailure records every row the route failed on");
factory.ReadOnlyRequests.Should().Equal(new[] { false, false },
"the poll reads from the primary database (no readOnly), and — as in Apache Camel (onConsume through the data " +
"source) — the lifecycle statements run on a connection of their own to it");
factory.OpenConnections.Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollStreamTransactedTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/PollStreamTransactedTestsBase.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// A streaming poll inside the consumer transaction (transacted=true ). As in Apache Camel, whose JdbcTemplate
/// uses the transaction's connection, onSuccess runs on the reader's connection and transaction. Whether that works
/// is the driver's fact: SQLite runs the statement; PostgreSQL and SQL Server refuse a second command while the reader is
/// open, and the transaction rolls back — never a second connection that the transaction would not cover.
///
public abstract class PollStreamTransactedTestsBase(ITestOutputHelper output) : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_db = await SqlE2EDatabase.CreateAsync(Provider);
for (var id = 1; id <= 3; id++)
await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "new"));
}
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task PollStream_Transacted_OnSuccess_RunsOnReaderConnectionAndTransaction()
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, $"SELECT id, val FROM {Db.Table} ORDER BY id", new()
{
["mode"] = "Poll",
["outputType"] = "StreamList",
["transacted"] = "true",
["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id",
["delay"] = "100",
["repeatCount"] = "1",
});
var processor = Substitute.For();
processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask);
var consumer = (SqlConsumer)endpoint.CreateConsumer(processor);
var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None));
var values = string.Join(",", (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]));
output.WriteLine($"[probe] {Provider.Name}: transacted poll StreamList + onSuccess: poll={Outcome.Describe(thrown)}, rows={values}, " +
$"readOnly requests={string.Join(",", factory.ReadOnlyRequests)}, open={factory.OpenConnections}");
thrown.Should().BeNull(Outcome.Describe(thrown));
factory.ReadOnlyRequests.Should().ContainSingle("inside the transaction no second connection is opened");
factory.OpenConnections.Should().Be(0);
if (Provider.ReaderConnectionRunsAnotherCommand)
values.Should().Be("done,done,done", "the driver runs onSuccess on the reader's connection, in its transaction");
else
values.Should().Be("new,new,new",
"the driver refuses a second command while the reader is open; the failure is logged and the transaction rolls back");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/ProviderSemanticsTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/ProviderSemanticsTestsBase.cs
----
using System.Data.Common;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// Characterization of the driver and server, without the connector: what happens to a multi-row write inside
/// one local transaction when a row fails. The batch design stands on these facts (savepoint per item in
/// continue mode, no command after a failed rollback-to-savepoint, rollback of the whole transaction in break
/// mode). They are green by definition; a red one means the provider changed and the design must be revisited.
///
public abstract class ProviderSemanticsTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
// ── Errors without savepoints ───────────────────────────────────────────
[Fact]
public async Task LoopContinue_DuplicateKey_RowsAfterCommit()
{
await RunLoopContinueAsync(Provider.InsertLiteral(Db.Table, 1, "dup"));
(await Db.ReadIdsAsync()).Should().Equal(Provider.LoopContinueDuplicateKeyRows);
}
[Fact]
public async Task LoopContinue_TransactionKillingError_RowsAfterCommit()
{
await RunLoopContinueAsync(Provider.TransactionKillingLiteral(Db.Table));
(await Db.ReadIdsAsync()).Should().Equal(Provider.LoopContinueTransactionKillingRows);
}
[Fact]
public async Task CommandAfterTransactionKillingError_RejectedOrRunOutsideTransaction()
{
await using (var connection = await Db.OpenAsync())
await using (var tx = await connection.BeginTransactionAsync())
{
await SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 1, "a"));
var failing = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.TransactionKillingLiteral(Db.Table)));
failing.Should().NotBeNull();
var next = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 3, "c")));
if (Provider.CommandAfterTransactionKillingErrorIsRejected)
next.Should().NotBeNull("the provider refuses statements on a failed transaction");
else
next.Should().BeNull("the provider runs the statement although the server transaction is gone");
// The rollback's own failure is not the fact under test; what survives it is.
await Outcome.Of(() => tx.RollbackAsync());
}
int[] expected = Provider.CommandAfterTransactionKillingErrorIsRejected ? [] : [3];
(await Db.ReadIdsAsync()).Should().Equal(expected,
"a statement run after the server rolled the transaction back is autocommitted and survives the rollback");
}
// ── Savepoints ──────────────────────────────────────────────────────────
[Fact]
public async Task SupportsSavepoints_ReportedVersusActual()
{
await using var connection = await Db.OpenAsync();
await using var tx = await connection.BeginTransactionAsync();
tx.SupportsSavepoints.Should().Be(Provider.ReportsSavepointSupport);
var save = await Outcome.Of(() => tx.SaveAsync("rsql_probe"));
save.Should().BeNull($"savepoints work on every tier-1 provider whatever SupportsSavepoints says ({Outcome.Describe(save)})");
}
[Fact]
public async Task Savepoint_DuplicateKey_OutcomeMatchesProvider() =>
await AssertSavepointOutcomeAsync(Provider.InsertLiteral(Db.Table, 1, "dup"), Provider.DuplicateKeyDestroysTransaction);
[Fact]
public async Task Savepoint_TransactionKillingError_OutcomeMatchesProvider() =>
await AssertSavepointOutcomeAsync(Provider.TransactionKillingLiteral(Db.Table), Provider.TransactionKillingErrorDestroysTransaction);
// ── Parameters and commands ─────────────────────────────────────────────
[Fact]
public async Task CanCreateBatch_MatchesProvider()
{
await using var connection = await Db.OpenAsync();
connection.CanCreateBatch.Should().Be(Provider.CanCreateBatch);
}
[Fact]
public async Task ReusedCommand_NullsAndMixedClrTypes_Persisted()
{
await using var nullable = await SqlE2EDatabase.CreateAsync(Provider, Provider.CreateNullableTableSql);
await using (var connection = await nullable.OpenAsync())
await using (var tx = await connection.BeginTransactionAsync())
await using (var command = connection.CreateCommand())
{
command.Transaction = tx;
command.CommandText = $"INSERT INTO {nullable.Table} (id, val, n) VALUES (@id, @val, @n)";
var id = AddParameter(command, "id");
var val = AddParameter(command, "val");
var n = AddParameter(command, "n");
foreach (var (i, v, k) in new (object, object, object)[] { (1, "a", 1), (2, DBNull.Value, 2L), (3, "ccc", DBNull.Value) })
{
id.Value = i;
val.Value = v;
n.Value = k;
await command.ExecuteNonQueryAsync();
}
await tx.CommitAsync();
}
var rows = await nullable.QueryAsync($"SELECT id, val, n FROM {nullable.Table} ORDER BY id");
rows.Select(Format).Should().Equal("1|a|1", "2|null|2", "3|ccc|null");
}
[Fact]
public async Task ReusedCommand_PrepareWithoutExplicitTypes_MatchesProvider()
{
await using (var connection = await Db.OpenAsync())
await using (var command = connection.CreateCommand())
{
command.CommandText = Provider.NativeInsertSql(Db.Table);
var id = AddParameter(command, "id");
var val = AddParameter(command, "val");
id.Value = 10;
val.Value = "a";
var prepare = await Outcome.Of(() => command.PrepareAsync());
if (Provider.PrepareRejectsUntypedParameters)
prepare.Should().BeOfType("the provider requires explicit parameter types to prepare");
else
prepare.Should().BeNull();
await command.ExecuteNonQueryAsync();
id.Value = 11;
val.Value = new string('b', 20);
await command.ExecuteNonQueryAsync();
}
(await Db.ReadIdsAsync()).Should().Equal(10, 11);
}
[Fact]
public async Task ExtraParameterFoundInsideLiteralOrComment_IsIgnoredByProvider()
{
await using (var connection = await Db.OpenAsync())
{
await InsertWithExtraParameterAsync(connection, $"INSERT INTO {Db.Table} (id, val) VALUES (@id, 'user@example.com')", 20, "example");
await InsertWithExtraParameterAsync(connection, $"INSERT INTO {Db.Table} (id, val) VALUES (@id, 'x') -- @todo", 21, "todo");
}
var rows = await Db.QueryAsync($"SELECT id, val FROM {Db.Table} ORDER BY id");
rows.Select(Format).Should().Equal("20|user@example.com", "21|x");
}
[Fact]
public async Task ReturningStatement_ReaderReturnsKeyAndRecordsAffected()
{
var ids = new List();
int recordsAffected;
await using (var connection = await Db.OpenAsync())
await using (var command = connection.CreateCommand())
{
command.CommandText = Provider.NativeReturningInsertSql(Db.Table);
AddParameter(command, "id").Value = 40;
AddParameter(command, "val").Value = "k";
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
ids.Add(Convert.ToInt32(reader.GetValue(0)));
await reader.CloseAsync();
recordsAffected = reader.RecordsAffected;
}
ids.Should().Equal(40);
recordsAffected.Should().Be(1);
}
// ── Helpers ─────────────────────────────────────────────────────────────
private async Task RunLoopContinueAsync(string failingStatement)
{
await using var connection = await Db.OpenAsync();
await using var tx = await connection.BeginTransactionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 1, "a"));
var failing = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, tx, failingStatement));
failing.Should().NotBeNull("the middle statement is built to fail");
// Exactly what SqlProducer.ProcessBatch does today with breakBatchOnError=false: keep going, then commit.
await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 3, "c")));
await Outcome.Of(() => tx.CommitAsync());
}
private async Task AssertSavepointOutcomeAsync(string failingStatement, bool destroysTransaction)
{
await using (var connection = await Db.OpenAsync())
await using (var tx = await connection.BeginTransactionAsync())
{
await SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 1, "a"));
await tx.SaveAsync("rsql_item");
var failing = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, tx, failingStatement));
failing.Should().NotBeNull("the statement is built to fail");
var rollbackToSavepoint = await Outcome.Of(() => tx.RollbackAsync("rsql_item"));
if (destroysTransaction)
{
rollbackToSavepoint.Should().NotBeNull("the error ended the server transaction, so its savepoint is gone");
// Stop here: a further statement would run outside the transaction on SQL Server.
}
else
{
rollbackToSavepoint.Should().BeNull($"the savepoint must recover the transaction ({Outcome.Describe(rollbackToSavepoint)})");
await SqlE2EDatabase.ExecuteAsync(connection, tx, Provider.InsertLiteral(Db.Table, 3, "c"));
await tx.CommitAsync();
}
}
int[] expected = destroysTransaction ? [] : [1, 3];
(await Db.ReadIdsAsync()).Should().Equal(expected);
}
private static async Task InsertWithExtraParameterAsync(DbConnection connection, string sql, int id, string extraName)
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
AddParameter(command, "id").Value = id;
AddParameter(command, extraName).Value = DBNull.Value;
await command.ExecuteNonQueryAsync();
}
private static DbParameter AddParameter(DbCommand command, string name)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
command.Parameters.Add(parameter);
return parameter;
}
private static string Format(object?[] row) => string.Join("|", row.Select(v => v?.ToString() ?? "null"));
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SequentialConnectionsInScopeTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SequentialConnectionsInScopeTestsBase.cs
----
using System.Transactions;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// Two sql: steps in one route transaction, as the connector runs them: each step opens a connection, runs its
/// statement and closes the connection before the next step opens one. Measured per driver: whether the second
/// connection reuses the first one's enlistment and the scope commits both statements, or the second open needs a
/// distributed transaction.
///
public abstract class SequentialConnectionsInScopeTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(Provider);
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task Two_steps_one_after_the_other_inside_one_scope_commit_both_statements()
{
var failure = await Outcome.Of(async () =>
{
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
await using (var first = await Db.OpenAsync())
await SqlE2EDatabase.ExecuteAsync(first, null, Provider.InsertLiteral(Db.Table, 1, "a"));
await using (var second = await Db.OpenAsync())
await SqlE2EDatabase.ExecuteAsync(second, null, Provider.InsertLiteral(Db.Table, 2, "b"));
scope.Complete();
});
failure.Should().BeNull($"the second step reuses the first one's enlistment ({Outcome.Describe(failure)})");
(await Db.ReadIdsAsync()).Should().BeEquivalentTo([1, 2]);
}
[Fact]
public async Task Two_steps_one_after_the_other_inside_one_scope_roll_back_together()
{
var failure = await Outcome.Of(async () =>
{
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
await using (var first = await Db.OpenAsync())
await SqlE2EDatabase.ExecuteAsync(first, null, Provider.InsertLiteral(Db.Table, 1, "a"));
await using (var second = await Db.OpenAsync())
await SqlE2EDatabase.ExecuteAsync(second, null, Provider.InsertLiteral(Db.Table, 2, "b"));
// Not completed: the route failed after both steps.
});
failure.Should().BeNull(Outcome.Describe(failure));
(await Db.ReadIdsAsync()).Should().BeEmpty();
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentAmbientTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentAmbientTestsBase.cs
----
using System.Transactions;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Repositories;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// tells the idempotent consumer whether a rollback of the
/// route transaction takes the key back by itself. It must say what the driver does: a false "no" makes the consumer delete
/// the key after the rollback, and in a cluster that delete can hit the key another node has claimed meanwhile; a false
/// "yes" leaves a key behind whose work never committed, and the redelivery is skipped as a duplicate.
///
public abstract class SqlIdempotentAmbientTestsBase : IAsyncLifetime
{
private readonly string _table = "rsql_idem_" + Guid.NewGuid().ToString("N")[..12];
private readonly List _connectionStrings = [];
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
/// Whether the provider's connections enlist in an ambient transaction with the default connection string.
protected abstract bool EnlistsByDefault { get; }
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
try
{
if (_connectionStrings.Count > 0)
{
await using var connection = await Factory(_connectionStrings[0]).CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null, $"DROP TABLE {_table}");
}
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task JoinsAmbientTransaction_SaysWhatTheRollbackDoesWithTheKey()
{
var repository = Repository(Provider.ConnectionString);
await repository.Add("warm-up"); // creates the table outside any transaction
var keptAfterRollback = await AddInRolledBackScopeAsync(repository, "k1");
((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().Be(EnlistsByDefault, $"{Provider.Name} with its default connection string");
((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().Be(!keptAfterRollback,
"the flag must match what the rollback did with the key: taken back when the connection enlisted, kept otherwise");
}
/// Enlist=false keeps the connection out of the ambient transaction; the flag follows it.
protected async Task AssertEnlistOffDoesNotJoin()
{
var repository = Repository(Provider.ConnectionString + ";Enlist=false");
await repository.Add("warm-up");
var keptAfterRollback = await AddInRolledBackScopeAsync(repository, "k1");
keptAfterRollback.Should().BeTrue("with Enlist=false the insert commits on its own, outside the route transaction");
((IIdempotentRepository)repository).JoinsAmbientTransaction.Should().BeFalse("the consumer has to remove the key itself after the rollback");
}
private static async Task AddInRolledBackScopeAsync(SqlIdempotentRepository repository, string key)
{
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
(await repository.Add(key)).Should().BeTrue();
// The route failed: the scope ends without Complete().
}
return await repository.Contains(key);
}
[Fact]
public async Task Claim_TellsAClaimInFlightFromAConfirmedOne()
{
var repository = Repository(Provider.ConnectionString);
(await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed);
(await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.InFlight);
await repository.Confirm("c1");
(await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Confirmed);
await repository.Remove("c1");
(await repository.Claim("c1", TimeSpan.FromMinutes(10))).Should().Be(IdempotentClaim.Claimed);
}
[Fact]
public async Task Claim_AnAbandonedClaim_IsTakenOver_AConfirmedOneNever()
{
var repository = Repository(Provider.ConnectionString);
await repository.Add("orphan");
await repository.Add("done");
await repository.Confirm("done");
await Task.Delay(TimeSpan.FromSeconds(1.5));
(await repository.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.TakenOver);
(await repository.Claim("orphan", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight, "the takeover is a fresh claim");
(await repository.Claim("done", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.Confirmed);
}
[Fact]
public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_OneWins_OneRowStays()
{
// Two repositories over one table, as two nodes are: both find the same stale row. It is written long abandoned and
// the timeout is a minute, so however the callers spread (SQLite serializes them), the winner's fresh claim stays
// inside it.
var nodeA = Repository(Provider.ConnectionString);
var nodeB = Repository(Provider.ConnectionString);
await SeedAbandonedAsync(nodeA, "stale");
var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i =>
Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim("stale", TimeSpan.FromMinutes(1)))));
// One caller holds the claim: the one that took the stale entry over, or one that found it gone and claimed it anew.
outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed).Should().Be(1);
outcomes.Count(o => o == IdempotentClaim.InFlight).Should().Be(outcomes.Length - 1);
(await nodeA.Claim("stale", null)).Should().Be(IdempotentClaim.InFlight, "one unconfirmed row: the winner's fresh claim");
}
/// A claim of left unconfirmed long ago, as a stopped node leaves it.
private async Task SeedAbandonedAsync(SqlIdempotentRepository repository, string key)
{
await repository.Contains("warm-up"); // creates the table
await using var connection = await Factory(Provider.ConnectionString).CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null,
$"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', '{key}', '2000-01-01T00:00:00.0000000+00:00', 0)");
}
[Fact]
public async Task Add_ThatLosesTheKeyToAConcurrentInsert_IsADuplicate_NotAnError()
{
// Another session inserts the key and commits while node A's insert of it is under way. PostgreSQL then fails
// node A's insert on the primary key (its existence check could not see the uncommitted row); SQL Server and SQLite
// wait on the row and find it. Either way the key is held: a duplicate, not an exception for the route.
var nodeA = Repository(Provider.ConnectionString);
await nodeA.Add("warm-up"); // creates the table
await using var other = await Factory(Provider.ConnectionString).CreateConnectionAsync();
await using var otherTx = await other.BeginTransactionAsync();
await SqlE2EDatabase.ExecuteAsync(other, otherTx,
$"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', 'race', '2026-01-01T00:00:00.0000000+00:00', 0)");
var addA = Task.Run(() => nodeA.Add("race"));
await Task.Delay(TimeSpan.FromMilliseconds(500));
await otherTx.CommitAsync();
(await addA).Should().BeFalse("the other session's row holds the key");
}
[Fact]
public async Task Claim_AnInsertThatWaitedPastTheTimeout_BecomesVisibleAsAFreshClaim()
{
// Another session holds the key, so node A's insert waits on it for longer than the timeout. The claim it then
// commits is new: node B must find it in flight, not abandoned.
var nodeA = Repository(Provider.ConnectionString);
var nodeB = Repository(Provider.ConnectionString);
await nodeA.Add("warm-up"); // creates the table
await using var blocker = await Factory(Provider.ConnectionString).CreateConnectionAsync();
await using var hold = await blocker.BeginTransactionAsync();
await SqlE2EDatabase.ExecuteAsync(blocker, hold,
$"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', 'slow', '2000-01-01T00:00:00.0000000+00:00', 0)");
var claimA = Task.Run(() => nodeA.Claim("slow", TimeSpan.FromSeconds(1)));
await Task.Delay(TimeSpan.FromSeconds(1.5));
claimA.IsCompleted.Should().BeFalse("node A's insert waits on the key the other session holds");
await hold.RollbackAsync();
(await claimA).Should().Be(IdempotentClaim.Claimed);
(await nodeB.Claim("slow", TimeSpan.FromSeconds(1))).Should().Be(IdempotentClaim.InFlight,
"node A's claim became visible a moment ago, however long its insert waited");
}
[ClaimRaceLoopFact]
public async Task Claim_TwoNodesTakingOverOneAbandonedClaim_200Times_OneWinsEachTime()
{
var nodeA = Repository(Provider.ConnectionString);
var nodeB = Repository(Provider.ConnectionString);
for (var iteration = 0; iteration < 200; iteration++)
{
var key = $"stale-{iteration}";
await SeedAbandonedAsync(nodeA, key);
var outcomes = await Task.WhenAll(Enumerable.Range(0, 8).Select(i =>
Task.Run(() => (i % 2 == 0 ? nodeA : nodeB).Claim(key, TimeSpan.FromMinutes(1)))));
outcomes.Count(o => o is IdempotentClaim.TakenOver or IdempotentClaim.Claimed)
.Should().Be(1, $"iteration {iteration}: {string.Join(",", outcomes)}");
}
}
private SqlIdempotentRepository Repository(string connectionString)
{
_connectionStrings.Add(connectionString);
return new SqlIdempotentRepository(Factory(connectionString),
new SqlIdempotentOptions { ProcessorName = "route-1", TableName = _table });
}
private ISqlConnectionFactory Factory(string connectionString) =>
new SqlConnectionFactory(new SqlConnectionOptions { ConnectionString = connectionString, ProviderFactory = Provider.Factory });
}
///
/// The claim race in a loop of 200: minutes per database, so it runs only with REDB_CLAIM_RACE_LOOP=1 and is
/// skipped, visibly, otherwise.
///
public sealed class ClaimRaceLoopFactAttribute : FactAttribute
{
public ClaimRaceLoopFactAttribute()
{
if (Environment.GetEnvironmentVariable("REDB_CLAIM_RACE_LOOP") != "1")
Skip = "The 200-iteration claim race runs with REDB_CLAIM_RACE_LOOP=1.";
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentLeaseTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlIdempotentLeaseTestsBase.cs
----
using System.Data.Common;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Repositories;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The claim id of : a holder that outlived the timeout and was taken over settles
/// nothing of the new holder's claim, rows without a claim id (written by Add or by a 4.7 node) are claimed as
/// before, a 4.7 node's unconditional Confirm and Remove still work on the table, and a table created before 4.8.0 gets
/// its claim_id column from the repository, or names the statement that adds it when the repository may not.
/// Takeovers are made deterministic by ageing the held row in the database, not by waiting.
///
public abstract class SqlIdempotentLeaseTestsBase : IAsyncLifetime
{
private static readonly TimeSpan Timeout = TimeSpan.FromMinutes(1);
private readonly string _table = "rsql_lease_" + Guid.NewGuid().ToString("N")[..12];
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
try
{
await using var connection = await Factory().CreateConnectionAsync();
try { await SqlE2EDatabase.ExecuteAsync(connection, null, $"DROP TABLE {_table}"); }
catch (DbException) { /* the test failed before the table existed */ }
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task StaleHolder_AfterATakeover_ConfirmsNothing_TheNewHolderConfirms()
{
var nodeA = Repository();
var nodeB = Repository();
var first = await nodeA.Lease("m1", Timeout);
first.Outcome.Should().Be(IdempotentClaim.Claimed);
first.Token.Should().NotBeNullOrEmpty();
await AgeAsync("m1");
var second = await nodeB.Lease("m1", Timeout);
second.Outcome.Should().Be(IdempotentClaim.TakenOver);
second.Token.Should().NotBe(first.Token);
(await nodeA.Confirm("m1", first.Token, default)).Should().BeFalse("node A's claim was taken over");
(await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.InFlight, "node B's claim is still unconfirmed");
(await nodeB.Confirm("m1", second.Token, default)).Should().BeTrue();
(await nodeA.Lease("m1", null)).Outcome.Should().Be(IdempotentClaim.Confirmed);
}
[Fact]
public async Task StaleHolder_AfterATakeover_ReleasesNothing_TheNewHolderReleases()
{
var nodeA = Repository();
var nodeB = Repository();
var first = await nodeA.Lease("m2", Timeout);
await AgeAsync("m2");
var second = await nodeB.Lease("m2", Timeout);
second.Outcome.Should().Be(IdempotentClaim.TakenOver);
(await nodeA.Release("m2", first.Token, default)).Should().BeFalse("node A's claim was taken over");
(await ClaimIdAsync("m2")).Should().Be(second.Token, "node B's claim stays");
(await nodeB.Release("m2", second.Token, default)).Should().BeTrue();
(await nodeA.Contains("m2")).Should().BeFalse();
(await nodeA.Lease("m2", Timeout)).Outcome.Should().Be(IdempotentClaim.Claimed);
}
[Fact]
public async Task OwnClaim_ConfirmsAndReleases_ByItsToken()
{
var repository = Repository();
var lease = await repository.Lease("own", Timeout);
(await ClaimIdAsync("own")).Should().Be(lease.Token);
(await repository.Confirm("own", lease.Token, default)).Should().BeTrue();
(await repository.Confirm("own", lease.Token, default)).Should().BeTrue("confirming again finds the same claim");
(await repository.Lease("own", Timeout)).Should().Be(new IdempotentLease(IdempotentClaim.Confirmed, null));
var other = await repository.Lease("own-2", Timeout);
(await repository.Release("own-2", other.Token, default)).Should().BeTrue();
(await repository.Contains("own-2")).Should().BeFalse();
}
[Fact]
public async Task RowWithoutClaimId_IsClaimedAsBefore_AndNoTokenSettlesIt()
{
// A row as a 4.7 node, or Add, writes it: no claim id.
var repository = Repository();
(await repository.Add("legacy")).Should().BeTrue();
(await ClaimIdAsync("legacy")).Should().BeNull();
(await repository.Lease("legacy", Timeout)).Should().Be(new IdempotentLease(IdempotentClaim.InFlight, null));
(await repository.Confirm("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse("no token holds a row without a claim id");
(await repository.Release("legacy", Guid.NewGuid().ToString("N"), default)).Should().BeFalse();
(await repository.Contains("legacy")).Should().BeTrue();
await AgeAsync("legacy");
var takeover = await repository.Lease("legacy", Timeout);
takeover.Outcome.Should().Be(IdempotentClaim.TakenOver, "an abandoned row without a claim id is taken over as before");
(await ClaimIdAsync("legacy")).Should().Be(takeover.Token);
await repository.Add("legacy-done");
await repository.Confirm("legacy-done");
await AgeAsync("legacy-done");
(await repository.Lease("legacy-done", Timeout)).Outcome.Should().Be(IdempotentClaim.Confirmed, "a confirmed row is never taken over");
}
[Fact]
public async Task OldNode_UnconditionalConfirmAndRemove_StillWorkOnAClaimWithAnId()
{
// The rolling upgrade: a 4.8 node holds a claim with an id; a 4.7 node settles the key with the calls it has.
var newNode = Repository();
var oldNode = Repository();
var held = await newNode.Lease("rolling", Timeout);
await oldNode.Confirm("rolling");
(await newNode.Lease("rolling", Timeout)).Outcome.Should().Be(IdempotentClaim.Confirmed);
(await newNode.Confirm("rolling", held.Token, default)).Should().BeTrue("the claim is still the one node A holds");
var again = await newNode.Lease("rolling-2", Timeout);
await oldNode.Remove("rolling-2");
(await newNode.Release("rolling-2", again.Token, default)).Should().BeFalse("the old node removed it already");
(await oldNode.Add("rolling-2")).Should().BeTrue("the old node's insert names its columns and leaves claim_id empty");
(await newNode.Lease("rolling-2", Timeout)).Outcome.Should().Be(IdempotentClaim.InFlight);
}
[Fact]
public async Task TableFromBefore48_GetsItsClaimIdColumn_WhenTheRepositoryCreatesTables()
{
await CreateTableWithoutClaimIdAsync();
await SeedAsync("before", confirmed: false, createdAt: "2000-01-01T00:00:00.0000000+00:00");
var repository = Repository();
var lease = await repository.Lease("after", Timeout);
lease.Outcome.Should().Be(IdempotentClaim.Claimed);
(await ClaimIdAsync("after")).Should().Be(lease.Token);
(await ClaimIdAsync("before")).Should().BeNull("rows written before keep an empty claim id");
(await repository.Lease("before", Timeout)).Outcome.Should().Be(IdempotentClaim.TakenOver);
}
[Fact]
public async Task TableFromBefore48_WithoutCreateTable_FailsTheFirstClaim_NamingTheAlter_AddStillWorks()
{
await CreateTableWithoutClaimIdAsync();
var repository = Repository(createTable: false);
(await repository.Add("plain")).Should().BeTrue("Add writes no claim id and needs no new column");
var act = () => repository.Lease("claimed", Timeout);
(await act.Should().ThrowAsync())
.WithMessage($"*{_table}*claim_id*ALTER TABLE {_table} ADD*claim_id*");
await using (var connection = await Factory().CreateConnectionAsync())
await SqlE2EDatabase.ExecuteAsync(connection, null, AlterSql());
(await repository.Lease("claimed", Timeout)).Outcome.Should().Be(IdempotentClaim.Claimed, "after the ALTER the node claims");
}
/// Makes the row of look abandoned: its stamp moves to the year 2000.
private async Task AgeAsync(string key)
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null,
$"UPDATE {_table} SET created_at = '2000-01-01T00:00:00.0000000+00:00' WHERE processor_name = 'route-1' AND message_key = '{key}'");
}
private async Task ClaimIdAsync(string key)
{
await using var connection = await Factory().CreateConnectionAsync();
await using var cmd = connection.CreateCommand();
cmd.CommandText = $"SELECT claim_id FROM {_table} WHERE processor_name = 'route-1' AND message_key = '{key}'";
return await cmd.ExecuteScalarAsync() is string id ? id : null;
}
/// The table as redb.Route 4.7 created it: no claim_id column.
private async Task CreateTableWithoutClaimIdAsync()
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null, $"""
CREATE TABLE {_table} (
processor_name VARCHAR(128) NOT NULL,
message_key VARCHAR(255) NOT NULL,
created_at VARCHAR(64) NOT NULL,
confirmed INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (processor_name, message_key)
)
""");
}
private async Task SeedAsync(string key, bool confirmed, string createdAt)
{
await using var connection = await Factory().CreateConnectionAsync();
await SqlE2EDatabase.ExecuteAsync(connection, null,
$"INSERT INTO {_table} (processor_name, message_key, created_at, confirmed) VALUES ('route-1', '{key}', '{createdAt}', {(confirmed ? 1 : 0)})");
}
private string AlterSql() => Provider.Factory.GetType().Name == "SqlClientFactory"
? $"ALTER TABLE {_table} ADD claim_id NVARCHAR(36) NULL"
: $"ALTER TABLE {_table} ADD COLUMN claim_id VARCHAR(36) NULL";
private SqlIdempotentRepository Repository(bool createTable = true) =>
new(Factory(), new SqlIdempotentOptions { ProcessorName = "route-1", TableName = _table, CreateTable = createTable });
private ISqlConnectionFactory Factory() =>
new SqlConnectionFactory(new SqlConnectionOptions { ConnectionString = Provider.ConnectionString, ProviderFactory = Provider.Factory });
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlRepositoryBootstrapAmbientTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/SqlRepositoryBootstrapAmbientTestsBase.cs
----
using System.Transactions;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Repositories;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The raw-ADO repositories create their table on first use. That first use may happen inside the transaction of whatever
/// message came first (a .Transacted() route); if that transaction rolls back, the table must still be there for the
/// next call. On PostgreSQL and SQL Server DDL is transactional, so a table created inside the message's transaction goes
/// with its rollback.
///
public abstract class SqlRepositoryBootstrapAmbientTestsBase : IAsyncLifetime
{
private readonly string _suffix = Guid.NewGuid().ToString("N")[..12];
private readonly List _tables = [];
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
try
{
await using var connection = await Factory().CreateConnectionAsync();
foreach (var table in _tables)
await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, null, $"DROP TABLE {table}"));
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
[Fact]
public async Task Idempotent_FirstCallInARolledBackTransaction_TheTableStays()
{
var table = Track("rsql_idem_" + _suffix);
var repository = new SqlIdempotentRepository(Factory(), new SqlIdempotentOptions { ProcessorName = "route-1", TableName = table });
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
(await repository.Add("k1")).Should().BeTrue();
// The route failed: the scope ends without Complete().
}
var next = await Outcome.Of(() => repository.Add("k2"));
next.Should().BeNull("the repository's table does not belong to the message that happened to come first: " +
Outcome.Describe(next));
}
[Fact]
public async Task ClaimCheck_FirstCallInARolledBackTransaction_TheTableStays()
{
var table = Track("rsql_claim_" + _suffix);
var repository = new SqlClaimCheckRepository(Factory(), new SqlClaimCheckOptions { TableName = table, CleanupInterval = 0 });
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await repository.Store("claim-1", new byte[] { 1 });
}
var next = await Outcome.Of(() => repository.Store("claim-2", new byte[] { 2 }));
next.Should().BeNull("the repository's table does not belong to the message that happened to come first: " +
Outcome.Describe(next));
}
private string Track(string table)
{
_tables.Add(table);
return table;
}
private ISqlConnectionFactory Factory() =>
new SqlConnectionFactory(new SqlConnectionOptions { ConnectionString = Provider.ConnectionString, ProviderFactory = Provider.Factory });
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Base/StreamListLifetimeTestsBase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Base/StreamListLifetimeTestsBase.cs
----
using System.Data.Common;
using System.Transactions;
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Base;
///
/// The lifetime of a streamed result (outputType=StreamList ) against real servers. The connector must release a
/// stream the route never read when the exchange ends. The provider facts below — measured, not wished — are why a stream is
/// refused inside a route transaction: a transaction does not commit while a reader is open, a volatile enlistment cannot
/// close the reader in time on every driver, and a second connection in the same scope needs a distributed transaction.
///
public abstract class StreamListLifetimeTestsBase : IAsyncLifetime
{
private SqlE2EDatabase? _db;
private SqlE2EDatabase? _target;
/// The provider under test.
protected abstract SqlE2EProvider Provider { get; }
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
private SqlE2EDatabase Target => _target ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
private string Select => $"SELECT id, val FROM {Db.Table} ORDER BY id";
///
public async Task InitializeAsync()
{
_db = await SqlE2EDatabase.CreateAsync(Provider);
_target = await SqlE2EDatabase.CreateAsync(Provider);
for (var id = 1; id <= 3; id++)
await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "v" + id));
}
///
public async Task DisposeAsync()
{
try
{
if (_db is not null)
await _db.DisposeAsync();
}
finally
{
try
{
if (_target is not null)
await _target.DisposeAsync();
}
finally
{
(Provider as IDisposable)?.Dispose();
}
}
}
[Fact]
public async Task StreamNotConsumed_ExchangeDisposed_ConnectionReleased()
{
var factory = Db.CreateConnectionFactory();
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, Select, new() { ["outputType"] = "StreamList" });
var exchange = new Exchange(new Message("go"));
await endpoint.CreateProducer().Process(exchange, CancellationToken.None);
await exchange.DisposeAsync();
factory.OpenConnections.Should().Be(0,
"a streamed result the route never read releases its reader, command, transaction and connection when the exchange ends");
}
[Fact]
public async Task ReaderOpen_ScopeCompletes_TransactionInDoubt()
{
// The connection outlives the scope, as a streamed result's connection would: the scope commits with the reader open.
DbConnection? connection = null;
DbCommand? command = null;
var thrown = await Outcome.Of(async () =>
{
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
connection = await Db.OpenAsync();
command = connection.CreateCommand();
command.CommandText = Select;
var reader = await command.ExecuteReaderAsync();
(await reader.ReadAsync()).Should().BeTrue();
scope.Complete();
});
try
{
thrown.Should().BeOfType(
$"the transaction cannot commit while the reader is still open on its connection ({Outcome.Describe(thrown)})");
}
finally
{
command?.Dispose();
if (connection is not null)
await connection.DisposeAsync();
}
}
[Fact]
public async Task ReaderClosedByVolatileEnlistmentOnPrepare_CommitsOnlyWhereDriverPreparesItFirst()
{
DbConnection? connection = null;
var thrown = await Outcome.Of(async () =>
{
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
connection = await Db.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = Select;
var reader = await command.ExecuteReaderAsync();
(await reader.ReadAsync()).Should().BeTrue();
Transaction.Current!.EnlistVolatile(new CloseOnPrepare(reader, command), EnlistmentOptions.None);
scope.Complete();
});
try
{
if (Provider.ReaderClosedOnPrepareLetsScopeCommit)
thrown.Should().BeNull(Outcome.Describe(thrown));
else
thrown.Should().BeAssignableTo(
$"the driver commits before the volatile enlistment closes the reader ({Outcome.Describe(thrown)})");
}
finally
{
if (connection is not null)
await connection.DisposeAsync();
}
}
[Fact]
public async Task ReaderOnOneConnection_WriteOnSecond_InsideOneScope_CannotCommit()
{
Exception? writeError = null;
var scopeError = await Outcome.Of(async () =>
{
using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
await using var readConnection = await Db.OpenAsync();
await using var readCommand = readConnection.CreateCommand();
readCommand.CommandText = Select;
await using var reader = await readCommand.ExecuteReaderAsync();
(await reader.ReadAsync()).Should().BeTrue();
// What a batch fed by a streamed result would do: a second connection writes while the first still reads.
writeError = await Outcome.Of(async () =>
{
await using var writeConnection = await Target.OpenAsync();
await SqlE2EDatabase.ExecuteAsync(writeConnection, null, Provider.InsertLiteral(Target.Table, 1, "w"));
});
while (await reader.ReadAsync()) { }
if (writeError is null)
scope.Complete();
});
// Either outcome means the scope cannot commit: the promotion is refused, or the driver waits for it until the
// write times out. Which one comes depends on the machine, not on the connector.
var failure = writeError ?? scopeError;
var outcome = $"write: {Outcome.Describe(writeError)}, scope: {Outcome.Describe(scopeError)}";
failure.Should().NotBeNull($"two connections at once in one scope need a distributed transaction ({outcome})");
(failure is TransactionException || Provider.IsSecondConnectionTimeout(failure!)).Should().BeTrue(
$"the scope fails with a transaction error or a timeout of the waiting write ({outcome})");
(await Target.ReadIdsAsync()).Should().BeEmpty();
}
/// A volatile resource manager that closes a reader and its command when the transaction prepares.
private sealed class CloseOnPrepare(DbDataReader reader, DbCommand command) : IEnlistmentNotification
{
public void Prepare(PreparingEnlistment preparingEnlistment)
{
Close();
preparingEnlistment.Prepared();
}
public void Commit(Enlistment enlistment) => enlistment.Done();
public void Rollback(Enlistment enlistment)
{
Close();
enlistment.Done();
}
public void InDoubt(Enlistment enlistment) => enlistment.Done();
private void Close()
{
reader.Dispose();
command.Dispose();
}
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/CrossProvider/PostgresToMsSqlStreamingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/CrossProvider/PostgresToMsSqlStreamingE2ETests.cs
----
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.CrossProvider;
///
/// The same route shape across two databases: a PostgreSQL query streamed straight into a SQL Server batch. The connector is
/// one component for any ADO.NET provider; only the data sources differ.
///
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres+mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresToMsSqlStreamingE2ETests : IAsyncLifetime
{
private const int Rows = 5_000;
private readonly PostgresE2EProvider _postgres = new();
private readonly MsSqlE2EProvider _msSql = new(xactAbortOn: false);
private SqlE2EDatabase? _source;
private SqlE2EDatabase? _target;
private SqlE2EDatabase Source => _source ?? throw new InvalidOperationException("The tables are created in InitializeAsync.");
private SqlE2EDatabase Target => _target ?? throw new InvalidOperationException("The tables are created in InitializeAsync.");
///
public async Task InitializeAsync()
{
_source = await SqlE2EDatabase.CreateAsync(_postgres, _postgres.CreateNullableTableSql);
_target = await SqlE2EDatabase.CreateAsync(_msSql, _msSql.CreateNullableTableSql);
}
///
public async Task DisposeAsync()
{
try
{
if (_source is not null)
await _source.DisposeAsync();
}
finally
{
if (_target is not null)
await _target.DisposeAsync();
}
}
[Fact]
public async Task StreamList_Postgres_ToBatch_MsSql_AllCopied()
{
var seed = Enumerable.Range(1, Rows)
.Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i, ["n"] = i % 7 == 0 ? null : (long)i })
.ToList();
var (_, seedError) = await SqlBatchRun.RunAsync(Source, $"INSERT INTO {Source.Table} (id, val, n) VALUES (:#id, :#val, :#n)",
seed, breakOnError: null, batchSize: 1000);
seedError.Should().BeNull(Outcome.Describe(seedError));
var sourceFactory = Source.CreateConnectionFactory();
var targetFactory = Target.CreateConnectionFactory();
await using var context = new RouteContext();
context.AddComponent(new SqlComponent());
context.AddToRegistry("pg", sourceFactory);
context.AddToRegistry("ms", targetFactory);
context.AddRoutes(r => r.From("direct://pg-to-ms")
.To($"sql:SELECT id, val, n FROM {Source.Table} ORDER BY id?dataSource=pg&outputType=StreamList")
.To($"sql:INSERT INTO {Target.Table} (id, val, n) VALUES (:#id, :#val, :#n)?dataSource=ms&batchSize=500&outputType=None"));
await context.Start();
var producer = context.GetEndpoint("direct://pg-to-ms").CreateProducer();
await producer.Start();
var thrown = await Outcome.Of(() => producer.Process(new Exchange(new Message("copy"))));
thrown.Should().BeNull(Outcome.Describe(thrown));
var copied = await Target.QueryAsync($"SELECT COUNT(*), COUNT(n), MAX(id) FROM {Target.Table}");
Convert.ToInt32(copied[0][0]).Should().Be(Rows);
Convert.ToInt32(copied[0][1]).Should().Be(Rows - Rows / 7, "NULLs travel as NULLs");
Convert.ToInt32(copied[0][2]).Should().Be(Rows);
sourceFactory.OpenConnections.Should().Be(0, "the PostgreSQL reader's connection is released after the stream is consumed");
targetFactory.OpenConnections.Should().Be(0);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/FirebirdE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/FirebirdE2EProvider.cs
----
using System.Data.Common;
using FirebirdSql.Data.FirebirdClient;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// Firebird 5 through FirebirdClient (tier 2). Container route-firebird , profile firebird of docker-compose.tests.yml ,
/// brought up for a run and removed after it. The connector reaches Firebird with the default placeholderStyle=At .
///
///
/// Pooling is off: a pooled attachment can keep the table in use and have the DROP TABLE of the test's dispose refused.
///
public sealed class FirebirdE2EProvider : SqlE2EProvider
{
private const string EnvironmentVariable = "ROUTE_SQL_FIREBIRD_CS";
private const string DefaultConnectionString =
"User=SYSDBA;Password=1;Database=/var/lib/firebird/data/route_sql.fdb;DataSource=127.0.0.1;Port=3050;Charset=UTF8;" +
"Pooling=false;Connection Timeout=15";
public override string Name => "firebird";
public override DbProviderFactory Factory => FirebirdClientFactory.Instance;
public override string ConnectionString =>
Environment.GetEnvironmentVariable(EnvironmentVariable)?.Trim() is { Length: > 0 } cs ? cs : DefaultConnectionString;
public override string StartHint =>
$"Tier 2, temporary: '{(global::redb.Route.Tests.Shared.TestStand.Up(Name))}' (container route-{Name}), " +
$"and 'docker compose -f redb.Route/docker-compose.tests.yml --profile {Name} down -v' after the run; override the connection with {EnvironmentVariable}.";
public override string CreateTableSql(string table) =>
$"CREATE TABLE {table} (id INTEGER NOT NULL PRIMARY KEY, val VARCHAR(50) NOT NULL)";
public override string CreateNullableTableSql(string table) =>
$"CREATE TABLE {table} (id INTEGER NOT NULL PRIMARY KEY, val VARCHAR(50), n BIGINT)";
public override string ReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (:#id, :#val) RETURNING id";
public override string NativeReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (@id, @val) RETURNING id";
public override string TransactionKillingLiteral(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST('abc' AS INTEGER), 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST(:#id AS INTEGER), :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "abc", ["val"] = "x" },
new() { ["id"] = "3", ["val"] = "c" },
];
// Measured 2026-09-15 (FirebirdE2ETests): every statement runs under its own implicit savepoint, so a failed one is undone
// and the transaction goes on.
public override int[] LoopContinueDuplicateKeyRows => [1, 3];
public override int[] LoopContinueTransactionKillingRows => [1, 3];
public override bool DuplicateKeyDestroysTransaction => false;
public override bool TransactionKillingErrorDestroysTransaction => false;
public override bool ReportsSavepointSupport => true;
public override bool CommandAfterTransactionKillingErrorIsRejected => false;
public override bool CanCreateBatch => false;
public override bool PrepareRejectsUntypedParameters => false;
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MariaDbE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MariaDbE2EProvider.cs
----
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// MariaDB 11 through MySqlConnector (tier 2). Container route-mariadb , profile mariadb of docker-compose.tests.yml , brought
/// up for a run and removed after it.
///
public sealed class MariaDbE2EProvider : MySqlFamilyE2EProvider
{
public override string Name => "mariadb";
protected override string EnvironmentVariable => "ROUTE_SQL_MARIADB_CS";
protected override string DefaultConnectionString =>
"Server=127.0.0.1;Port=3307;User ID=root;Password=1;Database=route_sql;Connection Timeout=15";
public override string ReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (:#id, :#val) RETURNING id";
public override string NativeReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (@id, @val) RETURNING id";
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MsSqlE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MsSqlE2EProvider.cs
----
using System.Data.Common;
using Microsoft.Data.SqlClient;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// SQL Server through Microsoft.Data.SqlClient, in two session flavours: XACT_ABORT OFF (server default)
/// and XACT_ABORT ON . Container msdb . Each flavour uses its own application name, so pooled
/// connections never carry one flavour's session setting into the other's tests.
///
public sealed class MsSqlE2EProvider : SqlE2EProvider
{
private const string EnvironmentVariable = "ROUTE_SQL_MSSQL_CS";
private const string DefaultConnectionString =
"Server=127.0.0.1,1433;Database=tempdb;User Id=sa;Password=1;TrustServerCertificate=true;Connect Timeout=5";
private readonly bool _xactAbortOn;
public MsSqlE2EProvider(bool xactAbortOn) => _xactAbortOn = xactAbortOn;
public override string Name => _xactAbortOn ? "mssql-xact-on" : "mssql";
public override DbProviderFactory Factory => SqlClientFactory.Instance;
public override string ConnectionString
{
get
{
var raw = Environment.GetEnvironmentVariable(EnvironmentVariable)?.Trim() is { Length: > 0 } cs ? cs : global::redb.Route.Tests.Shared.TestDatabases.MsSql(DefaultConnectionString);
return new SqlConnectionStringBuilder(raw) { ApplicationName = "rsql-e2e-" + Name }.ConnectionString;
}
}
public override string StartHint =>
$"Start it with 'docker start msdb' (or 'docker compose -f redb.Route/docker-compose.tests.yml up -d msdb'); " +
$"the stock compose image uses another sa password — set {EnvironmentVariable}. Use 127.0.0.1, not localhost.";
public override string SessionInitSql => _xactAbortOn ? "SET XACT_ABORT ON" : "SET XACT_ABORT OFF";
public override string CreateTableSql(string table) =>
$"CREATE TABLE {table} (id int PRIMARY KEY, val nvarchar(50) NOT NULL)";
public override string CreateNullableTableSql(string table) =>
$"CREATE TABLE {table} (id int PRIMARY KEY, val nvarchar(50) NULL, n bigint NULL)";
public override string ReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) OUTPUT inserted.id VALUES (:#id, :#val)";
public override string NativeReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) OUTPUT inserted.id VALUES (@id, @val)";
public override string TransactionKillingLiteral(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST('abc' AS int), 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST(:#id AS int), :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "abc", ["val"] = "x" },
new() { ["id"] = "3", ["val"] = "c" },
];
// Conversion error 245 rolls the server transaction back even with XACT_ABORT OFF; with ON any error does.
// SqlClient then runs the next command in autocommit and only Commit/Save reject the dead transaction.
public override int[] LoopContinueDuplicateKeyRows => _xactAbortOn ? [3] : [1, 3];
public override int[] LoopContinueTransactionKillingRows => [3];
public override bool DuplicateKeyDestroysTransaction => _xactAbortOn;
public override bool TransactionKillingErrorDestroysTransaction => true;
public override bool ReportsSavepointSupport => false;
public override bool CommandAfterTransactionKillingErrorIsRejected => false;
public override bool CanCreateBatch => true;
public override bool PrepareRejectsUntypedParameters => true;
public override bool ReaderClosedOnPrepareLetsScopeCommit => true;
///
/// Measured on the Linux gate (SQL Server 2022, 1.5 CPUs): the write on the second connection ran into the command
/// timeout (number -2) while the first one still read; on faster machines the promotion is refused at once.
///
public override bool IsSecondConnectionTimeout(Exception error) => error is SqlException { Number: -2 };
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MySqlE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MySqlE2EProvider.cs
----
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// MySQL 8.4 through MySqlConnector (tier 2). Container route-mysql , profile mysql of docker-compose.tests.yml , brought up
/// for a run and removed after it.
///
public sealed class MySqlE2EProvider : MySqlFamilyE2EProvider
{
public override string Name => "mysql";
protected override string EnvironmentVariable => "ROUTE_SQL_MYSQL_CS";
protected override string DefaultConnectionString =>
"Server=127.0.0.1;Port=3306;User ID=root;Password=1;Database=route_sql;Connection Timeout=15";
public override string ReturningInsertSql(string table) =>
throw new NotSupportedException("MySQL has no INSERT … RETURNING; its keys come from LAST_INSERT_ID(), which a batch does not collect.");
public override string NativeReturningInsertSql(string table) => ReturningInsertSql(table);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MySqlFamilyE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/MySqlFamilyE2EProvider.cs
----
using System.Data.Common;
using MySqlConnector;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// MySQL and MariaDB through MySqlConnector (tier 2): the same driver, the same statements and the same measured facts. The
/// connector reaches both with the default placeholderStyle=At .
///
public abstract class MySqlFamilyE2EProvider : SqlE2EProvider
{
public override DbProviderFactory Factory => MySqlConnectorFactory.Instance;
/// Environment variable that overrides .
protected abstract string EnvironmentVariable { get; }
/// Connection to the temporary container.
protected abstract string DefaultConnectionString { get; }
public override string ConnectionString =>
Environment.GetEnvironmentVariable(EnvironmentVariable)?.Trim() is { Length: > 0 } cs ? cs : DefaultConnectionString;
public override string StartHint =>
$"Tier 2, temporary: '{(global::redb.Route.Tests.Shared.TestStand.Up(Name))}' (container route-{Name}), " +
$"and 'docker compose -f redb.Route/docker-compose.tests.yml --profile {Name} down -v' after the run; override the connection with {EnvironmentVariable}.";
// Strict sql_mode (the default of both servers) turns a text that is not a number into error 1366 instead of a warning.
public override string TransactionKillingLiteral(string table) =>
$"INSERT INTO {table} (id, val) VALUES ('abc', 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (:#id, :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "abc", ["val"] = "x" },
new() { ["id"] = "3", ["val"] = "c" },
];
// Measured 2026-09-15 (MySqlE2ETests, MariaDbE2ETests): InnoDB rolls back the failed statement only and the transaction
// goes on; MySqlConnector 2.6 has DbBatch, does not name the failed command of a batch, and reports no savepoint support
// although Save / Rollback(name) work.
public override int[] LoopContinueDuplicateKeyRows => [1, 3];
public override int[] LoopContinueTransactionKillingRows => [1, 3];
public override bool DuplicateKeyDestroysTransaction => false;
public override bool TransactionKillingErrorDestroysTransaction => false;
public override bool ReportsSavepointSupport => false;
public override bool CommandAfterTransactionKillingErrorIsRejected => false;
public override bool CanCreateBatch => true;
public override bool PrepareRejectsUntypedParameters => false;
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/OracleE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/OracleE2EProvider.cs
----
using System.Data.Common;
using Oracle.ManagedDataAccess.Client;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// Oracle Free 23 through ODP.NET (tier 2). Container route-oracle , profile oracle of docker-compose.tests.yml , brought up for
/// a run and removed after it. The connector reaches Oracle with placeholderStyle=Colon .
///
public sealed class OracleE2EProvider : SqlE2EProvider
{
private const string EnvironmentVariable = "ROUTE_SQL_ORACLE_CS";
private const string DefaultConnectionString =
"User Id=rsql;Password=Rsql2026;Data Source=127.0.0.1:1521/FREEPDB1;Connection Timeout=15";
public override string Name => "oracle";
public override DbProviderFactory Factory => OracleClientFactory.Instance;
public override string ConnectionString =>
Environment.GetEnvironmentVariable(EnvironmentVariable)?.Trim() is { Length: > 0 } cs ? cs : DefaultConnectionString;
public override string StartHint =>
$"Tier 2, temporary: '{(global::redb.Route.Tests.Shared.TestStand.Up(Name))}' (container route-{Name}), " +
$"and 'docker compose -f redb.Route/docker-compose.tests.yml --profile {Name} down -v' after the run; override the connection with {EnvironmentVariable}.";
public override string CreateTableSql(string table) =>
$"CREATE TABLE {table} (id NUMBER(10) PRIMARY KEY, val VARCHAR2(50) NOT NULL)";
public override string CreateNullableTableSql(string table) =>
$"CREATE TABLE {table} (id NUMBER(10) PRIMARY KEY, val VARCHAR2(50) NULL, n NUMBER(19) NULL)";
public override string ReturningInsertSql(string table) =>
throw new NotSupportedException("Oracle returns keys only through RETURNING … INTO OUT parameters, which a batch does not collect.");
public override string NativeReturningInsertSql(string table) => ReturningInsertSql(table);
public override string TransactionKillingLiteral(string table) =>
$"INSERT INTO {table} (id, val) VALUES (TO_NUMBER('abc'), 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (TO_NUMBER(:#id), :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "abc", ["val"] = "x" },
new() { ["id"] = "3", ["val"] = "c" },
];
// Measured 2026-09-15 (OracleE2ETests): Oracle rolls back the failed statement only and the transaction goes on; ODP.NET
// 23.26 reports and supports savepoints, has no DbBatch and binds by position by default.
public override int[] LoopContinueDuplicateKeyRows => [1, 3];
public override int[] LoopContinueTransactionKillingRows => [1, 3];
public override bool DuplicateKeyDestroysTransaction => false;
public override bool TransactionKillingErrorDestroysTransaction => false;
public override bool ReportsSavepointSupport => true;
public override bool CommandAfterTransactionKillingErrorIsRejected => false;
public override bool CanCreateBatch => false;
public override bool PrepareRejectsUntypedParameters => false;
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/Outcome.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/Outcome.cs
----
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// Runs an operation whose failure is the observed fact, not a test error: the exception is returned so the
/// test can assert on it. Nothing is swallowed — every caller asserts on the result.
///
public static class Outcome
{
/// The exception the operation threw, or null when it completed.
public static async Task Of(Func operation)
{
try
{
await operation();
return null;
}
catch (Exception ex)
{
return ex;
}
}
/// Short description for assertion messages.
public static string Describe(Exception? exception) =>
exception is null ? "no exception" : $"{exception.GetType().Name}: {exception.Message.Split('\n')[0].Trim()}";
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/PostgresE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/PostgresE2EProvider.cs
----
using System.Data.Common;
using Npgsql;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
/// PostgreSQL through Npgsql. Container pgdb (profile pgdb of docker-compose.tests.yml ).
public sealed class PostgresE2EProvider : SqlE2EProvider
{
private const string EnvironmentVariable = "ROUTE_SQL_PG_CS";
private const string DefaultConnectionString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=postgres;Timeout=5";
public override string Name => "postgres";
public override DbProviderFactory Factory => NpgsqlFactory.Instance;
// Npgsql 10 leaves PostgresException.BatchCommand null unless the connection opts in, and the suite
// checks the exact failed item of a batch: the option is set here, also on an overriding string.
public override string ConnectionString => new NpgsqlConnectionStringBuilder(
Environment.GetEnvironmentVariable(EnvironmentVariable)?.Trim() is { Length: > 0 } cs ? cs : global::redb.Route.Tests.Shared.TestDatabases.Postgres(DefaultConnectionString))
{
IncludeFailedBatchedCommand = true,
}.ConnectionString;
public override string StartHint =>
$"Start it with 'docker start pgdb' (or 'docker compose -f redb.Route/docker-compose.tests.yml up -d pgdb'); override the connection with {EnvironmentVariable}.";
public override string ReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (:#id, :#val) RETURNING id";
public override string NativeReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (@id, @val) RETURNING id";
public override string TransactionKillingLiteral(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST('abc' AS int), 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (CAST(:#id AS int), :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = "1", ["val"] = "a" },
new() { ["id"] = "abc", ["val"] = "x" },
new() { ["id"] = "3", ["val"] = "c" },
];
// Any error aborts the transaction block; COMMIT then answers ROLLBACK and Npgsql does not raise.
public override int[] LoopContinueDuplicateKeyRows => [];
public override int[] LoopContinueTransactionKillingRows => [];
public override bool DuplicateKeyDestroysTransaction => false;
public override bool TransactionKillingErrorDestroysTransaction => false;
public override bool ReportsSavepointSupport => true;
public override bool CommandAfterTransactionKillingErrorIsRejected => true;
public override bool CanCreateBatch => true;
public override bool PrepareRejectsUntypedParameters => false;
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/RecordingConnectionFactory.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/RecordingConnectionFactory.cs
----
using System.Data;
using System.Data.Common;
using redb.Route.Sql.Connection;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// over , so connector connections get the
/// provider's session settings. Records the read-only hint of every request so routing decisions can be asserted, and counts
/// the connections it handed out that are still open, so a test can see a connection that was never returned.
///
public sealed class RecordingConnectionFactory : ISqlConnectionFactory
{
private readonly SqlE2EDatabase _database;
private readonly List _readOnlyRequests = [];
private int _openConnections;
internal RecordingConnectionFactory(SqlE2EDatabase database) => _database = database;
/// The readOnly argument of every request, in order.
public IReadOnlyList ReadOnlyRequests
{
get { lock (_readOnlyRequests) return [.. _readOnlyRequests]; }
}
/// Connections handed out and not closed yet.
public int OpenConnections => Volatile.Read(ref _openConnections);
///
public async Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default)
{
lock (_readOnlyRequests) _readOnlyRequests.Add(readOnly);
var connection = await _database.OpenAsync(ct);
Interlocked.Increment(ref _openConnections);
connection.StateChange += (_, change) =>
{
if (change.OriginalState == ConnectionState.Open && change.CurrentState == ConnectionState.Closed)
Interlocked.Decrement(ref _openConnections);
};
return connection;
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlBatchRun.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlBatchRun.cs
----
using System.Collections;
using redb.Route.Core;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
/// Runs the connector's batch once against an E2E table and captures the outcome for assertions.
public static class SqlBatchRun
{
/// Produces through a fresh Execute endpoint; returns the exchange and what it threw.
public static async Task<(Exchange Exchange, Exception? Thrown)> RunAsync(
SqlE2EDatabase database, string sql, IList items, bool? breakOnError, int batchSize = 10,
Dictionary? extraParameters = null)
{
var parameters = new Dictionary
{
["outputType"] = "None",
["batchSize"] = batchSize.ToString(),
};
if (breakOnError is { } mode)
parameters["breakBatchOnError"] = mode ? "true" : "false";
if (extraParameters is not null)
foreach (var (key, value) in extraParameters)
parameters[key] = value;
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, database.CreateConnectionFactory(), sql, parameters);
var producer = endpoint.CreateProducer();
var exchange = new Exchange(new Message(items));
var thrown = await Outcome.Of(() => producer.Process(exchange, CancellationToken.None));
return (exchange, thrown);
}
///
/// Indexes carried by the redbSql.batchErrors header, read by reflection so the tests compile against code that
/// does not have the header's element type yet.
///
public static IReadOnlyList BatchErrorIndexes(Exchange exchange)
{
if (!exchange.In.Headers.TryGetValue("redbSql.batchErrors", out var header) || header is not IEnumerable errors)
return [];
return errors.Cast()
.Select(e => Convert.ToInt32(e.GetType().GetProperty("Index")?.GetValue(e)))
.ToList();
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlE2EDatabase.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlE2EDatabase.cs
----
using System.Data.Common;
using System.Net.Sockets;
using redb.Route.Sql.Connection;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// A uniquely named table on one provider for the lifetime of a test. The three target frameworks run the
/// suites in parallel against the same servers, so tests share nothing but the server itself. The table is
/// dropped on dispose; a failing drop is not swallowed.
///
public sealed class SqlE2EDatabase : IAsyncDisposable
{
private bool _created;
private SqlE2EDatabase(SqlE2EProvider provider)
{
Provider = provider;
Table = "rsql_" + Guid.NewGuid().ToString("N")[..12];
}
/// The provider this table lives on.
public SqlE2EProvider Provider { get; }
/// Unique table name.
public string Table { get; }
/// Creates the table with the provider's default DDL, or with .
public static async Task CreateAsync(SqlE2EProvider provider, Func? createTableSql = null)
{
var database = new SqlE2EDatabase(provider);
await database.ExecuteAsync((createTableSql ?? provider.CreateTableSql)(database.Table));
database._created = true;
return database;
}
/// Opens a connection with the provider's session settings applied.
/// The server is not reachable; the message says how to start it.
public async Task OpenAsync(CancellationToken ct = default)
{
var connection = Provider.Factory.CreateConnection()
?? throw new InvalidOperationException($"{Provider.Factory.GetType().Name}.CreateConnection() returned null.");
var ready = false;
try
{
connection.ConnectionString = Provider.ConnectionString;
try
{
await connection.OpenAsync(ct);
}
// Inside an ambient transaction the open also enlists, and an enlistment failure (a promotion to a
// distributed transaction above all) is the outcome a test looks at, not an unreachable server.
catch (Exception ex) when ((ex is DbException or SocketException or TimeoutException or InvalidOperationException)
&& System.Transactions.Transaction.Current is null)
{
throw new InvalidOperationException(
$"SQL E2E: provider '{Provider.Name}' is not reachable. {Provider.StartHint}", ex);
}
if (Provider.SessionInitSql is { } init)
await ExecuteAsync(connection, null, init, ct);
ready = true;
return connection;
}
finally
{
if (!ready)
await connection.DisposeAsync();
}
}
/// Connection factory for the connector: every connection it hands out is opened by .
public RecordingConnectionFactory CreateConnectionFactory() => new(this);
/// Executes a non-query on an open connection.
public static async Task ExecuteAsync(DbConnection connection, DbTransaction? transaction, string sql, CancellationToken ct = default)
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
command.Transaction = transaction;
return await command.ExecuteNonQueryAsync(ct);
}
/// Executes a non-query on a fresh connection.
public async Task ExecuteAsync(string sql)
{
await using var connection = await OpenAsync();
await ExecuteAsync(connection, null, sql);
}
/// Ids in the table, ascending, read on a fresh connection — what is actually persisted.
public async Task ReadIdsAsync()
{
var rows = await QueryAsync($"SELECT id FROM {Table} ORDER BY id");
return rows.Select(r => Convert.ToInt32(r[0])).ToArray();
}
/// All rows of a query on a fresh connection; becomes null.
public async Task> QueryAsync(string sql)
{
await using var connection = await OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = sql;
var rows = new List();
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var row = new object?[reader.FieldCount];
for (var i = 0; i < row.Length; i++)
row[i] = reader.IsDBNull(i) ? null : reader.GetValue(i);
rows.Add(row);
}
return rows;
}
///
public async ValueTask DisposeAsync()
{
if (_created)
await ExecuteAsync($"DROP TABLE {Table}");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlE2EProvider.cs
----
using System.Data.Common;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// One database the SQL E2E suites run against: how to reach it, the statements each scenario needs, and
/// the driver/server facts the characterization suite pins down. The expectations are facts measured on
/// real servers, not wishes: when a driver upgrade changes one of them, the characterization suite fails
/// first and the batch design is revisited before any product code relies on the old fact.
///
///
/// "Transaction-killing error" means the error class that rolls the whole server transaction back on at
/// least one provider (SQL Server conversion error 245, SQLite INSERT OR ROLLBACK ). PostgreSQL gets a
/// conversion error too, for symmetry: there any error aborts the transaction block, yet a savepoint still
/// recovers it.
///
public abstract class SqlE2EProvider
{
/// Trait value (SqlProvider=... ) and the name used in messages.
public abstract string Name { get; }
/// ADO.NET factory; the connector gets it through a registered connection factory.
public abstract DbProviderFactory Factory { get; }
/// Connection string, environment override first.
public abstract string ConnectionString { get; }
/// How to bring the server up when it is not reachable.
public abstract string StartHint { get; }
/// SQL run on every opened connection (session settings), or null.
public virtual string? SessionInitSql => null;
// ── Statements ───────────────────────────────────────────────────────────
/// A two-column table: integer primary key and a non-null text value.
public virtual string CreateTableSql(string table) =>
$"CREATE TABLE {table} (id int PRIMARY KEY, val varchar(50) NOT NULL)";
/// Like , but val and a bigint column n are nullable.
public virtual string CreateNullableTableSql(string table) =>
$"CREATE TABLE {table} (id int PRIMARY KEY, val varchar(50) NULL, n bigint NULL)";
/// Insert through the connector (:#name ) that returns the inserted id as a result set (RETURNING / OUTPUT ).
public abstract string ReturningInsertSql(string table);
/// in the driver's own syntax (@name ), for ADO.NET commands built directly.
public abstract string NativeReturningInsertSql(string table);
/// Literal insert of one row.
public string InsertLiteral(string table, int id, string val) =>
$"INSERT INTO {table} (id, val) VALUES ({id}, '{val}')";
/// Parameterized insert the connector binds per batch item.
public string InsertSql(string table) => $"INSERT INTO {table} (id, val) VALUES (:#id, :#val)";
/// in the driver's own syntax (@name ), for ADO.NET commands built directly.
public string NativeInsertSql(string table) => $"INSERT INTO {table} (id, val) VALUES (@id, @val)";
/// Literal statement that raises the transaction-killing error after row 1 exists.
public abstract string TransactionKillingLiteral(string table);
/// Parameterized statement whose middle item of fails.
public abstract string TransactionKillingBatchSql(string table);
/// Three items for : ids 1 and 3 succeed, the middle one fails.
public abstract List> TransactionKillingItems();
/// Three items for : ids 1 and 3 succeed, the middle one repeats id 1.
public List> DuplicateKeyItems() =>
[
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 1, ["val"] = "dup" },
new() { ["id"] = 3, ["val"] = "c" },
];
// ── Measured facts (characterization expectations) ──────────────────────
/// Rows left after: insert 1, duplicate key, insert 3, commit — errors ignored, no savepoints.
public abstract int[] LoopContinueDuplicateKeyRows { get; }
/// Rows left after: insert 1, transaction-killing error, insert 3, commit attempt.
public abstract int[] LoopContinueTransactionKillingRows { get; }
/// After a duplicate key inside a savepoint, rolling back to that savepoint fails.
public abstract bool DuplicateKeyDestroysTransaction { get; }
/// After the transaction-killing error inside a savepoint, rolling back to that savepoint fails.
public abstract bool TransactionKillingErrorDestroysTransaction { get; }
/// What reports (not whether savepoints work).
public abstract bool ReportsSavepointSupport { get; }
///
/// The statement sent right after the transaction-killing error is refused by the driver or server.
/// False means it runs — on SQL Server outside any transaction, in autocommit.
///
public abstract bool CommandAfterTransactionKillingErrorIsRejected { get; }
/// What reports.
public abstract bool CanCreateBatch { get; }
/// refuses parameters whose type was never set explicitly.
public abstract bool PrepareRejectsUntypedParameters { get; }
///
/// A reader left open in a and closed by a volatile enlistment on
/// Prepare lets the scope commit. False where the driver commits before volatile enlistments are prepared.
///
public virtual bool ReaderClosedOnPrepareLetsScopeCommit => false;
///
/// The connection runs another statement while one of its readers is still open. False where the driver refuses it
/// ("a command is already in progress", "already an open DataReader").
///
public virtual bool ReaderConnectionRunsAnotherCommand => false;
///
/// The way a second connection in a scope can fail besides a :
/// a driver that waits for the promotion until the command times out. False where only the transaction error comes.
///
public virtual bool IsSecondConnectionTimeout(Exception error) => false;
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlEndpointHarness.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqlEndpointHarness.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql;
using redb.Route.Sql.Connection;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// Builds a sql: endpoint the production way: component registered on a route context, connection factory
/// in the context registry, options bound from URI parameters.
///
public static class SqlEndpointHarness
{
/// Registry name of the data source.
public const string DataSourceName = "e2e";
/// Creates an Execute-mode endpoint for with extra URI parameters.
public static SqlEndpoint CreateEndpoint(
RouteContext context, ISqlConnectionFactory factory, string sql, Dictionary? extraParameters = null)
{
var component = new SqlComponent();
context.AddComponent(component);
context.AddToRegistry(DataSourceName, factory);
var parameters = new Dictionary
{
["mode"] = "Execute",
["dataSource"] = DataSourceName,
};
if (extraParameters is not null)
foreach (var (key, value) in extraParameters)
parameters[key] = value;
var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters);
return (SqlEndpoint)component.CreateEndpoint(uri);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqliteFileE2EProvider.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Infrastructure/SqliteFileE2EProvider.cs
----
using System.Data.Common;
using Microsoft.Data.Sqlite;
namespace redb.Route.Tests.Sql.E2E.Infrastructure;
///
/// SQLite through Microsoft.Data.Sqlite on a temporary file (not shared memory), so the connector's own
/// connections and the verifying reader see the same database the way a deployment would. Pooling is off:
/// the file is deleted on dispose.
///
public sealed class SqliteFileE2EProvider : SqlE2EProvider, IDisposable
{
private readonly string _path = Path.Combine(Path.GetTempPath(), $"rsql-e2e-{Guid.NewGuid():N}.db");
public override string Name => "sqlite-file";
public override DbProviderFactory Factory => SqliteFactory.Instance;
public override string ConnectionString => $"Data Source={_path};Pooling=False";
public override string StartHint => $"The database is a temporary file ({_path}); nothing to start.";
public override string ReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (:#id, :#val) RETURNING id";
public override string NativeReturningInsertSql(string table) =>
$"INSERT INTO {table} (id, val) VALUES (@id, @val) RETURNING id";
public override string TransactionKillingLiteral(string table) =>
$"INSERT OR ROLLBACK INTO {table} (id, val) VALUES (1, 'x')";
public override string TransactionKillingBatchSql(string table) =>
$"INSERT OR ROLLBACK INTO {table} (id, val) VALUES (:#id, :#val)";
public override List> TransactionKillingItems() =>
[
new() { ["id"] = 1, ["val"] = "a" },
new() { ["id"] = 1, ["val"] = "x" },
new() { ["id"] = 3, ["val"] = "c" },
];
// Constraint errors abort the statement only; OR ROLLBACK ends the transaction and the driver then
// refuses every further command on it.
public override int[] LoopContinueDuplicateKeyRows => [1, 3];
public override int[] LoopContinueTransactionKillingRows => [];
public override bool DuplicateKeyDestroysTransaction => false;
public override bool TransactionKillingErrorDestroysTransaction => true;
public override bool ReportsSavepointSupport => true;
public override bool CommandAfterTransactionKillingErrorIsRejected => true;
public override bool CanCreateBatch => false;
public override bool PrepareRejectsUntypedParameters => false;
public override bool ReaderConnectionRunsAnotherCommand => true;
public void Dispose()
{
if (File.Exists(_path))
File.Delete(_path);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlAmbientTransactionBatchTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlAmbientTransactionBatchTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlAmbientTransactionBatchTests : AmbientTransactionBatchTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchBindingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchBindingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlBatchBindingE2ETests : BatchBindingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchEngineE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchEngineE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlBatchEngineE2ETests(ITestOutputHelper output) : BatchEngineE2ETestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchFailureSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchFailureSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlBatchFailureSemanticsTests : BatchFailureSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchResultsE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchResultsE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlBatchResultsE2ETests : BatchResultsE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchStreamingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlBatchStreamingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlBatchStreamingE2ETests : BatchStreamingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlDbBatchSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlDbBatchSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlDbBatchSemanticsTests : DbBatchSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlDeadlockSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlDeadlockSemanticsTests.cs
----
using System.Data.Common;
using Microsoft.Data.SqlClient;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
///
/// Characterization: a chosen as deadlock victim mid-batch. The server rolls the victim's
/// transaction back; the commands queued after the failing one in the same batch must not run in autocommit —
/// SqlClient does run a separate command after a server-side rollback, so this is not a given.
///
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlDeadlockSemanticsTests : IAsyncLifetime
{
private readonly MsSqlE2EProvider _provider = new(xactAbortOn: false);
private SqlE2EDatabase? _db;
private SqlE2EDatabase Db => _db ?? throw new InvalidOperationException("The table is created in InitializeAsync.");
///
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(_provider);
///
public async Task DisposeAsync()
{
if (_db is not null)
await _db.DisposeAsync();
}
[Fact]
public async Task DbBatch_DeadlockVictim_NoRowsOutsideTransaction()
{
var table = Db.Table;
await Db.ExecuteAsync(_provider.InsertLiteral(table, 1, "a"));
await Db.ExecuteAsync(_provider.InsertLiteral(table, 2, "b"));
await using var holder = await Db.OpenAsync();
await using var victim = await Db.OpenAsync();
await using var watcher = await Db.OpenAsync();
await SqlE2EDatabase.ExecuteAsync(victim, null, "SET DEADLOCK_PRIORITY LOW");
var victimSession = await ScalarIntAsync(victim, "SELECT @@SPID");
var holderSession = await ScalarIntAsync(holder, "SELECT @@SPID");
await using var holderTx = await holder.BeginTransactionAsync();
await SqlE2EDatabase.ExecuteAsync(holder, holderTx, $"UPDATE {table} SET val = 'holder' WHERE id = 2");
await using var victimTx = await victim.BeginTransactionAsync();
await using var batch = victim.CreateBatch();
batch.Transaction = victimTx;
foreach (var statement in new[]
{
_provider.InsertLiteral(table, 10, "victim"),
$"UPDATE {table} SET val = 'victim' WHERE id = 2",
_provider.InsertLiteral(table, 11, "victim"),
})
{
var command = batch.CreateBatchCommand();
command.CommandText = statement;
batch.BatchCommands.Add(command);
}
// The victim holds row 10 and waits for row 2; the holder then asks for row 10 — a cycle.
var victimRun = batch.ExecuteNonQueryAsync();
await WaitUntilBlockedAsync(watcher, victimSession, holderSession, TimeSpan.FromSeconds(20));
var holderRun = SqlE2EDatabase.ExecuteAsync(holder, holderTx, $"UPDATE {table} SET val = 'holder' WHERE id = 10");
var victimError = await Outcome.Of(() => victimRun);
victimError.Should().BeOfType().Which.Number.Should().Be(1205, "the low-priority batch is the deadlock victim");
await holderRun;
await holderTx.CommitAsync();
// The victim's transaction is gone on the server; its client-side rollback outcome is not the fact under test.
await Outcome.Of(() => victimTx.RollbackAsync());
(await Db.ReadIdsAsync()).Should().Equal(new[] { 1, 2 },
"no command of the victim batch — before or after the deadlock — may survive outside its transaction");
}
private static async Task ScalarIntAsync(DbConnection connection, string sql)
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
return Convert.ToInt32(await command.ExecuteScalarAsync());
}
///
/// Polls the server's request table until waits for a lock held by ;
/// a deadline, not a fixed sleep. Matching the blocker and a lock wait matters: blocking_session_id is also
/// non-zero (negative) for page-latch waits, which under load showed up before the victim reached its lock wait and let
/// the holder run its statement too early — no cycle, and the victim timed out (-2) instead of being chosen (1205).
///
private static async Task WaitUntilBlockedAsync(DbConnection watcher, int session, int blocker, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
var blocked = await ScalarIntAsync(watcher,
"SELECT COUNT(*) FROM sys.dm_exec_requests " +
$"WHERE session_id = {session} AND blocking_session_id = {blocker} AND wait_type LIKE 'LCK[_]M[_]%'");
if (blocked > 0)
return;
await Task.Delay(50);
}
throw new TimeoutException($"Session {session} did not wait for a lock held by session {blocker} within {timeout}.");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlParameterSyntaxE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlParameterSyntaxE2ETests.cs
----
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
///
/// SQL Server keeps @ for itself: a declared variable and the argument names of EXEC reach the server as
/// written, next to a :#name parameter. With @name placeholders the connector took them for its own and failed
/// with "has no value".
///
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlParameterSyntaxE2ETests : ParameterSyntaxE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
[Theory]
[InlineData("EXEC sp_executesql N'SELECT @p AS v', N'@p int', @p = :#value")]
[InlineData("DECLARE @n int = :#value; SELECT @n AS v")]
public async Task TsqlAtSyntax_ReachesTheServer(string sql)
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), sql, new() { ["outputType"] = "Scalar" });
var exchange = new Exchange(new Message());
exchange.In.Headers["value"] = 7;
var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None));
thrown.Should().BeNull(Outcome.Describe(thrown));
Convert.ToInt32(exchange.In.Body).Should().Be(7);
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPocoMappingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPocoMappingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
public sealed class MsSqlPocoMappingE2ETests : PocoMappingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
protected override string ZonedTimestampSql => "SELECT CAST('2024-01-02 03:04:05 +03:00' AS datetimeoffset) AS at";
protected override string UnzonedTimestampSql => "SELECT CAST('2024-01-02 03:04:05' AS datetime2) AS at";
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollFailureAfterRollbackTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollFailureAfterRollbackTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlPollFailureAfterRollbackTests(ITestOutputHelper output) : PollFailureAfterRollbackTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollListDeliveryTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollListDeliveryTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlPollListDeliveryTests(ITestOutputHelper output) : PollListDeliveryTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollStreamLifecycleTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollStreamLifecycleTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlPollStreamLifecycleTests(ITestOutputHelper output) : PollStreamLifecycleTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollStreamTransactedTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlPollStreamTransactedTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlPollStreamTransactedTests(ITestOutputHelper output) : PollStreamTransactedTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlProviderSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlProviderSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlProviderSemanticsTests : ProviderSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlRepositoryBootstrapAmbientTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlRepositoryBootstrapAmbientTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlRepositoryBootstrapAmbientTests : SqlRepositoryBootstrapAmbientTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlRepositoryBootstrapE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlRepositoryBootstrapE2ETests.cs
----
using redb.Route.Sql.Connection;
using redb.Route.Sql.Repositories;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
///
/// The tables the raw-ADO repositories create on SQL Server keep their primary key inside the 900-byte limit of a clustered
/// index: a key past it is created with warning 1946 and refuses the rows that reach the limit.
///
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlRepositoryBootstrapE2ETests : IAsyncLifetime
{
private const int ClusteredKeyLimit = 900;
private readonly MsSqlE2EProvider _provider = new(xactAbortOn: false);
private readonly string _suffix = Guid.NewGuid().ToString("N")[..12];
private readonly List _tables = [];
private ISqlConnectionFactory Factory => new SqlConnectionFactory(new SqlConnectionOptions
{
ConnectionString = _provider.ConnectionString,
ProviderFactory = _provider.Factory,
});
[Fact]
public async Task Idempotent_PrimaryKey_FitsTheClusteredIndex()
{
var table = Track("rsql_idem_" + _suffix);
var repository = new SqlIdempotentRepository(Factory, new SqlIdempotentOptions { ProcessorName = "route-1", TableName = table });
(await repository.Add("msg-1")).Should().BeTrue();
(await PrimaryKeyBytesAsync(table)).Should().BeLessThanOrEqualTo(ClusteredKeyLimit,
"processor_name and message_key together must fit a clustered key");
}
[Fact]
public async Task ClaimCheck_PrimaryKey_FitsTheClusteredIndex()
{
var table = Track("rsql_claim_" + _suffix);
var repository = new SqlClaimCheckRepository(Factory, new SqlClaimCheckOptions { TableName = table, CleanupInterval = 0 });
await repository.Store("claim-1", new byte[] { 1, 2, 3 });
(await PrimaryKeyBytesAsync(table)).Should().BeLessThanOrEqualTo(ClusteredKeyLimit);
}
/// The maximum byte length of the table's primary key, as the catalog reports it.
private async Task PrimaryKeyBytesAsync(string table)
{
await using var connection = await Factory.CreateConnectionAsync();
await using var command = connection.CreateCommand();
command.CommandText = """
SELECT SUM(CAST(c.max_length AS int))
FROM sys.indexes i
JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID(@table) AND i.is_primary_key = 1
""";
var parameter = command.CreateParameter();
parameter.ParameterName = "table";
parameter.Value = table;
command.Parameters.Add(parameter);
return Convert.ToInt32(await command.ExecuteScalarAsync());
}
private string Track(string table)
{
_tables.Add(table);
return table;
}
public Task InitializeAsync() => Task.CompletedTask;
public async Task DisposeAsync()
{
await using var connection = await Factory.CreateConnectionAsync();
foreach (var table in _tables)
await SqlE2EDatabase.ExecuteAsync(connection, null, $"IF OBJECT_ID(N'{table}', N'U') IS NOT NULL DROP TABLE {table}");
}
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSequentialConnectionsInScopeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSequentialConnectionsInScopeTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlSequentialConnectionsInScopeTests : SequentialConnectionsInScopeTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSqlIdempotentAmbientTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSqlIdempotentAmbientTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlSqlIdempotentAmbientTests : SqlIdempotentAmbientTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
protected override bool EnlistsByDefault => true;
[Fact]
public Task EnlistOff_DoesNotJoin() => AssertEnlistOffDoesNotJoin();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSqlIdempotentLeaseTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlSqlIdempotentLeaseTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlSqlIdempotentLeaseTests : SqlIdempotentLeaseTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlStreamListLifetimeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSql/MsSqlStreamListLifetimeTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSql;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlStreamListLifetimeTests : StreamListLifetimeTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: false);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnBatchFailureSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnBatchFailureSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSqlXactAbortOn;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql-xact-on")]
[Trait("SqlSuite", "Connector")]
public sealed class MsSqlXactAbortOnBatchFailureSemanticsTests : BatchFailureSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: true);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnDbBatchSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnDbBatchSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSqlXactAbortOn;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql-xact-on")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlXactAbortOnDbBatchSemanticsTests : DbBatchSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: true);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnProviderSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/MsSqlXactAbortOn/MsSqlXactAbortOnProviderSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.MsSqlXactAbortOn;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "mssql-xact-on")]
[Trait("SqlSuite", "Characterization")]
public sealed class MsSqlXactAbortOnProviderSemanticsTests : ProviderSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new MsSqlE2EProvider(xactAbortOn: true);
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresAmbientTransactionBatchTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresAmbientTransactionBatchTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresAmbientTransactionBatchTests : AmbientTransactionBatchTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchBindingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchBindingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresBatchBindingE2ETests : BatchBindingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchEngineE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchEngineE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresBatchEngineE2ETests(ITestOutputHelper output) : BatchEngineE2ETestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchFailureSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchFailureSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresBatchFailureSemanticsTests : BatchFailureSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchResultsE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchResultsE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresBatchResultsE2ETests : BatchResultsE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchStreamingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresBatchStreamingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresBatchStreamingE2ETests : BatchStreamingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresDbBatchSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresDbBatchSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Characterization")]
public sealed class PostgresDbBatchSemanticsTests : DbBatchSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresParameterSyntaxE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresParameterSyntaxE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresParameterSyntaxE2ETests : ParameterSyntaxE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPocoMappingE2ETests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPocoMappingE2ETests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
public sealed class PostgresPocoMappingE2ETests : PocoMappingE2ETestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
protected override string ZonedTimestampSql => "SELECT CAST('2024-01-02 03:04:05+03' AS timestamptz) AS at";
protected override string UnzonedTimestampSql => "SELECT CAST('2024-01-02 03:04:05' AS timestamp) AS at";
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollFailureAfterRollbackTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollFailureAfterRollbackTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresPollFailureAfterRollbackTests(ITestOutputHelper output) : PollFailureAfterRollbackTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollListDeliveryTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollListDeliveryTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresPollListDeliveryTests(ITestOutputHelper output) : PollListDeliveryTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollStreamLifecycleTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollStreamLifecycleTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresPollStreamLifecycleTests(ITestOutputHelper output) : PollStreamLifecycleTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollStreamTransactedTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresPollStreamTransactedTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
using Xunit.Abstractions;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresPollStreamTransactedTests(ITestOutputHelper output) : PollStreamTransactedTestsBase(output)
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresProviderSemanticsTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresProviderSemanticsTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Characterization")]
public sealed class PostgresProviderSemanticsTests : ProviderSemanticsTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresRepositoryBootstrapAmbientTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresRepositoryBootstrapAmbientTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresRepositoryBootstrapAmbientTests : SqlRepositoryBootstrapAmbientTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSequentialConnectionsInScopeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSequentialConnectionsInScopeTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Characterization")]
public sealed class PostgresSequentialConnectionsInScopeTests : SequentialConnectionsInScopeTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSqlIdempotentAmbientTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSqlIdempotentAmbientTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresSqlIdempotentAmbientTests : SqlIdempotentAmbientTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
protected override bool EnlistsByDefault => true;
[Fact]
public Task EnlistOff_DoesNotJoin() => AssertEnlistOffDoesNotJoin();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSqlIdempotentLeaseTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresSqlIdempotentLeaseTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Connector")]
public sealed class PostgresSqlIdempotentLeaseTests : SqlIdempotentLeaseTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresStreamListLifetimeTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Postgres/PostgresStreamListLifetimeTests.cs
----
using redb.Route.Tests.Sql.E2E.Base;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Postgres;
[Trait("Category", "Integration")]
[Trait("SqlProvider", "postgres")]
[Trait("SqlSuite", "Characterization")]
public sealed class PostgresStreamListLifetimeTests : StreamListLifetimeTestsBase
{
protected override SqlE2EProvider Provider { get; } = new PostgresE2EProvider();
}
Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileAmbientTransactionRefusalTests.cs
Snapshot: redb-route, 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-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileAmbientTransactionRefusalTests.cs
----
using System.Transactions;
using redb.Route.Core;
using redb.Route.Tests.Sql.E2E.Infrastructure;
namespace redb.Route.Tests.Sql.E2E.Sqlite;
///
/// Microsoft.Data.Sqlite does not enlist in System.Transactions. A sql: step inside a .Transacted() block
/// used to write in autocommit past the block's transaction: a rolled-back block left its rows behind. The step now
/// refuses before it writes; outside a block it works as always.
///
public sealed class SqliteFileAmbientTransactionRefusalTests : IAsyncLifetime
{
private readonly SqliteFileE2EProvider _provider = new();
private SqlE2EDatabase _db = null!;
public async Task InitializeAsync() => _db = await SqlE2EDatabase.CreateAsync(_provider);
public async Task DisposeAsync()
{
await _db.DisposeAsync();
_provider.Dispose();
}
private async Task RunStatement()
{
await using var context = new RouteContext();
var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateConnectionFactory(),
$"INSERT INTO {_db.Table}(id, val) VALUES (1, 'a')", new Dictionary { ["outputType"] = "None" });
var producer = endpoint.CreateProducer();
return await Outcome.Of(() => producer.Process(new Exchange(new Message(null)), CancellationToken.None));
}
[Fact]
public async Task A_statement_inside_a_transaction_is_refused_before_it_writes()
{
Exception? thrown;
using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
thrown = await RunStatement();
// Not completed: the block rolls back.
}
thrown.Should().BeOfType().Which.Message.Should().Contain("does not join");
(await _db.ReadIdsAsync()).Should().BeEmpty("a rolled-back block must not leave the step's row behind");
}
[Fact]
public async Task A_batch_inside_a_transaction_is_refused_before_it_writes()
{
var items = new List