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("""n1text""") }; 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> { new() { ["id"] = 1, ["val"] = "a" } }; Exception? thrown; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { (_, thrown) = await SqlBatchRun.RunAsync(_db, _provider.InsertSql(_db.Table), items, breakOnError: true); } thrown.Should().BeOfType().Which.Message.Should().Contain("does not join"); (await _db.ReadIdsAsync()).Should().BeEmpty(); } [Fact] public async Task Outside_a_transaction_the_statement_runs_as_always() { (await RunStatement()).Should().BeNull(); (await _db.ReadIdsAsync()).Should().Equal(1); } } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileBatchBindingE2ETests.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/SqliteFileBatchBindingE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileBatchBindingE2ETests : BatchBindingE2ETestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileBatchEngineE2ETests.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/SqliteFileBatchEngineE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; using Xunit.Abstractions; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileBatchEngineE2ETests(ITestOutputHelper output) : BatchEngineE2ETestsBase(output) { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileBatchFailureSemanticsTests.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/SqliteFileBatchFailureSemanticsTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileBatchFailureSemanticsTests : BatchFailureSemanticsTestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileBatchResultsE2ETests.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/SqliteFileBatchResultsE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileBatchResultsE2ETests : BatchResultsE2ETestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileParameterSyntaxE2ETests.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/SqliteFileParameterSyntaxE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileParameterSyntaxE2ETests : ParameterSyntaxE2ETestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFilePollListDeliveryTests.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/SqliteFilePollListDeliveryTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; using Xunit.Abstractions; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFilePollListDeliveryTests(ITestOutputHelper output) : PollListDeliveryTestsBase(output) { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFilePollStreamTransactedTests.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/SqliteFilePollStreamTransactedTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; using Xunit.Abstractions; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFilePollStreamTransactedTests(ITestOutputHelper output) : PollStreamTransactedTestsBase(output) { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileProviderSemanticsTests.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/SqliteFileProviderSemanticsTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Characterization")] public sealed class SqliteFileProviderSemanticsTests : ProviderSemanticsTestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileSqlIdempotentAmbientTests.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/SqliteFileSqlIdempotentAmbientTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileSqlIdempotentAmbientTests : SqlIdempotentAmbientTestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); /// Microsoft.Data.Sqlite does not enlist in System.Transactions. protected override bool EnlistsByDefault => false; } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Sqlite/SqliteFileSqlIdempotentLeaseTests.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/SqliteFileSqlIdempotentLeaseTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Sqlite; [Trait("Category", "Integration")] [Trait("SqlProvider", "sqlite-file")] [Trait("SqlSuite", "Connector")] public sealed class SqliteFileSqlIdempotentLeaseTests : SqlIdempotentLeaseTestsBase { protected override SqlE2EProvider Provider { get; } = new SqliteFileE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/FirebirdE2ETests.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/Tier2/FirebirdE2ETests.cs ---- using System.Collections; using FirebirdSql.Data.FirebirdClient; 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.Tier2; /// /// Firebird 5 through FirebirdClient 10.3 (tier 2, decision №11): the driver's facts for the provider matrix, measured on /// 2026-09-15, and the connector with the default placeholderStyle=At. Tier 2 runs only with the temporary /// route-firebird container; other runs exclude it with Category!=SqlE2ETier2. /// [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "firebird")] public sealed class FirebirdE2ETests(ITestOutputHelper output) : IAsyncLifetime { private readonly FirebirdE2EProvider _provider = new(); 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(); } // ── Driver facts (characterization) ───────────────────────────── [Fact] public async Task Facts_Batch_Savepoints_RepeatedNamedParameter() { await using var connection = await Db.OpenAsync(); await using var transaction = await connection.BeginTransactionAsync(); await using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = "SELECT CAST(@x AS INTEGER) * 100 + CAST(@y AS INTEGER) * 10 + CAST(@x AS INTEGER) FROM RDB$DATABASE"; command.Parameters.Add(new FbParameter("@y", 2)); command.Parameters.Add(new FbParameter("@x", 1)); var value = 0; var thrown = await Outcome.Of(async () => value = Convert.ToInt32(await command.ExecuteScalarAsync())); output.WriteLine($"[fact] firebird {connection.ServerVersion}: CanCreateBatch={connection.CanCreateBatch}, " + $"SupportsSavepoints={transaction.SupportsSavepoints}, repeated @x -> {Outcome.Describe(thrown)} {value}"); connection.CanCreateBatch.Should().Be(_provider.CanCreateBatch); transaction.SupportsSavepoints.Should().Be(_provider.ReportsSavepointSupport); thrown.Should().BeNull(Outcome.Describe(thrown)); value.Should().Be(121, "FirebirdClient binds @name by name, a repeated name included"); } [Fact] public async Task Facts_DuplicateKeyInTransaction_RollsBackTheStatementOnly() { Exception? duplicate; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "a")); duplicate = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "dup"))); await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } output.WriteLine($"[fact] firebird: duplicate key -> {Outcome.Describe(duplicate)} (ErrorCode {(duplicate as FbException)?.ErrorCode})"); duplicate.Should().BeOfType(Outcome.Describe(duplicate)).Which.ErrorCode.Should().Be(335544665, "unique_key_violation"); (await Db.ReadIdsAsync()).Should().Equal(_provider.LoopContinueDuplicateKeyRows, "the failed statement is undone, the transaction goes on"); } [Fact] public async Task Facts_ConversionErrorInTransaction_RollsBackTheStatementOnly() { Exception? conversion; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "a")); conversion = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.TransactionKillingLiteral(Db.Table))); await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } output.WriteLine($"[fact] firebird: conversion error -> {Outcome.Describe(conversion)}"); conversion.Should().BeOfType(Outcome.Describe(conversion)); (await Db.ReadIdsAsync()).Should().Equal(_provider.LoopContinueTransactionKillingRows); } [Fact] public async Task Facts_SavepointRecoversAfterDuplicateKey() { Exception? save, rollback; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "a")); save = await Outcome.Of(() => transaction.SaveAsync("redb_batch_item")); await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "dup"))); rollback = await Outcome.Of(() => transaction.RollbackAsync("redb_batch_item")); await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } save.Should().BeNull(Outcome.Describe(save)); rollback.Should().BeNull("rolling back to the savepoint after a duplicate key works: " + Outcome.Describe(rollback)); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } // ── Connector with placeholderStyle=At ────────────────────────── [Fact] public async Task Connector_Break_DuplicateKey_NoRows() { var (_, thrown) = await SqlBatchRun.RunAsync(Db, _provider.InsertSql(Db.Table), _provider.DuplicateKeyItems(), breakOnError: true, batchSize: 10); thrown.Should().BeOfType("the provider's exception reaches the route as is: " + Outcome.Describe(thrown)); thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(1, "commands run one by one, so the failed item is known exactly"); (await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls everything back"); } [Fact] public async Task Connector_Continue_DuplicateKey_OthersCommitted() { var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, _provider.InsertSql(Db.Table), _provider.DuplicateKeyItems(), breakOnError: false, batchSize: 10); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers[SqlHeaders.BatchStrategy].Should().Be("Savepoints"); SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Connector_Continue_ConversionError_OthersCommitted() { var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, _provider.TransactionKillingBatchSql(Db.Table), _provider.TransactionKillingItems(), breakOnError: false, batchSize: 10); thrown.Should().BeNull(Outcome.Describe(thrown)); SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Connector_ReturningKeys_CollectedInHeader() { 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" }); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers.Should().ContainKey(SqlHeaders.GeneratedKeys, "RETURNING rows are collected with outputType=SelectList"); exchange.In.Headers[SqlHeaders.GeneratedKeys].Should().BeAssignableTo().Subject .Cast>() .Select(row => Convert.ToInt32(row.Values.First())) .Should().Equal(21, 22); } [Fact] public async Task Connector_RepeatedPlaceholder_BoundByName() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), "SELECT CAST(:#x AS INTEGER) * 100 + CAST(:#y AS INTEGER) * 10 + CAST(:#x AS INTEGER) FROM RDB$DATABASE", new() { ["outputType"] = "Scalar" }); var exchange = new Exchange(new Message()); exchange.In.Headers["x"] = 1; exchange.In.Headers["y"] = 2; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); Convert.ToInt32(exchange.In.Body).Should().Be(121); } [Fact] public async Task Connector_LiteralsWithAtAndPlaceholderText_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 :#x')", new() { ["outputType"] = "None" }); var exchange = new Exchange(new Message()); exchange.In.Headers["id"] = 7; 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(7); rows[0][1].Should().Be("user@example.com :#x"); } [Fact] public async Task Connector_Poll_OnSuccess_MarksEveryRow() { for (var id = 1; id <= 3; id++) await Db.ExecuteAsync(_provider.InsertLiteral(Db.Table, id, "new")); await using var context = new RouteContext(); var parameters = new Dictionary { ["mode"] = "Poll", ["transacted"] = "true", ["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id", ["repeatCount"] = "1", }; var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), $"SELECT id, val FROM {Db.Table} ORDER BY id", parameters); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var thrown = await Outcome.Of(() => ((SqlConsumer)endpoint.CreateConsumer(processor)).Poll(CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); var values = (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]); values.Should().Equal("done", "done", "done"); } } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/MariaDbE2ETests.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/Tier2/MariaDbE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Infrastructure; using Xunit.Abstractions; namespace redb.Route.Tests.Sql.E2E.Tier2; /// MariaDB 11 (tier 2): the temporary route-mariadb container; unlike MySQL it returns keys with RETURNING. [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "mariadb")] public sealed class MariaDbE2ETests(ITestOutputHelper output) : MySqlFamilyE2ETestsBase(new MariaDbE2EProvider(), output) { [Fact] public async Task Connector_ReturningKeys_CollectedInHeader() { 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" }); thrown.Should().BeNull(Outcome.Describe(thrown)); KeyIds(exchange).Should().Equal(21, 22); } } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/MariaDbIdempotentLeaseTests.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/Tier2/MariaDbIdempotentLeaseTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Tier2; [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "mariadb")] public sealed class MariaDbIdempotentLeaseTests : SqlIdempotentLeaseTestsBase { protected override SqlE2EProvider Provider { get; } = new MariaDbE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/MySqlE2ETests.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/Tier2/MySqlE2ETests.cs ---- using redb.Route.Tests.Sql.E2E.Infrastructure; using Xunit.Abstractions; namespace redb.Route.Tests.Sql.E2E.Tier2; /// MySQL 8.4 (tier 2): the temporary route-mysql container. [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "mysql")] public sealed class MySqlE2ETests(ITestOutputHelper output) : MySqlFamilyE2ETestsBase(new MySqlE2EProvider(), output); Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/MySqlFamilyE2ETestsBase.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/Tier2/MySqlFamilyE2ETestsBase.cs ---- using System.Collections; using System.Data.Common; using MySqlConnector; 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.Tier2; /// /// MySQL and MariaDB through MySqlConnector (tier 2, decision №11): the driver's facts for the provider matrix, measured on /// 2026-09-15, and the connector with the default placeholderStyle=At. Tier 2 runs only with the temporary containers; /// other runs exclude it with Category!=SqlE2ETier2. /// public abstract class MySqlFamilyE2ETestsBase(MySqlFamilyE2EProvider provider, ITestOutputHelper output) : IAsyncLifetime { private SqlE2EDatabase? _db; protected MySqlFamilyE2EProvider Provider { get; } = provider; protected ITestOutputHelper Output { get; } = output; 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() { if (_db is not null) await _db.DisposeAsync(); } // ── Driver facts (characterization) ───────────────────────────── [Fact] public async Task Facts_DbBatch_Savepoints() { await using var connection = await Db.OpenAsync(); await using var transaction = await connection.BeginTransactionAsync(); Output.WriteLine($"[fact] {Provider.Name} {connection.ServerVersion}: CanCreateBatch={connection.CanCreateBatch}, " + $"SupportsSavepoints={transaction.SupportsSavepoints}"); connection.CanCreateBatch.Should().Be(Provider.CanCreateBatch); transaction.SupportsSavepoints.Should().Be(Provider.ReportsSavepointSupport); } [Fact] public async Task Facts_DbBatch_DuplicateKey_FailedCommandNotNamed() { Exception? thrown; int position; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) await using (var batch = connection.CreateBatch()) { batch.Transaction = transaction; foreach (var (id, val) in new[] { (1, "a"), (1, "dup"), (3, "c") }) { var command = batch.CreateBatchCommand(); command.CommandText = Provider.InsertLiteral(Db.Table, id, val); batch.BatchCommands.Add(command); } thrown = await Outcome.Of(() => batch.ExecuteNonQueryAsync()); position = (thrown as DbException)?.BatchCommand is { } failed ? batch.BatchCommands.IndexOf(failed) : -1; Output.WriteLine($"[fact] {Provider.Name}: DbBatch duplicate key -> {Outcome.Describe(thrown)}, BatchCommand index={position}"); await transaction.RollbackAsync(); } thrown.Should().BeOfType(Outcome.Describe(thrown)).Which.Number.Should().Be(1062, "ER_DUP_ENTRY"); position.Should().Be(-1, "MySqlConnector 2.6 leaves DbException.BatchCommand empty"); } [Fact] public async Task Facts_DuplicateKeyInTransaction_RollsBackTheStatementOnly() { Exception? duplicate; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 1, "a")); duplicate = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 1, "dup"))); await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } duplicate.Should().BeOfType(Outcome.Describe(duplicate)).Which.Number.Should().Be(1062); (await Db.ReadIdsAsync()).Should().Equal(Provider.LoopContinueDuplicateKeyRows, "the failed statement is undone, the transaction goes on"); } [Fact] public async Task Facts_ConversionErrorInTransaction_RollsBackTheStatementOnly() { Exception? conversion; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 1, "a")); conversion = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.TransactionKillingLiteral(Db.Table))); await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } conversion.Should().BeOfType(Outcome.Describe(conversion)).Which.Number.Should().Be(1366, "ER_TRUNCATED_WRONG_VALUE_FOR_FIELD"); (await Db.ReadIdsAsync()).Should().Equal(Provider.LoopContinueTransactionKillingRows); } [Fact] public async Task Facts_SavepointRecoversAfterDuplicateKey() { Exception? save, rollback; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 1, "a")); save = await Outcome.Of(() => transaction.SaveAsync("redb_batch_item")); await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 1, "dup"))); rollback = await Outcome.Of(() => transaction.RollbackAsync("redb_batch_item")); await SqlE2EDatabase.ExecuteAsync(connection, transaction, Provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } save.Should().BeNull(Outcome.Describe(save)); rollback.Should().BeNull("rolling back to the savepoint after a duplicate key works: " + Outcome.Describe(rollback)); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Facts_UserVariable_IsTakenForAParameterUnlessAllowUserVariables() { var refused = await Outcome.Of(() => AddUserVariableAsync(Provider.ConnectionString)); var allowed = await Outcome.Of(() => AddUserVariableAsync(Provider.ConnectionString + ";AllowUserVariables=True")); Output.WriteLine($"[fact] {Provider.Name}: '@u' without AllowUserVariables -> {Outcome.Describe(refused)}"); refused.Should().NotBeNull("MySqlConnector reads every @name of a command with parameters as a parameter"); refused!.Message.Should().Contain("Allow User Variables"); allowed.Should().BeNull(Outcome.Describe(allowed)); } private static async Task AddUserVariableAsync(string connectionString) { await using var connection = new MySqlConnection(connectionString); await connection.OpenAsync(); await using var command = connection.CreateCommand(); command.CommandText = "SET @u = 5; SELECT @x + @u"; command.Parameters.AddWithValue("@x", 1); Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(6); } // ── Connector with placeholderStyle=At ────────────────────────── [Fact] public async Task Connector_Break_DuplicateKey_NoRows_FailedChunkReported() { var (_, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: true, batchSize: 10); thrown.Should().BeOfType("the provider's exception reaches the route as is: " + Outcome.Describe(thrown)); thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(0, "the driver does not name the failed command: the chunk's first item"); thrown.Data["redbSql.batchFailedChunk"].Should().Be("0..2", "the failed item is somewhere in this chunk"); (await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls everything back"); } [Fact] public async Task Connector_Continue_DuplicateKey_OthersCommitted() { var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), Provider.DuplicateKeyItems(), breakOnError: false, batchSize: 10); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers[SqlHeaders.BatchStrategy].Should().Be("Savepoints"); SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Connector_Continue_ConversionError_OthersCommitted() { var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.TransactionKillingBatchSql(Db.Table), Provider.TransactionKillingItems(), breakOnError: false, batchSize: 10); thrown.Should().BeNull(Outcome.Describe(thrown)); SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Connector_Break_Batch_ChunksThroughDbBatch() { var items = Enumerable.Range(1, 5).Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i }).ToList(); var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, Provider.InsertSql(Db.Table), items, breakOnError: null, batchSize: 2); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers[SqlHeaders.BatchStrategy].Should().Be("DbBatch"); (await Db.ReadIdsAsync()).Should().Equal(1, 2, 3, 4, 5); } [Fact] public async Task Connector_RepeatedPlaceholder_BoundByName() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), "SELECT :#x * 100 + :#y * 10 + :#x", new() { ["outputType"] = "Scalar" }); var exchange = new Exchange(new Message()); exchange.In.Headers["x"] = 1; exchange.In.Headers["y"] = 2; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); Convert.ToInt32(exchange.In.Body).Should().Be(121); } [Fact] public async Task Connector_LiteralsWithAtAndPlaceholderText_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 :#x')", new() { ["outputType"] = "None" }); var exchange = new Exchange(new Message()); exchange.In.Headers["id"] = 7; 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(7); rows[0][1].Should().Be("user@example.com :#x"); } [Fact] public async Task Connector_BackslashEscapes_QuoteEscapedWithBackslash_PersistedAndPlaceholderBound() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), $"INSERT INTO {Db.Table} (val, id) VALUES ('it\\'s :#x', :#id)", new() { ["outputType"] = "None", ["backslashEscapes"] = "true" }); var exchange = new Exchange(new Message()); exchange.In.Headers["id"] = 7; exchange.In.Headers["x"] = "must not be bound"; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull("MySQL escapes a quote with a backslash by default: " + Outcome.Describe(thrown)); var rows = await Db.QueryAsync($"SELECT id, val FROM {Db.Table}"); rows.Should().ContainSingle(); Convert.ToInt32(rows[0][0]).Should().Be(7); rows[0][1].Should().Be("it's :#x", "text inside the literal is left as written"); } [Fact] public async Task Connector_Poll_OnSuccess_MarksEveryRow() { for (var id = 1; id <= 3; id++) await Db.ExecuteAsync(Provider.InsertLiteral(Db.Table, id, "new")); await using var context = new RouteContext(); var parameters = new Dictionary { ["mode"] = "Poll", ["transacted"] = "true", ["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id", ["repeatCount"] = "1", }; var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), $"SELECT id, val FROM {Db.Table} ORDER BY id", parameters); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var thrown = await Outcome.Of(() => ((SqlConsumer)endpoint.CreateConsumer(processor)).Poll(CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); var values = (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]); values.Should().Equal("done", "done", "done"); } /// Ids in the redbSql.generatedKeys header: the first column of every collected row. protected static List KeyIds(Exchange exchange) { exchange.In.Headers.Should().ContainKey(SqlHeaders.GeneratedKeys, "RETURNING 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/Tier2/MySqlIdempotentLeaseTests.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/Tier2/MySqlIdempotentLeaseTests.cs ---- using redb.Route.Tests.Sql.E2E.Base; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Tier2; [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "mysql")] public sealed class MySqlIdempotentLeaseTests : SqlIdempotentLeaseTestsBase { protected override SqlE2EProvider Provider { get; } = new MySqlE2EProvider(); } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/MySqlRepositoriesE2ETests.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/Tier2/MySqlRepositoriesE2ETests.cs ---- using System.Text; using redb.Route.Sql.Connection; using redb.Route.Sql.Repositories; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql.E2E.Tier2; /// /// The raw-ADO repositories bootstrap their tables on MySQL 8.4 (tier 2, the temporary route-mysql container): the key /// columns must be sized, since MySQL refuses a TEXT column in a primary key (error 1170). /// [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "mysql")] public sealed class MySqlRepositoriesE2ETests : IAsyncLifetime { private readonly MySqlE2EProvider _provider = new(); 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_BootstrapsAndRoundTrips() { var table = Track("rsql_idem_" + _suffix); var repository = new SqlIdempotentRepository(Factory, new SqlIdempotentOptions { ProcessorName = "route-1", TableName = table }); var added = await Outcome.Of(() => repository.Add("msg-1")); added.Should().BeNull("the table is created with sized key columns, which MySQL accepts in a primary key: " + Outcome.Describe(added)); (await repository.Add("msg-1")).Should().BeFalse(); (await repository.Contains("msg-1")).Should().BeTrue(); await repository.Confirm("msg-1"); await repository.Remove("msg-1"); (await repository.Contains("msg-1")).Should().BeFalse(); } [Fact] public async Task ClaimCheck_BootstrapsAndRoundTrips() { var table = Track("rsql_claim_" + _suffix); var repository = new SqlClaimCheckRepository(Factory, new SqlClaimCheckOptions { TableName = table, CleanupInterval = 0 }); var payload = Encoding.UTF8.GetBytes("payload"); var stored = await Outcome.Of(() => repository.Store("claim-1", payload)); stored.Should().BeNull("the claim key column is sized, which MySQL accepts in a primary key: " + Outcome.Describe(stored)); (await repository.Retrieve("claim-1")).Should().Equal(payload); (await repository.RetrieveAndRemove("claim-1")).Should().Equal(payload); (await repository.Retrieve("claim-1")).Should().BeNull(); } 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, $"DROP TABLE IF EXISTS {table}"); } } Path: redb-route/tests/redb.Route.Tests.Sql/E2E/Tier2/OracleE2ETests.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/Tier2/OracleE2ETests.cs ---- using System.Data.Common; using Oracle.ManagedDataAccess.Client; 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.Tier2; /// /// Oracle Free 23 through ODP.NET 23.26 (tier 2, decision №11): the driver's facts for the provider matrix, measured on /// 2026-09-15, and the connector with placeholderStyle=Colon — a batch that breaks on a duplicate key leaves nothing, a /// batch that goes on keeps the other rows, a repeated :#name binds by position, a poll marks its rows. Tier 2 runs /// only with the temporary route-oracle container; other runs exclude it with Category!=SqlE2ETier2. /// [Trait("Category", "SqlE2ETier2")] [Trait("SqlProvider", "oracle")] public sealed class OracleE2ETests(ITestOutputHelper output) : IAsyncLifetime { private static readonly Dictionary Colon = new() { ["placeholderStyle"] = "Colon" }; private readonly OracleE2EProvider _provider = new(); 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(); } // ── Driver facts (characterization) ───────────────────────────── [Fact] public async Task Facts_NoDbBatch_PositionalBinding_Savepoints() { await using var connection = await Db.OpenAsync(); await using var transaction = await connection.BeginTransactionAsync(); await using var command = (OracleCommand)connection.CreateCommand(); command.Transaction = (OracleTransaction)transaction; command.CommandText = "SELECT :a * 100 + :b FROM DUAL"; command.Parameters.Add(new OracleParameter("b", 2)); command.Parameters.Add(new OracleParameter("a", 1)); var result = Convert.ToInt32(await command.ExecuteScalarAsync()); output.WriteLine($"[fact] oracle: CanCreateBatch={connection.CanCreateBatch}, BindByName={command.BindByName}, " + $"result={result}, SupportsSavepoints={transaction.SupportsSavepoints}"); connection.CanCreateBatch.Should().Be(_provider.CanCreateBatch, "ODP.NET 23.26 has no DbBatch: a batch runs as commands"); command.BindByName.Should().BeFalse("ODP.NET binds by position unless told otherwise"); result.Should().Be(201, "parameters added b then a bind to :a and :b in the order they were added"); transaction.SupportsSavepoints.Should().Be(_provider.ReportsSavepointSupport); } [Fact] public async Task Facts_DuplicateKeyInTransaction_RollsBackTheStatementOnly() { Exception? duplicate; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "a")); duplicate = await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "dup"))); await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } duplicate.Should().BeOfType(Outcome.Describe(duplicate)).Which.Number.Should().Be(1, "ORA-00001"); (await Db.ReadIdsAsync()).Should().Equal(_provider.LoopContinueDuplicateKeyRows, "the failed statement is undone, the transaction goes on"); } [Fact] public async Task Facts_SavepointRecoversAfterDuplicateKey() { Exception? save, rollback; await using (var connection = await Db.OpenAsync()) await using (var transaction = await connection.BeginTransactionAsync()) { await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "a")); save = await Outcome.Of(() => transaction.SaveAsync("redb_batch_item")); await Outcome.Of(() => SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 1, "dup"))); rollback = await Outcome.Of(() => transaction.RollbackAsync("redb_batch_item")); await SqlE2EDatabase.ExecuteAsync(connection, transaction, _provider.InsertLiteral(Db.Table, 3, "c")); await transaction.CommitAsync(); } save.Should().BeNull(Outcome.Describe(save)); rollback.Should().BeNull("rolling back to the savepoint after a duplicate key works: " + Outcome.Describe(rollback)); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } // ── Connector with placeholderStyle=Colon ─────────────────────── [Fact] public async Task Connector_Break_DuplicateKey_NoRows() { var (_, thrown) = await SqlBatchRun.RunAsync(Db, _provider.InsertSql(Db.Table), _provider.DuplicateKeyItems(), breakOnError: true, batchSize: 10, Colon); thrown.Should().BeOfType("the provider's exception reaches the route as is: " + Outcome.Describe(thrown)); thrown!.Data[SqlHeaders.BatchFailedIndex].Should().Be(1); (await Db.ReadIdsAsync()).Should().BeEmpty("a batch that breaks on error rolls everything back"); } [Fact] public async Task Connector_Continue_DuplicateKey_OthersCommitted() { var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, _provider.InsertSql(Db.Table), _provider.DuplicateKeyItems(), breakOnError: false, batchSize: 10, Colon); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers[SqlHeaders.BatchStrategy].Should().Be("Savepoints"); SqlBatchRun.BatchErrorIndexes(exchange).Should().Equal(1); (await Db.ReadIdsAsync()).Should().Equal(1, 3); } [Fact] public async Task Connector_Break_Batch_RunsAsCommands() { var items = Enumerable.Range(1, 5).Select(i => new Dictionary { ["id"] = i, ["val"] = "v" + i }).ToList(); var (exchange, thrown) = await SqlBatchRun.RunAsync(Db, _provider.InsertSql(Db.Table), items, breakOnError: null, batchSize: 2, Colon); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Headers[SqlHeaders.BatchStrategy].Should().Be("Commands", "ODP.NET has no DbBatch"); (await Db.ReadIdsAsync()).Should().Equal(1, 2, 3, 4, 5); } [Fact] public async Task Connector_ColonStyle_RepeatedPlaceholder_BoundInOrder() { await using var context = new RouteContext(); var parameters = new Dictionary(Colon) { ["outputType"] = "Scalar" }; var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), "SELECT :#x * 100 + :#y * 10 + :#x FROM DUAL", parameters); var exchange = new Exchange(new Message()); exchange.In.Headers["x"] = 1; exchange.In.Headers["y"] = 2; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); Convert.ToInt32(exchange.In.Body).Should().Be(121, "every occurrence gets its parameter, in order"); } [Fact] public async Task Connector_LiteralsWithAtAndPlaceholderText_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 :#x')", new(Colon) { ["outputType"] = "None" }); var exchange = new Exchange(new Message()); exchange.In.Headers["id"] = 7; 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(7); rows[0][1].Should().Be("user@example.com :#x"); } [Fact] public async Task Connector_Poll_OnSuccess_MarksEveryRow() { for (var id = 1; id <= 3; id++) await Db.ExecuteAsync(_provider.InsertLiteral(Db.Table, id, "new")); await using var context = new RouteContext(); var parameters = new Dictionary(Colon) { ["mode"] = "Poll", ["transacted"] = "true", ["onSuccess"] = $"UPDATE {Db.Table} SET val = 'done' WHERE id = :#id", ["repeatCount"] = "1", }; var endpoint = SqlEndpointHarness.CreateEndpoint(context, Db.CreateConnectionFactory(), $"SELECT id, val FROM {Db.Table} ORDER BY id", parameters); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var thrown = await Outcome.Of(() => ((SqlConsumer)endpoint.CreateConsumer(processor)).Poll(CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); var values = (await Db.QueryAsync($"SELECT val FROM {Db.Table} ORDER BY id")).Select(r => r[0]); values.Should().Equal("done", "done", "done"); } } Path: redb-route/tests/redb.Route.Tests.Sql/RowMapperTests.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/RowMapperTests.cs ---- using System.Data.Common; using Microsoft.Data.Sqlite; using redb.Route.Sql.Mapping; namespace redb.Route.Tests.Sql; public class RowMapperTests : IDisposable { private readonly SqliteTestHelper _db = new(); public RowMapperTests() { _db.Execute(""" CREATE TABLE mapper_test ( id INTEGER PRIMARY KEY, name TEXT, score REAL, data BLOB, empty TEXT ) """); _db.Execute("INSERT INTO mapper_test(id, name, score, data, empty) VALUES(1, 'Alice', 95.5, X'CAFE', NULL)"); _db.Execute("INSERT INTO mapper_test(id, name, score, data, empty) VALUES(2, 'Bob', 85.0, X'BABE', NULL)"); } // ── DictionaryRowMapper ───────────────────────────────────────── [Fact] public void DictionaryMapper_MapsAllColumns() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read().Should().BeTrue(); var mapper = new DictionaryRowMapper(); var row = mapper.Map(reader); row.Should().ContainKey("id"); row.Should().ContainKey("name"); row.Should().ContainKey("score"); row.Should().ContainKey("data"); row.Should().ContainKey("empty"); } [Fact] public void DictionaryMapper_ValuesAreCorrect() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id, name, score FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new DictionaryRowMapper(); var row = mapper.Map(reader); row["id"].Should().Be(1L); row["name"].Should().Be("Alice"); row["score"].Should().Be(95.5); } [Fact] public void DictionaryMapper_DBNull_BecomesNull() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT empty FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new DictionaryRowMapper(); var row = mapper.Map(reader); row["empty"].Should().BeNull(); } [Fact] public void DictionaryMapper_CaseInsensitiveKeys() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT name FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new DictionaryRowMapper(); var row = mapper.Map(reader); // Keys are case-insensitive row["NAME"].Should().Be("Alice"); row["Name"].Should().Be("Alice"); } [Fact] public void DictionaryMapper_MultipleRows() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id, name FROM mapper_test ORDER BY id"; using var reader = cmd.ExecuteReader(); var mapper = new DictionaryRowMapper(); var rows = new List>(); while (reader.Read()) rows.Add(mapper.Map(reader)); rows.Should().HaveCount(2); rows[0]["name"].Should().Be("Alice"); rows[1]["name"].Should().Be("Bob"); } // ── ScalarMapper ──────────────────────────────────────────────── [Fact] public void ScalarMapper_LongValue() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM mapper_test"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new ScalarMapper(); var result = mapper.Map(reader); result.Should().Be(2L); } [Fact] public void ScalarMapper_StringValue() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT name FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new ScalarMapper(); var result = mapper.Map(reader); result.Should().Be("Alice"); } [Fact] public void ScalarMapper_DBNull_ReturnsDefault() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT empty FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new ScalarMapper(); var result = mapper.Map(reader); result.Should().BeNull(); } [Fact] public void ScalarMapper_IntConversion() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new ScalarMapper(); var result = mapper.Map(reader); result.Should().Be(1); } // ── PocoRowMapper ─────────────────────────────────────────────── [Fact] public void PocoMapper_MapsProperties_CaseInsensitive() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id, name, score FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new PocoRowMapper(); var obj = mapper.Map(reader); obj.Id.Should().Be(1); obj.Name.Should().Be("Alice"); obj.Score.Should().Be(95.5); } [Fact] public void PocoMapper_DBNull_SkipsProperty() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id, name, empty as Description FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new PocoRowMapper(); var obj = mapper.Map(reader); obj.Description.Should().BeNull(); } [Fact] public void PocoMapper_SnakeCase_ToPascalCase() { _db.Execute("CREATE TABLE snake_test (user_name TEXT, created_at TEXT)"); _db.Execute("INSERT INTO snake_test VALUES('Alice', '2024-01-01')"); using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT user_name, created_at FROM snake_test"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new PocoRowMapper(); var obj = mapper.Map(reader); obj.UserName.Should().Be("Alice"); obj.CreatedAt.Should().Be("2024-01-01"); } [Fact] public void PocoMapper_ColumnAttribute() { _db.Execute("CREATE TABLE col_attr_test (full_name TEXT)"); _db.Execute("INSERT INTO col_attr_test VALUES('Bob')"); using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT full_name FROM col_attr_test"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new PocoRowMapper(); var obj = mapper.Map(reader); obj.Name.Should().Be("Bob"); } [Fact] public void PocoMapper_UnknownColumn_Skipped() { using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); // 'data' column has no matching property cmd.CommandText = "SELECT id, name, data FROM mapper_test WHERE id = 1"; using var reader = cmd.ExecuteReader(); reader.Read(); var mapper = new PocoRowMapper(); var obj = mapper.Map(reader); obj.Id.Should().Be(1); obj.Name.Should().Be("Alice"); } [Fact] public void PocoMapper_PropertyCache_IsCaseInsensitive() { // Call Map twice with same column names to test cache using var conn = _db.CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT id, name FROM mapper_test ORDER BY id"; using var reader = cmd.ExecuteReader(); var mapper = new PocoRowMapper(); reader.Read(); var obj1 = mapper.Map(reader); reader.Read(); var obj2 = mapper.Map(reader); obj1.Name.Should().Be("Alice"); obj2.Name.Should().Be("Bob"); } public void Dispose() => _db.Dispose(); // ── Test POCOs ────────────────────────────────────────────────── private class TestPoco { public long Id { get; set; } public string? Name { get; set; } public double Score { get; set; } public string? Description { get; set; } } private class SnakePoco { public string? UserName { get; set; } public string? CreatedAt { get; set; } } private class ColumnAttrPoco { [System.ComponentModel.DataAnnotations.Schema.Column("full_name")] public string? Name { get; set; } } } Path: redb-route/tests/redb.Route.Tests.Sql/ServiceCollectionExtensionsTests.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/ServiceCollectionExtensionsTests.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Abstractions; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// Tests for the DI registration extension method AddRedbRouteSql. /// public class ServiceCollectionExtensionsTests { [Fact] public void AddRedbRouteSql_RegistersSqlComponent() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteSql(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public void AddRedbRouteSql_RegistersNamedQueryRegistry() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteSql(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public async Task AddDataSource_RegistersFactoryInContextRegistry() { var services = new ServiceCollection(); services.AddRedbRouteSql(sql => { sql.AddDataSource("test", Substitute.For()); }); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.GetFromRegistry("test").Should().NotBeNull(); } [Fact] public async Task AddDataSource_WithFactory_RegistersInContextRegistry() { var mockFactory = Substitute.For(); var services = new ServiceCollection(); services.AddRedbRouteSql(sql => { sql.AddDataSource("custom", mockFactory); }); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.GetFromRegistry("custom").Should().BeSameAs(mockFactory); } [Fact] public async Task AddRedbRouteSql_Twice_KeepsNamedQueriesAndDataSourcesOfBothCalls() { var services = new ServiceCollection(); services.AddRedbRouteSql(sql => sql.AddNamedQuery("q1", "SELECT 1").AddDataSource("a", Substitute.For())); services.AddRedbRouteSql(sql => sql.AddNamedQuery("q2", "SELECT 2").AddDataSource("b", Substitute.For())); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); var registry = context.GetService(); registry.Should().NotBeNull(); registry!.Resolve("q1").Should().Be("SELECT 1", "a second registration (another module) must not drop the first one's queries"); registry.Resolve("q2").Should().Be("SELECT 2"); context.GetFromRegistry("a").Should().NotBeNull(); context.GetFromRegistry("b").Should().NotBeNull(); context.HasComponent("sql").Should().BeTrue(); } [Fact] public void AddNamedQuery_RegistersQuery() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteSql(sql => { sql.AddNamedQuery("getOrders", "SELECT * FROM orders"); }); var sp = services.BuildServiceProvider(); var registry = sp.GetRequiredService(); registry.Resolve("getOrders").Should().Be("SELECT * FROM orders"); } [Fact] public async Task AddMultipleDataSources_AllRegisteredInContext() { var services = new ServiceCollection(); services.AddRedbRouteSql(sql => { sql.AddDataSource("db1", Substitute.For()); sql.AddDataSource("db2", Substitute.For()); }); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.GetFromRegistry("db1").Should().NotBeNull(); context.GetFromRegistry("db2").Should().NotBeNull(); } [Fact] public void SqlConfigurationBuilder_FluentChaining() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteSql(sql => { var result = sql .AddDataSource("ds", Substitute.For()) .AddNamedQuery("q1", "SELECT 1") .AddNamedQuery("q2", "SELECT 2"); result.Should().BeSameAs(sql); }); } [Fact] public void Configurator_IsRegistered() { var services = new ServiceCollection(); services.AddRedbRouteSql(); // The startup hook RouteHostedService applies must be present var descriptor = services.FirstOrDefault(d => d.ServiceType == typeof(IRouteContextConfigurator)); descriptor.Should().NotBeNull(); descriptor!.Lifetime.Should().Be(ServiceLifetime.Singleton); } [Fact] public void AddRedbRouteSql_NullConfigure_Works() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); // Should not throw services.AddRedbRouteSql(null); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public void AddRedbRouteSql_NoConfigure_Works() { var services = new ServiceCollection(); services.AddSingleton(Substitute.For()); services.AddRedbRouteSql(); var sp = services.BuildServiceProvider(); sp.GetService().Should().NotBeNull(); } [Fact] public async Task Configurator_AddsComponentToContext() { var services = new ServiceCollection(); services.AddRedbRouteSql(sql => { sql.AddDataSource("main", Substitute.For()); }); await using var sp = services.BuildServiceProvider(); await using var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); context.HasComponent("sql").Should().BeTrue(); } // ── Named queries through the host path ───────────────────────── [Fact] public async Task AddNamedQuery_RefResolvesInProducer() { using var db = NamedItemsDatabase(); await using var sp = NamedQueryServices(db).BuildServiceProvider(); await using var context = ConfiguredContext(sp); var endpoint = RefEndpoint(sp, new() { ["mode"] = "Execute", ["outputType"] = "SelectList" }); var exchange = new Exchange(new Message("untouched")); var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Body.Should().BeAssignableTo>>() .Which.Select(r => r["val"]).Should().Equal("a", "b"); } [Fact] public async Task AddNamedQuery_RefResolvesInPollConsumer() { using var db = NamedItemsDatabase(); await using var sp = NamedQueryServices(db).BuildServiceProvider(); await using var context = ConfiguredContext(sp); var endpoint = RefEndpoint(sp, new() { ["mode"] = "Poll", ["repeatCount"] = "1" }); var received = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(((Dictionary)ci.Arg().In.Body!)["val"]); return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); var thrown = await Outcome.Of(() => consumer.Poll(CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); received.Should().Equal("a", "b"); } private static SqliteTestHelper NamedItemsDatabase() { var db = new SqliteTestHelper(); db.Execute("CREATE TABLE named_items (id INTEGER PRIMARY KEY, val TEXT)"); db.Execute("INSERT INTO named_items (id, val) VALUES (1, 'a'), (2, 'b')"); return db; } private static ServiceCollection NamedQueryServices(SqliteTestHelper db) { var services = new ServiceCollection(); services.AddRedbRouteSql(sql => sql .AddDataSource("main", db.CreateFactory()) .AddNamedQuery("allItems", "SELECT id, val FROM named_items ORDER BY id")); return services; } /// A context configured the way RouteHostedService configures it at startup. private static RouteContext ConfiguredContext(IServiceProvider sp) { var context = new RouteContext(); foreach (var configurator in sp.GetServices()) configurator.Configure(context); return context; } private static SqlEndpoint RefEndpoint(IServiceProvider sp, Dictionary parameters) { parameters["dataSource"] = "main"; var uri = new EndpointUri("sql", "ref:allItems", "sql:ref:allItems", parameters); return (SqlEndpoint)sp.GetRequiredService().CreateEndpoint(uri); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlBuilderTests.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/SqlBuilderTests.cs ---- using System.Data; using System.Globalization; using redb.Route.Sql; using redb.Route.Expressions; using redb.Route.Expressions; using SqlDsl = redb.Route.Sql.Sql; namespace redb.Route.Tests.Sql; public class SqlBuilderTests { private static ConstantExpression C(string s) => new(s); // ── Factory methods ───────────────────────────────────────────── [Fact] public void Poll_SetsMode() { var uri = SqlDsl.Poll("SELECT * FROM t").DataSource(C("main")).Build(); uri.Should().Contain("mode=Poll"); } [Fact] public void Execute_SetsMode() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(1)").DataSource(C("main")).Build(); uri.Should().Contain("mode=Execute"); } [Fact] public void Procedure_SetsMode() { var uri = SqlDsl.Procedure("sp_Calc").DataSource(C("main")).Build(); uri.Should().Contain("mode=Procedure"); } [Fact] public void NullQuery_Throws() { var act = () => SqlDsl.Poll(null!); act.Should().Throw(); } [Fact] public void EmptyQuery_Throws() { var act = () => SqlDsl.Execute(""); act.Should().Throw(); } [Fact] public void WhitespaceQuery_Throws() { var act = () => SqlDsl.Execute(" "); act.Should().Throw(); } // ── URI structure ─────────────────────────────────────────────── [Fact] public void Build_StartsWithSqlScheme() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build(); uri.Should().StartWith("sql:"); } [Fact] public void Build_ContainsSqlInPath() { var uri = SqlDsl.Execute("SELECT * FROM orders").DataSource(C("main")).Build(); uri.Should().StartWith("sql:SELECT * FROM orders"); } [Fact] public void Build_FirstParamAfterQuestionMark() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build(); uri.Should().Contain("?mode="); } // ── Connection ────────────────────────────────────────────────── [Fact] public void DataSource_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build(); uri.Should().Contain("dataSource=main"); } [Fact] public void ConnectionString_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").ConnectionString(C("Server=localhost")).Build(); uri.Should().Contain("connectionString="); } [Fact] public void Provider_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).Provider("Npgsql").Build(); uri.Should().Contain("provider=Npgsql"); } [Fact] public void CommandTimeout_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).CommandTimeout(120).Build(); uri.Should().Contain("commandTimeout=120"); } // ── Transaction ───────────────────────────────────────────────── [Fact] public void Transacted_SetsParam() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(1)").DataSource(C("main")).Transacted().Build(); uri.Should().Contain("transacted=true"); } [Fact] public void WithIsolationLevel_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")) .WithIsolationLevel(IsolationLevel.Serializable).Build(); uri.Should().Contain("isolationLevel=Serializable"); } // ── Output ────────────────────────────────────────────────────── [Fact] public void OutputType_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).OutputType(SqlOutputType.Scalar).Build(); uri.Should().Contain("outputType=Scalar"); } [Fact] public void OutputClass_SetsParam() { var uri = SqlDsl.Execute("SELECT * FROM t").DataSource(C("main")).OutputClass("MyPoco").Build(); uri.Should().Contain("outputClass=MyPoco"); } [Fact] public void OutputHeader_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).OutputHeader(C("myHeader")).Build(); uri.Should().Contain("outputHeader=myHeader"); } [Fact] public void Noop_SetsParam() { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")).Noop().Build(); uri.Should().Contain("noop=true"); } // ── Polling ───────────────────────────────────────────────────── [Fact] public void Delay_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).Delay(5000).Build(); uri.Should().Contain("delay=5000"); } [Fact] public void InitialDelay_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).InitialDelay(3000).Build(); uri.Should().Contain("initialDelay=3000"); } [Fact] public void FixedRate_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).FixedRate().Build(); uri.Should().Contain("fixedRate=true"); } [Fact] public void RepeatCount_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).RepeatCount(100).Build(); uri.Should().Contain("repeatCount=100"); } [Fact] public void MaxMessagesPerPoll_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).MaxMessagesPerPoll(50).Build(); uri.Should().Contain("maxMessagesPerPoll=50"); } [Fact] public void RouteEmptyResultSet_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).RouteEmptyResultSet().Build(); uri.Should().Contain("routeEmptyResultSet=true"); } [Fact] public void PlaceholderStyle_SetsParam_AndDefaultWritesNothing() { SqlDsl.Execute("SELECT 1").DataSource(C("main")).PlaceholderStyle(SqlPlaceholderStyle.Colon).Build() .Should().Contain("placeholderStyle=Colon"); SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build() .Should().NotContain("placeholderStyle", "the default style is left to the options"); } [Fact] public void BackslashEscapes_SetsParam_AndDefaultWritesNothing() { SqlDsl.Execute("SELECT 1").DataSource(C("main")).BackslashEscapes().Build() .Should().Contain("backslashEscapes=true"); SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build() .Should().NotContain("backslashEscapes", "standard SQL literals are left to the options"); } [Fact] public void ReadOnly_SetsParam_AndDefaultWritesNothing() { SqlDsl.Execute("SELECT 1").DataSource(C("main")).ReadOnly().Build() .Should().Contain("readOnly=true"); SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build() .Should().NotContain("readOnly", "the primary database is the default"); } [Fact] public void PollDelivery_SetsParam_AndDefaultWritesNothing() { SqlDsl.Poll("SELECT 1").DataSource(C("main")).PollDelivery(SqlPollDelivery.List).Build() .Should().Contain("pollDelivery=List"); SqlDsl.Poll("SELECT 1").DataSource(C("main")).Build() .Should().NotContain("pollDelivery", "the default is left to the options"); } [Fact] public void SendEmptyMessageWhenIdle_SetsParam() { var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).SendEmptyMessageWhenIdle().Build(); uri.Should().Contain("sendEmptyMessageWhenIdle=true"); } // ── Lifecycle SQL ─────────────────────────────────────────────── [Fact] public void OnSuccess_SetsParam() { var uri = SqlDsl.Poll("SELECT * FROM outbox") .DataSource(C("main")) .OnSuccess("UPDATE outbox SET done=1 WHERE id=:#id") .Build(); uri.Should().Contain("onSuccess="); } [Fact] public void OnFailure_SetsParam() { var uri = SqlDsl.Poll("SELECT 1") .DataSource(C("main")) .OnFailure("INSERT INTO err(msg) VALUES(:#redbError)") .Build(); uri.Should().Contain("onFailure="); } [Fact] public void OnBatchComplete_SetsParam() { var uri = SqlDsl.Poll("SELECT 1") .DataSource(C("main")) .OnBatchComplete("EXEC sp_Notify") .Build(); uri.Should().Contain("onBatchComplete="); } // ── Batch ─────────────────────────────────────────────────────── [Fact] public void Batch_SetsParam() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)").DataSource(C("main")).Batch(100).Build(); uri.Should().Contain("batchSize=100"); } [Fact] public void BreakBatchOnError_SetsParam() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)") .DataSource(C("main")).BreakBatchOnError().Build(); uri.Should().Contain("breakBatchOnError=true"); } // ── Procedure ─────────────────────────────────────────────────── [Fact] public void AsFunction_SetsParam() { var uri = SqlDsl.Procedure("fn_Calc").DataSource(C("main")).AsFunction().Build(); uri.Should().Contain("asFunction=true"); } [Fact] public void In_AddsParamDef() { var uri = SqlDsl.Procedure("sp_Test") .DataSource(C("main")) .In("userId", DbType.Int32) .Build(); uri.Should().Contain("procedureParams="); uri.Should().Contain("IN"); uri.Should().Contain("userId"); } [Fact] public void In_WithExpression_AddsParamDef() { var uri = SqlDsl.Procedure("sp_Test") .DataSource(C("main")) .In("userId", DbType.Int32, "${header.userId}") .Build(); uri.Should().Contain("procedureParams="); } [Fact] public void Out_AddsParamDef() { var uri = SqlDsl.Procedure("sp_Test") .DataSource(C("main")) .Out("result", DbType.String) .Build(); uri.Should().Contain("OUT"); uri.Should().Contain("result"); } [Fact] public void InOut_AddsParamDef() { var uri = SqlDsl.Procedure("sp_Test") .DataSource(C("main")) .InOut("counter", DbType.Int32) .Build(); uri.Should().Contain("INOUT"); uri.Should().Contain("counter"); } [Fact] public void MultipleParams_SerializeCorrectly() { var uri = SqlDsl.Procedure("sp_Test") .DataSource(C("main")) .In("id", DbType.Int32) .Out("name", DbType.String) .InOut("count", DbType.Int64) .Build(); // Should contain comma-separated param defs uri.Should().Contain("procedureParams="); } // ── Implicit conversion ───────────────────────────────────────── [Fact] public void ImplicitStringConversion_Works() { string uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")); uri.Should().StartWith("sql:"); } [Fact] public void ToString_SameasBuild() { var builder = SqlDsl.Execute("SELECT 1").DataSource(C("main")); builder.ToString().Should().Be(builder.Build()); } // ── Full fluent chain ─────────────────────────────────────────── [Fact] public void FullPollChain_GeneratesValidUri() { var uri = SqlDsl.Poll("SELECT * FROM outbox WHERE processed = 0") .DataSource(C("main")) .Delay(5000) .InitialDelay(1000) .Transacted() .MaxMessagesPerPoll(100) .OnSuccess("UPDATE outbox SET processed = 1 WHERE id = :#id") .OnFailure("INSERT INTO errors(msg) VALUES(:#redbError)") .Build(); uri.Should().StartWith("sql:SELECT * FROM outbox"); uri.Should().Contain("mode=Poll"); uri.Should().Contain("dataSource=main"); uri.Should().Contain("delay=5000"); uri.Should().Contain("initialDelay=1000"); uri.Should().Contain("transacted=true"); uri.Should().Contain("maxMessagesPerPoll=100"); uri.Should().Contain("onSuccess="); uri.Should().Contain("onFailure="); } [Fact] public void FullExecuteChain_GeneratesValidUri() { var uri = SqlDsl.Execute("INSERT INTO audit(event) VALUES(:#event)") .DataSource(C("main")) .CommandTimeout(120) .Transacted() .WithIsolationLevel(IsolationLevel.Serializable) .OutputType(SqlOutputType.None) .Build(); uri.Should().StartWith("sql:INSERT INTO audit"); uri.Should().Contain("mode=Execute"); uri.Should().Contain("commandTimeout=120"); uri.Should().Contain("transacted=true"); uri.Should().Contain("isolationLevel=Serializable"); uri.Should().Contain("outputType=None"); } [Fact] public void FullProcedureChain_GeneratesValidUri() { var uri = SqlDsl.Procedure("sp_ProcessOrder") .DataSource(C("main")) .In("orderId", DbType.Int32) .Out("total", DbType.Decimal) .Transacted() .Build(); uri.Should().StartWith("sql:sp_ProcessOrder"); uri.Should().Contain("mode=Procedure"); uri.Should().Contain("dataSource=main"); uri.Should().Contain("transacted=true"); uri.Should().Contain("procedureParams="); } // ── URL encoding ──────────────────────────────────────────────── [Fact] public void SpecialCharsInSql_PreservedInPath() { var sql = "SELECT * FROM t WHERE x > 5 AND y < 10"; var uri = SqlDsl.Execute(sql).DataSource(C("main")).Build(); uri.Should().StartWith($"sql:{sql}"); } [Fact] public void OnSuccess_WithSpecialChars_UrlEncoded() { var onSuccess = "UPDATE t SET done=1 WHERE id=:#id AND status='OK'"; var uri = SqlDsl.Poll("SELECT 1").DataSource(C("main")).OnSuccess(onSuccess).Build(); // The value should be URL-encoded uri.Should().Contain("onSuccess="); uri.Should().NotContain("onSuccess=" + onSuccess); // should be encoded } // ── Explicit Parameters (.Param) ──────────────────────────────── [Fact] public void Param_WithPlaceholderPrefix_SetsParamInUri() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)") .DataSource(C("main")) .Param(":#x", 42) .Build(); uri.Should().Contain("param.x=42"); } [Fact] public void Param_ObjectValue_IsWrittenInvariantly() { var culture = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); try { var uri = SqlDsl.Execute("SELECT 1").DataSource(C("main")) .Param("price", 12.5) .Param("at", new DateTime(2026, 9, 16, 10, 0, 0, DateTimeKind.Utc)) .Build(); uri.Should().Contain("param.price=12.5", "a constant is written the way the database reads it, whatever the process culture"); uri.Should().Contain(Uri.EscapeDataString("2026-09-16T10:00:00.0000000Z"), "a date is written as ISO 8601 round-trip text"); } finally { CultureInfo.CurrentCulture = culture; } } [Fact] public void DataSource_WithDynamicExpression_IsRejected() { var act = () => SqlDsl.Execute("SELECT 1").DataSource(new HeaderExpression("ds")); act.Should().Throw("the data source is fixed per endpoint, as in Apache Camel") .WithMessage("*dataSource*"); SqlDsl.Execute("SELECT 1").DataSource(C("main")).Build().Should().Contain("dataSource=main"); } [Fact] public void ConnectionString_Constant_SetsParam() { SqlDsl.Execute("SELECT 1").ConnectionString("Data Source=:memory:").Build() .Should().Contain("connectionString=" + Uri.EscapeDataString("Data Source=:memory:")); var act = () => SqlDsl.Execute("SELECT 1").ConnectionString(new HeaderExpression("cs")); act.Should().Throw().WithMessage("*connectionString*"); } [Fact] public void Param_WithAtPrefix_IsRejected() { var act = () => SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)").DataSource(C("main")).Param("@x", 42); act.Should().Throw("@ is not a placeholder any more; a param named @x would never match :#x") .WithMessage("*:#x*"); } [Fact] public void Param_WithoutAtPrefix_SetsParamInUri() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)") .DataSource(C("main")) .Param("x", "hello") .Build(); uri.Should().Contain("param.x=hello"); } [Fact] public void Param_MultipleParams_AllPresent() { var uri = SqlDsl.Execute("INSERT INTO t(a,b,c) VALUES(:#a,:#b,:#c)") .DataSource(C("main")) .Param(":#a", 1) .Param(":#b", "text") .Param(":#c", true) .Build(); uri.Should().Contain("param.a=1"); uri.Should().Contain("param.b=text"); uri.Should().Contain("param.c=True"); } [Fact] public void Param_NullValue_SetsEmptyString() { var uri = SqlDsl.Execute("INSERT INTO t(x) VALUES(:#x)") .DataSource(C("main")) .Param(":#x", (object?)null) .Build(); uri.Should().Contain("param.x="); } [Fact] public void Param_Chainable() { var builder = SqlDsl.Execute("SELECT 1").DataSource(C("main")); var result = builder.Param(":#x", 1); result.Should().BeSameAs(builder); } // ── Param with IExpression ───────────────────────────────────────── [Fact] public void Param_WithExpression_SetsTemplateString() { var uri = SqlDsl.Execute("UPDATE t SET x=:#x WHERE id=:#id") .DataSource(C("main")) .Param(":#x", new HeaderExpression("myValue")) .Build(); uri.Should().Contain("param.x=%24%7Bheader.myValue%7D"); } [Fact] public void Param_WithConstantExpression_SetsValue() { var uri = SqlDsl.Execute("UPDATE t SET x=:#x WHERE id=:#id") .DataSource(C("main")) .Param(":#x", C("42")) .Build(); uri.Should().Contain("param.x=42"); } [Fact] public void Param_Expression_Chainable() { var builder = SqlDsl.Execute("SELECT 1").DataSource(C("main")); var result = builder.Param(":#x", new HeaderExpression("val")); result.Should().BeSameAs(builder); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlClaimCheckRepositoryTests.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/SqlClaimCheckRepositoryTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Sql.Repositories; namespace redb.Route.Tests.Sql; /// /// Integration tests for using in-memory SQLite. /// public class SqlClaimCheckRepositoryTests : IDisposable { private readonly SqliteTestHelper _db = new(); private SqlClaimCheckRepository CreateRepo(TimeSpan? ttl = null, int cleanupInterval = 0) { var options = new SqlClaimCheckOptions { TableName = "redb_claim_check", DefaultTtl = ttl, CreateTable = true, CleanupInterval = cleanupInterval, }; return new SqlClaimCheckRepository(_db.CreateFactory(), options); } // ── Options defaults ───────────────────────────────────────── [Fact] public void Options_Defaults() { var opts = new SqlClaimCheckOptions(); opts.TableName.Should().Be("redb_claim_check"); opts.DefaultTtl.Should().BeNull(); opts.CreateTable.Should().BeTrue(); opts.CleanupInterval.Should().Be(100); } // ── Store / Retrieve ───────────────────────────────────────── [Fact] public async Task Store_ReturnsUniqueKey() { var repo = CreateRepo(); var data = Encoding.UTF8.GetBytes("payload"); var key1 = await repo.Store(data); var key2 = await repo.Store(data); key1.Should().NotBeNullOrEmpty(); key2.Should().NotBeNullOrEmpty(); key1.Should().NotBe(key2); } [Fact] public async Task Store_And_Retrieve_Roundtrip() { var repo = CreateRepo(); var data = Encoding.UTF8.GetBytes("test payload"); var key = await repo.Store(data); var retrieved = await repo.Retrieve(key); retrieved.Should().BeEquivalentTo(data); } [Fact] public async Task Store_ExplicitKey_Roundtrip() { var repo = CreateRepo(); var data = Encoding.UTF8.GetBytes("keyed data"); await repo.Store("my-key", data); var retrieved = await repo.Retrieve("my-key"); retrieved.Should().BeEquivalentTo(data); } [Fact] public async Task Store_ExplicitKey_Overwrites() { var repo = CreateRepo(); await repo.Store("same", Encoding.UTF8.GetBytes("first")); await repo.Store("same", Encoding.UTF8.GetBytes("second")); var retrieved = await repo.Retrieve("same"); Encoding.UTF8.GetString(retrieved!).Should().Be("second"); } [Fact] public async Task Retrieve_Missing_ReturnsNull() { var repo = CreateRepo(); var result = await repo.Retrieve("nonexistent"); result.Should().BeNull(); } // ── RetrieveAndRemove ──────────────────────────────────────── [Fact] public async Task RetrieveAndRemove_RemovesEntry() { var repo = CreateRepo(); var key = await repo.Store(Encoding.UTF8.GetBytes("temp")); var data = await repo.RetrieveAndRemove(key); data.Should().NotBeNull(); (await repo.Retrieve(key)).Should().BeNull(); } [Fact] public async Task RetrieveAndRemove_Missing_ReturnsNull() { var repo = CreateRepo(); var result = await repo.RetrieveAndRemove("missing"); result.Should().BeNull(); } // ── Remove ─────────────────────────────────────────────────── [Fact] public async Task Remove_DeletesEntry() { var repo = CreateRepo(); var key = await repo.Store(Encoding.UTF8.GetBytes("delete me")); await repo.Remove(key); (await repo.Retrieve(key)).Should().BeNull(); } [Fact] public async Task Remove_Missing_NoOp() { var repo = CreateRepo(); var act = async () => await repo.Remove("missing"); await act.Should().NotThrowAsync(); } // ── TTL ────────────────────────────────────────────────────── [Fact] public async Task Store_WithTtl_Retrieve_ReturnsNull_AfterExpiry() { var repo = CreateRepo(ttl: TimeSpan.FromMilliseconds(50)); var key = await repo.Store(Encoding.UTF8.GetBytes("ttl data")); (await repo.Retrieve(key)).Should().NotBeNull(); await Task.Delay(80); (await repo.Retrieve(key)).Should().BeNull(); } [Fact] public async Task Store_ExplicitTtl_OverridesDefault() { var repo = CreateRepo(ttl: TimeSpan.FromSeconds(30)); var key = await repo.Store( Encoding.UTF8.GetBytes("short-lived"), ttl: TimeSpan.FromMilliseconds(50)); await Task.Delay(80); (await repo.Retrieve(key)).Should().BeNull(); } // ── Auto-create table ──────────────────────────────────────── [Fact] public async Task AutoCreateTable_CreatesTable() { var repo = CreateRepo(); // First operation triggers table creation var key = await repo.Store(Encoding.UTF8.GetBytes("test")); var rows = _db.Query($"SELECT * FROM redb_claim_check WHERE claim_key = '{key}'"); rows.Should().HaveCount(1); } // ── Binary data ────────────────────────────────────────────── [Fact] public async Task Store_BinaryData_Roundtrip() { var repo = CreateRepo(); var data = new byte[] { 0x00, 0xFF, 0x42, 0x13, 0x80 }; var key = await repo.Store(data); var retrieved = await repo.Retrieve(key); retrieved.Should().BeEquivalentTo(data); } // ── Constructor validation ─────────────────────────────────── [Fact] public void Ctor_NullFactory_Throws() { var act = () => new SqlClaimCheckRepository(null!, new SqlClaimCheckOptions()); act.Should().Throw(); } [Fact] public void Ctor_NullOptions_Throws() { var act = () => new SqlClaimCheckRepository(_db.CreateFactory(), null!); act.Should().Throw(); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlComponentTests.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/SqlComponentTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; public class SqlComponentTests { [Fact] public void Scheme_ReturnsSql() { var component = new SqlComponent(); component.Scheme.Should().Be("sql"); } [Fact] public void CreateEndpoint_ValidUri_ReturnsSqlEndpoint() { var component = new SqlComponent(); var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", new Dictionary { ["dataSource"] = "main" }); var endpoint = component.CreateEndpoint(uri); endpoint.Should().BeOfType(); endpoint.Uri.Should().BeSameAs(uri); endpoint.Component.Should().BeSameAs(component); } [Fact] public void CreateEndpoint_NullUri_Throws() { var component = new SqlComponent(); var act = () => component.CreateEndpoint(null!); act.Should().Throw(); } [Fact] public void CreateEndpoint_WithOptions_BindsCorrectly() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main", ["delay"] = "2000", ["transacted"] = "true", ["outputType"] = "Scalar", ["commandTimeout"] = "60" }; var uri = new EndpointUri("sql", "SELECT COUNT(*) FROM users", "sql:SELECT...", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); endpoint.EndpointOptions.Mode.Should().Be(SqlMode.Poll); endpoint.EndpointOptions.DataSource.Should().Be("main"); endpoint.EndpointOptions.Delay.Should().Be(2000); endpoint.EndpointOptions.Transacted.Should().BeTrue(); endpoint.EndpointOptions.OutputType.Should().Be(SqlOutputType.Scalar); endpoint.EndpointOptions.CommandTimeout.Should().Be(60); } [Fact] public void CreateEndpoint_InvalidOptions_Throws() { var component = new SqlComponent(); // No DataSource or ConnectionString → Validate throws var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", new Dictionary()); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } [Fact] public void Endpoint_QueryOrProcedure_ReturnsParsedPath() { var component = new SqlComponent(); var sqlText = "SELECT * FROM orders WHERE status = 'new'"; var uri = new EndpointUri("sql", sqlText, $"sql:{sqlText}", new Dictionary { ["dataSource"] = "main" }); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); endpoint.QueryOrProcedure.Should().Be(sqlText); } // ── Endpoint CreateConsumer ───────────────────────────────────── [Fact] public void Endpoint_CreateConsumer_PollMode_ReturnsSqlConsumer() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main" }; var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); var consumer = endpoint.CreateConsumer(processor); consumer.Should().BeOfType(); } [Fact] public void Endpoint_CreateConsumer_ExecuteMode_Throws() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main" }; var uri = new EndpointUri("sql", "INSERT INTO t(x) VALUES(1)", "sql:INSERT...", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var processor = Substitute.For(); var act = () => endpoint.CreateConsumer(processor); act.Should().Throw().WithMessage("*Poll*"); } [Fact] public void Endpoint_CreateConsumer_NullProcessor_Throws() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main" }; var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var act = () => endpoint.CreateConsumer(null!); act.Should().Throw(); } // ── Endpoint CreateProducer ───────────────────────────────────── [Fact] public void Endpoint_CreateProducer_ExecuteMode_ReturnsSqlProducer() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main" }; var uri = new EndpointUri("sql", "INSERT INTO t(x) VALUES(:#x)", "sql:INSERT...", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } [Fact] public void Endpoint_CreateProducer_ProcedureMode_ReturnsSqlProcedureProducer() { var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Procedure", ["dataSource"] = "main", ["procedureName"] = "sp_Test" }; var uri = new EndpointUri("sql", "sp_Test", "sql:sp_Test", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } [Fact] public void Endpoint_CreateProducer_PollMode_ReturnsSqlProducer() { // Poll mode still creates a producer (for bi-directional routes) var component = new SqlComponent(); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main" }; var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", parameters); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); producer.Should().BeOfType(); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlConnectionTests.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/SqlConnectionTests.cs ---- using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Microsoft.Data.Sqlite; using redb.Route.Sql.Connection; namespace redb.Route.Tests.Sql; public class SqlConnectionTests : IDisposable { private readonly SqliteTestHelper _db = new(); // ── SqlConnectionOptions defaults ─────────────────────────────── [Fact] public void SqlConnectionOptions_Defaults() { var opts = new SqlConnectionOptions(); opts.ConnectionString.Should().BeEmpty(); opts.ReadConnectionString.Should().BeNull(); opts.ProviderName.Should().BeEmpty(); opts.ProviderFactory.Should().BeNull(); opts.MinPoolSize.Should().Be(0); opts.MaxPoolSize.Should().Be(100); opts.ConnectionLifetime.Should().Be(TimeSpan.Zero); opts.ConnectionIdleTimeout.Should().Be(TimeSpan.FromMinutes(5)); opts.TestOnBorrow.Should().BeFalse(); opts.ValidationQuery.Should().Be("SELECT 1"); opts.ValidationTimeout.Should().Be(5); opts.ConnectTimeout.Should().Be(15); opts.CommandTimeout.Should().Be(30); opts.MaxRetries.Should().Be(0); opts.RetryDelay.Should().Be(TimeSpan.FromSeconds(1)); opts.EnableRetryOnFailure.Should().BeFalse(); } // ── SqliteConnectionFactory ───────────────────────────────────── [Fact] public async Task SqliteFactory_CreatesOpenConnection() { var factory = _db.CreateFactory(); await using var conn = await factory.CreateConnectionAsync(); conn.Should().NotBeNull(); conn.State.Should().Be(System.Data.ConnectionState.Open); } [Fact] public async Task SqliteFactory_CanExecuteQuery() { var factory = _db.CreateFactory(); await using var conn = await factory.CreateConnectionAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT 42"; var result = await cmd.ExecuteScalarAsync(); result.Should().Be(42L); } [Fact] public async Task SqliteFactory_ReadOnlyParam_Ignored() { var factory = _db.CreateFactory(); await using var conn1 = await factory.CreateConnectionAsync(readOnly: false); await using var conn2 = await factory.CreateConnectionAsync(readOnly: true); conn1.State.Should().Be(System.Data.ConnectionState.Open); conn2.State.Should().Be(System.Data.ConnectionState.Open); } // ── SqlConnectionFactory with SQLite ───────────────────────────── [Fact] public async Task SqlConnectionFactory_WithProviderFactory_CreatesConnection() { var options = new SqlConnectionOptions { ConnectionString = _db.ConnectionString, ProviderFactory = SqliteFactory.Instance }; var factory = new SqlConnectionFactory(options); await using var conn = await factory.CreateConnectionAsync(); conn.Should().NotBeNull(); conn.State.Should().Be(System.Data.ConnectionState.Open); } [Fact] public async Task SqlConnectionFactory_ReadWriteSplit() { // Both strings point at same DB for testing, but validates the split logic works var options = new SqlConnectionOptions { ConnectionString = _db.ConnectionString, ReadConnectionString = _db.ConnectionString, ProviderFactory = SqliteFactory.Instance }; var factory = new SqlConnectionFactory(options); await using var writeConn = await factory.CreateConnectionAsync(readOnly: false); await using var readConn = await factory.CreateConnectionAsync(readOnly: true); writeConn.State.Should().Be(System.Data.ConnectionState.Open); readConn.State.Should().Be(System.Data.ConnectionState.Open); } [Fact] public async Task SqlConnectionFactory_TestOnBorrow_Succeeds() { var options = new SqlConnectionOptions { ConnectionString = _db.ConnectionString, ProviderFactory = SqliteFactory.Instance, TestOnBorrow = true, ValidationQuery = "SELECT 1" }; var factory = new SqlConnectionFactory(options); await using var conn = await factory.CreateConnectionAsync(); conn.State.Should().Be(System.Data.ConnectionState.Open); } [Fact] public void SqlConnectionFactory_NoProviderOrFactoryString_Throws() { var options = new SqlConnectionOptions { ConnectionString = "something" // No ProviderName or ProviderFactory }; var act = () => new SqlConnectionFactory(options); act.Should().Throw(); } [Fact] public void SqlConnectionFactory_UnknownProviderName_Throws() { var options = new SqlConnectionOptions { ConnectionString = "something", ProviderName = "NonExistentProvider.12345" }; var act = () => new SqlConnectionFactory(options); act.Should().Throw().WithMessage("*NonExistentProvider*"); } // ── Retry logic ───────────────────────────────────────────────── [Fact] public async Task Retry_SucceedsAfterTransientFailure() { var failCount = 2; var factory = new SqlConnectionFactory(new SqlConnectionOptions { ProviderFactory = new CountingProviderFactory(failCount, _db.ConnectionString), ConnectionString = _db.ConnectionString, EnableRetryOnFailure = true, MaxRetries = 3, RetryDelay = TimeSpan.FromMilliseconds(10) }); await using var conn = await factory.CreateConnectionAsync(); conn.State.Should().Be(System.Data.ConnectionState.Open); } [Fact] public async Task Retry_ExhaustsAttemptsAndThrows() { var failCount = 5; // More than MaxRetries + 1 var factory = new SqlConnectionFactory(new SqlConnectionOptions { ProviderFactory = new CountingProviderFactory(failCount, _db.ConnectionString), ConnectionString = _db.ConnectionString, EnableRetryOnFailure = true, MaxRetries = 2, RetryDelay = TimeSpan.FromMilliseconds(10) }); var act = () => factory.CreateConnectionAsync(); await act.Should().ThrowAsync().WithMessage("Simulated*"); } [Fact] public async Task Retry_DisabledByDefault_FailsImmediately() { var factory = new SqlConnectionFactory(new SqlConnectionOptions { ProviderFactory = new CountingProviderFactory(1, _db.ConnectionString), ConnectionString = _db.ConnectionString, EnableRetryOnFailure = false // default }); var act = () => factory.CreateConnectionAsync(); await act.Should().ThrowAsync().WithMessage("Simulated*"); } [Fact] public async Task Retry_CancellationRespected() { var factory = new SqlConnectionFactory(new SqlConnectionOptions { ProviderFactory = new CountingProviderFactory(10, _db.ConnectionString), ConnectionString = _db.ConnectionString, EnableRetryOnFailure = true, MaxRetries = 10, RetryDelay = TimeSpan.FromSeconds(10) }); using var cts = new CancellationTokenSource(); cts.Cancel(); var act = () => factory.CreateConnectionAsync(ct: cts.Token); await act.Should().ThrowAsync(); } // ── Helpers for retry tests ───────────────────────────────────── /// /// A DbProviderFactory that fails the first N calls to CreateConnection with a /// FailingConnection, then delegates to the real SQLite factory. /// private sealed class CountingProviderFactory : DbProviderFactory { private int _failsRemaining; private readonly string _realConnectionString; public CountingProviderFactory(int failCount, string realConnectionString) { _failsRemaining = failCount; _realConnectionString = realConnectionString; } public override DbConnection CreateConnection() { if (Interlocked.Decrement(ref _failsRemaining) >= 0) return new FailingConnection(); var conn = Microsoft.Data.Sqlite.SqliteFactory.Instance.CreateConnection()!; return conn; } } /// /// A DbConnection stub that always throws on Open/OpenAsync. /// private sealed class FailingConnection : DbConnection { private string _connectionString = ""; [AllowNull] public override string ConnectionString { get => _connectionString; set => _connectionString = value ?? ""; } public override string Database => ""; public override string DataSource => ""; public override string ServerVersion => ""; public override System.Data.ConnectionState State => System.Data.ConnectionState.Closed; public override void Open() => throw new InvalidOperationException("Simulated transient failure"); public override void Close() { } public override void ChangeDatabase(string databaseName) { } protected override DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel) => throw new NotSupportedException(); protected override DbCommand CreateDbCommand() => throw new NotSupportedException(); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlConsumerLifecycleLoggingTests.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/SqlConsumerLifecycleLoggingTests.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// A failing onSuccess statement leaves the row unmarked, so the next poll processes it again. The failure must be /// visible: it is logged, whatever onFailure and the transaction mode do with it afterwards. /// public sealed class SqlConsumerLifecycleLoggingTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlConsumerLifecycleLoggingTests() { _db.Execute("CREATE TABLE outbox_items (id INTEGER NOT NULL, message TEXT NOT NULL)"); _db.Execute("INSERT INTO outbox_items (id, message) VALUES (1, 'm1')"); } public void Dispose() => _db.Dispose(); [Fact] public async Task OnSuccessFails_WithoutOnFailure_FailureIsLogged() { var logs = new CapturingLoggerFactory(); await using var context = new RouteContext(loggerFactory: logs); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "SELECT id, message FROM outbox_items", new() { ["mode"] = "Poll", ["onSuccess"] = "UPDATE no_such_table SET done = 1 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); await consumer.Poll(CancellationToken.None); logs.Entries.Should().Contain(e => e.Level >= LogLevel.Error && e.Message.Contains("onSuccess") && e.Error != null, $"a failed onSuccess leaves the row to be processed again and must not pass unnoticed; logged: {string.Join(" | ", logs.Entries.Select(e => e.Message))}"); } [Fact] public async Task Stop_WhileProcessing_IsNotAFailureOfTheRow() { var logs = new CapturingLoggerFactory(); await using var context = new RouteContext(loggerFactory: logs); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "SELECT id, message FROM outbox_items", new() { ["mode"] = "Poll", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox_items SET message = 'done' WHERE id = :#id", ["onFailure"] = "UPDATE outbox_items SET message = 'failed' WHERE id = :#id", ["delay"] = "100", ["repeatCount"] = "1", }); using var cts = new CancellationTokenSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => { cts.Cancel(); throw new OperationCanceledException(cts.Token); }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); var thrown = await Outcome.Of(() => consumer.Poll(cts.Token)); thrown.Should().BeAssignableTo("the stop goes up as a cancellation: " + Outcome.Describe(thrown)); _db.Query("SELECT message FROM outbox_items")[0]["message"].Should().Be("m1", "neither onSuccess nor onFailure ran; the row is polled again after the restart"); logs.Entries.Should().NotContain(e => e.Level >= LogLevel.Error, $"a stop is not an error of the poll or of the rollback; logged: {string.Join(" | ", logs.Entries.Select(e => e.Message))}"); } private sealed class CapturingLoggerFactory : ILoggerFactory { public List<(LogLevel Level, string Message, Exception? Error)> Entries { get; } = []; public ILogger CreateLogger(string categoryName) => new CapturingLogger(this); public void AddProvider(ILoggerProvider provider) { } public void Dispose() { } private sealed class CapturingLogger(CapturingLoggerFactory owner) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { lock (owner.Entries) owner.Entries.Add((logLevel, formatter(state, exception), exception)); } } } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlConsumerListDeliveryTests.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/SqlConsumerListDeliveryTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// A poll that delivers one list (pollDelivery=List, Apache Camel useIterator=false): one exchange carries every /// polled row; onSuccess / onFailure and onBatchComplete run once for it, with values from headers and /// param.* — a list has no row columns to bind. /// public sealed class SqlConsumerListDeliveryTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlConsumerListDeliveryTests() { _db.Execute("CREATE TABLE outbox (id INTEGER PRIMARY KEY, message TEXT NOT NULL, processed INTEGER NOT NULL DEFAULT 0)"); _db.Execute("CREATE TABLE poll_log (note TEXT)"); _db.Execute("INSERT INTO outbox (id, message) VALUES (1, 'm1'), (2, 'm2'), (3, 'm3')"); } public void Dispose() => _db.Dispose(); [Fact] public async Task ListDelivery_OneExchangeWithAllRows() { var received = new List(); await PollAsync(new(), received); received.Should().ContainSingle("the whole poll is one exchange"); var rows = received[0].In.Body.Should().BeAssignableTo>>().Subject; rows.Select(r => r["message"]).Should().Equal("m1", "m2", "m3"); received[0].In.Headers[SqlHeaders.RowCount].Should().Be(3); } [Fact] public async Task ListDelivery_OutputClass_TypedList() { var received = new List(); await PollAsync(new() { ["outputClass"] = typeof(OutboxRow).AssemblyQualifiedName! }, received); received.Should().ContainSingle(); received[0].In.Body.Should().BeAssignableTo>() .Which.Select(r => r.Message).Should().Equal("m1", "m2", "m3"); } [Fact] public async Task ListDelivery_MaxMessagesPerPoll_LimitsRows() { var received = new List(); await PollAsync(new() { ["maxMessagesPerPoll"] = "2" }, received); received.Should().ContainSingle(); received[0].In.Body.Should().BeAssignableTo>>().Which.Should().HaveCount(2); } [Fact] public async Task ListDelivery_OnSuccessAndOnBatchComplete_RunOnce() { await PollAsync(new() { ["onSuccess"] = "INSERT INTO poll_log (note) VALUES ('success')", ["onBatchComplete"] = "INSERT INTO poll_log (note) VALUES ('complete')", }, []); Notes().Should().Equal(new object?[] { "success", "complete" }, "the list is one exchange: one onSuccess, one onBatchComplete"); } [Fact] public async Task ListDelivery_ProcessorFails_OnFailureOnce_TransactedRollsBack() { await PollAsync(new() { ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1", ["onFailure"] = "INSERT INTO poll_log (note) VALUES (:#redbError)", }, [], fail: true); Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM outbox WHERE processed = 1")).Should().Be(0); Notes().Should().BeEmpty("onFailure ran in the consumer transaction, which the failure rolled back"); } [Fact] public async Task ListDelivery_ProcessorFails_OnFailureOnce_NotTransacted() { await PollAsync(new() { ["onFailure"] = "INSERT INTO poll_log (note) VALUES (:#redbError)" }, [], fail: true); Notes().Should().ContainSingle("the list failed once").Which.Should().Be("route failed"); } [Fact] public async Task ListDelivery_EmptyResult_RouteEmptyResultSet_DeliversEmptyList() { _db.Execute("DELETE FROM outbox"); var received = new List(); await PollAsync(new() { ["routeEmptyResultSet"] = "true" }, received); received.Should().ContainSingle(); received[0].In.Body.Should().BeAssignableTo>>().Which.Should().BeEmpty(); } [Fact] public async Task ListDelivery_StreamList_BodyIsAStreamTheRouteReads() { var read = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var stream = (IAsyncEnumerable>)ci.Arg().In.Body!; await foreach (var row in stream) read.Add(row["message"]); }); await PollAsync(new() { ["outputType"] = "StreamList", ["onSuccess"] = "INSERT INTO poll_log (note) VALUES ('success')", }, processor); read.Should().Equal("m1", "m2", "m3"); Notes().Should().Equal(new object?[] { "success" }); } public sealed class OutboxRow { public long Id { get; set; } public string Message { get; set; } = ""; } private Task PollAsync(Dictionary extra, List received, bool fail = false) { var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var exchange = ci.Arg(); // The consumer disposes the exchange after processing: keep what the route saw. var copy = new Exchange(new Message(exchange.In.Body is System.Collections.IList list ? CopyList(list) : exchange.In.Body)); foreach (var (key, value) in exchange.In.Headers) copy.In.Headers[key] = value; received.Add(copy); return fail ? Task.FromException(new InvalidOperationException("route failed")) : Task.CompletedTask; }); return PollAsync(extra, processor); } private async Task PollAsync(Dictionary extra, IProcessor processor) { var parameters = new Dictionary { ["mode"] = "Poll", ["pollDelivery"] = "List", ["delay"] = "100", ["repeatCount"] = "1", }; foreach (var (key, value) in extra) parameters[key] = value; await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "SELECT id, message FROM outbox ORDER BY id", parameters); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); } private static object CopyList(System.Collections.IList list) { var copy = (System.Collections.IList)Activator.CreateInstance(list.GetType())!; foreach (var item in list) copy.Add(item); return copy; } private List Notes() => _db.Query("SELECT note FROM poll_log ORDER BY rowid").Select(r => r["note"]).ToList(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlConsumerOutputClassTests.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/SqlConsumerOutputClassTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// /// A poll consumer with outputClass must hand the route a mapped POCO as the body, /// while still copying the raw columns into headers — OnSuccess/OnFailure parameter binding /// runs off those columns and must keep working even for columns the POCO has no property for. /// public class SqlConsumerOutputClassTests : IAsyncLifetime, IDisposable { private readonly SqliteTestHelper _db = new(); private SqlConsumer? _consumer; private readonly List _captured = []; public Task InitializeAsync() { _db.Execute(""" CREATE TABLE outbox ( id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT NOT NULL, processed INTEGER NOT NULL DEFAULT 0 ) """); _db.Execute("INSERT INTO outbox(message) VALUES('first'), ('second')"); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) try { await _consumer.Stop(); } catch (ObjectDisposedException) { } } public void Dispose() => _db.Dispose(); /// Deliberately has no property for the processed column. public class OutboxRow { public long Id { get; set; } public string? Message { get; set; } } private SqlEndpoint CreateConsumerEndpoint(string sql, Dictionary extra) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main", ["delay"] = "100" }; foreach (var kv in extra) parameters[kv.Key] = kv.Value; var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private IProcessor CaptureProcessor() { var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { lock (_captured) _captured.Add(ci.Arg()); return Task.CompletedTask; }); return processor; } // Generous: three TFM test processes run in parallel and contend for the CPU, // and a missed poll cycle here would surface as a bogus assertion failure. private async Task WaitForCaptured(int count, int timeoutMs = 15000) { var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); while (DateTime.UtcNow < deadline) { lock (_captured) if (_captured.Count >= count) return; await Task.Delay(50); } } [Fact] public async Task OutputClass_BodyIsPoco_HeadersStillCarryRawColumns() { var endpoint = CreateConsumerEndpoint( "SELECT id, message, processed FROM outbox WHERE processed = 0 ORDER BY id", new() { ["repeatCount"] = "1", ["outputClass"] = typeof(OutboxRow).AssemblyQualifiedName! }); _consumer = (SqlConsumer)endpoint.CreateConsumer(CaptureProcessor()); await _consumer.Start(); await WaitForCaptured(2); await _consumer.Stop(); List exchanges; lock (_captured) exchanges = [.. _captured]; exchanges.Should().HaveCount(2); var first = exchanges[0].In.Body.Should().BeOfType().Subject; first.Id.Should().Be(1); first.Message.Should().Be("first"); // The POCO has no 'processed' property, but the header must still be there — // this is what OnSuccess/OnFailure bind against. exchanges[0].In.Headers.Should().ContainKey("id"); exchanges[0].In.Headers.Should().ContainKey("message"); exchanges[0].In.Headers.Should().ContainKey("processed"); exchanges[0].In.Headers["id"].Should().Be(1L); } [Fact] public async Task OutputClass_WithOnSuccess_LifecycleSqlStillBinds() { var endpoint = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0 ORDER BY id", new() { ["repeatCount"] = "1", ["outputClass"] = typeof(OutboxRow).AssemblyQualifiedName!, ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); _consumer = (SqlConsumer)endpoint.CreateConsumer(CaptureProcessor()); await _consumer.Start(); await WaitForCaptured(2); await _consumer.Stop(); var remaining = _db.ExecuteScalar("SELECT COUNT(*) FROM outbox WHERE processed = 0"); Convert.ToInt64(remaining).Should().Be(0); } [Fact] public async Task OutputClass_NotSet_BodyStaysADictionary() { // Regression guard for the default path. var endpoint = CreateConsumerEndpoint( "SELECT id, message FROM outbox ORDER BY id", new() { ["repeatCount"] = "1" }); _consumer = (SqlConsumer)endpoint.CreateConsumer(CaptureProcessor()); await _consumer.Start(); await WaitForCaptured(2); await _consumer.Stop(); List exchanges; lock (_captured) exchanges = [.. _captured]; exchanges[0].In.Body.Should().BeOfType>(); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlConsumerTests.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/SqlConsumerTests.cs ---- using System.Text.Json; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// Integration tests for SqlConsumer using an in-memory SQLite database. /// public class SqlConsumerTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlConsumerTests() { _db.Execute(""" CREATE TABLE outbox ( id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT NOT NULL, processed INTEGER NOT NULL DEFAULT 0 ) """); } private SqlEndpoint CreateEndpoint(Dictionary parameters) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var sql = parameters.ContainsKey("_sql") ? parameters["_sql"] : "SELECT * FROM outbox WHERE processed = 0"; parameters.Remove("_sql"); if (!parameters.ContainsKey("mode")) parameters["mode"] = "Poll"; if (!parameters.ContainsKey("dataSource")) parameters["dataSource"] = "main"; var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private void InsertOutboxRow(string message) { _db.Execute($"INSERT INTO outbox(message) VALUES('{message}')"); } private static async Task WaitForCondition(Func condition, int timeoutMs = 5000) { var sw = System.Diagnostics.Stopwatch.StartNew(); while (!condition() && sw.ElapsedMilliseconds < timeoutMs) await Task.Delay(50); } // ── Basic polling ─────────────────────────────────────────────── [Fact] public async Task Consumer_PollsAndProcessesRows() { InsertOutboxRow("msg-1"); InsertOutboxRow("msg-2"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 2); await consumer.Stop(); processed.Should().HaveCountGreaterThanOrEqualTo(2); // Verify headers are set var exchange = processed[0]; exchange.In.Headers.Should().ContainKey(SqlHeaders.Query); exchange.In.Headers.Should().ContainKey(SqlHeaders.RowCount); exchange.In.Headers.Should().ContainKey(SqlHeaders.ExecutionTime); exchange.In.Headers[SqlHeaders.DataSource].Should().Be("main"); } [Fact] public async Task Consumer_RowBody_IsDictionary() { InsertOutboxRow("hello"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 1); await consumer.Stop(); processed.Should().HaveCountGreaterThanOrEqualTo(1); var body = processed[0].In.Body as Dictionary; body.Should().NotBeNull(); body!["message"].Should().Be("hello"); } [Fact] public async Task Consumer_EmptyTable_NoProcessing() { var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1" }); var processor = Substitute.For(); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await Task.Delay(300); await consumer.Stop(); await processor.DidNotReceive().Process(Arg.Any(), Arg.Any()); } // ── MaxMessagesPerPoll ────────────────────────────────────────── [Fact] public async Task Consumer_MaxMessagesPerPoll_Limits() { InsertOutboxRow("msg-1"); InsertOutboxRow("msg-2"); InsertOutboxRow("msg-3"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["maxMessagesPerPoll"] = "2" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 2); await Task.Delay(200); await consumer.Stop(); // Should process at most 2 per poll cycle processed.Should().HaveCountLessThanOrEqualTo(2); } // ── RepeatCount ───────────────────────────────────────────────── [Fact] public async Task Consumer_RepeatCount_LimitsCycles() { // With empty table and repeatCount=2, consumer should stop after 2 polls var endpoint = CreateEndpoint(new() { ["delay"] = "50", ["repeatCount"] = "2" }); var processor = Substitute.For(); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await Task.Delay(500); // Enough time for 2 cycles await consumer.Stop(); // Consumer should have stopped by itself } // ── OnSuccess ─────────────────────────────────────────────────── [Fact] public async Task Consumer_OnSuccess_ExecutedAfterProcessing() { InsertOutboxRow("msg-1"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); // Verify OnSuccess SQL was executed var rows = _db.Query("SELECT processed FROM outbox WHERE id = 1"); rows.Should().HaveCount(1); rows[0]["processed"].Should().Be(1L); } [Fact] public async Task Consumer_OnSuccess_ValuesNormalisedLikeTheProducer() { InsertOutboxRow("msg-1"); InsertOutboxRow("msg-2"); _db.Execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, note TEXT)"); var endpoint = CreateEndpoint(new() { ["repeatCount"] = "1", ["onSuccess"] = "INSERT INTO notes(id, note) VALUES(:#id, :#note)" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var exchange = ci.Arg(); exchange.In.Headers["note"] = Convert.ToInt64(exchange.In.Headers["id"]) == 1 ? "" : JsonDocument.Parse("\"from json\"").RootElement; return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var notes = _db.Query("SELECT id, note FROM notes ORDER BY id"); notes.Should().HaveCount(2, "lifecycle SQL binds under the producer's rule; a value it cannot bind is not a silent failure"); (notes[0]["note"] is null or DBNull).Should().BeTrue("an empty string binds NULL, as in the producer"); notes[1]["note"].Should().Be("from json", "a JSON value binds as its scalar, as in the producer"); } // ── OnFailure ─────────────────────────────────────────────────── [Fact] public async Task Consumer_OnFailure_ExecutedOnError() { InsertOutboxRow("msg-1"); _db.Execute(""" CREATE TABLE error_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT, err TEXT ) """); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["onFailure"] = "INSERT INTO error_log(msg, err) VALUES(:#message, :#redbError)" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => throw new InvalidOperationException("Processing failed!")); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var errors = _db.Query("SELECT msg, err FROM error_log"); errors.Should().HaveCount(1); errors[0]["msg"].Should().Be("msg-1"); errors[0]["err"]!.ToString().Should().Contain("Processing failed!"); } private SqlConsumer TransactedOutbox(bool afterRollback, Func fails, string? outputType = null) { var parameters = new Dictionary { ["repeatCount"] = "1", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id", ["onFailure"] = "UPDATE outbox SET processed = 2 WHERE id = :#id", }; if (afterRollback) parameters["onFailureAfterRollback"] = "true"; if (outputType is not null) parameters["outputType"] = outputType; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => fails(ci.Arg()) ? Task.FromException(new InvalidOperationException("bad row")) : Task.CompletedTask); return (SqlConsumer)CreateEndpoint(parameters).CreateConsumer(processor); } private List ProcessedStates() => _db.Query("SELECT processed FROM outbox ORDER BY id").Select(r => Convert.ToInt64(r["processed"])).ToList(); [Fact] public async Task Transacted_OnFailureAfterRollback_MarksTheFailedRow_AndGoesOnWithTheOthers() { InsertOutboxRow("ok-1"); InsertOutboxRow("bad"); InsertOutboxRow("ok-2"); var consumer = TransactedOutbox(afterRollback: true, e => (string?)e.In.Headers["message"] == "bad"); await consumer.Poll(CancellationToken.None); ProcessedStates().Should().Equal([1L, 2L, 1L], "the failed row is rolled back to its savepoint and marked; the rows around it commit in the same poll"); } [Fact] public async Task Transacted_ByDefault_RollsTheWholePollBack_AndTheRowIsReadAgain() { InsertOutboxRow("ok-1"); InsertOutboxRow("bad"); InsertOutboxRow("ok-2"); var consumer = TransactedOutbox(afterRollback: false, e => (string?)e.In.Headers["message"] == "bad"); await consumer.Poll(CancellationToken.None); ProcessedStates().Should().Equal([0L, 0L, 0L], "as in Apache Camel: the cycle is one transaction and rolls back whole"); } [Fact] public async Task Transacted_OnFailureAfterRollback_SelectOne_KeepsTheMarkInATransactionOfItsOwn() { InsertOutboxRow("bad"); var consumer = TransactedOutbox(afterRollback: true, _ => true, outputType: "SelectOne"); await consumer.Poll(CancellationToken.None); ProcessedStates().Should().Equal([2L]); } [Theory] [InlineData("transacted=false", "needs transacted=true")] [InlineData("outputType=StreamList", "StreamList")] public void OnFailureAfterRollback_IsRefused_WhereItCannotHold(string other, string message) { var parameters = new Dictionary { ["onFailureAfterRollback"] = "true", ["transacted"] = "true" }; var (key, value) = (other.Split('=')[0], other.Split('=')[1]); parameters[key] = value; var act = () => CreateEndpoint(parameters); act.Should().Throw().WithMessage($"*{message}*"); } /// The ways a route returns without throwing: a failure left unhandled, a handled one, a rollback-only exchange. public static TheoryData RouteOutcomes => new() { { "unhandled", true }, // onException handled="false": the failure stays on the exchange { "handled", false }, // onException handled="true": the row is done { "rollbackOnly", true }, }; [Theory] [MemberData(nameof(RouteOutcomes))] public async Task Consumer_FailureLeftOnTheExchange_RunsOnFailure_NotOnSuccess(string outcome, bool fails) { InsertOutboxRow("msg-1"); _db.Execute("CREATE TABLE marks (id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT, err TEXT)"); var endpoint = CreateEndpoint(new() { ["repeatCount"] = "1", ["onSuccess"] = "INSERT INTO marks(kind) VALUES('success')", ["onFailure"] = "INSERT INTO marks(kind, err) VALUES('failure', :#redbError)" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var exchange = ci.Arg(); switch (outcome) { case "unhandled": exchange.Exception = new InvalidOperationException("left on the exchange"); break; case "handled": exchange.Exception = new InvalidOperationException("handled by onException"); exchange.ExceptionHandled = true; break; default: exchange.MarkRollbackOnly(); break; } return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var marks = _db.Query("SELECT kind, err FROM marks"); marks.Should().ContainSingle().Which["kind"].Should().Be(fails ? "failure" : "success"); if (outcome == "unhandled") marks[0]["err"]!.ToString().Should().Contain("left on the exchange"); } [Fact] public async Task Consumer_OnSuccess_MissingParameter_IsAnError() { InsertOutboxRow("msg-1"); _db.Execute("CREATE TABLE lifecycle_error_log (msg TEXT, err TEXT)"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id AND message = :#nosuch", ["onFailure"] = "INSERT INTO lifecycle_error_log(msg, err) VALUES(:#message, :#redbError)" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); // As in Apache Camel: a placeholder with no value is an error; onFailure records it instead of a silent NULL. var errors = _db.Query("SELECT msg, err FROM lifecycle_error_log"); errors.Should().ContainSingle(); errors[0]["err"]!.ToString().Should().Contain(":#nosuch"); _db.Query("SELECT processed FROM outbox WHERE id = 1")[0]["processed"].Should().Be(0L); } [Fact] public async Task Consumer_OnSuccess_RedbErrorWithoutException_BindsNull() { InsertOutboxRow("msg-1"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id AND :#redbError IS NULL" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); _db.Query("SELECT processed FROM outbox WHERE id = 1")[0]["processed"].Should().Be(1L, ":#redbError always has a value: the error message, or NULL when nothing failed"); } // ── OnBatchComplete ───────────────────────────────────────────── [Fact] public async Task Consumer_OnBatchComplete_ExecutedAfterBatch() { InsertOutboxRow("msg-1"); _db.Execute("CREATE TABLE batch_log (ts TEXT)"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["onBatchComplete"] = "INSERT INTO batch_log(ts) VALUES(datetime('now'))" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var logs = _db.Query("SELECT * FROM batch_log"); logs.Should().HaveCountGreaterThanOrEqualTo(1); } // ── Transacted ────────────────────────────────────────────────── [Fact] public async Task Consumer_Transacted_CommitsOnSuccess() { InsertOutboxRow("msg-1"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var rows = _db.Query("SELECT processed FROM outbox WHERE id = 1"); rows[0]["processed"].Should().Be(1L); } // ── RouteEmptyResultSet ───────────────────────────────────────── [Fact] public async Task Consumer_RouteEmptyResultSet_CreatesExchange() { // Empty table var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["routeEmptyResultSet"] = "true" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 1); await consumer.Stop(); processed.Should().HaveCountGreaterThanOrEqualTo(1); processed[0].In.Headers[SqlHeaders.RowCount].Should().Be(0); } // ── SendEmptyMessageWhenIdle ──────────────────────────────────── [Fact] public async Task Consumer_SendEmptyMessageWhenIdle_SendsIdleMessage() { var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["sendEmptyMessageWhenIdle"] = "true" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 1); await consumer.Stop(); processed.Should().HaveCountGreaterThanOrEqualTo(1); processed[0].In.Headers[SqlHeaders.RowCount].Should().Be(0); } // ── Row data in headers ───────────────────────────────────────── [Fact] public async Task Consumer_CopiesRowFieldsToHeaders() { InsertOutboxRow("test-msg"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => processed.Count >= 1); await consumer.Stop(); var headers = processed[0].In.Headers; headers.Should().ContainKey("id"); headers.Should().ContainKey("message"); headers["message"].Should().Be("test-msg"); } // ── InitialDelay ──────────────────────────────────────────────── [Fact] public async Task Consumer_InitialDelay_DelaysFirstPoll() { InsertOutboxRow("msg-1"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["initialDelay"] = "300", ["repeatCount"] = "1" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); // After 100ms should not have polled yet await Task.Delay(100); processed.Should().BeEmpty(); // After 400ms should have polled await WaitForCondition(() => processed.Count >= 1, 2000); await consumer.Stop(); processed.Should().HaveCountGreaterThanOrEqualTo(1); } // ── Graceful shutdown ─────────────────────────────────────────── [Fact] public async Task Consumer_Stop_StopsGracefully() { var endpoint = CreateEndpoint(new() { ["delay"] = "50" }); var processor = Substitute.For(); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await consumer.Stop(); // Should not throw or hang } // ── Poll method directly ──────────────────────────────────────── [Fact] public async Task Poll_DirectCall_ProcessesRows() { InsertOutboxRow("direct-poll"); var endpoint = CreateEndpoint(new() { ["delay"] = "100" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); processed.Should().HaveCount(1); (processed[0].In.Body as Dictionary)!["message"].Should().Be("direct-poll"); } // ── Transacted Rollback on processing error ───────────────────── [Fact] public async Task Consumer_Transacted_RollsBackOnProcessingError() { // Insert 2 rows — row 1 will succeed, row 2 will fail. // Because of transacted mode, row 1's OnSuccess should be rolled back. InsertOutboxRow("msg-1"); InsertOutboxRow("msg-2"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var callCount = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { if (Interlocked.Increment(ref callCount) == 2) throw new InvalidOperationException("Boom on second row!"); return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); // Transaction was rolled back — OnSuccess SQL for row 1 should also be rolled back. // Both rows should still be unprocessed. var rows = _db.Query("SELECT id, processed FROM outbox ORDER BY id"); rows.Should().HaveCount(2); rows[0]["processed"].Should().Be(0L, "row 1's OnSuccess should be rolled back"); rows[1]["processed"].Should().Be(0L, "row 2 should remain unprocessed"); } // ── Fixed-rate polling ────────────────────────────────────────── [Fact] public async Task Consumer_FixedRate_PollsAtFixedInterval() { // With fixedRate: delay measured from START of poll, not end. // So if poll takes 0ms and delay is 200ms, next poll starts ~200ms after start. // Without fixedRate: next poll starts ~200ms after END of poll. var endpoint = CreateEndpoint(new() { ["delay"] = "200", ["fixedRate"] = "true", ["repeatCount"] = "3", ["initialDelay"] = "0" }); var pollTimes = new List(); var sw = System.Diagnostics.Stopwatch.StartNew(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); // We need the poll to trigger even with empty table — use sendEmptyMessageWhenIdle var endpoint2 = CreateEndpoint(new() { ["delay"] = "200", ["fixedRate"] = "true", ["repeatCount"] = "3", ["initialDelay"] = "0", ["sendEmptyMessageWhenIdle"] = "true" }); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => pollTimes.Add(sw.ElapsedMilliseconds)); var consumer = (SqlConsumer)endpoint2.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => pollTimes.Count >= 3, 3000); await consumer.Stop(); pollTimes.Should().HaveCountGreaterThanOrEqualTo(3); // Intervals should be roughly 200ms (fixedRate) // Tolerance: between 100ms and 400ms for (var i = 1; i < pollTimes.Count; i++) { var interval = pollTimes[i] - pollTimes[i - 1]; interval.Should().BeGreaterThan(100, "fixed-rate interval should be ~200ms"); interval.Should().BeLessThan(400, "fixed-rate interval should not exceed ~400ms"); } } // ── Non-fixedRate polling ─────────────────────────────────────── [Fact] public async Task Consumer_NonFixedRate_PollsWithDelayAfterEnd() { var endpoint = CreateEndpoint(new() { ["delay"] = "200", ["fixedRate"] = "false", ["repeatCount"] = "3", ["initialDelay"] = "0", ["sendEmptyMessageWhenIdle"] = "true" }); var pollTimes = new List(); var sw = System.Diagnostics.Stopwatch.StartNew(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => pollTimes.Add(sw.ElapsedMilliseconds)); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Start(); await WaitForCondition(() => pollTimes.Count >= 3, 3000); await consumer.Stop(); pollTimes.Should().HaveCountGreaterThanOrEqualTo(3); // Intervals should also be roughly 200ms (same, but delay-after-end) for (var i = 1; i < pollTimes.Count; i++) { var interval = pollTimes[i] - pollTimes[i - 1]; interval.Should().BeGreaterThan(100); } } // ── StreamList ────────────────────────────────────────────────── [Fact] public async Task StreamList_ProcessesRowsWithoutBuffering() { InsertOutboxRow("s1"); InsertOutboxRow("s2"); InsertOutboxRow("s3"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); processed.Should().HaveCount(3); var messages = processed .Select(e => ((Dictionary)e.In.Body!)["message"]!.ToString()) .ToList(); messages.Should().BeEquivalentTo(["s1", "s2", "s3"]); } [Fact] public async Task StreamList_RowCount_IsMinusOne() { InsertOutboxRow("rc1"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); processed.Should().HaveCount(1); processed[0].In.Headers[SqlHeaders.RowCount].Should().Be(-1); } [Fact] public async Task StreamList_OnSuccess_ExecutedPerRow() { InsertOutboxRow("os1"); InsertOutboxRow("os2"); // As in Apache Camel, onSuccess of a streaming poll runs on the reader's connection only inside a transaction; outside // one it takes a connection of its own, which SQLite blocks from writing the table the open reader holds. var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var rows = _db.Query("SELECT id, processed FROM outbox ORDER BY id"); rows.Should().HaveCount(2); rows[0]["processed"].Should().Be(1L); rows[1]["processed"].Should().Be(1L); } [Fact] public async Task StreamList_OnFailure_ExecutedOnError() { InsertOutboxRow("fail-stream"); _db.Execute(""" CREATE TABLE stream_error_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, msg TEXT, err TEXT ) """); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["onFailure"] = "INSERT INTO stream_error_log(msg, err) VALUES(:#message, :#redbError)" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(_ => throw new InvalidOperationException("Stream row failed!")); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var errors = _db.Query("SELECT msg, err FROM stream_error_log"); errors.Should().HaveCount(1); errors[0]["msg"].Should().Be("fail-stream"); errors[0]["err"]!.ToString().Should().Contain("Stream row failed!"); } [Fact] public async Task StreamList_MaxMessagesPerPoll_Limits() { InsertOutboxRow("lim1"); InsertOutboxRow("lim2"); InsertOutboxRow("lim3"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["maxMessagesPerPoll"] = "2" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); processed.Should().HaveCount(2); } [Fact] public async Task StreamList_EmptyTable_HandlesCorrectly() { var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["routeEmptyResultSet"] = "true" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); processed.Should().HaveCount(1); processed[0].In.Headers[SqlHeaders.RowCount].Should().Be(0); } [Fact] public async Task StreamList_OnBatchComplete_Executed() { InsertOutboxRow("batch1"); _db.Execute("CREATE TABLE stream_batch_log (ts TEXT)"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["onBatchComplete"] = "INSERT INTO stream_batch_log(ts) VALUES(datetime('now'))" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var logs = _db.Query("SELECT * FROM stream_batch_log"); logs.Should().HaveCount(1); } [Fact] public async Task StreamList_Transacted_RollsBackOnError() { InsertOutboxRow("tx1"); InsertOutboxRow("tx2"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var callCount = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { if (Interlocked.Increment(ref callCount) == 2) throw new InvalidOperationException("Boom on second row!"); return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); // Transaction rolled back — row 1's OnSuccess should also be rolled back var rows = _db.Query("SELECT id, processed FROM outbox ORDER BY id"); rows.Should().HaveCount(2); rows[0]["processed"].Should().Be(0L, "row 1's OnSuccess should be rolled back"); rows[1]["processed"].Should().Be(0L, "row 2 should remain unprocessed"); } [Fact] public async Task StreamList_CopiesRowFieldsToHeaders() { InsertOutboxRow("header-test"); var endpoint = CreateEndpoint(new() { ["delay"] = "100", ["repeatCount"] = "1", ["outputType"] = "StreamList" }); var processed = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(x => processed.Add(x.Arg())); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); var headers = processed[0].In.Headers; headers.Should().ContainKey("id"); headers.Should().ContainKey("message"); headers["message"].Should().Be("header-test"); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlEndpointOptionsTests.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/SqlEndpointOptionsTests.cs ---- using System.Data; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; public class SqlEndpointOptionsTests { // ── Defaults ──────────────────────────────────────────────────── [Fact] public void Defaults_AreCorrect() { var o = new SqlEndpointOptions(); o.Mode.Should().Be(SqlMode.Execute); o.DataSource.Should().BeNull(); o.ConnectionString.Should().BeNull(); o.Provider.Should().BeNull(); o.CommandTimeout.Should().Be(30); o.Transacted.Should().BeFalse(); o.IsolationLevel.Should().BeNull(); o.ReadOnly.Should().BeFalse("the primary database unless the endpoint declares readOnly=true"); o.PlaceholderStyle.Should().Be(SqlPlaceholderStyle.At, ":#name is sent as @name unless the provider needs another style"); o.BackslashEscapes.Should().BeFalse("standard SQL literals unless the endpoint declares backslashEscapes=true"); o.Query.Should().BeNull(); o.OutputType.Should().Be(SqlOutputType.Auto); o.OutputClass.Should().BeNull(); o.OutputHeader.Should().BeNull(); o.Noop.Should().BeFalse(); o.Delay.Should().Be(500); o.InitialDelay.Should().Be(1000); o.FixedRate.Should().BeFalse(); o.RepeatCount.Should().Be(0); o.MaxMessagesPerPoll.Should().Be(-1); o.RouteEmptyResultSet.Should().BeFalse(); o.SendEmptyMessageWhenIdle.Should().BeFalse(); o.OnSuccess.Should().BeNull(); o.OnFailure.Should().BeNull(); o.OnBatchComplete.Should().BeNull(); o.PollDelivery.Should().Be(SqlPollDelivery.PerRow, "an exchange per row unless a list is asked for, as Camel's useIterator=true"); o.BatchSize.Should().Be(0); o.BreakBatchOnError.Should().BeTrue("a failing batch item rolls the whole batch back unless told otherwise, as in Camel"); o.ProcedureName.Should().BeNull(); o.AsFunction.Should().BeFalse(); o.ProcedureParams.Should().BeNull(); } // ── Validate ──────────────────────────────────────────────────── [Fact] public void Validate_NoDataSourceOrConnectionString_Throws() { var o = new SqlEndpointOptions(); var act = () => o.Validate(); act.Should().Throw().WithMessage("*DataSource*ConnectionString*"); } [Fact] public void Validate_WithDataSource_Valid() { var o = new SqlEndpointOptions { DataSource = "main" }; o.Validate(); // no throw } [Fact] public void Validate_WithConnectionString_Valid() { var o = new SqlEndpointOptions { ConnectionString = "Server=localhost" }; o.Validate(); // no throw } [Fact] public void Validate_PollWithoutQuery_Valid() { // Query is optional in options — it can come from URI path var o = new SqlEndpointOptions { Mode = SqlMode.Poll, DataSource = "main" }; o.Validate(); // no throw } [Fact] public void Validate_PollWithQuery_Valid() { var o = new SqlEndpointOptions { Mode = SqlMode.Poll, DataSource = "main", Query = DynamicValue.FromStatic("SELECT 1") }; o.Validate(); // no throw } [Fact] public void Validate_ProcedureWithoutName_Throws() { var o = new SqlEndpointOptions { Mode = SqlMode.Procedure, DataSource = "main" }; var act = () => o.Validate(); act.Should().Throw().WithMessage("*ProcedureName*Procedure*"); } [Fact] public void Validate_ProcedureWithName_Valid() { var o = new SqlEndpointOptions { Mode = SqlMode.Procedure, DataSource = "main", ProcedureName = "sp_Calculate" }; o.Validate(); // no throw } [Fact] public void Validate_NegativeCommandTimeout_Throws() { var o = new SqlEndpointOptions { DataSource = "main", CommandTimeout = -1 }; var act = () => o.Validate(); act.Should().Throw().WithMessage("*CommandTimeout*"); } [Fact] public void Validate_NegativeDelay_Throws() { var o = new SqlEndpointOptions { DataSource = "main", Delay = -1 }; var act = () => o.Validate(); act.Should().Throw().WithMessage("*Delay*"); } [Fact] public void Validate_ReadOnlyWithBatchSize_Throws() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["dataSource"] = "main", ["readOnly"] = "true", ["batchSize"] = "10" }); var act = () => o.Validate(); act.Should().Throw("a batch writes, and readOnly sends it to the replica").WithMessage("*readOnly*batchSize*"); } [Theory] [InlineData("onSuccess", "UPDATE t SET done = 1")] [InlineData("onFailure", "UPDATE t SET failed = 1")] [InlineData("onBatchComplete", "DELETE FROM t WHERE done = 1")] [InlineData("transacted", "true")] public void Validate_ReadOnlyPollThatMarksRows_Throws(string option, string value) { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main", ["readOnly"] = "true", [option] = value, }); var act = () => o.Validate(); act.Should().Throw("rows read on a lagging replica and marked on the primary come back") .WithMessage("*readOnly*"); } [Fact] public void Validate_FunctionWithOutParameters_Throws() { var o = new SqlEndpointOptions { DataSource = "main", Mode = SqlMode.Procedure, ProcedureName = "fn", AsFunction = true, ProcedureParams = "IN:x:Int32,OUT:r:Int32", }; var act = () => o.Validate(); act.Should().Throw("SELECT fn(...) returns its result as the scalar; an OUT parameter has no place in " + "the text and shifts the positions of the others under a positional placeholder style") .WithMessage("*OUT*"); } [Theory] [InlineData(SqlOutputType.Scalar)] [InlineData(SqlOutputType.SelectOne)] public void Validate_ListDeliveryWithSingleValueOutput_Throws(SqlOutputType outputType) { var o = new SqlEndpointOptions { DataSource = "main", Mode = SqlMode.Poll, PollDelivery = SqlPollDelivery.List, OutputType = outputType, }; var act = () => o.Validate(); act.Should().Throw("a single value is not a list; the option would be ignored silently") .WithMessage("*pollDelivery*"); } [Fact] public void Validate_ReadOnlyPollWithoutLifecycleSql_Valid() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main", ["readOnly"] = "true" }); o.Validate(); // no throw } // ── BindFromUri ───────────────────────────────────────────────── [Fact] public void BindFromUri_Mode_ParsesCorrectly() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main" }); o.Mode.Should().Be(SqlMode.Poll); } [Fact] public void BindFromUri_OutputType_ParsesCorrectly() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["outputType"] = "Scalar", ["dataSource"] = "main" }); o.OutputType.Should().Be(SqlOutputType.Scalar); } [Fact] public void BindFromUri_IntProperties() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["delay"] = "2000", ["initialDelay"] = "500", ["commandTimeout"] = "60", ["maxMessagesPerPoll"] = "10", ["batchSize"] = "50", ["dataSource"] = "main" }); o.Delay.Should().Be(2000); o.InitialDelay.Should().Be(500); o.CommandTimeout.Should().Be(60); o.MaxMessagesPerPoll.Should().Be(10); o.BatchSize.Should().Be(50); } [Fact] public void BindFromUri_BoolProperties() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["transacted"] = "true", ["fixedRate"] = "true", ["noop"] = "true", ["routeEmptyResultSet"] = "true", ["sendEmptyMessageWhenIdle"] = "true", ["breakBatchOnError"] = "true", ["asFunction"] = "true", ["dataSource"] = "main" }); o.Transacted.Should().BeTrue(); o.FixedRate.Should().BeTrue(); o.Noop.Should().BeTrue(); o.RouteEmptyResultSet.Should().BeTrue(); o.SendEmptyMessageWhenIdle.Should().BeTrue(); o.BreakBatchOnError.Should().BeTrue(); o.AsFunction.Should().BeTrue(); } [Fact] public void BindFromUri_StringProperties() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["dataSource"] = "main", ["connectionString"] = "Server=localhost", ["provider"] = "Microsoft.Data.SqlClient", ["outputClass"] = "MyPoco", ["outputHeader"] = "resultHeader", ["onSuccess"] = "UPDATE t SET done=1 WHERE id=:#id", ["onFailure"] = "INSERT INTO errors(msg) VALUES(:#redbError)", ["onBatchComplete"] = "EXEC sp_Notify", ["procedureName"] = "sp_Process", ["procedureParams"] = "IN:id:Int32,OUT:result:String" }); o.DataSource.Should().Be("main"); o.ConnectionString.Should().Be("Server=localhost"); o.Provider.Should().Be("Microsoft.Data.SqlClient"); o.OutputClass.Should().Be("MyPoco"); o.OutputHeader.Should().Be("resultHeader"); o.OnSuccess.Should().Be("UPDATE t SET done=1 WHERE id=:#id"); o.OnFailure.Should().Be("INSERT INTO errors(msg) VALUES(:#redbError)"); o.OnBatchComplete.Should().Be("EXEC sp_Notify"); o.ProcedureName.Should().Be("sp_Process"); o.ProcedureParams.Should().Be("IN:id:Int32,OUT:result:String"); } [Fact] public void BindFromUri_RepeatCount_Long() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["repeatCount"] = "1000000", ["dataSource"] = "main" }); o.RepeatCount.Should().Be(1_000_000); } [Fact] public void BindFromUri_IsolationLevel_Enum() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["isolationLevel"] = "ReadCommitted", ["dataSource"] = "main" }); o.IsolationLevel.Should().Be(IsolationLevel.ReadCommitted); } [Fact] public void BindFromUri_CaseInsensitive() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["MODE"] = "Procedure", ["DATASOURCE"] = "main", ["PROCEDURENAME"] = "sp_Test" }); o.Mode.Should().Be(SqlMode.Procedure); o.DataSource.Should().Be("main"); o.ProcedureName.Should().Be("sp_Test"); } // ── Explicit Parameters ───────────────────────────────────────── [Fact] public void ExplicitParameters_ExtractsFromUnmapped() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main", ["param.id"] = "42", ["param.name"] = "Alice" }); o.ExplicitParameters.Should().HaveCount(2); o.ExplicitParameters["id"].Should().Be("42"); o.ExplicitParameters["name"].Should().Be("Alice"); } [Fact] public void ExplicitParameters_CaseInsensitiveLookup() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["dataSource"] = "main", ["param.MyParam"] = "val" }); o.ExplicitParameters.TryGetValue("myparam", out var v).Should().BeTrue(); v.Should().Be("val"); } [Fact] public void ExplicitParameters_EmptyWhenNoParams() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["dataSource"] = "main" }); o.ExplicitParameters.Should().BeEmpty(); } [Fact] public void ExplicitParameters_ExpressionValuePreserved() { var o = new SqlEndpointOptions(); o.BindFromUri(new Dictionary { ["dataSource"] = "main", ["param.userId"] = "${header.currentUser}" }); o.ExplicitParameters["userId"].Should().Be("${header.currentUser}"); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlEnumsTests.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/SqlEnumsTests.cs ---- using redb.Route.Sql; namespace redb.Route.Tests.Sql; public class SqlEnumsTests { // ── SqlMode ───────────────────────────────────────────────────── [Fact] public void SqlMode_HasThreeValues() { Enum.GetValues().Should().HaveCount(3); } [Theory] [InlineData(SqlMode.Poll, 0)] [InlineData(SqlMode.Execute, 1)] [InlineData(SqlMode.Procedure, 2)] public void SqlMode_Values_AreCorrect(SqlMode mode, int expected) { ((int)mode).Should().Be(expected); } [Theory] [InlineData("Poll", SqlMode.Poll)] [InlineData("Execute", SqlMode.Execute)] [InlineData("Procedure", SqlMode.Procedure)] [InlineData("poll", SqlMode.Poll)] [InlineData("execute", SqlMode.Execute)] [InlineData("procedure", SqlMode.Procedure)] public void SqlMode_Parse_CaseInsensitive(string text, SqlMode expected) { Enum.Parse(text, ignoreCase: true).Should().Be(expected); } // ── SqlOutputType ─────────────────────────────────────────────── [Fact] public void SqlOutputType_HasSixValues() { Enum.GetValues().Should().HaveCount(6); } [Theory] [InlineData(SqlOutputType.Auto, 0)] [InlineData(SqlOutputType.SelectList, 1)] [InlineData(SqlOutputType.SelectOne, 2)] [InlineData(SqlOutputType.StreamList, 3)] [InlineData(SqlOutputType.Scalar, 4)] [InlineData(SqlOutputType.None, 5)] public void SqlOutputType_Values_AreCorrect(SqlOutputType type, int expected) { ((int)type).Should().Be(expected); } [Theory] [InlineData("SelectList", SqlOutputType.SelectList)] [InlineData("selectone", SqlOutputType.SelectOne)] [InlineData("StreamList", SqlOutputType.StreamList)] [InlineData("Scalar", SqlOutputType.Scalar)] [InlineData("NONE", SqlOutputType.None)] public void SqlOutputType_Parse_CaseInsensitive(string text, SqlOutputType expected) { Enum.Parse(text, ignoreCase: true).Should().Be(expected); } // ── SqlParamDirection ─────────────────────────────────────────── [Fact] public void SqlParamDirection_HasThreeValues() { Enum.GetValues().Should().HaveCount(3); } [Theory] [InlineData(SqlParamDirection.In, 0)] [InlineData(SqlParamDirection.Out, 1)] [InlineData(SqlParamDirection.InOut, 2)] public void SqlParamDirection_Values_AreCorrect(SqlParamDirection dir, int expected) { ((int)dir).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlExecutionTimeTests.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/SqlExecutionTimeTests.cs ---- using System.Data.Common; using Microsoft.Data.Sqlite; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// redbSql.executionTime measures the statement itself: a statement that takes a known time to run reports at least /// that time, in the producer and in the poll consumer. The delay comes from a SQLite function that sleeps while the /// statement executes. /// public sealed class SqlExecutionTimeTests : IDisposable { private const int SleepMs = 100; private const int AtLeastMs = 90; private readonly SqliteTestHelper _db = new(); public void Dispose() => _db.Dispose(); [Fact] public async Task Execute_ExecutionTime_IncludesCommandExecution() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, new SleepFunctionFactory(_db.ConnectionString), $"SELECT redb_sleep({SleepMs}) AS v", new() { ["outputType"] = "Scalar" }); var exchange = new Exchange(new Message()); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); Convert.ToInt64(exchange.In.Headers[SqlHeaders.ExecutionTime]).Should().BeGreaterThanOrEqualTo(AtLeastMs, "the statement sleeps for {0} ms while it executes", SleepMs); } [Fact] public async Task Poll_ExecutionTime_IncludesQueryExecution() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, new SleepFunctionFactory(_db.ConnectionString), $"SELECT redb_sleep({SleepMs}) AS v", new() { ["mode"] = "Poll", ["repeatCount"] = "1" }); var reported = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { reported.Add(Convert.ToInt64(ci.Arg().In.Headers[SqlHeaders.ExecutionTime])); return Task.CompletedTask; }); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(CancellationToken.None); reported.Should().ContainSingle().Which.Should().BeGreaterThanOrEqualTo(AtLeastMs, "the poll query sleeps for {0} ms while it executes", SleepMs); } /// Opens connections to the test database with redb_sleep(ms) registered. private sealed class SleepFunctionFactory(string connectionString) : ISqlConnectionFactory { public async Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) { var connection = new SqliteConnection(connectionString); await connection.OpenAsync(ct); connection.CreateFunction("redb_sleep", (long ms) => { Thread.Sleep((int)ms); return ms; }); return connection; } } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlHeadersTests.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/SqlHeadersTests.cs ---- using redb.Route.Sql; namespace redb.Route.Tests.Sql; public class SqlHeadersTests { [Fact] public void Prefix_IsRedbSql() { SqlHeaders.Prefix.Should().Be("redbSql."); } [Theory] [InlineData(nameof(SqlHeaders.Query), "redbSql.query")] [InlineData(nameof(SqlHeaders.UpdateCount), "redbSql.updateCount")] [InlineData(nameof(SqlHeaders.RowCount), "redbSql.rowCount")] [InlineData(nameof(SqlHeaders.DataSource), "redbSql.dataSource")] [InlineData(nameof(SqlHeaders.OutputType), "redbSql.outputType")] [InlineData(nameof(SqlHeaders.GeneratedKeys), "redbSql.generatedKeys")] [InlineData(nameof(SqlHeaders.Error), "redbSql.error")] [InlineData(nameof(SqlHeaders.TransactionId), "redbSql.transactionId")] [InlineData(nameof(SqlHeaders.StoredProcedure), "redbSql.storedProcedure")] [InlineData(nameof(SqlHeaders.ExecutionTime), "redbSql.executionTime")] [InlineData("BatchStrategy", "redbSql.batchStrategy")] [InlineData("BatchItemCount", "redbSql.batchItemCount")] [InlineData("BatchFailedIndex", "redbSql.batchFailedIndex")] [InlineData("BatchErrors", "redbSql.batchErrors")] [InlineData("BatchChunkCount", "redbSql.batchChunkCount")] public void Header_HasCorrectValue(string fieldName, string expectedValue) { var field = typeof(SqlHeaders).GetField(fieldName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); field.Should().NotBeNull(); field!.GetValue(null).Should().Be(expectedValue); } [Fact] public void AllHeaders_StartWithPrefix() { var fields = typeof(SqlHeaders) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Where(f => f.Name != nameof(SqlHeaders.Prefix)) .Select(f => (string)f.GetValue(null)!) .ToList(); fields.Should().NotBeEmpty(); fields.Should().AllSatisfy(h => h.Should().StartWith(SqlHeaders.Prefix)); } [Fact] public void AllHeaders_AreUnique() { var fields = typeof(SqlHeaders) .GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) .Select(f => (string)f.GetValue(null)!) .ToList(); fields.Should().OnlyHaveUniqueItems(); } [Fact] public void Prefix_FollowsNamingConvention() { SqlHeaders.Prefix.Should().EndWith("."); SqlHeaders.Prefix.Should().NotContain(" "); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlIdempotentRepositoryTests.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/SqlIdempotentRepositoryTests.cs ---- using redb.Route.Sql.Connection; using redb.Route.Sql.Repositories; namespace redb.Route.Tests.Sql; public class SqlIdempotentRepositoryTests : IDisposable { private readonly SqliteTestHelper _db = new(); private SqlIdempotentRepository CreateRepo(string processorName = "test-route", bool createTable = true, TimeSpan? ttl = null) { var options = new SqlIdempotentOptions { ProcessorName = processorName, TableName = "redb_idempotent", CreateTable = createTable, Ttl = ttl }; return new SqlIdempotentRepository(_db.CreateFactory(), options); } // ── Options defaults ──────────────────────────────────────────── [Fact] public void SqlIdempotentOptions_Defaults() { var opts = new SqlIdempotentOptions(); opts.DataSource.Should().BeEmpty(); opts.TableName.Should().Be("redb_idempotent"); opts.ProcessorName.Should().BeEmpty(); opts.Ttl.Should().BeNull(); opts.CreateTable.Should().BeTrue(); } [Theory] [InlineData("x; DROP TABLE y")] [InlineData("keys'")] [InlineData("")] public void SqlIdempotentOptions_TableName_IsValidated(string tableName) { var act = () => new SqlIdempotentOptions { TableName = tableName }; act.Should().Throw("the name goes into DDL and, on SQL Server, into a string literal"); } // ── Add ───────────────────────────────────────────────────────── [Fact] public async Task Add_NewKey_ReturnsTrue() { var repo = CreateRepo(); var result = await repo.Add("msg-1"); result.Should().BeTrue(); } [Fact] public async Task Add_DuplicateKey_ReturnsFalse() { var repo = CreateRepo(); await repo.Add("msg-1"); var result = await repo.Add("msg-1"); result.Should().BeFalse(); } [Fact] public async Task Add_DifferentKeys_AllReturnTrue() { var repo = CreateRepo(); (await repo.Add("msg-1")).Should().BeTrue(); (await repo.Add("msg-2")).Should().BeTrue(); (await repo.Add("msg-3")).Should().BeTrue(); } [Fact] public async Task Add_DifferentProcessors_IndependentKeys() { var repo1 = CreateRepo("route-1"); var repo2 = CreateRepo("route-2"); (await repo1.Add("msg-1")).Should().BeTrue(); (await repo2.Add("msg-1")).Should().BeTrue(); // different processor → OK } // ── Contains ──────────────────────────────────────────────────── [Fact] public async Task Contains_AfterAdd_ReturnsTrue() { var repo = CreateRepo(); await repo.Add("msg-1"); var result = await repo.Contains("msg-1"); result.Should().BeTrue(); } [Fact] public async Task Contains_NonExistentKey_ReturnsFalse() { var repo = CreateRepo(); var result = await repo.Contains("nonexistent"); result.Should().BeFalse(); } // ── Confirm ───────────────────────────────────────────────────── [Fact] public async Task Confirm_AfterAdd_NoError() { var repo = CreateRepo(); await repo.Add("msg-1"); await repo.Confirm("msg-1"); // should not throw (await repo.Contains("msg-1")).Should().BeTrue(); } [Fact] public async Task Confirm_NonExistentKey_NoError() { var repo = CreateRepo(); // Confirm on nonexistent key is a no-op await repo.Confirm("nonexistent"); } // ── Remove ────────────────────────────────────────────────────── [Fact] public async Task Remove_AfterAdd_KeyGone() { var repo = CreateRepo(); await repo.Add("msg-1"); await repo.Remove("msg-1"); (await repo.Contains("msg-1")).Should().BeFalse(); } [Fact] public async Task Remove_NonExistentKey_NoError() { var repo = CreateRepo(); await repo.Remove("nonexistent"); // no throw } [Fact] public async Task Remove_AllowsReAdd() { var repo = CreateRepo(); await repo.Add("msg-1"); await repo.Remove("msg-1"); var result = await repo.Add("msg-1"); result.Should().BeTrue(); } // ── Clear ─────────────────────────────────────────────────────── [Fact] public async Task Clear_RemovesAllKeysForProcessor() { var repo = CreateRepo(); await repo.Add("msg-1"); await repo.Add("msg-2"); await repo.Add("msg-3"); await repo.Clear(); (await repo.Contains("msg-1")).Should().BeFalse(); (await repo.Contains("msg-2")).Should().BeFalse(); (await repo.Contains("msg-3")).Should().BeFalse(); } [Fact] public async Task Clear_DoesNotAffectOtherProcessors() { var repo1 = CreateRepo("route-1"); var repo2 = CreateRepo("route-2"); await repo1.Add("msg-1"); await repo2.Add("msg-1"); await repo1.Clear(); (await repo1.Contains("msg-1")).Should().BeFalse(); (await repo2.Contains("msg-1")).Should().BeTrue(); } // ── Auto-create table ─────────────────────────────────────────── [Fact] public async Task AutoCreateTable_CreatesOnFirstUse() { var repo = CreateRepo(createTable: true); // First call triggers table creation await repo.Add("msg-1"); var rows = _db.Query("SELECT * FROM redb_idempotent"); rows.Should().HaveCount(1); } // ── TTL cleanup ───────────────────────────────────────────────── [Fact] public async Task TtlCleanup_RemovesOldEntries() { // Create a repo with very short TTL var repo = CreateRepo(ttl: TimeSpan.FromMilliseconds(50)); await repo.Add("old-msg"); await Task.Delay(100); // Wait for TTL to expire // Next Add triggers cleanup await repo.Add("new-msg"); (await repo.Contains("old-msg")).Should().BeFalse(); (await repo.Contains("new-msg")).Should().BeTrue(); } [Fact] public async Task TtlCleanup_PreservesRecentEntries() { var repo = CreateRepo(ttl: TimeSpan.FromSeconds(30)); await repo.Add("recent-1"); await repo.Add("recent-2"); // Next Add triggers cleanup — nothing should be removed await repo.Add("recent-3"); (await repo.Contains("recent-1")).Should().BeTrue(); (await repo.Contains("recent-2")).Should().BeTrue(); (await repo.Contains("recent-3")).Should().BeTrue(); } [Fact] public async Task TtlCleanup_OnlyAffectsOwnProcessor() { var repoA = CreateRepo(processorName: "routeA", ttl: TimeSpan.FromMilliseconds(50)); var repoB = CreateRepo(processorName: "routeB", ttl: TimeSpan.FromMilliseconds(50)); await repoA.Add("shared-key"); await repoB.Add("shared-key"); await Task.Delay(100); // Both expire // repoA cleanup should not affect repoB await repoA.Add("trigger-cleanup-A"); (await repoA.Contains("shared-key")).Should().BeFalse("routeA cleanup removed its own expired entry"); (await repoB.Contains("shared-key")).Should().BeTrue("routeB's entry was not touched by routeA cleanup"); } [Fact] public async Task TtlCleanup_NoTtl_NeverCleans() { var repo = CreateRepo(ttl: null); // No TTL await repo.Add("msg-1"); await Task.Delay(50); await repo.Add("msg-2"); // Without TTL, nothing is ever cleaned up (await repo.Contains("msg-1")).Should().BeTrue(); (await repo.Contains("msg-2")).Should().BeTrue(); } // ── Full lifecycle ────────────────────────────────────────────── [Fact] public async Task FullLifecycle_AddConfirmContains() { var repo = CreateRepo(); // Step 1: Add (reserve) (await repo.Add("msg-1")).Should().BeTrue(); (await repo.Contains("msg-1")).Should().BeTrue(); // Step 2: Duplicate Add returns false (await repo.Add("msg-1")).Should().BeFalse(); // Step 3: Confirm await repo.Confirm("msg-1"); (await repo.Contains("msg-1")).Should().BeTrue(); // Step 4: Remove await repo.Remove("msg-1"); (await repo.Contains("msg-1")).Should().BeFalse(); // Step 5: Re-add after remove (await repo.Add("msg-1")).Should().BeTrue(); } // ── Constructor validation ────────────────────────────────────── [Fact] public void Constructor_NullFactory_Throws() { var act = () => new SqlIdempotentRepository(null!, new SqlIdempotentOptions()); act.Should().Throw(); } [Fact] public void Constructor_NullOptions_Throws() { var act = () => new SqlIdempotentRepository(_db.CreateFactory(), null!); act.Should().Throw(); } // ── Concurrent operations ─────────────────────────────────────── [Fact] public async Task ConcurrentAdd_SameKey_OnlyOneSucceeds() { var repo = CreateRepo(); var results = new System.Collections.Concurrent.ConcurrentBag(); var tasks = Enumerable.Range(0, 10).Select(_ => Task.Run(async () => { var result = await repo.Add("concurrent-key"); results.Add(result); })); await Task.WhenAll(tasks); results.Count(r => r).Should().Be(1); results.Count(r => !r).Should().Be(9); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlIntegrationTests.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/SqlIntegrationTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// /// End-to-end integration tests: SqlConsumer (Poll) → IProcessor → SqlProducer (Execute). /// Simulates a real route that reads rows from one table and writes results to another, /// all running against an in-memory SQLite database. /// public class SqlIntegrationTests : IAsyncLifetime, IDisposable { private readonly SqliteTestHelper _db = new(); private SqlConsumer? _consumer; // Captured exchanges private readonly List _capturedExchanges = []; public Task InitializeAsync() { // Create tables _db.Execute(""" CREATE TABLE outbox ( id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT NOT NULL, processed INTEGER NOT NULL DEFAULT 0 ) """); _db.Execute(""" CREATE TABLE audit ( id INTEGER PRIMARY KEY AUTOINCREMENT, source_id INTEGER NOT NULL, message TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'OK' ) """); return Task.CompletedTask; } public async Task DisposeAsync() { if (_consumer is not null) try { await _consumer.Stop(); } catch (ObjectDisposedException) { } } public void Dispose() { _db.Dispose(); } private SqlEndpoint CreateConsumerEndpoint(string sql, Dictionary? extra = null) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var parameters = new Dictionary { ["mode"] = "Poll", ["dataSource"] = "main", ["delay"] = "100" }; if (extra != null) foreach (var kv in extra) parameters[kv.Key] = kv.Value; var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private SqlEndpoint CreateProducerEndpoint(string sql, Dictionary? extra = null) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var parameters = new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main" }; if (extra != null) foreach (var kv in extra) parameters[kv.Key] = kv.Value; var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private void InsertOutboxRow(string message) { _db.Execute($"INSERT INTO outbox(message) VALUES('{message}')"); } // ── End-to-end: Consumer polls → Processor → Producer writes ──── [Fact] public async Task EndToEnd_ConsumerPollsRows_ProducerInsertsToAudit() { InsertOutboxRow("order-created"); InsertOutboxRow("order-shipped"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1" }); var producerEp = CreateProducerEndpoint( "INSERT INTO audit(source_id, message) VALUES(:#id, :#message)"); var producer = producerEp.CreateProducer(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); lock (_capturedExchanges) _capturedExchanges.Add(ex); await producer.Process(ex, ci.Arg()); }); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 2; }, 5000); await _consumer.Stop(); var auditRows = _db.Query("SELECT * FROM audit ORDER BY source_id"); auditRows.Should().HaveCountGreaterThanOrEqualTo(2); ((string)auditRows[0]["message"]!).Should().Be("order-created"); ((string)auditRows[1]["message"]!).Should().Be("order-shipped"); } [Fact] public async Task EndToEnd_OnSuccess_MarksRowsAsProcessed() { InsertOutboxRow("msg-1"); InsertOutboxRow("msg-2"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { lock (_capturedExchanges) _capturedExchanges.Add(ci.Arg()); }); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 2; }, 5000); await _consumer.Stop(); // All rows should be marked processed var unprocessed = _db.Query("SELECT * FROM outbox WHERE processed = 0"); unprocessed.Should().BeEmpty("all rows should have been marked processed via onSuccess"); var processed = _db.Query("SELECT * FROM outbox WHERE processed = 1"); processed.Should().HaveCount(2); } [Fact] public async Task EndToEnd_Headers_PropagatedFromConsumerToProducer() { InsertOutboxRow("check-headers"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1" }); var processor = Substitute.For(); IExchange? captured = null; processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => captured = ci.Arg()); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => captured != null, 5000); await _consumer.Stop(); captured.Should().NotBeNull(); captured!.In.Headers.Should().ContainKey(SqlHeaders.Query); captured.In.Headers.Should().ContainKey(SqlHeaders.RowCount); captured.In.Headers.Should().ContainKey(SqlHeaders.ExecutionTime); captured.In.Headers[SqlHeaders.DataSource].Should().Be("main"); captured.Pattern.Should().Be(ExchangePattern.InOnly); // Body should be row dict captured.In.Body.Should().BeAssignableTo>(); var row = (Dictionary)captured.In.Body!; row.Should().ContainKey("message"); ((string)row["message"]!).Should().Be("check-headers"); } [Fact] public async Task EndToEnd_TransactedConsumer_CommitsOnSuccess() { InsertOutboxRow("tx-msg"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1", ["transacted"] = "true", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { lock (_capturedExchanges) _capturedExchanges.Add(ci.Arg()); }); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 1; }, 5000); await _consumer.Stop(); var processed = _db.Query("SELECT * FROM outbox WHERE processed = 1"); processed.Should().HaveCount(1, "transacted consumer should commit onSuccess update"); } [Fact] public async Task EndToEnd_ProducerSelectList_ReturnsQueryResults() { _db.Execute("INSERT INTO audit(source_id, message, status) VALUES(1, 'A', 'OK')"); _db.Execute("INSERT INTO audit(source_id, message, status) VALUES(2, 'B', 'FAIL')"); _db.Execute("INSERT INTO audit(source_id, message, status) VALUES(3, 'C', 'OK')"); var producerEp = CreateProducerEndpoint( "SELECT * FROM audit ORDER BY source_id", new() { ["outputType"] = "SelectList" }); var producer = producerEp.CreateProducer(); var exchange = new Exchange(new Message()); await producer.Process(exchange, CancellationToken.None); var rows = exchange.In.Body as List>; rows.Should().NotBeNull(); rows.Should().HaveCount(3); ((string)rows![0]["message"]!).Should().Be("A"); ((string)rows[2]["message"]!).Should().Be("C"); } [Fact] public async Task EndToEnd_DataArrivesWhilePolling_StillProcessed() { var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["delete"] = "false", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var count = 0; var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(_ => Interlocked.Increment(ref count)); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); // Wait a poll cycle await Task.Delay(200); // Insert data while consumer is running InsertOutboxRow("late-arrival-1"); InsertOutboxRow("late-arrival-2"); await WaitForCondition(() => count >= 2, 5000); await _consumer.Stop(); count.Should().BeGreaterThanOrEqualTo(2); var processed = _db.Query("SELECT * FROM outbox WHERE processed = 1"); processed.Should().HaveCount(2); } [Fact] public async Task EndToEnd_MaxMessagesPerPoll_LimitsRowsPerCycle() { for (var i = 0; i < 5; i++) InsertOutboxRow($"batch-{i}"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1", ["maxMessagesPerPoll"] = "2", ["onSuccess"] = "UPDATE outbox SET processed = 1 WHERE id = :#id" }); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(Task.CompletedTask) .AndDoes(ci => { lock (_capturedExchanges) _capturedExchanges.Add(ci.Arg()); }); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => { lock (_capturedExchanges) return _capturedExchanges.Count >= 2; }, 5000); await _consumer.Stop(); // Only 2 rows should have been processed in the single poll cycle lock (_capturedExchanges) { _capturedExchanges.Should().HaveCount(2, "maxMessagesPerPoll=2 should limit to 2 rows"); } } [Fact] public async Task EndToEnd_ConsumerToProducer_TransformInProcessor() { InsertOutboxRow("transform-me"); var consumerEp = CreateConsumerEndpoint( "SELECT id, message FROM outbox WHERE processed = 0", new() { ["repeatCount"] = "1" }); var producerEp = CreateProducerEndpoint( "INSERT INTO audit(source_id, message, status) VALUES(:#source_id, :#message, :#status)"); var producer = producerEp.CreateProducer(); // Processor transforms the exchange before sending to producer var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(async ci => { var ex = ci.Arg(); var row = (Dictionary)ex.In.Body!; // Transform: set headers for producer parameter binding ex.In.Headers["source_id"] = row["id"]; ex.In.Headers["message"] = ((string)row["message"]!).ToUpperInvariant(); ex.In.Headers["status"] = "TRANSFORMED"; await producer.Process(ex, ci.Arg()); }); _consumer = (SqlConsumer)consumerEp.CreateConsumer(processor); await _consumer.Start(); await WaitForCondition(() => _db.Query("SELECT * FROM audit").Count >= 1, 5000); await _consumer.Stop(); var auditRows = _db.Query("SELECT * FROM audit"); auditRows.Should().HaveCount(1); ((string)auditRows[0]["message"]!).Should().Be("TRANSFORM-ME"); ((string)auditRows[0]["status"]!).Should().Be("TRANSFORMED"); } // ── Helpers ────────────────────────────────────────────────────── private static async Task WaitForCondition(Func condition, int timeoutMs) { var sw = System.Diagnostics.Stopwatch.StartNew(); while (!condition() && sw.ElapsedMilliseconds < timeoutMs) { await Task.Delay(50); } } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlNamedQueryRegistryTests.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/SqlNamedQueryRegistryTests.cs ---- using redb.Route.Sql; namespace redb.Route.Tests.Sql; public class SqlNamedQueryRegistryTests { // ── Register + Resolve ────────────────────────────────────────── [Fact] public void Register_And_Resolve() { var registry = new SqlNamedQueryRegistry(); registry.Register("findOrders", "SELECT * FROM orders WHERE status = 'new'"); var sql = registry.Resolve("findOrders"); sql.Should().Be("SELECT * FROM orders WHERE status = 'new'"); } [Fact] public void Resolve_CaseInsensitive() { var registry = new SqlNamedQueryRegistry(); registry.Register("FindOrders", "SELECT 1"); registry.Resolve("findorders").Should().Be("SELECT 1"); registry.Resolve("FINDORDERS").Should().Be("SELECT 1"); } [Fact] public void Resolve_NotFound_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.Resolve("nonexistent"); act.Should().Throw().WithMessage("*nonexistent*"); } [Fact] public void Register_Duplicate_Throws() { var registry = new SqlNamedQueryRegistry(); registry.Register("q1", "SELECT 1"); var act = () => registry.Register("q1", "SELECT 2"); act.Should().Throw().WithMessage("*q1*already*"); } [Fact] public void Register_DuplicateCaseInsensitive_Throws() { var registry = new SqlNamedQueryRegistry(); registry.Register("MyQuery", "SELECT 1"); var act = () => registry.Register("myquery", "SELECT 2"); act.Should().Throw(); } [Fact] public void Register_NullName_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.Register(null!, "SELECT 1"); act.Should().Throw(); } [Fact] public void Register_EmptyName_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.Register("", "SELECT 1"); act.Should().Throw(); } [Fact] public void Register_NullSql_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.Register("q", null!); act.Should().Throw(); } [Fact] public void Register_EmptySql_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.Register("q", ""); act.Should().Throw(); } // ── TryResolve ────────────────────────────────────────────────── [Fact] public void TryResolve_Found_ReturnsTrue() { var registry = new SqlNamedQueryRegistry(); registry.Register("q1", "SELECT 1"); var found = registry.TryResolve("q1", out var sql); found.Should().BeTrue(); sql.Should().Be("SELECT 1"); } [Fact] public void TryResolve_NotFound_ReturnsFalse() { var registry = new SqlNamedQueryRegistry(); var found = registry.TryResolve("nonexistent", out var sql); found.Should().BeFalse(); sql.Should().BeNull(); } // ── GetAll ────────────────────────────────────────────────────── [Fact] public void GetAll_Empty() { var registry = new SqlNamedQueryRegistry(); registry.GetAll().Should().BeEmpty(); } [Fact] public void GetAll_ReturnsAllRegistered() { var registry = new SqlNamedQueryRegistry(); registry.Register("q1", "SELECT 1"); registry.Register("q2", "SELECT 2"); var all = registry.GetAll(); all.Should().HaveCount(2); all.Should().ContainKey("q1"); all.Should().ContainKey("q2"); } // ── ResolveRef ────────────────────────────────────────────────── [Fact] public void ResolveRef_WithPrefix_ResolvesQuery() { var registry = new SqlNamedQueryRegistry(); registry.Register("findOrders", "SELECT * FROM orders"); var result = registry.ResolveRef("ref:findOrders"); result.Should().Be("SELECT * FROM orders"); } [Fact] public void ResolveRef_WithoutPrefix_ReturnsSameSql() { var registry = new SqlNamedQueryRegistry(); var result = registry.ResolveRef("SELECT 1"); result.Should().Be("SELECT 1"); } [Fact] public void ResolveRef_CaseInsensitive_Prefix() { var registry = new SqlNamedQueryRegistry(); registry.Register("q1", "SELECT 1"); var result = registry.ResolveRef("REF:q1"); result.Should().Be("SELECT 1"); } [Fact] public void ResolveRef_UnknownName_Throws() { var registry = new SqlNamedQueryRegistry(); var act = () => registry.ResolveRef("ref:unknown"); act.Should().Throw(); } [Fact] public void RefPrefix_IsRefColon() { SqlNamedQueryRegistry.RefPrefix.Should().Be("ref:"); } // ── Thread safety ─────────────────────────────────────────────── [Fact] public void ConcurrentRegisterAndResolve_NoErrors() { var registry = new SqlNamedQueryRegistry(); // Pre-register for (var i = 0; i < 100; i++) registry.Register($"q{i}", $"SELECT {i}"); // Concurrent resolve var errors = new System.Collections.Concurrent.ConcurrentBag(); Parallel.For(0, 100, i => { try { var sql = registry.Resolve($"q{i}"); sql.Should().Be($"SELECT {i}"); } catch (Exception ex) { errors.Add(ex); } }); errors.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlOutputMappingTests.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/SqlOutputMappingTests.cs ---- using System.Data; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using SqlDsl = redb.Route.Sql.Sql; namespace redb.Route.Tests.Sql; /// /// Covers the three options that were bound from the URI but never honoured: /// procedureName falling back to the URI path, outputClass (POCO mapping), /// and outputHeader (result to a header instead of the body). /// public class SqlOutputMappingTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlOutputMappingTests() { _db.Execute(""" CREATE TABLE orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, customer TEXT NOT NULL, total_price REAL NOT NULL, processed INTEGER NOT NULL DEFAULT 0 ) """); _db.Execute("INSERT INTO orders (customer, total_price) VALUES ('alice', 10.5), ('bob', 20.25)"); } public void Dispose() => _db.Dispose(); /// POCO target for outputClass. Note total_price → TotalPrice (snake_case mapping). public class Order { public long Id { get; set; } public string? Customer { get; set; } public double TotalPrice { get; set; } } private SqlEndpoint CreateEndpoint(string sql, Dictionary parameters) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private SqlEndpoint CreateEndpointFromUri(string uriString) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); return (SqlEndpoint)component.CreateEndpoint(EndpointUriParser.Parse(uriString)); } private static Exchange CreateExchange(object? body = null, Dictionary? headers = null) { var ex = new Exchange(new Message(body)); if (headers != null) foreach (var kv in headers) ex.In.Headers[kv.Key] = kv.Value; return ex; } // ── procedureName falls back to the URI path ──────────────────── [Fact] public async Task ProcedureMode_WithoutProcedureName_TakesNameFromUriPath() { // No procedureName= at all — the path must supply it. var endpoint = CreateEndpoint("abs", new() { ["mode"] = "Procedure", ["dataSource"] = "main", ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["x"] = -42L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(42L); exchange.In.Headers[SqlHeaders.StoredProcedure].Should().Be("abs"); } [Fact] public void ProcedureMode_ExplicitProcedureName_WinsOverPath() { var endpoint = CreateEndpoint("ignored_path", new() { ["mode"] = "Procedure", ["dataSource"] = "main", ["procedureName"] = "real_proc" }); endpoint.EndpointOptions.ProcedureName.Should().Be("real_proc"); } [Fact] public async Task FluentProcedureBuilder_ProducesAWorkingEndpoint() { // Sql.Procedure() only ever emitted the name into the path, so before the fix // this URI failed validation with "ProcedureName is required for Procedure mode." string uri = SqlDsl.Procedure("abs") .DataSource(new redb.Route.Expressions.ConstantExpression("main")) .AsFunction() .In("x", DbType.Int64); var endpoint = CreateEndpointFromUri(uri); endpoint.EndpointOptions.ProcedureName.Should().Be("abs"); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["x"] = -7L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(7L); } // ── outputClass: POCO mapping ─────────────────────────────────── [Fact] public async Task OutputClass_SelectList_MapsToTypedListOfPoco() { var endpoint = CreateEndpoint("SELECT id, customer, total_price FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "SelectList", ["outputClass"] = typeof(Order).AssemblyQualifiedName! }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var orders = exchange.In.Body.Should().BeOfType>().Subject; orders.Should().HaveCount(2); orders[0].Customer.Should().Be("alice"); orders[0].TotalPrice.Should().Be(10.5); // total_price → TotalPrice orders[1].Id.Should().Be(2); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(2); } [Fact] public async Task OutputClass_SelectOne_MapsToSinglePoco() { var endpoint = CreateEndpoint("SELECT id, customer, total_price FROM orders WHERE customer = 'bob'", new() { ["dataSource"] = "main", ["outputType"] = "SelectOne", ["outputClass"] = typeof(Order).AssemblyQualifiedName! }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var order = exchange.In.Body.Should().BeOfType().Subject; order.Customer.Should().Be("bob"); order.TotalPrice.Should().Be(20.25); } [Fact] public async Task OutputClass_StreamList_YieldsTypedAsyncEnumerable() { var endpoint = CreateEndpoint("SELECT id, customer, total_price FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "StreamList", ["outputClass"] = typeof(Order).AssemblyQualifiedName! }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var stream = exchange.In.Body.Should().BeAssignableTo>().Subject; var seen = new List(); await foreach (var order in stream) seen.Add(order); seen.Should().HaveCount(2); seen[0].Customer.Should().Be("alice"); } [Fact] public async Task OutputClass_NotSet_StillYieldsDictionaries() { // Regression guard: the default path must be untouched. var endpoint = CreateEndpoint("SELECT id, customer FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "SelectList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().BeOfType>>(); } [Fact] public void OutputClass_UnknownType_ThrowsWithAClearMessage() { var endpoint = CreateEndpoint("SELECT 1", new() { ["dataSource"] = "main", ["outputType"] = "SelectList", ["outputClass"] = "Nope.NotAType" }); var producer = endpoint.CreateProducer(); var act = async () => await producer.Process(CreateExchange(), CancellationToken.None); act.Should().ThrowAsync() .WithMessage("*Nope.NotAType*could not be resolved*"); } // ── outputHeader: result to header, body preserved ────────────── [Fact] public async Task OutputHeader_SelectList_PutsResultInHeaderAndKeepsBody() { var endpoint = CreateEndpoint("SELECT id, customer FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "SelectList", ["outputHeader"] = "lookup" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: "original payload"); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("original payload"); // body survives the enrichment var rows = exchange.In.Headers["lookup"] .Should().BeOfType>>().Subject; rows.Should().HaveCount(2); } [Fact] public async Task OutputHeader_Scalar_PutsScalarInHeader() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM orders", new() { ["dataSource"] = "main", ["outputType"] = "Scalar", ["outputHeader"] = "orderCount" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: "keep me"); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("keep me"); exchange.In.Headers["orderCount"].Should().Be(2L); } [Fact] public async Task OutputHeader_WithOutputClass_PutsTypedListInHeader() { var endpoint = CreateEndpoint("SELECT id, customer, total_price FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "SelectList", ["outputClass"] = typeof(Order).AssemblyQualifiedName!, ["outputHeader"] = "orders" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: 42); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(42); exchange.In.Headers["orders"].Should().BeOfType>() .Which.Should().HaveCount(2); } [Fact] public async Task OutputHeader_Expression_NamesTheHeaderPerExchange() { var endpoint = CreateEndpoint("SELECT id FROM orders ORDER BY id", new() { ["dataSource"] = "main", ["outputType"] = "SelectList", ["outputHeader"] = "${header.target}" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: 42, headers: new() { ["target"] = "rows" }); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(42); exchange.In.Headers.Should().ContainKey("rows", "the expression names the header"); exchange.In.Headers.Should().NotContainKey("${header.target}"); } [Fact] public async Task OutputHeader_Procedure_AsFunction_PutsResultInHeader() { var endpoint = CreateEndpoint("abs", new() { ["mode"] = "Procedure", ["dataSource"] = "main", ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64", ["outputHeader"] = "absValue" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: "payload", headers: new() { ["x"] = -5L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("payload"); exchange.In.Headers["absValue"].Should().Be(5L); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlParameterNormalizationTests.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/SqlParameterNormalizationTests.cs ---- using System.Text.Json; using System.Text.Json.Nodes; using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// JSON values become values a provider can bind: scalars as CLR values, objects and arrays as JSON text. public sealed class SqlParameterNormalizationTests { [Fact] public void JsonElement_Numbers_LongThenDecimalThenDouble() { SqlParameterBinder.NormalizeForDb(Element("42")).Should().Be(42L); SqlParameterBinder.NormalizeForDb(Element("1.5")).Should().Be(1.5m); SqlParameterBinder.NormalizeForDb(Element("1e300")).Should().Be(1e300); } [Fact] public void JsonElement_StringBoolNull() { SqlParameterBinder.NormalizeForDb(Element("\"text\"")).Should().Be("text"); SqlParameterBinder.NormalizeForDb(Element("\"\"")).Should().Be(DBNull.Value); SqlParameterBinder.NormalizeForDb(Element("true")).Should().Be(true); SqlParameterBinder.NormalizeForDb(Element("false")).Should().Be(false); SqlParameterBinder.NormalizeForDb(Element("null")).Should().Be(DBNull.Value); } [Fact] public void JsonNode_ParsedScalars_SameAsJsonElement() { SqlParameterBinder.NormalizeForDb(JsonNode.Parse("12")).Should().Be(12L); SqlParameterBinder.NormalizeForDb(JsonNode.Parse("\"a\"")).Should().Be("a"); SqlParameterBinder.NormalizeForDb(JsonNode.Parse("true")).Should().Be(true); } [Fact] public void JsonNode_CreatedFromClrValue_IsThatValue() { SqlParameterBinder.NormalizeForDb(JsonValue.Create(5)).Should().Be(5); SqlParameterBinder.NormalizeForDb(JsonValue.Create("x")).Should().Be("x"); SqlParameterBinder.NormalizeForDb(JsonValue.Create("")).Should().Be(DBNull.Value); } [Fact] public void JsonNode_ObjectAndArray_AreJsonTextWithoutEscapingLetters() { SqlParameterBinder.NormalizeForDb(JsonNode.Parse("""{"a":"я"}""")).Should().Be("""{"a":"я"}"""); SqlParameterBinder.NormalizeForDb(JsonNode.Parse("[1,2]")).Should().Be("[1,2]"); } private static JsonElement Element(string json) => JsonDocument.Parse(json).RootElement.Clone(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlParameterParserTests.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/SqlParameterParserTests.cs ---- using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// /// Placeholders are written as in Apache Camel, :#name, and are found only in the SQL itself — not inside string /// literals, quoted identifiers, comments or PostgreSQL dollar-quoted bodies. @ belongs to the database (T-SQL variables /// and EXEC argument names, MySQL user variables, @@IDENTITY) and is never a placeholder. /// public class SqlParameterParserTests { // ── Names ─────────────────────────────────────────────────────── [Fact] public void ExtractParameterNames_SingleParam() { SqlParameterParser.ExtractParameterNames("SELECT * FROM t WHERE id = :#id").Should().Equal("id"); } [Fact] public void ExtractParameterNames_MultipleParams_InOrder() { SqlParameterParser.ExtractParameterNames("INSERT INTO t(name, age) VALUES(:#name, :#age)").Should().Equal("name", "age"); } [Fact] public void ExtractParameterNames_DuplicatesRemoved_FirstOccurrenceKept() { SqlParameterParser.ExtractParameterNames("UPDATE t SET name = :#name WHERE name = :#name AND id = :#id") .Should().Equal("name", "id"); } [Fact] public void ExtractParameterNames_NoParams() => SqlParameterParser.ExtractParameterNames("SELECT 1").Should().BeEmpty(); [Fact] public void ExtractParameterNames_EmptyString() => SqlParameterParser.ExtractParameterNames("").Should().BeEmpty(); [Fact] public void ExtractParameterNames_NullString() => SqlParameterParser.ExtractParameterNames(null!).Should().BeEmpty(); [Fact] public void ExtractParameterNames_UnderscoreAndDigitsInName() => SqlParameterParser.ExtractParameterNames("SELECT * FROM t WHERE user_id = :#user_id OR x = :#param2") .Should().Equal("user_id", "param2"); [Fact] public void ExtractParameterNames_ComplexSql() { var sql = """ INSERT INTO orders(customer_id, product_id, qty, price) VALUES(:#customerId, :#productId, :#qty, :#price); UPDATE inventory SET stock = stock - :#qty WHERE product_id = :#productId; """; SqlParameterParser.ExtractParameterNames(sql).Should().Equal("customerId", "productId", "qty", "price"); } [Fact] public void ExtractParameterNames_CaseInsensitiveDedupe() => SqlParameterParser.ExtractParameterNames("SELECT :#Id, :#ID, :#id FROM t").Should().ContainSingle(); [Fact] public void ExtractParameterNames_CastAfterPlaceholder() => SqlParameterParser.ExtractParameterNames("SELECT :#details::jsonb, CAST(:#id AS int)").Should().Equal("details", "id"); // ── What is not a placeholder ─────────────────────────────────── [Fact] public void AtSigns_BelongToTheDatabase() => SqlParameterParser.ExtractParameterNames("DECLARE @n int = :#v; EXEC p @arg = @n; SELECT @@IDENTITY, @user_var") .Should().Equal("v"); [Fact] public void SkipsSingleQuotedLiteral_WithEscapedQuote() => SqlParameterParser.ExtractParameterNames("SELECT 'O''Brien :#x', :#y").Should().Equal("y"); [Fact] public void SkipsLineAndBlockComments() => SqlParameterParser.ExtractParameterNames("SELECT :#a -- :#b\n, /* :#c */ :#d").Should().Equal("a", "d"); [Fact] public void SkipsDoubleQuotedAndBacktickIdentifiers() => SqlParameterParser.ExtractParameterNames("SELECT \"col:#x\", `c:#y`, :#z").Should().Equal("z"); [Fact] public void SkipsDollarQuotedBodies() => SqlParameterParser.ExtractParameterNames("SELECT $$ :#a $$, $fn$ :#b $fn$, :#c").Should().Equal("c"); [Fact] public void PostgresPositionalParameter_IsNotADollarQuote() => SqlParameterParser.ExtractParameterNames("SELECT $1, :#x, $2").Should().Equal("x"); [Fact] public void UnterminatedLiteral_HidesTheRest() => SqlParameterParser.ExtractParameterNames("SELECT :#a, 'open :#b").Should().Equal("a"); // ── Occurrences and rewrite ───────────────────────────────────── [Fact] public void FindPlaceholders_InOrder_WithRepeats_AndPositions() { var placeholders = SqlParameterParser.FindPlaceholders("a = :#a OR b = :#bb OR c = :#a::int"); placeholders.Select(p => (p.Name, p.Offset, p.Length)).Should().Equal(("a", 4, 3), ("bb", 15, 4), ("a", 27, 3)); } [Theory] [InlineData("SELECT :#${header.x}")] [InlineData("SELECT * FROM t WHERE id IN (:#in:ids)")] [InlineData("SELECT :# x")] public void FindPlaceholders_UnsupportedForms_Throw(string sql) { var act = () => SqlParameterParser.FindPlaceholders(sql); act.Should().Throw().WithMessage("*:#*"); } [Fact] public void FindPlaceholders_NamedInWithCast_IsAPlaceholder() => SqlParameterParser.FindPlaceholders("SELECT :#in::int").Should().ContainSingle().Which.Name.Should().Be("in"); [Fact] public void BackslashEscapes_EscapedQuoteStaysInsideTheLiteral() => SqlParameterParser.FindPlaceholders(@"VALUES ('it\'s :#a', "":#b \"" :#c"", :#d)", backslashEscapes: true) .Select(p => p.Name).Should().Equal("d"); [Fact] public void BackslashEscapes_EscapedBackslashBeforeTheClosingQuote() => SqlParameterParser.FindPlaceholders(@"VALUES ('C:\\', :#a)", backslashEscapes: true) .Should().ContainSingle().Which.Name.Should().Be("a"); [Fact] public void BackslashEscapes_BackQuotedIdentifier_BackslashIsOrdinary() => SqlParameterParser.FindPlaceholders(@"SELECT `c\`, :#a", backslashEscapes: true) .Should().ContainSingle().Which.Name.Should().Be("a"); [Fact] public void BackslashEscapes_Default_BackslashIsOrdinary() => SqlParameterParser.FindPlaceholders(@"VALUES ('C:\', :#a)") .Should().ContainSingle().Which.Name.Should().Be("a"); [Theory] [InlineData(SqlPlaceholderStyle.At, "WHERE a = @a AND n = ':#a' -- :#a\nOR b = @b OR c = @a")] [InlineData(SqlPlaceholderStyle.Colon, "WHERE a = :a AND n = ':#a' -- :#a\nOR b = :b OR c = :a")] [InlineData(SqlPlaceholderStyle.Question, "WHERE a = ? AND n = ':#a' -- :#a\nOR b = ? OR c = ?")] public void Rewrite_ReplacesOnlyPlaceholders(SqlPlaceholderStyle style, string expected) { const string sql = "WHERE a = :#a AND n = ':#a' -- :#a\nOR b = :#b OR c = :#a"; SqlParameterParser.Rewrite(sql, SqlParameterParser.FindPlaceholders(sql), style).Should().Be(expected); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlParameterSyntaxTests.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/SqlParameterSyntaxTests.cs ---- using System.Data.Common; 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; /// /// Parameters are written as in Apache Camel, :#name, in every statement the connector sends — the single statement, /// a batch, the poll query, a function call — and placeholderStyle decides what the provider receives: @name /// (the default), :name (Oracle) or ? (ODBC), with one parameter per occurrence where the style is positional. /// public sealed class SqlParameterSyntaxTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlParameterSyntaxTests() { _db.Execute("CREATE TABLE syntax_items (id INTEGER PRIMARY KEY, val TEXT)"); _db.Execute("INSERT INTO syntax_items (id, val) VALUES (1, 'a'), (2, 'b')"); } public void Dispose() => _db.Dispose(); // ── Syntax ────────────────────────────────────────────────────── [Fact] public async Task Execute_ColonHashPlaceholder_BoundFromHeader() { var (exchange, thrown) = await ProduceAsync("SELECT val FROM syntax_items WHERE id = :#id", new() { ["outputType"] = "Scalar" }, e => e.In.Headers["id"] = 2); thrown.Should().BeNull(Outcome.Describe(thrown)); exchange.In.Body.Should().Be("b"); } [Fact] public async Task Execute_PlaceholderInsideLiteralAndComment_IsNotBound() { var (exchange, thrown) = await ProduceAsync("SELECT ':#id' || val FROM syntax_items WHERE id = :#id -- :#other", new() { ["outputType"] = "Scalar" }, e => e.In.Headers["id"] = 1); thrown.Should().BeNull("':#id' is text and '-- :#other' a comment, so neither needs a value: " + Outcome.Describe(thrown)); exchange.In.Body.Should().Be(":#ida"); } [Theory] [InlineData("SELECT :#${header.id}")] [InlineData("SELECT val FROM syntax_items WHERE id IN (:#in:ids)")] public async Task Execute_UnsupportedCamelForms_AreRefused(string sql) { var (_, thrown) = await ProduceAsync(sql, new() { ["outputType"] = "Scalar" }, e => e.In.Headers["id"] = 1); thrown.Should().BeOfType(Outcome.Describe(thrown)) .Which.Message.Should().Contain(":#", "the message names the placeholder form that is not supported"); } [Fact] public async Task Poll_QueryPlaceholder_BoundFromParam() { var (received, thrown) = await PollAsync("SELECT val FROM syntax_items WHERE id > :#since ORDER BY id", new() { ["param.since"] = "1" }); thrown.Should().BeNull(Outcome.Describe(thrown)); received.Should().Equal("b"); } [Fact] public async Task Poll_QueryPlaceholderWithoutParam_IsAnError() { var (_, thrown) = await PollAsync("SELECT val FROM syntax_items WHERE id > :#since ORDER BY id", new()); thrown.Should().BeOfType(Outcome.Describe(thrown)) .Which.Message.Should().Contain(":#since", "a poll query takes its values from param.* only"); } // ── Placeholder styles ────────────────────────────────────────── /// /// Placeholders are not repeated here: Colon adds a parameter per occurrence for ODP.NET's positional binding, and /// Microsoft.Data.Sqlite, which binds :name by name, refuses two parameters with one name (measured 2026-09-15). /// The per-occurrence parameters are covered by the plan's tests. /// [Fact] public async Task ColonStyle_ProviderReceivesColonNames() { var (exchange, thrown) = await ProduceAsync("SELECT :#a + :#b", new() { ["outputType"] = "Scalar", ["placeholderStyle"] = "Colon" }, e => { e.In.Headers["a"] = 2; e.In.Headers["b"] = 3; }); thrown.Should().BeNull(Outcome.Describe(thrown)); Convert.ToInt64(exchange.In.Body).Should().Be(5, "SQLite reads :a and :b"); } [Fact] public async Task QuestionStyle_BatchSendsPositionalTextAndOneParameterPerOccurrence() { var texts = new List(); var values = new List(); var connection = new FakeBatchConnection { SupportsBatch = true, OnExecuteBatch = (_, batch) => { foreach (var command in batch.BatchCommands) { texts.Add(command.CommandText); values.AddRange(command.Parameters.Cast().Select(p => p.Value)); } return batch.BatchCommands.Count; }, }; await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), "INSERT INTO t (a, b, c) VALUES (:#b, :#a, :#b)", new() { ["outputType"] = "None", ["batchSize"] = "10", ["placeholderStyle"] = "Question" }); var items = new List> { new() { ["a"] = 1, ["b"] = 2 } }; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message(items)), CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); texts.Should().Equal("INSERT INTO t (a, b, c) VALUES (?, ?, ?)"); values.Should().Equal(new object?[] { 2, 1, 2 }, "positional parameters follow the occurrences, repeats included"); } // ── Contract details ──────────────────────────────────────────── [Fact] public async Task Execute_RepeatedNameInAnotherCase_IsBoundOnce() { var (exchange, thrown) = await ProduceAsync("SELECT :#Id + :#id", new() { ["outputType"] = "Scalar" }, e => e.In.Headers["Id"] = 2); thrown.Should().BeNull("names are compared ignoring case, so the provider gets one name: " + Outcome.Describe(thrown)); Convert.ToInt64(exchange.In.Body).Should().Be(4); } [Fact] public async Task Execute_MissingValue_MessageNamesThePlaceholderAsWritten() { var (_, thrown) = await ProduceAsync("SELECT :#missing", new() { ["outputType"] = "Scalar" }, _ => { }); thrown.Should().BeOfType(Outcome.Describe(thrown)) .Which.Message.Should().StartWith("SQL parameter ':#missing' has no value", "@ is not a placeholder any more"); } [Fact] public async Task Poll_QueryPlaceholderWithExpressionParam_IsAnError() { var (_, thrown) = await PollAsync("SELECT val FROM syntax_items WHERE id > :#since ORDER BY id", new() { ["param.since"] = "${header.x}" }); thrown.Should().BeOfType("a poll query has no exchange to evaluate an expression in, " + "and the template text must not be bound as the value: " + Outcome.Describe(thrown)) .Which.Message.Should().Contain("since").And.Contain("${"); } [Fact] public async Task Poll_DynamicQuery_IsAnError() { var (_, thrown) = await PollAsync("SELECT val FROM syntax_items ORDER BY id", new() { ["query"] = "${header.q}" }); thrown.Should().BeOfType("a poll has no exchange to resolve query=${...} against, " + "and must not fall back to the URI path silently: " + Outcome.Describe(thrown)) .Which.Message.Should().Contain("query"); } // ── Backslash escapes (MySQL, MariaDB) ────────────────────────── [Fact] public async Task BackslashEscapes_QuoteEscapedWithBackslash_PlaceholderAfterTheLiteralIsBound() { var texts = await BatchTextsAsync(@"INSERT INTO t (val, id) VALUES ('it\'s :#no', :#id)", new() { ["backslashEscapes"] = "true" }); texts.Should().ContainSingle().Which.Should().Be(@"INSERT INTO t (val, id) VALUES ('it\'s :#no', @id)", "with backslashEscapes=true \\' stays inside the literal, as MySQL reads it"); } [Fact] public async Task BackslashEscapes_Default_BackslashIsAnOrdinaryCharacter() { var texts = await BatchTextsAsync(@"INSERT INTO t (val, id) VALUES ('C:\', :#id)", new()); texts.Should().ContainSingle().Which.Should().Be(@"INSERT INTO t (val, id) VALUES ('C:\', @id)", "standard SQL (PostgreSQL, SQL Server, Oracle, SQLite) ends 'C:\\' at its second quote"); } [Fact] public async Task FunctionCall_HonoursPlaceholderStyle() { var connection = new FakeBatchConnection(); await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), "fn", new() { ["mode"] = "Procedure", ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int32", ["placeholderStyle"] = "Colon", }); var exchange = new Exchange(new Message()); exchange.In.Headers["x"] = 3; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); connection.ExecutedCommandTexts.Should().Equal("SELECT fn(:x)"); } // ── Helpers ───────────────────────────────────────────────────── /// Runs a one-item batch of on a fake connection; returns the command texts it received. private static async Task> BatchTextsAsync(string sql, Dictionary extraParameters) { var texts = new List(); var connection = new FakeBatchConnection { SupportsBatch = true, OnExecuteBatch = (_, batch) => { texts.AddRange(batch.BatchCommands.Select(c => c.CommandText)); return batch.BatchCommands.Count; }, }; var parameters = new Dictionary(extraParameters) { ["outputType"] = "None", ["batchSize"] = "10" }; await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, new FixedConnectionFactory(connection), sql, parameters); var items = new List> { new() { ["id"] = 7 } }; var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message(items)), CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); return texts; } private async Task<(Exchange Exchange, Exception? Thrown)> ProduceAsync( string sql, Dictionary parameters, Action prepare) { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), sql, parameters); var exchange = new Exchange(new Message()); prepare(exchange); var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); return (exchange, thrown); } private async Task<(List Received, Exception? Thrown)> PollAsync(string sql, Dictionary extra) { await using var context = new RouteContext(); var parameters = new Dictionary { ["mode"] = "Poll", ["repeatCount"] = "1" }; foreach (var (key, value) in extra) parameters[key] = value; var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), sql, parameters); var received = new List(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.Add(((Dictionary)ci.Arg().In.Body!)["val"]); return Task.CompletedTask; }); var thrown = await Outcome.Of(() => ((SqlConsumer)endpoint.CreateConsumer(processor)).Poll(CancellationToken.None)); return (received, thrown); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProcedureProducerTests.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/SqlProcedureProducerTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// /// Integration tests for SqlProcedureProducer. /// SQLite doesn't support stored procedures, so we test: /// - AsFunction mode (SQLite user-defined functions or simple SELECT) /// - Noop mode /// - ParseProcedureParams parsing /// - Parameter binding logic /// public class SqlProcedureProducerTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlProcedureProducerTests() { _db.Execute(""" CREATE TABLE proc_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT ) """); } private SqlEndpoint CreateProcedureEndpoint( string procedureName, Dictionary? extraParams = null) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var parameters = new Dictionary { ["mode"] = "Procedure", ["dataSource"] = "main", ["procedureName"] = procedureName }; if (extraParams != null) foreach (var kv in extraParams) parameters[kv.Key] = kv.Value; var uri = new EndpointUri("sql", procedureName, $"sql:{procedureName}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private static Exchange CreateExchange(object? body = null, Dictionary? headers = null) { var ex = new Exchange(new Message(body)); if (headers != null) foreach (var kv in headers) ex.In.Headers[kv.Key] = kv.Value; return ex; } // ── Noop mode ─────────────────────────────────────────────────── [Fact] public async Task Noop_SetsProcedureNameHeader() { var endpoint = CreateProcedureEndpoint("my_proc", new() { ["noop"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.StoredProcedure].Should().Be("my_proc"); // No actual execution exchange.In.Body.Should().BeNull(); } // ── AsFunction mode ───────────────────────────────────────────── [Fact] public async Task AsFunction_NoParams_ExecutesSelectFunction() { // SQLite built-in: typeof() var endpoint = CreateProcedureEndpoint("typeof", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:val:String" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["val"] = "hello" }); await producer.Process(exchange, CancellationToken.None); // typeof('hello') → 'text' exchange.In.Body.Should().Be("text"); exchange.In.Headers[SqlHeaders.StoredProcedure].Should().Be("typeof"); exchange.In.Headers.Should().ContainKey(SqlHeaders.ExecutionTime); } [Fact] public async Task AsFunction_WithParams_BindsFromHeaders() { // Use abs() as a simple function var endpoint = CreateProcedureEndpoint("abs", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["x"] = (object)-42L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(42L); } [Fact] public async Task AsFunction_WithParams_BindsFromBody() { var endpoint = CreateProcedureEndpoint("abs", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); var body = new Dictionary { ["x"] = -99L }; var exchange = CreateExchange(body: body); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be(99L); } [Fact] public async Task AsFunction_NullResult_ReturnsNull() { // nullif(x, x) always returns null var endpoint = CreateProcedureEndpoint("nullif", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:a:String,IN:b:String" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["a"] = "same", ["b"] = "same" }); await producer.Process(exchange, CancellationToken.None); // nullif('same', 'same') → NULL exchange.In.Body.Should().BeNull(); } // ── ProcedureParams parsing ───────────────────────────────────── [Fact] public async Task AsFunction_MultipleParams_CorrectOrder() { // coalesce(null, 'fallback') → 'fallback' var endpoint = CreateProcedureEndpoint("coalesce", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:a:String,IN:b:String" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["b"] = "fallback" }); // a is not set → NULL, b = 'fallback' await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("fallback"); } [Fact] public async Task EmptyProcedureParams_NoBinding() { // Simple function with no explicit params var endpoint = CreateProcedureEndpoint("random", new() { ["asFunction"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); // random() returns an integer — just verify it doesn't throw exchange.In.Body.Should().NotBeNull(); } // ── Transacted ────────────────────────────────────────────────── [Fact] public async Task AsFunction_Transacted_SetsTransactionHeader() { var endpoint = CreateProcedureEndpoint("abs", new() { ["asFunction"] = "true", ["transacted"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["x"] = (object)5L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers.Should().ContainKey(SqlHeaders.TransactionId); exchange.In.Body.Should().Be(5L); } // ── DataSource header ─────────────────────────────────────────── [Fact] public async Task DataSource_SetInHeaders() { var endpoint = CreateProcedureEndpoint("abs", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["x"] = (object)1L }); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.DataSource].Should().Be("main"); } // ── Error: no DataSource or ConnectionString ──────────────────── [Fact] public void NoDataSource_NoConnectionString_Throws() { var component = new SqlComponent(); var uri = new EndpointUri("sql", "my_proc", "sql:my_proc", new Dictionary { ["mode"] = "Procedure", ["procedureName"] = "my_proc" }); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } // ── Start/Stop are no-ops ─────────────────────────────────────── [Fact] public async Task StartStop_AreNoop() { var endpoint = CreateProcedureEndpoint("abs", new() { ["asFunction"] = "true", ["procedureParams"] = "IN:x:Int64" }); var producer = endpoint.CreateProducer(); // Should not throw await producer.Start(); await producer.Stop(); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProducerAutoOutputTypeTests.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/SqlProducerAutoOutputTypeTests.cs ---- using redb.Route.Core; using redb.Route.Sql; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// outputType=Auto is decided by the statement that runs — the query option or a named query — not by the URI /// path, which is then only a label. /// public sealed class SqlProducerAutoOutputTypeTests : IDisposable { private const string Select = "SELECT id, val FROM auto_items ORDER BY id"; private readonly SqliteTestHelper _db = new(); public SqlProducerAutoOutputTypeTests() { _db.Execute("CREATE TABLE auto_items (id INTEGER PRIMARY KEY, val TEXT)"); _db.Execute("INSERT INTO auto_items (id, val) VALUES (1, 'a'), (2, 'b')"); } public void Dispose() => _db.Dispose(); [Fact] public async Task Auto_QueryOptionSelect_ReturnsRows() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "items", new() { ["query"] = Select }); var exchange = await ProcessAsync(endpoint); Values(exchange).Should().Equal(new object?[] { "a", "b" }, "a SELECT in the query option returns its rows"); } [Fact] public async Task Auto_QueryOptionExpressionSelect_ReturnsRows() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "items", new() { ["query"] = "${header.sql}" }); var exchange = await ProcessAsync(endpoint, e => e.In.Headers["sql"] = Select); Values(exchange).Should().Equal(new object?[] { "a", "b" }, "the statement the expression produced decides the output type"); } [Fact] public async Task Auto_NamedQuerySelect_ReturnsRows() { var registry = new SqlNamedQueryRegistry(); registry.Register("allItems", Select); await using var context = new RouteContext(); context.AddService(typeof(ISqlNamedQueryRegistry), registry); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "ref:allItems"); var exchange = await ProcessAsync(endpoint); Values(exchange).Should().Equal(new object?[] { "a", "b" }, "a named SELECT returns its rows"); } [Fact] public async Task Auto_SelectPathButQueryOptionInsert_ReportsUpdateCount() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "SELECT 1", new() { ["query"] = "INSERT INTO auto_items (id, val) VALUES (3, 'c')" }); var exchange = await ProcessAsync(endpoint); exchange.In.Body.Should().Be("untouched", "an INSERT leaves the body alone"); exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(1, "the statement that ran is an INSERT, whatever the path says"); } // ── Decided by the driver, not by the first word of the text (Apache Camel: execute() says whether there is a result set) ── [Theory] [InlineData("-- the newest first\nSELECT id, val FROM auto_items ORDER BY id")] [InlineData("/* hint */ SELECT id, val FROM auto_items ORDER BY id")] [InlineData(" \n\t SELECT id, val FROM auto_items ORDER BY id")] public async Task Auto_SelectBehindACommentOrWhitespace_ReturnsRows(string sql) { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "items", new() { ["query"] = sql }); var exchange = await ProcessAsync(endpoint); Values(exchange).Should().Equal(new object?[] { "a", "b" }, "what the statement returns decides, not how its text starts"); exchange.In.Headers[SqlHeaders.OutputType].Should().Be("SelectList", "the header reports what Auto resolved to"); } [Fact] public async Task Auto_CteThatWrites_ReportsUpdateCount() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "items", new() { ["query"] = "WITH x AS (SELECT 3 AS id) INSERT INTO auto_items (id, val) SELECT id, 'c' FROM x" }); var exchange = await ProcessAsync(endpoint); exchange.In.Body.Should().Be("untouched", "a WITH that writes returns no rows"); exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(1); exchange.In.Headers[SqlHeaders.OutputType].Should().Be("None"); _db.ExecuteScalar("SELECT COUNT(*) FROM auto_items").Should().Be(3L); } [Fact] public async Task Auto_InsertReturning_ReturnsTheRowsItReturns() { await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "items", new() { ["query"] = "INSERT INTO auto_items (id, val) VALUES (4, 'd') RETURNING id, val" }); var exchange = await ProcessAsync(endpoint); Values(exchange).Should().Equal(new object?[] { "d" }, "the statement returned a row, so Auto returns it, as Camel does"); _db.ExecuteScalar("SELECT COUNT(*) FROM auto_items").Should().Be(3L, "the write happened and was committed"); } private static async Task ProcessAsync(SqlEndpoint endpoint, Action? prepare = null) { var exchange = new Exchange(new Message("untouched")); prepare?.Invoke(exchange); var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(exchange, CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); return exchange; } private static List Values(Exchange exchange) => exchange.In.Body.Should().BeAssignableTo>>( $"outputType=Auto returns the rows of a SELECT (body: {exchange.In.Body ?? "null"}, " + $"updateCount: {(exchange.In.Headers.TryGetValue(SqlHeaders.UpdateCount, out var count) ? count : "absent")})") .Subject.Select(r => r["val"]).ToList(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProducerConnectionLifecycleTests.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/SqlProducerConnectionLifecycleTests.cs ---- using System.Data; using System.Data.Common; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql.Connection; using Xunit; using ConnectionState = System.Data.ConnectionState; namespace redb.Route.Tests.Sql; /// /// A connection the producer opened must be back in the pool whatever happens next. This is the /// hot path for audit and usage writes, so a leak here is not a slow drip — it is the pool /// draining under the exact conditions (dropped sockets, cancellations) that come in bursts. /// /// Two holes, both found by review: BeginTransactionAsync ran before the try, so a /// throw there lost the connection with no finally to catch it; and the StreamList branch /// skipped disposal by option value rather than by whether ownership actually reached the /// stream, so any error before the handoff — the reader failing to open, say — leaked connection /// and transaction both. /// /// public sealed class SqlProducerConnectionLifecycleTests { // ── Fakes: a connection that fails at a chosen point and records its disposal ── private sealed class RecordingFactory(DbConnection connection) : ISqlConnectionFactory { public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) => Task.FromResult(connection); } private sealed class FakeConnection : DbConnection { public bool Disposed; public bool FailOnBeginTransaction; public bool FailOnExecuteReader; public bool FailOnTransactionDispose; public FakeTransaction? Transaction; public override string ConnectionString { get; set; } = ""; 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() { } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { if (FailOnBeginTransaction) throw new InvalidOperationException("socket died while starting the transaction"); return Transaction = new FakeTransaction(this, isolationLevel); } protected override DbCommand CreateDbCommand() => new FakeCommand(this); protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } public override ValueTask DisposeAsync() { Disposed = true; return base.DisposeAsync(); } } private sealed class FakeTransaction(FakeConnection connection, IsolationLevel level) : DbTransaction { public bool Disposed; public override IsolationLevel IsolationLevel => level; protected override DbConnection DbConnection => connection; public override void Commit() { } public override void Rollback() { } protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } public override ValueTask DisposeAsync() { Disposed = true; if (connection.FailOnTransactionDispose) throw new InvalidOperationException("the server dropped the session; the transaction cannot be disposed cleanly"); return base.DisposeAsync(); } } private sealed class FakeCommand(FakeConnection connection) : DbCommand { public override string CommandText { get; set; } = ""; 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 => throw new NotSupportedException("the test SQL carries no :parameters"); protected override DbTransaction? DbTransaction { get; set; } public override void Cancel() { } public override void Prepare() { } public override int ExecuteNonQuery() => 1; public override object? ExecuteScalar() => 1; protected override DbParameter CreateDbParameter() => throw new NotSupportedException("the test SQL carries no :parameters"); protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { if (connection.FailOnExecuteReader) throw new InvalidOperationException("reader refused to open"); throw new NotSupportedException("these tests only exercise the failure path"); } } // ── Harness ── private static async Task Producer(RouteContext context, FakeConnection connection, string uri, string from) { context.AddComponent(new redb.Route.Sql.SqlComponent()); context.AddToRegistry("lifecycle", (ISqlConnectionFactory)new RecordingFactory(connection)); context.AddRoutes(r => r.From(from).To(uri)); await context.Start(); var producer = context.GetEndpoint(from).CreateProducer(); await producer.Start(); return producer; } // ── The holes ── [Fact] public async Task A_transaction_whose_disposal_throws_does_not_strand_the_connection() { var connection = new FakeConnection { FailOnExecuteReader = true, FailOnTransactionDispose = true }; await using var context = new RouteContext(); var producer = await Producer(context, connection, "sql:SELECT x FROM audit?dataSource=lifecycle&outputType=SelectList", "direct:sql-txdispose"); var act = () => producer.Process(new Exchange(new Message("m")), CancellationToken.None); await act.Should().ThrowAsync(); connection.Transaction!.Disposed.Should().BeTrue(); connection.Disposed.Should().BeTrue("each resource is released even when the one before it fails, as the streamed result does"); } [Fact] public async Task A_connection_whose_transaction_never_started_is_still_returned() { var connection = new FakeConnection { FailOnBeginTransaction = true }; await using var context = new RouteContext(); var producer = await Producer(context, connection, "sql:INSERT INTO audit (x) VALUES (1)?dataSource=lifecycle&outputType=None", "direct:sql-txfail"); var act = () => producer.Process(new Exchange(new Message("m"))); (await act.Should().ThrowAsync()).WithMessage("*socket died*"); connection.Disposed.Should().BeTrue( "a throw from BeginTransactionAsync (dropped socket, cancellation) must not strand the connection"); } [Fact] public async Task A_stream_that_never_received_ownership_does_not_keep_the_connection() { // StreamList hands connection, command and transaction to the stream — but only once the // reader opened. An error before that handoff must be cleaned up by the producer itself: // skipping disposal because the OPTION says StreamList leaks all three on any such error. var connection = new FakeConnection { FailOnExecuteReader = true }; await using var context = new RouteContext(); var producer = await Producer(context, connection, "sql:SELECT * FROM orders?dataSource=lifecycle&outputType=StreamList", "direct:sql-streamfail"); var act = () => producer.Process(new Exchange(new Message("m"))); await act.Should().ThrowAsync(); connection.Disposed.Should().BeTrue("ownership never reached the stream, so the producer still owns the cleanup"); connection.Transaction!.Disposed.Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProducerReadOnlyRoutingTests.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/SqlProducerReadOnlyRoutingTests.cs ---- using System.Data.Common; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// The read-only hint decides whether a data source with a replica hands out the replica connection. Only the endpoint's /// author knows that a statement does not write — a SELECT can call a function that writes, take a lock or advance a /// sequence — so the hint is the explicit readOnly=true option, never a guess from the SQL text or the output type. /// public sealed class SqlProducerReadOnlyRoutingTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlProducerReadOnlyRoutingTests() { _db.Execute("CREATE TABLE ro_items (id INTEGER PRIMARY KEY AUTOINCREMENT, val TEXT)"); _db.Execute("INSERT INTO ro_items (val) VALUES ('a')"); } public void Dispose() => _db.Dispose(); // ── Execute ───────────────────────────────────────────────────── [Fact] public async Task Execute_InsertReturningScalar_UsesPrimaryConnection() { var factory = new ReadOnlyRecordingFactory(_db); await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, "INSERT INTO ro_items (val) VALUES (:#val) RETURNING id", new() { ["outputType"] = "Scalar" }); var exchange = new Exchange(new Message()); exchange.In.Headers["val"] = "x"; await endpoint.CreateProducer().Process(exchange, CancellationToken.None); Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM ro_items")).Should().Be(2); factory.ReadOnlyRequests.Should().Equal(new[] { false }, "an INSERT must not be routed to a read replica"); } [Fact] public async Task Execute_SelectWithoutReadOnly_UsesPrimary() { var factory = await ProduceAsync("SELECT id, val FROM ro_items", new() { ["outputType"] = "SelectList" }); factory.ReadOnlyRequests.Should().Equal(new[] { false }, "a replica is used only when the endpoint declares readOnly=true"); } [Fact] public async Task Execute_ReadOnlyTrue_UsesReplica() { var factory = await ProduceAsync("SELECT COUNT(*) FROM ro_items", new() { ["outputType"] = "Scalar", ["readOnly"] = "true" }); factory.ReadOnlyRequests.Should().Equal(true); } [Fact] public async Task Execute_ReadOnlyTrue_DecidesWhateverTheOutputType() { var factory = await ProduceAsync("SELECT COUNT(*) FROM ro_items", new() { ["outputType"] = "None", ["readOnly"] = "true" }); factory.ReadOnlyRequests.Should().Equal(new[] { true }, "the option, not the output type, picks the replica"); } // ── Procedure ─────────────────────────────────────────────────── [Fact] public async Task Procedure_ReadOnlyTrue_UsesReplica() { var factory = await ProduceAsync("ro_fn", new() { ["mode"] = "Procedure", ["asFunction"] = "true", ["readOnly"] = "true" }); factory.ReadOnlyRequests.Should().Equal(new[] { true }, "a procedure the author declares read-only may run on the replica"); } [Fact] public async Task Procedure_Default_UsesPrimary() { var factory = await ProduceAsync("ro_fn", new() { ["mode"] = "Procedure", ["asFunction"] = "true" }); factory.ReadOnlyRequests.Should().Equal(false); } // ── Poll ──────────────────────────────────────────────────────── [Fact] public async Task Poll_Default_UsesPrimary() { var factory = await PollAsync(new()); factory.ReadOnlyRequests.Should().Equal(new[] { false }, "a poll reads from the replica only with readOnly=true"); } [Fact] public async Task Poll_ReadOnlyTrue_UsesReplica() { var factory = await PollAsync(new() { ["readOnly"] = "true" }); factory.ReadOnlyRequests.Should().Equal(true); } // ── Helpers ───────────────────────────────────────────────────── private async Task ProduceAsync(string sql, Dictionary parameters) { var factory = new ReadOnlyRecordingFactory(_db); await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, sql, parameters); var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message()), CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); return factory; } private async Task PollAsync(Dictionary extra) { var factory = new ReadOnlyRecordingFactory(_db); await using var context = new RouteContext(); var parameters = new Dictionary { ["mode"] = "Poll", ["repeatCount"] = "1" }; foreach (var (key, value) in extra) parameters[key] = value; var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, "SELECT id, val FROM ro_items", parameters); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(Task.CompletedTask); var thrown = await Outcome.Of(() => ((SqlConsumer)endpoint.CreateConsumer(processor)).Poll(CancellationToken.None)); thrown.Should().BeNull(Outcome.Describe(thrown)); return factory; } /// Records the read-only hint of every request; connections have the function ro_fn(). private sealed class ReadOnlyRecordingFactory(SqliteTestHelper db) : ISqlConnectionFactory { public List ReadOnlyRequests { get; } = []; public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) { ReadOnlyRequests.Add(readOnly); var connection = db.CreateConnection(); connection.CreateFunction("ro_fn", () => 1L); return Task.FromResult(connection); } } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProducerStreamListLifetimeTests.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/SqlProducerStreamListLifetimeTests.cs ---- using System.Data; using System.Data.Common; using System.Transactions; using Microsoft.Data.Sqlite; using redb.Route.Components; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Tests.Sql.E2E.Infrastructure; using ConnectionState = System.Data.ConnectionState; namespace redb.Route.Tests.Sql; /// /// A streamed result (outputType=StreamList) holds a reader, its command, a transaction and a connection past the /// endpoint. As in Apache Camel, they are released when the exchange ends, whether or not the route read the stream and /// whatever became of the body; the stream reads once; inside a route transaction it is refused, because the transaction /// cannot commit while the reader is open. /// public sealed class SqlProducerStreamListLifetimeTests : IDisposable { private const string Select = "SELECT id, val FROM stream_items ORDER BY id"; private readonly SqliteTestHelper _db = new(); public SqlProducerStreamListLifetimeTests() { _db.Execute("CREATE TABLE stream_items (id INTEGER NOT NULL, val TEXT NOT NULL)"); _db.Execute("INSERT INTO stream_items (id, val) VALUES (1, 'a'), (2, 'b'), (3, 'c')"); } public void Dispose() => _db.Dispose(); [Fact] public async Task StreamList_NotConsumed_ExchangeDisposed_ConnectionClosed() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); factory.Open.Should().Be(1, "the stream keeps its connection while the route runs"); await exchange.DisposeAsync(); factory.Open.Should().Be(0, "the exchange ended: the stream nobody read releases its connection"); } [Fact] public async Task StreamList_CopyOfTheExchangeDisposed_TheStreamStaysWithTheOriginal() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); // WireTap, RecipientList, Enrich, Threads: a copy shares the body and is disposed when its own work is done. var copy = exchange.CloneLinked(); copy.In.Body.Should().BeSameAs(exchange.In.Body); await copy.DisposeAsync(); factory.Open.Should().Be(1, "the stream belongs to the exchange that registered it, not to a copy that shares the body"); var ids = new List(); await foreach (var row in (IAsyncEnumerable>)exchange.In.Body!) ids.Add(row["id"]); ids.Should().Equal(1L, 2L, 3L); await exchange.DisposeAsync(); factory.Open.Should().Be(0); } [Fact] public async Task StreamList_BodyReplaced_ExchangeDisposed_ConnectionClosed() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); exchange.In.Body = "replaced by a later step"; await exchange.DisposeAsync(); factory.Open.Should().Be(0, "release is tied to the exchange, not to whatever is the body when it ends"); } [Fact] public async Task StreamList_InOutputHeader_ExchangeDisposed_ConnectionClosed() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory, new() { ["outputHeader"] = "rows" }); exchange.In.Headers["rows"].Should().NotBeNull(); await exchange.DisposeAsync(); factory.Open.Should().Be(0); } [Fact] public async Task StreamList_FullyConsumed_ConnectionClosedAtEndOfStream() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); var ids = new List(); await foreach (var row in (IAsyncEnumerable>)exchange.In.Body!) ids.Add(row["id"]); ids.Should().Equal(1L, 2L, 3L); factory.Open.Should().Be(0, "reading to the end releases the connection at once"); await exchange.DisposeAsync(); factory.Open.Should().Be(0); } [Fact] public async Task StreamList_EarlyExit_ConnectionClosed() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); await foreach (var _ in (IAsyncEnumerable>)exchange.In.Body!) break; factory.Open.Should().Be(0, "leaving the loop disposes the enumerator, which releases the connection"); await exchange.DisposeAsync(); } [Fact] public async Task StreamList_ReadTwice_SecondReadFails() { var factory = new TrackingFactory(_db.ConnectionString); var exchange = await ProduceAsync(factory); var stream = (IAsyncEnumerable>)exchange.In.Body!; await foreach (var _ in stream) { } var thrown = await Outcome.Of(async () => { await foreach (var _ in stream) { } }); thrown.Should().BeOfType(Outcome.Describe(thrown)) .Which.Message.Should().Contain("once"); await exchange.DisposeAsync(); } [Fact] public async Task StreamList_InsideTransactionScope_RefusedBeforeOpeningConnection() { var factory = new TrackingFactory(_db.ConnectionString); Exception? thrown; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { thrown = await Outcome.Of(() => ProduceAsync(factory)); } thrown.Should().BeOfType(Outcome.Describe(thrown)) .Which.Message.Should().Contain("StreamList"); factory.Requests.Should().Be(0, "the refusal comes before any connection is opened"); } // ── ProducerTemplate: the request ends the exchange that owns the stream ── [Fact] public async Task StreamList_RequestBody_IsRefusedAtTheCall_AndTheConnectionIsReturned() { var factory = new TrackingFactory(_db.ConnectionString); await using var context = await StartStreamRouteAsync(factory, "direct:stream-body"); var template = new ProducerTemplate(context); template.Start(); try { var thrown = await Outcome.Of(() => template.RequestBody("direct:stream-body", "go")); thrown.Should().BeOfType( "RequestBody ends the exchange before it returns, and the stream reads from that exchange's connection: " + Outcome.Describe(thrown)) .Which.Message.Should().Contain("RequestAsync", "the message points to the call that keeps the exchange open"); factory.Open.Should().Be(0, "the refused reply's exchange was still released, with the connection behind the stream"); } finally { template.Stop(); } } [Fact] public async Task StreamList_RequestAsync_ReadThenDispose_ReadsEveryRow() { var factory = new TrackingFactory(_db.ConnectionString); await using var context = await StartStreamRouteAsync(factory, "direct:stream-async"); var template = new ProducerTemplate(context); template.Start(); try { var ids = new List(); await using (var exchange = await template.RequestAsync("direct:stream-async", new Exchange(new Message("go")))) { var body = exchange.Out?.Body ?? exchange.In.Body; await foreach (var row in (IAsyncEnumerable>)body!) ids.Add(row["id"]); } ids.Should().Equal(1L, 2L, 3L); factory.Open.Should().Be(0); } finally { template.Stop(); } } private static async Task StartStreamRouteAsync(TrackingFactory factory, string from) { var context = new RouteContext(); context.AddComponent(new DirectComponent()); context.AddComponent(new SqlComponent()); context.AddToRegistry("stream-db", (ISqlConnectionFactory)factory); context.AddRoutes(r => r.From(from).To($"sql:{Select}?dataSource=stream-db&outputType=StreamList")); await context.Start(); return context; } private async Task ProduceAsync(TrackingFactory factory, Dictionary? extra = null) { var parameters = new Dictionary { ["outputType"] = "StreamList" }; if (extra is not null) foreach (var (key, value) in extra) parameters[key] = value; var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, factory, Select, parameters); var exchange = new Exchange(new Message("go")); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); return exchange; } /// SQLite connections that count requests and the connections still open. private sealed class TrackingFactory(string connectionString) : ISqlConnectionFactory { private int _open; public int Requests { get; private set; } public int Open => Volatile.Read(ref _open); public async Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) { Requests++; var connection = new SqliteConnection(connectionString); await connection.OpenAsync(ct); Interlocked.Increment(ref _open); connection.StateChange += (_, change) => { if (change.OriginalState == ConnectionState.Open && change.CurrentState == ConnectionState.Closed) Interlocked.Decrement(ref _open); }; return connection; } } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlProducerTests.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/SqlProducerTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; namespace redb.Route.Tests.Sql; /// /// Integration tests for SqlProducer using an in-memory SQLite database. /// Tests all 5 OutputType branches plus parameter binding, transactions, noop, and headers. /// public class SqlProducerTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlProducerTests() { _db.Execute(""" CREATE TABLE products ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL NOT NULL ) """); _db.Execute("INSERT INTO products(name, price) VALUES('Widget', 9.99)"); _db.Execute("INSERT INTO products(name, price) VALUES('Gadget', 19.99)"); _db.Execute("INSERT INTO products(name, price) VALUES('Doohickey', 4.50)"); } private SqlEndpoint CreateEndpoint(string sql, Dictionary? extraParams = null) { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var parameters = new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main" }; if (extraParams != null) foreach (var kv in extraParams) parameters[kv.Key] = kv.Value; var uri = new EndpointUri("sql", sql, $"sql:{sql}", parameters); return (SqlEndpoint)component.CreateEndpoint(uri); } private static Exchange CreateExchange(object? body = null, Dictionary? headers = null) { var ex = new Exchange(new Message(body)); if (headers != null) foreach (var kv in headers) ex.In.Headers[kv.Key] = kv.Value; return ex; } // ── OutputType: SelectList ────────────────────────────────────── [Fact] public async Task SelectList_ReturnsAllRows() { var endpoint = CreateEndpoint("SELECT * FROM products ORDER BY id", new() { ["outputType"] = "SelectList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var rows = exchange.In.Body as List>; rows.Should().NotBeNull(); rows.Should().HaveCount(3); rows![0]["name"].Should().Be("Widget"); rows[2]["name"].Should().Be("Doohickey"); } [Fact] public async Task SelectList_SetsRowCountHeader() { var endpoint = CreateEndpoint("SELECT * FROM products", new() { ["outputType"] = "SelectList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(3); } [Fact] public async Task SelectList_EmptyResult_ReturnsEmptyList() { var endpoint = CreateEndpoint("SELECT * FROM products WHERE id = -1", new() { ["outputType"] = "SelectList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var rows = exchange.In.Body as List>; rows.Should().NotBeNull(); rows.Should().BeEmpty(); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(0); } // ── OutputType: SelectOne ─────────────────────────────────────── [Fact] public async Task SelectOne_ReturnsSingleRow() { var endpoint = CreateEndpoint("SELECT * FROM products WHERE id = 1", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("Widget"); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(1); } [Fact] public async Task SelectOne_NoResult_ReturnsNull() { var endpoint = CreateEndpoint("SELECT * FROM products WHERE id = -1", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().BeNull(); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(0); } // ── OutputType: Scalar ────────────────────────────────────────── [Fact] public async Task Scalar_ReturnsCount() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM products", new() { ["outputType"] = "Scalar" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); // SQLite returns long Convert.ToInt32(exchange.In.Body).Should().Be(3); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(1); } [Fact] public async Task Scalar_NullResult_ReturnsNull() { _db.Execute("DELETE FROM products"); var endpoint = CreateEndpoint("SELECT name FROM products WHERE id = 1", new() { ["outputType"] = "Scalar" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().BeNull(); } // ── OutputType: StreamList ────────────────────────────────────── [Fact] public async Task StreamList_ReturnsAllRows() { var endpoint = CreateEndpoint("SELECT * FROM products ORDER BY id", new() { ["outputType"] = "StreamList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().BeAssignableTo>>(); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(-1); var stream = (IAsyncEnumerable>)exchange.In.Body!; var rows = new List>(); await foreach (var row in stream) rows.Add(row); rows.Should().HaveCount(3); } // ── OutputType: None (NonQuery) ───────────────────────────────── [Fact] public async Task None_Insert_ReturnsAffectedRows() { var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES('Thingamajig', 2.99)", new() { ["outputType"] = "None" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(1); } [Fact] public async Task None_Update_ReturnsAffectedRows() { var endpoint = CreateEndpoint( "UPDATE products SET price = 0.01 WHERE price > 5", new() { ["outputType"] = "None" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); // Widget (9.99) and Gadget (19.99) → 2 rows updated exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(2); } [Fact] public async Task None_Delete_ReturnsAffectedRows() { var endpoint = CreateEndpoint( "DELETE FROM products WHERE id = 1", new() { ["outputType"] = "None" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(1); _db.Query("SELECT * FROM products").Should().HaveCount(2); } // ── Parameter binding ─────────────────────────────────────────── [Fact] public async Task BindParameters_FromHeaders() { var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#name", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["name"] = "Gadget" }); await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("Gadget"); } [Fact] public async Task BindParameters_FromBodyDictionary() { var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#name", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var body = new Dictionary { ["name"] = "Doohickey" }; var exchange = CreateExchange(body: body); await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("Doohickey"); } [Fact] public async Task BindParameters_HeaderTakesPriority() { var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#name", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var body = new Dictionary { ["name"] = "Doohickey" }; var exchange = CreateExchange(body: body, headers: new() { ["name"] = "Widget" }); await producer.Process(exchange, CancellationToken.None); // Header wins over body var row = exchange.In.Body as Dictionary; row!["name"].Should().Be("Widget"); } [Fact] public async Task BindParameters_MissingParam_FailsWithParameterName() { var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#nonExistent OR 1=1 ORDER BY id LIMIT 1", new() { ["outputType"] = "SelectOne" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); var thrown = await Record.ExceptionAsync(() => producer.Process(exchange, CancellationToken.None)); // As in Apache Camel: a placeholder with no value anywhere is an error, not a silent NULL. thrown.Should().BeOfType().Which.Message.Should().Contain(":#nonExistent"); } [Fact] public async Task BindParameters_HeaderWithNullOrDbNull_BindsNull() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM products WHERE :#a IS NULL AND :#b IS NULL", new() { ["outputType"] = "Scalar" }); var exchange = CreateExchange(headers: new() { ["a"] = null, ["b"] = DBNull.Value }); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); Convert.ToInt64(exchange.In.Body).Should().Be(3, "a header that is present binds its value, null included"); } [Fact] public async Task BindParameters_BodyKeyWithNullValue_BindsNull() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM products WHERE :#a IS NULL", new() { ["outputType"] = "Scalar" }); var exchange = CreateExchange(new Dictionary { ["a"] = null }); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); Convert.ToInt64(exchange.In.Body).Should().Be(3); } [Fact] public async Task BindParameters_ExplicitExpressionEvaluatingToNull_BindsNull() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM products WHERE :#a IS NULL", new() { ["outputType"] = "Scalar", ["param.a"] = "${header.missing}" }); var exchange = CreateExchange(); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); Convert.ToInt64(exchange.In.Body).Should().Be(3, "an explicit param.* always has a value, even when it evaluates to null"); } [Fact] public async Task BindParameters_JsonElementHeaders_BindScalars() { var endpoint = CreateEndpoint("INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None" }); var exchange = CreateExchange(headers: new() { ["name"] = System.Text.Json.JsonDocument.Parse("\"Json\"").RootElement.Clone(), ["price"] = System.Text.Json.JsonDocument.Parse("12.5").RootElement.Clone(), }); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'Json'").Should().Be(12.5); } // ── Map-like bodies: as in Apache Camel, a body that converts to a Map (Jackson JsonNode included) binds by key ── [Fact] public async Task BindParameters_JsonElementObjectBody_BindsByKey() { using var document = System.Text.Json.JsonDocument.Parse("""{"name":"JsonElement","price":12.5}"""); await InsertProductAsync(document.RootElement.Clone()); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'JsonElement'").Should().Be(12.5); } [Fact] public async Task BindParameters_JsonDocumentBody_BindsByKey() { using var document = System.Text.Json.JsonDocument.Parse("""{"name":"JsonDocument","price":7}"""); await InsertProductAsync(document); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'JsonDocument'").Should().Be(7.0); } [Fact] public async Task BindParameters_JsonObjectBody_BindsByKey() { var body = System.Text.Json.Nodes.JsonNode.Parse("""{"name":"JsonObject","price":3.5}""")!.AsObject(); await InsertProductAsync(body); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'JsonObject'").Should().Be(3.5); } [Fact] public async Task BindParameters_StringDictionaryBody_BindsByKey() { await InsertProductAsync(new Dictionary { ["name"] = "Csv", ["price"] = "2.5" }); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'Csv'").Should().Be(2.5); } [Fact] public async Task BindParameters_DictionaryBody_CaseInsensitiveKeyFallback() { await InsertProductAsync(new Dictionary { ["NAME"] = "Upper", ["Price"] = 1.5 }); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'Upper'").Should().Be(1.5); } [Fact] public async Task BindParameters_JsonObjectBody_NestedValueIsJsonText() { var endpoint = CreateEndpoint("SELECT :#extra", new() { ["outputType"] = "Scalar" }); using var document = System.Text.Json.JsonDocument.Parse("""{"extra":{"a":[1,2]}}"""); var exchange = CreateExchange(document.RootElement.Clone()); await endpoint.CreateProducer().Process(exchange, CancellationToken.None); exchange.In.Body.Should().Be("""{"a":[1,2]}"""); } [Fact] public async Task BindParameters_HeaderWinsOverJsonBodyKey() { using var document = System.Text.Json.JsonDocument.Parse("""{"name":"FromBody","price":4}"""); await InsertProductAsync(document.RootElement.Clone(), new() { ["name"] = "FromHeader" }); _db.ExecuteScalar("SELECT price FROM products WHERE name = 'FromHeader'").Should().Be(4.0); } [Fact] public async Task BindParameters_PocoBody_IsNotReadByProperty() { var thrown = await Record.ExceptionAsync(() => InsertProductAsync(new ProductBody { Name = "Poco", Price = 1 })); // As in Apache Camel: a POJO body does not convert to a Map, so it gives no named values. thrown.Should().BeOfType().Which.Message.Should().Contain(":#name"); } [Fact] public async Task BindParameters_JsonTextBody_IsNotReadByKey() { var thrown = await Record.ExceptionAsync(() => InsertProductAsync("""{"name":"Text","price":1}""")); // JSON text is a string, not a map: unmarshal it first. thrown.Should().BeOfType().Which.Message.Should().Contain(":#name"); } public sealed class ProductBody { public string Name { get; set; } = ""; public double Price { get; set; } } private async Task InsertProductAsync(object body, Dictionary? headers = null) { var endpoint = CreateEndpoint("INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None" }); await endpoint.CreateProducer().Process(CreateExchange(body, headers), CancellationToken.None); } // ── Common headers ────────────────────────────────────────────── [Fact] public async Task CommonHeaders_SetCorrectly() { var endpoint = CreateEndpoint("SELECT 1", new() { ["outputType"] = "Scalar" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.Query].Should().Be("SELECT 1"); exchange.In.Headers[SqlHeaders.DataSource].Should().Be("main"); exchange.In.Headers[SqlHeaders.OutputType].Should().Be("Scalar"); exchange.In.Headers.Should().ContainKey(SqlHeaders.ExecutionTime); } // ── Noop mode ─────────────────────────────────────────────────── [Fact] public async Task Noop_SetsQueryHeaderOnly() { var endpoint = CreateEndpoint("SELECT * FROM products", new() { ["outputType"] = "SelectList", ["noop"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers[SqlHeaders.Query].Should().Be("SELECT * FROM products"); // Body should NOT be set (no actual execution) exchange.In.Body.Should().BeNull(); } // ── Transacted ────────────────────────────────────────────────── [Fact] public async Task Transacted_CommitsOnSuccess() { var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES('TxProduct', 1.00)", new() { ["outputType"] = "None", ["transacted"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Headers.Should().ContainKey(SqlHeaders.TransactionId); _db.Query("SELECT * FROM products WHERE name = 'TxProduct'").Should().HaveCount(1); } // ── Error handling ────────────────────────────────────────────── [Fact] public async Task InvalidSql_Throws() { var endpoint = CreateEndpoint("INVALID SQL STATEMENT", new() { ["outputType"] = "None" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); var act = () => producer.Process(exchange, CancellationToken.None); await act.Should().ThrowAsync(); } [Fact] public void NoDataSourceAndNoConnectionString_Throws() { var component = new SqlComponent(); var uri = new EndpointUri("sql", "SELECT 1", "sql:SELECT 1", new Dictionary { ["mode"] = "Execute" }); var act = () => component.CreateEndpoint(uri); act.Should().Throw(); } // ── Multiple queries in sequence ──────────────────────────────── [Fact] public async Task MultipleExecutions_IndependentState() { var endpoint = CreateEndpoint("SELECT COUNT(*) FROM products", new() { ["outputType"] = "Scalar" }); var producer = endpoint.CreateProducer(); var ex1 = CreateExchange(); await producer.Process(ex1, CancellationToken.None); Convert.ToInt32(ex1.In.Body).Should().Be(3); // Insert a row via another producer var insertEndpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES('NewItem', 5.00)", new() { ["outputType"] = "None" }); var insertProducer = insertEndpoint.CreateProducer(); await insertProducer.Process(CreateExchange(), CancellationToken.None); // Count should now be 4 var ex2 = CreateExchange(); await producer.Process(ex2, CancellationToken.None); Convert.ToInt32(ex2.In.Body).Should().Be(4); } // ── Explicit Parameters (.Param) ──────────────────────────────── [Fact] public async Task ExplicitParam_ConstantValue_OverridesHeader() { // :#name is bound to explicit "Widget" even though header has "Gadget" var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#name", new() { ["outputType"] = "SelectOne", ["param.name"] = "Widget" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["name"] = "Gadget" }); await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("Widget"); } [Fact] public async Task ExplicitParam_ConstantValue_OverridesBody() { var endpoint = CreateEndpoint( "SELECT * FROM products WHERE name = :#name", new() { ["outputType"] = "SelectOne", ["param.name"] = "Doohickey" }); var producer = endpoint.CreateProducer(); var body = new Dictionary { ["name"] = "Widget" }; var exchange = CreateExchange(body: body); await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("Doohickey"); } [Fact] public async Task ExplicitParam_MixedWithAutoBindHeaders() { // :#name explicit, :#price from header _db.Execute("CREATE TABLE filtered (id INTEGER PRIMARY KEY, name TEXT, price REAL)"); _db.Execute("INSERT INTO filtered(name, price) VALUES('A', 10)"); _db.Execute("INSERT INTO filtered(name, price) VALUES('A', 20)"); _db.Execute("INSERT INTO filtered(name, price) VALUES('B', 10)"); var endpoint = CreateEndpoint( "SELECT * FROM filtered WHERE name = :#name AND price = :#price", new() { ["outputType"] = "SelectOne", ["param.name"] = "A" // explicit constant }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["price"] = 20 }); // auto-bind from header await producer.Process(exchange, CancellationToken.None); var row = exchange.In.Body as Dictionary; row.Should().NotBeNull(); row!["name"].Should().Be("A"); Convert.ToDouble(row["price"]).Should().Be(20); } [Fact] public async Task ExplicitParam_InsertWithConstants() { var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None", ["param.name"] = "ExplicitItem", ["param.price"] = "7.77" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var count = Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM products WHERE name = 'ExplicitItem'")); count.Should().Be(1); } [Fact] public async Task ExplicitParam_EmptyValue_BindsAsDBNull() { _db.Execute("CREATE TABLE notes (id INTEGER PRIMARY KEY, text TEXT)"); var endpoint = CreateEndpoint( "INSERT INTO notes(text) VALUES(:#text)", new() { ["outputType"] = "None", ["param.text"] = "" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["text"] = "should be ignored" }); await producer.Process(exchange, CancellationToken.None); // Empty explicit param → DBNull → NULL in DB var result = _db.ExecuteScalar("SELECT text FROM notes LIMIT 1"); result.Should().Be(DBNull.Value); } [Fact] public async Task ExplicitParam_SingleExpression_PreservesType() { _db.Execute("CREATE TABLE typed_test (tag TEXT, num INTEGER)"); var endpoint = CreateEndpoint( "INSERT INTO typed_test(tag, num) VALUES(:#tag, :#num)", new() { ["outputType"] = "None", ["param.tag"] = "${header.tag}", ["param.num"] = "${header.num}" }); var producer = endpoint.CreateProducer(); // header.num is int 42in — single expression should preserve the type var exchange = CreateExchange(headers: new() { ["tag"] = "hello", ["num"] = 42 }); await producer.Process(exchange, CancellationToken.None); var tagResult = _db.ExecuteScalar("SELECT tag FROM typed_test LIMIT 1"); tagResult.Should().Be("hello"); var numResult = _db.ExecuteScalar("SELECT num FROM typed_test LIMIT 1"); Convert.ToInt32(numResult).Should().Be(42); } [Fact] public async Task ExplicitParam_CompositeTemplate_ReturnsString() { _db.Execute("CREATE TABLE composite_test (label TEXT)"); var endpoint = CreateEndpoint( "INSERT INTO composite_test(label) VALUES(:#label)", new() { ["outputType"] = "None", ["param.label"] = "prefix-${header.tag}-suffix" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(headers: new() { ["tag"] = "mid" }); await producer.Process(exchange, CancellationToken.None); var result = _db.ExecuteScalar("SELECT label FROM composite_test LIMIT 1"); result.Should().Be("prefix-mid-suffix"); } // ── Batch Mode ────────────────────────────────────────────────── [Fact] public async Task Batch_InsertsAllItems() { var items = new List> { new() { ["name"] = "Batch1", ["price"] = 1.0 }, new() { ["name"] = "Batch2", ["price"] = 2.0 }, new() { ["name"] = "Batch3", ["price"] = 3.0 }, }; var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None", ["batchSize"] = "10" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: items); await producer.Process(exchange, CancellationToken.None); var count = Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM products")); count.Should().Be(6); // 3 original + 3 batch exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(3); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(3); } [Fact] public async Task Batch_Transacted_CommitsAll() { var items = new List> { new() { ["name"] = "TX1", ["price"] = 1.0 }, new() { ["name"] = "TX2", ["price"] = 2.0 }, }; var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None", ["batchSize"] = "10", ["transacted"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: items); await producer.Process(exchange, CancellationToken.None); var count = Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM products WHERE name IN ('TX1','TX2')")); count.Should().Be(2); exchange.In.Headers.Should().ContainKey(SqlHeaders.TransactionId); } [Fact] public async Task Batch_BreakOnError_StopsAndRollsBack() { // products has NOT NULL on name, so inserting null fails var items = new List> { new() { ["name"] = "Good1", ["price"] = 1.0 }, new() { ["name"] = DBNull.Value, ["price"] = 2.0 }, // fails NOT NULL new() { ["name"] = "Good2", ["price"] = 3.0 }, }; var endpoint = CreateEndpoint( "INSERT INTO products(name, price) VALUES(:#name, :#price)", new() { ["outputType"] = "None", ["batchSize"] = "10", ["breakBatchOnError"] = "true", ["transacted"] = "true" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: items); // The provider's exception as is, as in Camel (Record.ExceptionAsync does not look inside an AggregateException). var thrown = await Record.ExceptionAsync(() => producer.Process(exchange, CancellationToken.None)); thrown.Should().BeOfType(); // Transaction rolled back — Good1 should NOT be persisted var count = Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM products WHERE name = 'Good1'")); count.Should().Be(0); } [Fact] public async Task Batch_ContinueOnError_ProcessesRemaining() { _db.Execute("CREATE TABLE batch_test (id INTEGER PRIMARY KEY, val TEXT NOT NULL)"); var items = new List> { new() { ["id"] = 1, ["val"] = "ok1" }, new() { ["id"] = 1, ["val"] = "duplicate PK" }, // fails new() { ["id"] = 3, ["val"] = "ok3" }, }; var endpoint = CreateEndpoint( "INSERT INTO batch_test(id, val) VALUES(:#id, :#val)", new() { ["outputType"] = "None", ["batchSize"] = "10", ["breakBatchOnError"] = "false" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(body: items); await producer.Process(exchange, CancellationToken.None); // 2 of 3 succeeded, 1 error Convert.ToInt32(exchange.In.Headers[SqlHeaders.RowCount]).Should().Be(2); exchange.In.Headers[SqlHeaders.Error]!.ToString().Should().Contain("1 batch error"); var count = Convert.ToInt64(_db.ExecuteScalar("SELECT COUNT(*) FROM batch_test")); count.Should().Be(2); } [Fact] public async Task Batch_EmptyListWithSelect_ExecutesNothing() { var endpoint = CreateEndpoint( "SELECT COUNT(*) FROM products", new() { ["outputType"] = "Scalar", ["batchSize"] = "10" }); var producer = endpoint.CreateProducer(); var empty = new List>(); var exchange = CreateExchange(body: empty); await producer.Process(exchange, CancellationToken.None); // An empty batch source runs no statement, as Camel's empty executeBatch() reports zero updates. exchange.In.Body.Should().BeSameAs(empty); exchange.In.Headers[SqlHeaders.UpdateCount].Should().Be(0); exchange.In.Headers["redbSql.batchStrategy"].Should().Be("None"); } // ── StreamList OutputType ─────────────────────────────────────── [Fact] public async Task StreamList_ReturnsIAsyncEnumerable() { var endpoint = CreateEndpoint("SELECT * FROM products ORDER BY id", new() { ["outputType"] = "StreamList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); exchange.In.Body.Should().BeAssignableTo>>(); exchange.In.Headers[SqlHeaders.RowCount].Should().Be(-1); // unknown until iterated } [Fact] public async Task StreamList_CanIterateAllRows() { var endpoint = CreateEndpoint("SELECT name FROM products ORDER BY id", new() { ["outputType"] = "StreamList" }); var producer = endpoint.CreateProducer(); var exchange = CreateExchange(); await producer.Process(exchange, CancellationToken.None); var stream = (IAsyncEnumerable>)exchange.In.Body!; var names = new List(); await foreach (var row in stream) names.Add((string)row["name"]!); names.Should().BeEquivalentTo(["Widget", "Gadget", "Doohickey"]); } // ── Transacted Rollback ───────────────────────────────────────── [Fact] public async Task Transacted_RollsBackOnError() { // Create a table to verify rollback _db.Execute("CREATE TABLE tx_test (id INTEGER PRIMARY KEY, val TEXT)"); var endpoint = CreateEndpoint( "INSERT INTO tx_test(id, val) VALUES(1, 'should-rollback')", new() { ["outputType"] = "None", ["transacted"] = "true" }); // Simulate error: use a query that succeeds for insert but the producer // encounters an error in the commit flow. Instead, we inject error via bad SQL in // a second step. Let's use a dual-query scenario: // Actually, simplest: execute valid INSERT, then throw from the test. // But we can't intercept. Better approach: force SQL error after insert // by using a constraint violation in the same command. // Simplest test: invalid SQL should throw and rollback. var badEndpoint = CreateEndpoint( "INSERT INTO tx_test(id, val) VALUES(1, 'a'); INSERT INTO tx_test(id, val) VALUES(1, 'b')", new() { ["outputType"] = "None", ["transacted"] = "true" }); var producer = badEndpoint.CreateProducer(); var exchange = CreateExchange(); // SQLite handles multi-statement differently; let's use a simpler approach // First insert succeeds, second with same PK fails var firstEndpoint = CreateEndpoint( "INSERT INTO tx_test(id, val) VALUES(1, 'first')", new() { ["outputType"] = "None", ["transacted"] = "false" }); var p1 = firstEndpoint.CreateProducer(); await p1.Process(CreateExchange(), CancellationToken.None); // Now try to insert duplicate with transaction var dupeEndpoint = CreateEndpoint( "INSERT INTO tx_test(id, val) VALUES(1, 'duplicate')", new() { ["outputType"] = "None", ["transacted"] = "true" }); var p2 = dupeEndpoint.CreateProducer(); var act = () => p2.Process(CreateExchange(), CancellationToken.None); await act.Should().ThrowAsync(); // Original row should still be there (duplicate was rolled back) var rows = _db.Query("SELECT val FROM tx_test"); rows.Should().HaveCount(1); rows[0]["val"].Should().Be("first"); } [Fact] public async Task Transacted_CommitsOnSuccess_InsertVisible() { _db.Execute("CREATE TABLE tx_success (id INTEGER PRIMARY KEY, val TEXT)"); var endpoint = CreateEndpoint( "INSERT INTO tx_success(id, val) VALUES(1, 'committed')", new() { ["outputType"] = "None", ["transacted"] = "true" }); var producer = endpoint.CreateProducer(); await producer.Process(CreateExchange(), CancellationToken.None); var rows = _db.Query("SELECT val FROM tx_success"); rows.Should().HaveCount(1); rows[0]["val"].Should().Be("committed"); } public void Dispose() => _db.Dispose(); } Path: redb-route/tests/redb.Route.Tests.Sql/SqlTelemetrySmokeTests.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/SqlTelemetrySmokeTests.cs ---- using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Trace; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Telemetry; namespace redb.Route.Tests.Sql; /// Smoke test for the P1 transport span opened by . /// /// The in-memory exporter listens to the process-wide route activity source, so spans of SQL producers in tests running /// in parallel land in the same list. Each test therefore gives its endpoint a unique marker and picks its span by the /// redb.route.endpoint tag — never by position — and stops the tracer before reading the list. /// public sealed class SqlTelemetrySmokeTests : IDisposable { private readonly SqliteTestHelper _db = new(); public SqlTelemetrySmokeTests() { _db.Execute("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)"); _db.Execute("INSERT INTO t(v) VALUES('a')"); } public void Dispose() => _db.Dispose(); [Fact] public async Task SqlProducer_EmitsTransportSpanWithDbSystemTag() { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var marker = $"telemetry-{Guid.NewGuid():N}"; var sql = $"SELECT * FROM t /* {marker} */"; var pars = new Dictionary { ["mode"] = "Execute", ["dataSource"] = "main", ["outputType"] = "SelectList" }; var uri = new EndpointUri("sql", sql, $"sql:{sql}", pars); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); var activities = new List(); using var tracer = Sdk.CreateTracerProviderBuilder() .AddSource(RouteActivitySource.SourceName) .AddInMemoryExporter(activities) .Build()!; var exchange = new Exchange(new Message(null)); await producer.Process(exchange, CancellationToken.None); tracer.ForceFlush(1000); tracer.Dispose(); var activity = activities.Should().ContainSingle(a => HasMarker(a, marker)).Which; activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.Kind.Should().Be(ActivityKind.Client); activity.GetTagItem("db.system").Should().NotBeNull(); activity.DisplayName.Should().Be("sql.execute"); } [Fact] public async Task SqlProcedureProducer_EmitsTransportSpanWithProcedureDestination() { var context = new RouteContext(); var component = new SqlComponent(); context.AddComponent(component); context.AddToRegistry("main", _db.CreateFactory()); var procName = $"sp_smoke_{Guid.NewGuid():N}"; var pars = new Dictionary { ["mode"] = "Procedure", ["dataSource"] = "main", ["procedureName"] = procName, ["noop"] = "true" }; var uri = new EndpointUri("sql", procName, $"sql:{procName}", pars); var endpoint = (SqlEndpoint)component.CreateEndpoint(uri); var producer = endpoint.CreateProducer(); var activities = new List(); using var tracer = Sdk.CreateTracerProviderBuilder() .AddSource(RouteActivitySource.SourceName) .AddInMemoryExporter(activities) .Build()!; await producer.Process(new Exchange(new Message(null)), CancellationToken.None); tracer.ForceFlush(1000); tracer.Dispose(); var activity = activities.Should().ContainSingle(a => HasMarker(a, procName)).Which; activity.Source.Name.Should().Be(RouteActivitySource.SourceName); activity.Kind.Should().Be(ActivityKind.Client); activity.DisplayName.Should().Be("sql.procedure"); activity.GetTagItem("db.system").Should().NotBeNull(); activity.GetTagItem("messaging.destination.name").Should().Be(procName); } 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/SqlTraceTests.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/SqlTraceTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Telemetry; using redb.Route.Tests.Sql.E2E.Infrastructure; using redb.Route.Tests.Telemetry; namespace redb.Route.Tests.Sql; /// /// A polled row carries no trace context: the consumer opens a root span per routed exchange — a row, or the list of a /// batch — never a child of the activity the poll runs under, and none for an empty poll. A failed route marks it red, /// our own stop does not; the producers mark a failed statement red. EnableTelemetry=false opens none of these /// spans. Each test tags its query with a marker and reads only the spans of that endpoint. /// public sealed class SqlTraceTests : IDisposable { private readonly SqliteTestHelper _db = new(); private readonly string _marker = $"trace-{Guid.NewGuid():N}"; public SqlTraceTests() { _db.Execute("CREATE TABLE outbox (id INTEGER NOT NULL, message TEXT NOT NULL)"); } public void Dispose() => _db.Dispose(); private string Query => $"SELECT id, message FROM outbox /* {_marker} */"; private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_marker, StringComparison.Ordinal) == true); private void Rows(int count) { for (var i = 1; i <= count; i++) _db.Execute($"INSERT INTO outbox (id, message) VALUES ({i}, 'm{i}')"); } private static IProcessor Route(Func? step = null) { var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => step?.Invoke(ci.Arg(), ci.Arg()) ?? Task.CompletedTask); return processor; } private async Task Poll(IProcessor processor, Dictionary? extra = null, bool telemetry = true, CancellationToken ct = default) { await using var context = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); var parameters = new Dictionary { ["mode"] = "Poll", ["delay"] = "100", ["repeatCount"] = "1" }; foreach (var (key, value) in extra ?? []) parameters[key] = value; var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), Query, parameters); var consumer = (SqlConsumer)endpoint.CreateConsumer(processor); await consumer.Poll(ct); } [Fact] public async Task Each_row_opens_a_root_span_even_under_an_ambient_activity() { Rows(2); using var probe = Spans(ActivityKind.Consumer); using (new Activity("poll loop").SetIdFormat(ActivityIdFormat.W3C).Start()) await Poll(Route()); probe.Activities.Should().HaveCount(2, "one span per routed row"); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "a row carries no context, so its span starts a trace rather than joining the poll loop's"); probe.Activities[0].GetTagItem("db.system").Should().Be("sql"); } [Fact] public async Task A_batch_delivered_as_a_list_opens_one_span() { Rows(3); using var probe = Spans(ActivityKind.Consumer); await Poll(Route(), new() { ["pollDelivery"] = "List" }); probe.Activities.Should().ContainSingle(); } [Fact] public async Task An_empty_poll_opens_no_span() { using var probe = Spans(ActivityKind.Consumer); await Poll(Route()); probe.Activities.Should().BeEmpty(); } [Theory] [InlineData("routeEmptyResultSet")] [InlineData("sendEmptyMessageWhenIdle")] public async Task An_empty_poll_that_still_runs_the_route_opens_its_span(string option) { using var probe = Spans(ActivityKind.Consumer); var routed = 0; await Poll(Route((_, _) => { routed++; return Task.CompletedTask; }), new() { [option] = "true" }); routed.Should().Be(1, "the option routes one empty exchange"); probe.Activities.Should().ContainSingle("an exchange the route runs has its span") .Which.ParentSpanId.Should().Be(default(ActivitySpanId)); } [Fact] public async Task A_failed_route_marks_the_span_red() { Rows(1); using var probe = Spans(ActivityKind.Consumer); await Poll(Route((_, _) => throw new InvalidOperationException("route failed"))); probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Our_own_stop_does_not_mark_the_span_red() { Rows(1); using var probe = Spans(ActivityKind.Consumer); using var stop = new CancellationTokenSource(); var act = () => Poll(Route((_, _) => { stop.Cancel(); throw new OperationCanceledException(stop.Token); }), ct: stop.Token); await act.Should().ThrowAsync(); probe.Activities.Should().ContainSingle().Which.Status.Should().NotBe(ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span() { Rows(2); using var probe = new RouteTelemetryProbe(a => RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.EndpointTag)?.Contains(_marker, StringComparison.Ordinal) == true); await Poll(Route(), telemetry: false); probe.Activities.Should().BeEmpty(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task A_failed_statement_marks_the_producer_span_red_and_tracing_off_opens_none(bool telemetry) { using var probe = Spans(ActivityKind.Client); await using var context = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), $"SELECT * FROM no_such_table /* {_marker} */"); var producer = endpoint.CreateProducer(); var act = () => producer.Process(new Exchange(new Message(null)), CancellationToken.None); await act.Should().ThrowAsync(); if (telemetry) probe.Activities.Should().ContainSingle().Which.Status.Should().Be(ActivityStatusCode.Error); else probe.Activities.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqlValueMappingStrictTests.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/SqlValueMappingStrictTests.cs ---- using System.Globalization; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Sql.Mapping; using redb.Route.Tests.Sql.E2E.Infrastructure; namespace redb.Route.Tests.Sql; /// /// A column reaches a typed property only when the conversion is lossless and unambiguous; anything else fails loudly with /// the column, the property and both types — never the value — as Apache Camel's BeanPropertyRowMapper throws /// TypeMismatchException. A NULL goes into a nullable or reference property as null and is an error for a value type. /// public sealed class SqlValueMappingStrictTests : IDisposable { private readonly SqliteTestHelper _db = new(); public void Dispose() => _db.Dispose(); public enum Kind { None = 0, First = 1, Second = 2 } public sealed class Target { public int Small { get; set; } public int? MaybeSmall { get; set; } public string? Text { get; set; } = "initial"; public decimal Amount { get; set; } public bool Flag { get; set; } public Kind Kind { get; set; } public Guid Key { get; set; } public DateOnly Day { get; set; } public DateTimeOffset At { get; set; } public TimeSpan Span { get; set; } } // ── Errors instead of silent defaults ─────────────────────────── [Fact] public void Null_IntoValueTypeProperty_Throws() => AssertFails("SELECT NULL AS small", "small", "Small"); [Fact] public void Overflow_IntoInt_Throws_WithoutTheValue() { var error = AssertFails("SELECT 5000000000 AS small", "small", "Small"); error.Message.Should().NotContain("5000000000", "column values stay out of messages and logs"); } [Fact] public void NonNumericText_IntoInt_Throws() => AssertFails("SELECT 'abc' AS small", "small", "Small"); [Fact] public void FractionalReal_IntoInt_Throws() => AssertFails("SELECT 12.5 AS small", "small", "Small"); [Fact] public void IntegerOtherThanZeroOrOne_IntoBool_Throws() => AssertFails("SELECT 2 AS flag", "flag", "Flag"); [Fact] public void RealWithIntegralValue_IntoBool_Mapped() => Map("SELECT 1.0 AS flag").Flag.Should().BeTrue("a numeric column holding 0 or 1 (Oracle NUMBER(1), PostgreSQL numeric) is a Boolean, as an integer one is"); [Fact] public void RealWithIntegralValue_IntoEnum_Mapped() => Map("SELECT 2.0 AS kind").Kind.Should().Be(Kind.Second, "a numeric column holding a member's number is that member"); [Fact] public void FractionalReal_IntoBool_Throws() => AssertFails("SELECT 0.5 AS flag", "flag", "Flag"); [Fact] public void InvalidIsoText_IntoDateTimeOffset_Throws_WithoutTheValue() { var error = AssertFails("SELECT '2024-13-45T00:00:00+00:00' AS at", "at", "At"); error.Message.Should().NotContain("2024-13-45", "column values stay out of messages and logs"); } [Fact] public void UndefinedEnumValue_Throws() => AssertFails("SELECT 7 AS kind", "kind", "Kind"); [Fact] public void TextWithoutOffset_IntoDateTimeOffset_Throws() => AssertFails("SELECT '2024-01-02 03:04:05' AS at", "at", "At"); [Fact] public async Task ProducerSelectList_UnconvertibleColumn_FailsTheExchange() { _db.Execute("CREATE TABLE strict_items (id INTEGER PRIMARY KEY, small INTEGER)"); _db.Execute("INSERT INTO strict_items (id, small) VALUES (1, 5000000000)"); await using var context = new RouteContext(); var endpoint = SqlEndpointHarness.CreateEndpoint(context, _db.CreateFactory(), "SELECT small FROM strict_items", new() { ["outputType"] = "SelectList", ["outputClass"] = typeof(Target).AssemblyQualifiedName! }); var thrown = await Outcome.Of(() => endpoint.CreateProducer().Process(new Exchange(new Message()), CancellationToken.None)); thrown.Should().BeAssignableTo(Outcome.Describe(thrown)) .Which.Message.Should().Contain("small").And.Contain("Small"); } // ── Lossless conversions ──────────────────────────────────────── [Fact] public void Null_IntoNullableAndReferenceProperties_SetsNull() { var target = Map("SELECT NULL AS maybe_small, NULL AS text"); target.MaybeSmall.Should().BeNull(); target.Text.Should().BeNull("a NULL column sets the property, it does not leave the initializer's value"); } [Fact] public void EnumFromIntegerAndFromName_Mapped() { Map("SELECT 2 AS kind").Kind.Should().Be(Kind.Second); Map("SELECT 'first' AS kind").Kind.Should().Be(Kind.First); } [Fact] public void TextColumns_IntoGuidDateOnlyTimeSpan_Mapped() { var target = Map("SELECT '6f9619ff-8b86-d011-b42d-00c04fc964ff' AS key, '2024-01-02' AS day, '01:02:03' AS span"); target.Key.Should().Be(Guid.Parse("6f9619ff-8b86-d011-b42d-00c04fc964ff")); target.Day.Should().Be(new DateOnly(2024, 1, 2)); target.Span.Should().Be(new TimeSpan(1, 2, 3)); } [Fact] public void TextWithOffset_IntoDateTimeOffset_Mapped() { Map("SELECT '2024-01-02T03:04:05+03:00' AS at").At .Should().Be(new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.FromHours(3))); } [Fact] public void NumericText_ParsedWithInvariantCulture() { var previous = CultureInfo.CurrentCulture; CultureInfo.CurrentCulture = new CultureInfo("ru-RU"); try { Map("SELECT '12.5' AS amount").Amount.Should().Be(12.5m, "the database's text does not depend on the process culture"); } finally { CultureInfo.CurrentCulture = previous; } } [Fact] public void LosslessNumbers_Mapped() { var target = Map("SELECT 12.0 AS small, 12.5 AS amount, 1 AS flag"); target.Small.Should().Be(12); target.Amount.Should().Be(12.5m); target.Flag.Should().BeTrue(); } // ── ScalarMapper follows the same contract ────────────────────── [Fact] public void Scalar_NullIntoValueType_Throws() { var act = () => MapScalar(new ScalarMapper(), "SELECT NULL"); act.Should().Throw(); } [Fact] public void Scalar_NullIntoNullable_ReturnsNull() => MapScalar(new ScalarMapper(), "SELECT NULL").Should().BeNull(); [Fact] public void Scalar_Overflow_ThrowsInvalidOperation() { var act = () => MapScalar(new ScalarMapper(), "SELECT 5000000000"); act.Should().Throw(); } // ── Helpers ───────────────────────────────────────────────────── private Target Map(string select) { using var connection = _db.CreateConnection(); using var command = connection.CreateCommand(); command.CommandText = select; using var reader = command.ExecuteReader(); reader.Read().Should().BeTrue(); return new PocoRowMapper().Map(reader); } private InvalidOperationException AssertFails(string select, string column, string property) { var act = () => Map(select); var error = act.Should().Throw($"{select} must not map silently").Which; error.Message.Should().Contain(column, "the message names the column").And.Contain(property, "and the property"); return error; } private T? MapScalar(ScalarMapper mapper, string select) { using var connection = _db.CreateConnection(); using var command = connection.CreateCommand(); command.CommandText = select; using var reader = command.ExecuteReader(); reader.Read().Should().BeTrue(); return mapper.Map(reader); } } Path: redb-route/tests/redb.Route.Tests.Sql/SqliteTestHelper.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/SqliteTestHelper.cs ---- using System.Data.Common; using Microsoft.Data.Sqlite; using redb.Route.Sql.Connection; namespace redb.Route.Tests.Sql; /// /// Helper for creating in-memory SQLite connections for integration tests. /// Each instance maintains a shared in-memory database that persists until disposed. /// internal sealed class SqliteTestHelper : IDisposable { private readonly SqliteConnection _keepAlive; /// Connection string for the shared in-memory database. public string ConnectionString { get; } public SqliteTestHelper() { var dbName = $"test_{Guid.NewGuid():N}"; ConnectionString = $"Data Source={dbName};Mode=Memory;Cache=Shared"; // Keep one connection open to preserve the in-memory DB _keepAlive = new SqliteConnection(ConnectionString); _keepAlive.Open(); } /// Creates a new opened connection to the shared in-memory database. public SqliteConnection CreateConnection() { var conn = new SqliteConnection(ConnectionString); conn.Open(); return conn; } /// Executes a non-query SQL statement. public int Execute(string sql) { using var conn = CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = sql; return cmd.ExecuteNonQuery(); } /// Executes a scalar query. public object? ExecuteScalar(string sql) { using var conn = CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = sql; return cmd.ExecuteScalar(); } /// Executes a query and returns all rows as dictionaries. public List> Query(string sql) { using var conn = CreateConnection(); using var cmd = conn.CreateCommand(); cmd.CommandText = sql; using var reader = cmd.ExecuteReader(); var rows = new List>(); while (reader.Read()) { var row = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var i = 0; i < reader.FieldCount; i++) row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); rows.Add(row); } return rows; } /// Creates a connection factory pointing at this in-memory database. public ISqlConnectionFactory CreateFactory() { return new SqliteConnectionFactory(ConnectionString); } public void Dispose() { _keepAlive.Dispose(); } } /// /// Simple ISqlConnectionFactory for SQLite. Bypasses DbProviderFactories. /// internal sealed class SqliteConnectionFactory : ISqlConnectionFactory { private readonly string _connectionString; public SqliteConnectionFactory(string connectionString) => _connectionString = connectionString; public async Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) { var conn = new SqliteConnection(_connectionString); await conn.OpenAsync(ct); return conn; } } Path: redb-route/tests/redb.Route.Tests.Sql/TestDatabasesTests.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/TestDatabasesTests.cs ---- using Microsoft.Data.SqlClient; using Npgsql; using redb.Route.Tests.Shared; namespace redb.Route.Tests.Sql; /// /// REDB_TEST_PG / REDB_TEST_MSSQL move the database suites to another server (the release gate's fresh test databases) /// without touching any other part of a connection string; without them nothing changes. /// public class TestDatabasesTests { private const string Pg = "Host=pgdb;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Include Error Detail=true;Options=-c jit=off"; private const string Ms = "Server=msdb;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;"; [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Without_a_target_the_strings_come_back_unchanged(string? target) { TestDatabases.Postgres(Pg, target).Should().BeSameAs(Pg); TestDatabases.MsSql(Ms, target).Should().BeSameAs(Ms); } [Fact] public void A_postgres_target_replaces_host_and_port_only() { var moved = new NpgsqlConnectionStringBuilder(TestDatabases.Postgres(Pg, "192.0.2.9:15432")); var original = new NpgsqlConnectionStringBuilder(Pg); moved.Host.Should().Be("192.0.2.9"); moved.Port.Should().Be(15432); moved.Database.Should().Be(original.Database); moved.Username.Should().Be(original.Username); moved.Password.Should().Be(original.Password); moved.Options.Should().Be("-c jit=off"); moved.IncludeErrorDetail.Should().BeTrue(); } [Fact] public void A_postgres_target_without_a_port_uses_5432() { var moved = new NpgsqlConnectionStringBuilder(TestDatabases.Postgres("Host=localhost;Database=postgres", "pg-test")); moved.Host.Should().Be("pg-test"); moved.Port.Should().Be(5432); } [Fact] public void A_sql_server_target_replaces_the_server_only() { var moved = new SqlConnectionStringBuilder(TestDatabases.MsSql(Ms, "192.0.2.9,11433")); var original = new SqlConnectionStringBuilder(Ms); moved.DataSource.Should().Be("192.0.2.9,11433"); moved.InitialCatalog.Should().Be(original.InitialCatalog); moved.UserID.Should().Be(original.UserID); moved.Password.Should().Be(original.Password); moved.TrustServerCertificate.Should().BeTrue(); moved.CommandTimeout.Should().Be(600); } [Fact] public void A_sql_server_string_written_with_data_source_is_moved_too() { var moved = new SqlConnectionStringBuilder( TestDatabases.MsSql("Data Source=127.0.0.1,1433;Initial Catalog=tempdb;User Id=sa;Password=1", "db-test,11433")); moved.DataSource.Should().Be("db-test,11433"); moved.InitialCatalog.Should().Be("tempdb"); } [Fact] public void A_sql_server_database_replaces_the_database_only() { var moved = new SqlConnectionStringBuilder(TestDatabases.MsSql(Ms, "127.0.0.1,1433", "routegate_s1")); var original = new SqlConnectionStringBuilder(Ms); moved.DataSource.Should().Be("127.0.0.1,1433"); moved.InitialCatalog.Should().Be("routegate_s1"); moved.UserID.Should().Be(original.UserID); moved.CommandTimeout.Should().Be(600); new SqlConnectionStringBuilder( TestDatabases.MsSql("Data Source=127.0.0.1,1433;Initial Catalog=tempdb;User Id=sa;Password=1", null, "routegate_s2")) .InitialCatalog.Should().Be("routegate_s2"); } } Path: redb-route/tests/redb.Route.Tests.Sql/redb.Route.Tests.Sql.csproj 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/redb.Route.Tests.Sql.csproj ---- 7.1.1