Path: redb-route/tests/redb.Route.Tests.Core/Sql/RedbSqlDataSourceTestsBase.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.Core/Sql/RedbSqlDataSourceTestsBase.cs ---- using System.Transactions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Sql; using redb.Route.Sql; using redb.Route.Sql.Connection; using redb.Route.Sql.Repositories; namespace redb.Route.Tests.Core.Sql; /// /// dataSource=redb: a sql: step runs on the connection the exchange's redb service works on. Inside /// .Transacted() the statement and a .RedbSave() into the same database commit or roll back together on one /// connection; outside a transaction the statement commits on its own. Every count is read through a fresh scope outside /// any transaction. /// public abstract class RedbSqlDataSourceTestsBase { /// The probe table every engine creates: route_sql_lease_rows (tag). protected const string Table = "route_sql_lease_rows"; /// The name the second instance is registered under. protected const string NamedService = "orders"; /// The provider of the default redb service. protected abstract IServiceProvider Services { get; } /// The provider of the instance registered under , in a database of its own. protected abstract IServiceProvider NamedServices { get; } /// /// Whether the transaction may be checked for staying local. PostgreSQL and SQL Server enlist and would promote a /// second connection to a distributed transaction; SQLite never enlists. /// protected abstract bool ChecksDistributedTransaction { get; } private static string NewTag() => "rsl-" + Guid.NewGuid().ToString("N")[..12]; private static string Insert(string dataSource, string extra = "") => $"sql:INSERT INTO {Table} (tag) VALUES (:#tag)?dataSource={dataSource}&outputType=None{extra}"; private static void SetObject(IExchange exchange, string tag) => exchange.In.Body = new RedbObject { name = tag, Props = new RedbSqlLeaseProps { Tag = tag } }; private RouteContext NewContext(bool withNamed = true) { var context = new RouteContext(Services); context.AddComponent(new SqlComponent()); context.AddRedbSqlDataSource(); if (withNamed) context.RegisterRedbService(NamedService, NamedServices.GetRequiredService()); return context; } private static async Task Start(RouteContext context, string uri) { await context.Start(); var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); return producer; } private static Exchange Delivery(string tag) { var exchange = new Exchange(new Message(null)); exchange.In.Headers["tag"] = tag; return exchange; } /// Rows of the probe table and redb objects carrying , committed in ' database. protected static async Task<(long Rows, long Objects)> CountAsync(IServiceProvider services, string tag) { await using var scope = services.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var rows = await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM {Table} WHERE tag = '{tag}'"); var objects = await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM _objects WHERE _name = '{tag}'"); return (rows, objects); } [Fact] public async Task A_transacted_block_commits_the_statement_and_the_redb_save_together() { var tag = NewTag(); var distributed = Guid.Empty; await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-commit") .Transacted() .To(Insert("redb")) .Process(e => SetObject(e, tag)) .RedbSave() .Process(_ => distributed = Transaction.Current!.TransactionInformation.DistributedIdentifier) .End()); var producer = await Start(context, "direct://rsl-commit"); await producer.Process(Delivery(tag)); (await CountAsync(Services, tag)).Should().Be((1L, 1L), "the statement and the save commit with the block"); if (ChecksDistributedTransaction) distributed.Should().Be(Guid.Empty, "the statement and the save share one connection, so the transaction stays local"); } [Fact] public async Task A_failure_after_the_statement_rolls_back_the_statement_and_the_redb_save() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-rollback") .Transacted() .To(Insert("redb")) .Process(e => SetObject(e, tag)) .RedbSave() .Process(_ => throw new InvalidOperationException("the block fails after the statement and the save")) .End()); var producer = await Start(context, "direct://rsl-rollback"); var send = () => producer.Process(Delivery(tag)); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Should().Be((0L, 0L), "the block's rollback takes back the statement's row and the object"); } [Fact] public async Task A_batch_runs_in_the_block_transaction() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-batch") .Transacted() .To(Insert("redb", "&batchSize=10")) .Process(_ => throw new InvalidOperationException("the block fails after the batch")) .End()); var producer = await Start(context, "direct://rsl-batch"); var items = new List> { new() { ["tag"] = tag }, new() { ["tag"] = tag } }; var send = () => producer.Process(new Exchange(new Message(items))); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Rows.Should().Be(0, "the batch wrote in the block's transaction, which rolled back"); } [Fact] public async Task A_function_call_runs_inside_the_block() { await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-function") .Transacted() .To("sql:abs?mode=Procedure&asFunction=true&procedureParams=IN:x:Int64&dataSource=redb") .End()); var producer = await Start(context, "direct://rsl-function"); var exchange = new Exchange(new Message(null)); exchange.In.Headers["x"] = -42L; await producer.Process(exchange); Convert.ToInt64(exchange.In.Body).Should().Be(42L); } [Fact] public async Task The_named_service_runs_the_statement_in_its_own_database() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-named") .Transacted() .To(Insert("redb:" + NamedService)) .Process(e => SetObject(e, tag)) .RedbSave(storage: NamedService) .End()); var producer = await Start(context, "direct://rsl-named"); await producer.Process(Delivery(tag)); (await CountAsync(NamedServices, tag)).Should().Be((1L, 1L), "redb:orders writes where the orders service works"); (await CountAsync(Services, tag)).Should().Be((0L, 0L), "nothing lands in the default service's database"); } /// /// The context starts every endpoint and goes on in degraded mode past one that fails (it logs the failure), so the /// refusal is read from the endpoint's own start; the first exchange is refused with the same message. /// private static async Task<(Exception? AtStart, Exception? AtFirstExchange)> StartFailures( RouteContext context, string from, string sqlUri) { var producer = await Start(context, from); var atStart = await Record.ExceptionAsync(() => context.GetEndpoint(sqlUri).Start()); var atFirstExchange = await Record.ExceptionAsync(() => producer.Process(Delivery(NewTag()))); return (atStart, atFirstExchange); } [Fact] public async Task A_route_naming_an_unregistered_service_fails_at_start() { await using var context = NewContext(withNamed: false); context.AddRoutes(r => r.From("direct://rsl-missing").To(Insert("redb:missing"))); var (atStart, atFirstExchange) = await StartFailures(context, "direct://rsl-missing", Insert("redb:missing")); atStart.Should().BeOfType().Which.Message.Should().Contain("redb:missing"); atFirstExchange.Should().BeOfType().Which.Message.Should().Contain("redb:missing"); } [Fact] public async Task A_route_on_a_context_without_redb_fails_at_start() { await using var context = new RouteContext(new ServiceCollection().BuildServiceProvider()); context.AddComponent(new SqlComponent()); context.AddRedbSqlDataSource(); context.AddRoutes(r => r.From("direct://rsl-no-redb").To(Insert("redb"))); var (atStart, atFirstExchange) = await StartFailures(context, "direct://rsl-no-redb", Insert("redb")); atStart.Should().BeOfType().Which.Message.Should().Contain("no IRedbService"); atFirstExchange.Should().BeOfType().Which.Message.Should().Contain("no IRedbService"); } [Fact] public async Task Outside_a_transaction_the_statement_commits_on_its_own() { var tag = NewTag(); await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-autocommit") .To(Insert("redb")) .Process(_ => throw new InvalidOperationException("a failure after the statement, no transaction"))); var producer = await Start(context, "direct://rsl-autocommit"); var send = () => producer.Process(Delivery(tag)); await send.Should().ThrowAsync(); (await CountAsync(Services, tag)).Rows.Should().Be(1, "without a transaction the statement commits as it runs"); } [Fact] public async Task A_streamed_result_is_refused() { await using var context = NewContext(); context.AddRoutes(r => r .From("direct://rsl-stream") .To($"sql:SELECT tag FROM {Table}?dataSource=redb&outputType=StreamList")); var producer = await Start(context, "direct://rsl-stream"); var send = () => producer.Process(new Exchange(new Message(null))); (await send.Should().ThrowAsync()).Which.Message.Should().Contain("StreamList"); } [Fact] public async Task A_batch_that_continues_past_errors_is_refused() { await using var context = NewContext(); context.AddRoutes(r => r.From("direct://rsl-savepoints").To(Insert("redb", "&batchSize=10&breakBatchOnError=false"))); var producer = await Start(context, "direct://rsl-savepoints"); var items = new List> { new() { ["tag"] = NewTag() } }; var send = () => producer.Process(new Exchange(new Message(items))); (await send.Should().ThrowAsync()).Which.Message.Should().Contain("breakBatchOnError"); } [Fact] public async Task The_polling_consumer_is_refused_at_start() { var uri = $"sql:SELECT tag FROM {Table}?mode=Poll&dataSource=redb"; await using var context = NewContext(); context.AddRoutes(r => r.From(uri).RouteId("rsl-poll").Process(_ => { })); await context.Start(); var consumerStart = () => context.GetEndpoint(uri).CreateConsumer(Substitute.For()).Start(); context.GetRoute("rsl-poll")!.Status.Should().Be(RouteStatus.Errored, "the route's consumer refused to start"); (await consumerStart.Should().ThrowAsync()).Which.Message.Should().Contain("dataSource=redb"); } [Fact] public void The_repositories_refuse_the_lending_data_source() { var factory = new RedbSqlConnectionFactory(new RouteContext(Services)); var idempotent = () => new SqlIdempotentRepository(factory, new SqlIdempotentOptions()); var claimCheck = () => new SqlClaimCheckRepository(factory, new SqlClaimCheckOptions()); idempotent.Should().Throw().Which.Message.Should().Contain("lends"); claimCheck.Should().Throw().Which.Message.Should().Contain("lends"); } [Fact] public void A_factory_that_implements_only_CreateConnectionAsync_keeps_its_defaults() { ISqlConnectionFactory plain = new PlainFactory(); plain.LendsConnection.Should().BeFalse(); plain.ForQualifier(null).Should().BeSameAs(plain); var qualified = () => plain.ForQualifier("x"); qualified.Should().Throw(); } /// A factory written before the lease: it implements only . private sealed class PlainFactory : ISqlConnectionFactory { public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) => throw new NotSupportedException("never opened by this test"); } }