Bundle: redb-route / redb.Route.Sql (redb.Route.Sql.txt), 52 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/redb.Route.Sql/Batch/BatchItemAccessor.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemAccessor.cs
----
using System.Collections;
using System.Collections.Concurrent;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml.Linq;
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
/// Result of looking a name up in a batch item.
internal enum ItemLookup
{
/// The item has a value for the name, possibly null.
Found,
/// The item has named values, but none for this name.
Missing,
/// Several keys equal the name ignoring case and none equals it exactly.
Ambiguous,
/// The item is null, a scalar, a collection, an XML node or another .NET type: it has no named values at all.
NoNamedValues,
}
///
/// Reads a named value out of a batch item in whatever shape the route produced it: a dictionary (generic, read-only or
/// non-generic — CSV rows are Dictionary<string, string> ), a JSON object ( ,
/// , or a whose root is one), or a POCO. A key equal to the name wins;
/// failing that, the single key equal to it ignoring case — two such keys name nothing. POCO properties match by the rule that
/// maps result columns to properties ( ).
///
/// A POCO is a type of the application: the properties of a .NET type ( , ,
/// ) are not the fields of a record. An XML node carries no named values, as in Apache Camel, where
/// a DOM node is iterated but only a Map is looked up by key; its values are bound with xpath expressions.
///
///
internal static class BatchItemAccessor
{
// Weak per type: a POCO of an unloadable module (collectible load context) does not stay alive in this cache.
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable PocoShapes = new();
/// A POCO type's readable properties (null: no named values) and the property each name matched.
private sealed class PocoShape(PropertyInfo[]? properties)
{
public PropertyInfo[]? Properties { get; } = properties;
public ConcurrentDictionary Matches { get; } = new(StringComparer.Ordinal);
}
/// Looks up in a batch item: by key in a map or JSON object, by property in a POCO.
internal static ItemLookup Find(object? item, string name, out object? value) => Find(item, name, readProperties: true, out value);
///
/// Looks up by key only — in a map or a JSON object. This is how the body of a single statement is
/// read, as in Apache Camel, where a body that converts to a Map (Jackson's JsonNode included) is looked up
/// by key and a POJO is not.
///
internal static ItemLookup FindByKey(object? item, string name, out object? value) => Find(item, name, readProperties: false, out value);
private static ItemLookup Find(object? item, string name, bool readProperties, out object? value)
{
value = null;
switch (item)
{
case IDictionary dictionary:
if (dictionary.TryGetValue(name, out value))
return ItemLookup.Found;
return FindIgnoringCase(dictionary.Keys, name, key => dictionary[key], out value);
case IReadOnlyDictionary readOnly:
if (readOnly.TryGetValue(name, out value))
return ItemLookup.Found;
return FindIgnoringCase(readOnly.Keys, name, key => readOnly[key], out value);
case JsonElement { ValueKind: JsonValueKind.Object } json:
if (json.TryGetProperty(name, out var property))
{
value = property;
return ItemLookup.Found;
}
return FindIgnoringCase(json.EnumerateObject().Select(p => p.Name), name, key => json.GetProperty(key), out value);
case JsonDocument document:
return Find(document.RootElement, name, out value);
case JsonObject jsonObject:
if (jsonObject.TryGetPropertyValue(name, out var node))
{
value = node;
return ItemLookup.Found;
}
return FindIgnoringCase(jsonObject.Select(p => p.Key), name, key => jsonObject[key], out value);
case IDictionary nonGeneric:
if (nonGeneric.Contains(name))
{
value = nonGeneric[name];
return ItemLookup.Found;
}
return FindIgnoringCase(nonGeneric.Keys.OfType(), name, key => nonGeneric[key], out value);
case null:
case JsonElement:
case JsonNode:
case XObject:
case IEnumerable:
return ItemLookup.NoNamedValues;
default:
return readProperties ? FindProperty(item, name, out value) : ItemLookup.NoNamedValues;
}
}
/// The item is XML (a LINQ to XML object or a DOM node), whose values are reached with xpath expressions.
internal static bool IsXml(object? item) => item is XObject or System.Xml.XmlNode;
/// The entries of a dictionary item, which an item's ${header.name} expressions see; nothing for other shapes.
internal static IEnumerable> Entries(object? item) => item switch
{
IDictionary dictionary => dictionary,
IReadOnlyDictionary readOnly => readOnly,
IDictionary nonGeneric => nonGeneric.Keys.OfType().Select(key => new KeyValuePair(key, nonGeneric[key])),
_ => [],
};
private static ItemLookup FindIgnoringCase(IEnumerable keys, string name, Func read, out object? value)
{
value = null;
string? match = null;
foreach (var key in keys)
{
if (!string.Equals(key, name, StringComparison.OrdinalIgnoreCase))
continue;
if (match is not null)
return ItemLookup.Ambiguous;
match = key;
}
if (match is null)
return ItemLookup.Missing;
value = read(match);
return ItemLookup.Found;
}
private static ItemLookup FindProperty(object item, string name, out object? value)
{
value = null;
var type = item.GetType();
var shape = PocoShapes.GetValue(type, static t => new PocoShape(ReadableProperties(t)));
if (shape.Properties is not { } properties)
return ItemLookup.NoNamedValues;
var property = shape.Matches.GetOrAdd(name, static (key, all) => ColumnNameMatcher.Find(all, key), properties);
if (property is null)
return ItemLookup.Missing;
value = property.GetValue(item);
return ItemLookup.Found;
}
///
/// Public readable instance properties of a POCO; null for a type that carries no named values: a scalar, or any type of
/// .NET itself (System.* , Microsoft.* ). Anonymous types and records of the application are POCOs.
///
private static PropertyInfo[]? ReadableProperties(Type type)
{
if (type.IsPrimitive || type.IsEnum || IsFrameworkType(type))
return null;
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.GetMethod is { IsPublic: true } && p.GetIndexParameters().Length == 0)
.ToArray();
return properties.Length == 0 ? null : properties;
}
private static bool IsFrameworkType(Type type) =>
type.Namespace is { } ns
&& (ns == "System" || ns.StartsWith("System.", StringComparison.Ordinal)
|| ns == "Microsoft" || ns.StartsWith("Microsoft.", StringComparison.Ordinal));
}
Path: redb-route/redb.Route.Sql/Batch/BatchItemBinder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemBinder.cs
----
using System.Data.Common;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Sql.Batch;
///
/// Binds one batch item to the statement. Sources, first match wins: explicit param.name ; the item's own value
/// ( ); the carrying exchange's header. An item that is itself an exchange (grouped by an
/// aggregation) is looked up in its own headers and body instead, and evaluates ${...} on itself. A placeholder with no
/// value is an error of that item, as in Apache Camel; a value that is present but null binds NULL.
///
internal static class BatchItemBinder
{
///
/// Fills — one slot per entry, in that order — with the
/// normalised values of the item at .
///
/// A placeholder has no value for this item.
internal static void ResolveValues(SqlParameterPlan plan, IExchange carrier, object? item, int index, object[] values)
{
IExchange? expressionContext = null;
for (var slot = 0; slot < plan.Names.Count; slot++)
{
var name = plan.Names[slot];
object? value;
if (plan.TryGetExplicit(name, out var explicitParameter))
{
value = explicitParameter.IsExpression
? explicitParameter.Resolve(expressionContext ??= CreateExpressionContext(carrier, item))
: explicitParameter.Resolve(null);
}
else if (!TryGetValue(carrier, item, name, out value, out var lookup))
{
throw new InvalidOperationException(MissingValueMessage(plan, item, name, index, lookup));
}
values[slot] = SqlParameterBinder.NormalizeForDb(value);
}
}
private static bool TryGetValue(IExchange carrier, object? item, string name, out object? value, out ItemLookup lookup)
{
if (item is IExchange itemExchange)
{
if (itemExchange.In.Headers.TryGetValue(name, out value))
{
lookup = ItemLookup.Found;
return true;
}
lookup = BatchItemAccessor.Find(itemExchange.In.Body, name, out value);
return lookup == ItemLookup.Found;
}
lookup = BatchItemAccessor.Find(item, name, out value);
return lookup == ItemLookup.Found || carrier.In.Headers.TryGetValue(name, out value);
}
///
/// The exchange an item's ${...} values are evaluated in: an item exchange itself; otherwise a linked child of the
/// carrying exchange (its properties, route context and DI scope) with the item as body and, as headers, the carrier's
/// headers overlaid by the entries of a dictionary item. The child is not disposed: it owns no scope, and disposing it
/// would dispose its body, which is an element of the carrier's list.
///
private static IExchange CreateExpressionContext(IExchange carrier, object? item)
{
if (item is IExchange itemExchange)
return itemExchange;
var child = carrier.CreateLinkedChild(new Message(item));
foreach (var (key, value) in carrier.In.Headers)
child.In.Headers[key] = value;
foreach (var (key, value) in BatchItemAccessor.Entries(item))
child.In.Headers[key] = value;
return child;
}
private static string MissingValueMessage(SqlParameterPlan plan, object? item, string name, int index, ItemLookup lookup)
{
var lookedAt = item switch
{
IExchange => $"no param.{name} option, no '{name}' header on the item exchange and no '{name}' key in its body",
_ when BatchItemAccessor.IsXml(item) =>
$"the item is {item!.GetType().Name}, an XML node, and XML carries no named values (as in Apache Camel), and there " +
$"is no param.{name} option and no '{name}' header; bind it with param.{name}=${{xpath('...')}} relative to the item",
_ when lookup == ItemLookup.NoNamedValues =>
$"the item is {(item is null ? "null" : item.GetType().Name)} and carries no named values, and there is no " +
$"param.{name} option and no '{name}' header; bind it with param.{name}=${{body}} or a ${{body...}} expression",
_ when lookup == ItemLookup.Ambiguous =>
$"the item has several keys equal to '{name}' ignoring case and none equal to it exactly, and there is no " +
$"param.{name} option and no '{name}' header",
_ => $"no param.{name} option, no '{name}' key or property in the item and no '{name}' header",
};
return $"Batch item {index}: " + SqlParameterBinder.MissingValueMessage(name, plan.SourceSql, lookedAt);
}
}
Path: redb-route/redb.Route.Sql/Batch/BatchItemCommand.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemCommand.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Batch;
///
/// The statement of a batch as one command: created and given its parameters once, then run for every item with only the
/// parameter values replaced. is not called: SQL Server refuses it for parameters without an
/// explicit size.
///
internal sealed class BatchItemCommand : IAsyncDisposable
{
private readonly BatchWriteRequest _request;
private readonly DbCommand _command;
private readonly object[] _values;
internal BatchItemCommand(BatchWriteRequest request, SqlEndpointOptions options)
{
_request = request;
_values = new object[request.Plan.Names.Count];
var command = request.Connection.CreateCommand();
var ready = false;
try
{
command.CommandText = request.Plan.Sql;
command.CommandTimeout = options.CommandTimeout;
if (request.Transaction is not null)
command.Transaction = request.Transaction;
for (var slot = 0; slot < request.Plan.Slots.Count; slot++)
{
var parameter = command.CreateParameter();
parameter.ParameterName = request.Plan.ParameterName(slot);
parameter.Value = DBNull.Value;
command.Parameters.Add(parameter);
}
ready = true;
}
finally
{
if (!ready)
command.Dispose();
}
_command = command;
}
///
/// Binds the values of (at ) and executes the statement; returns the rows
/// affected. When the batch collects returned rows, the statement runs as a reader and its rows go to the collector; the
/// reader is closed before this returns or throws.
///
/// A placeholder has no value for this item.
internal async Task ExecuteAsync(object? item, int index, CancellationToken ct)
{
BatchItemBinder.ResolveValues(_request.Plan, _request.Exchange, item, index, _values);
for (var slot = 0; slot < _request.Plan.Slots.Count; slot++)
_command.Parameters[slot].Value = _values[_request.Plan.Slots[slot]];
if (_request.Keys is not { } keys)
return await _command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
await using var reader = await _command.ExecuteReaderAsync(ct).ConfigureAwait(false);
await keys.ReadAllAsync(reader, ct).ConfigureAwait(false);
await reader.CloseAsync().ConfigureAwait(false);
return Math.Max(reader.RecordsAffected, 0);
}
///
public ValueTask DisposeAsync() => _command.DisposeAsync();
}
Path: redb-route/redb.Route.Sql/Batch/BatchItemFailedException.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemFailedException.cs
----
namespace redb.Route.Sql.Batch;
///
/// Internal carrier from a batch writer to the batch processor: the item at ended the batch. It never
/// leaves the connector — the processor rolls back and rethrows the provider's exception, which is the inner exception.
///
internal sealed class BatchItemFailedException(int index, Exception providerException)
: Exception($"Batch item {index} failed.", providerException)
{
/// Zero-based position of the failed item in the batch source.
public int Index { get; } = index;
}
Path: redb-route/redb.Route.Sql/Batch/BatchItemReader.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchItemReader.cs
----
using System.Collections;
using System.Runtime.CompilerServices;
namespace redb.Route.Sql.Batch;
///
/// Reads the items of a batch source one at a time, whatever the source is — a list, a lazy sequence, an asynchronous stream.
/// Nothing is read ahead of what the writer asks for, except the first item, which the processor reads before it opens a
/// connection so that an empty source costs none. A failure of the source itself (not of an item's statement) ends the batch:
/// it is reported with the number of items read before it.
///
internal sealed class BatchItemReader : IAsyncDisposable
{
private readonly IAsyncEnumerator _enumerator;
private readonly CancellationToken _ct;
private bool _pending;
private BatchItemReader(IAsyncEnumerator enumerator, CancellationToken ct)
{
_enumerator = enumerator;
_ct = ct;
}
/// Items read from the source so far.
internal int ItemsRead { get; private set; }
/// Zero-based index of .
internal int Index => ItemsRead - 1;
/// The item last read.
internal object? Current => _enumerator.Current;
/// A reader over an asynchronous source.
internal static BatchItemReader Over(IAsyncEnumerable source, CancellationToken ct) =>
new(source.GetAsyncEnumerator(ct), ct);
/// A reader over a synchronous source.
internal static BatchItemReader Over(IEnumerable source, CancellationToken ct) =>
new(Enumerate(source, ct).GetAsyncEnumerator(ct), ct);
/// Reads the first item and keeps it for the first ; false for an empty source.
/// The source failed.
internal async ValueTask HasItemsAsync()
{
_pending = await MoveAsync().ConfigureAwait(false);
return _pending;
}
/// Advances to the next item; false when the source is exhausted.
/// The source failed.
internal async ValueTask ReadAsync()
{
if (_pending)
{
_pending = false;
return true;
}
return await MoveAsync().ConfigureAwait(false);
}
///
public ValueTask DisposeAsync() => _enumerator.DisposeAsync();
private async ValueTask MoveAsync()
{
bool moved;
try
{
moved = await _enumerator.MoveNextAsync().ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException && !_ct.IsCancellationRequested)
{
// The source's own failure: the batch ends at the item that could not be read. Under a cancellation the source's
// exception (a driver answering the stop in its own way) goes up as is, as the writers' do.
throw new BatchItemFailedException(ItemsRead, ex);
}
if (moved)
ItemsRead++;
return moved;
}
private static async IAsyncEnumerable Enumerate(IEnumerable source, [EnumeratorCancellation] CancellationToken ct)
{
foreach (var item in source)
{
ct.ThrowIfCancellationRequested();
yield return item;
}
await Task.CompletedTask.ConfigureAwait(false);
}
}
Path: redb-route/redb.Route.Sql/Batch/BatchOutcome.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchOutcome.cs
----
namespace redb.Route.Sql.Batch;
/// What a batch writer achieved: rows the statements reported, items written, round trips, and items undone to a savepoint.
internal sealed class BatchOutcome
{
/// Sum of the rows affected reported by the provider.
public int RowsAffected { get; set; }
/// Items whose statement succeeded and stays in the batch.
public int ItemsWritten { get; set; }
/// DbBatch round trips; null for strategies that send one statement at a time.
public int? ChunkCount { get; set; }
/// Items that failed and were undone to their savepoint (continue mode only).
public List Errors { get; } = [];
}
Path: redb-route/redb.Route.Sql/Batch/BatchRollback.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchRollback.cs
----
using System.Data.Common;
using Microsoft.Extensions.Logging;
namespace redb.Route.Sql.Batch;
/// Rolls a failed batch back without letting a failing rollback replace the error that caused it.
internal static class BatchRollback
{
///
/// Rolls back with — a cancelled batch still has to release its transaction. A rollback
/// that fails (typically: the server already ended the transaction) is logged; the caller's original exception is what
/// propagates.
///
internal static async Task RunAsync(DbTransaction transaction, ILogger? logger)
{
try
{
await transaction.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex)
{
logger?.LogError(ex, "SQL batch transaction rollback failed; the error that ended the batch is rethrown");
}
}
}
Path: redb-route/redb.Route.Sql/Batch/BatchRowCollector.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchRowCollector.cs
----
using System.Collections;
using System.Data.Common;
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
///
/// Collects the rows a batch's statements return (INSERT … RETURNING , OUTPUT inserted.* ) in item order, for
/// . Rows are Dictionary<string, object?> , or the outputClass type.
///
internal sealed class BatchRowCollector
{
private readonly Func _map;
private BatchRowCollector(IList rows, Func map)
{
Rows = rows;
_map = map;
}
/// The rows collected so far: a List<T> of the row type.
internal IList Rows { get; }
/// Number of rows collected so far.
internal int Count => Rows.Count;
///
/// A collector when ask for rows — an outputType other than None , with
/// Auto decided by — or null, when the batch reads no rows. Rows map to
/// , the endpoint's outputClass mapping, or to dictionaries without one.
///
internal static BatchRowCollector? Create(SqlEndpointOptions options, SqlRowMapperFactory.PocoMapping? poco, string sql)
{
// Under Auto a batch reads no rows, as Apache Camel's executeBatch collects no result sets: the keys of a batch are
// asked for with an explicit outputType. The text is never parsed for it.
if (options.OutputType is SqlOutputType.None or SqlOutputType.Auto)
return null;
if (poco is not null)
return new BatchRowCollector(poco.CreateList(), poco.Map);
var mapper = new DictionaryRowMapper();
return new BatchRowCollector(new List>(), reader => mapper.Map(reader));
}
/// Reads every row of every result set of , in order.
internal async Task ReadAllAsync(DbDataReader reader, CancellationToken ct)
{
do
{
while (await reader.ReadAsync(ct).ConfigureAwait(false))
Rows.Add(_map(reader));
}
while (await reader.NextResultAsync(ct).ConfigureAwait(false));
}
/// Drops the rows collected after the first : those of an item undone to its savepoint.
internal void Truncate(int count)
{
while (Rows.Count > count)
Rows.RemoveAt(Rows.Count - 1);
}
}
Path: redb-route/redb.Route.Sql/Batch/BatchSource.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchSource.cs
----
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Xml;
namespace redb.Route.Sql.Batch;
///
/// Decides whether a message body is a batch source and opens a reader over its items. A source is a list, any other
/// sequence (a HashSet , a LINQ query, a yield method), an IAsyncEnumerable of a reference type (a
/// streamed query result), or a JSON array ( , a whose root is an array,
/// ). A value that merely happens to be enumerable is one value, not a batch: a string or any other
/// sequence of characters, a byte[] or any other sequence of bytes, a dictionary or JSON object (a map of named
/// values), and an XML document or node — XML carries no batch shape of its own, as in Apache Camel.
///
internal static class BatchSource
{
/// Opens a reader over the items of when it is a batch source.
internal static bool TryOpen(object? body, CancellationToken ct, [NotNullWhen(true)] out BatchItemReader? reader)
{
reader = body switch
{
null or string or byte[] => null,
IEnumerable or IEnumerable => null,
JsonElement { ValueKind: JsonValueKind.Array } array => BatchItemReader.Over(array.EnumerateArray().Cast(), ct),
JsonDocument { RootElement.ValueKind: JsonValueKind.Array } document =>
BatchItemReader.Over(document.RootElement.EnumerateArray().Cast(), ct),
JsonElement or JsonDocument => null,
IDictionary or XmlNode => null,
_ when IsGenericMap(body.GetType()) => null,
IAsyncEnumerable stream => BatchItemReader.Over(stream, ct),
IEnumerable sequence => BatchItemReader.Over(sequence, ct),
_ => null,
};
return reader is not null;
}
/// A generic dictionary — included — is a map of named values, not a sequence of items.
private static bool IsGenericMap(Type type) =>
type.GetInterfaces().Any(i => i.IsGenericType
&& (i.GetGenericTypeDefinition() == typeof(IDictionary<,>) || i.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>)));
}
Path: redb-route/redb.Route.Sql/Batch/BatchWriteRequest.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/BatchWriteRequest.cs
----
using System.Data.Common;
using redb.Route.Abstractions;
namespace redb.Route.Sql.Batch;
/// What a batch writer works on: the open connection, the transaction (null inside an ambient one), the parameter
/// plan of the resolved statement, the reader over the items, the exchange that carries them, and the collector of the rows
/// the statements return (null when the batch reads no rows).
internal sealed record BatchWriteRequest(
DbConnection Connection, DbTransaction? Transaction, SqlParameterPlan Plan, BatchItemReader Items, IExchange Exchange,
BatchRowCollector? Keys);
Path: redb-route/redb.Route.Sql/Batch/CommandsBatchWriter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/CommandsBatchWriter.cs
----
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
///
/// Break-on-first-error batch on a connection that cannot create a DbBatch : one command, its parameters reused, runs
/// the items one after another as they are read. The first failing item ends the batch — nothing is read or sent after it,
/// and the processor rolls the whole transaction back.
///
internal sealed class CommandsBatchWriter(SqlEndpointOptions options) : IBatchWriter
{
///
public string Strategy => "Commands";
///
public async Task WriteAsync(BatchWriteRequest request, CancellationToken ct)
{
var outcome = new BatchOutcome();
await using var command = new BatchItemCommand(request, options);
while (await request.Items.ReadAsync().ConfigureAwait(false))
{
var index = request.Items.Index;
int affected;
try
{
affected = await command.ExecuteAsync(request.Items.Current, index, ct).ConfigureAwait(false);
}
// A returned row that cannot be mapped is the endpoint's configuration, not this item's failure: it goes up as is.
catch (Exception ex) when (ex is not OperationCanceledException && !ct.IsCancellationRequested && ex is not SqlRowMappingException)
{
throw new BatchItemFailedException(index, ex);
}
outcome.RowsAffected += affected;
outcome.ItemsWritten++;
}
return outcome;
}
}
Path: redb-route/redb.Route.Sql/Batch/DbBatchWriter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/DbBatchWriter.cs
----
using System.Data.Common;
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
///
/// Break-on-first-error batch over : the items go in chunks of
/// statements, one round trip per chunk, all in the batch's transaction. A chunk is read, then sent, before the next one is
/// read. A failed chunk ends the batch; the failed item is the command the provider names in
/// , or — when the provider does not name it — the chunk's first item, with the chunk's
/// range in under . When the batch collects returned rows, a chunk
/// runs as a reader: one result set per command, in item order.
///
internal sealed class DbBatchWriter(SqlEndpointOptions options) : IBatchWriter
{
/// Strategy name, as reported in .
internal const string Name = "DbBatch";
/// key of the failed chunk's item range when the failed command is unknown.
internal const string FailedChunkKey = "redbSql.batchFailedChunk";
///
public string Strategy => Name;
///
public async Task WriteAsync(BatchWriteRequest request, CancellationToken ct)
{
var outcome = new BatchOutcome { ChunkCount = 0 };
var plan = request.Plan;
var values = new object[plan.Names.Count];
DbCommand? parameterFactory = null;
try
{
while (await request.Items.ReadAsync().ConfigureAwait(false))
{
var start = request.Items.Index;
var count = 0;
await using var batch = request.Connection.CreateBatch();
batch.Transaction = request.Transaction;
batch.Timeout = options.CommandTimeout;
do
{
var index = request.Items.Index;
try
{
BatchItemBinder.ResolveValues(plan, request.Exchange, request.Items.Current, index, values);
}
catch (Exception ex) when (ex is not OperationCanceledException && !ct.IsCancellationRequested)
{
throw new BatchItemFailedException(index, ex);
}
var command = batch.CreateBatchCommand();
command.CommandText = plan.Sql;
for (var slot = 0; slot < plan.Slots.Count; slot++)
{
// .NET 8 lets a batch command create its own parameters; older providers need a command for that.
var parameter = command.CanCreateParameter
? command.CreateParameter()
: (parameterFactory ??= request.Connection.CreateCommand()).CreateParameter();
parameter.ParameterName = plan.ParameterName(slot);
parameter.Value = values[plan.Slots[slot]];
command.Parameters.Add(parameter);
}
batch.BatchCommands.Add(command);
count++;
}
// A full chunk is sent before anything more is read from the source.
while (count < options.BatchSize && await request.Items.ReadAsync().ConfigureAwait(false));
int affected;
try
{
affected = request.Keys is { } keys
? await ExecuteForRowsAsync(batch, keys, ct).ConfigureAwait(false)
: await batch.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
// A returned row that cannot be mapped is the endpoint's configuration, not a chunk's failure: it goes up as is.
catch (Exception ex) when (ex is not OperationCanceledException && !ct.IsCancellationRequested && ex is not SqlRowMappingException)
{
throw ChunkFailure(ex, batch, start, start + count);
}
outcome.RowsAffected += affected;
outcome.ItemsWritten += count;
outcome.ChunkCount++;
}
}
finally
{
if (parameterFactory is not null)
await parameterFactory.DisposeAsync().ConfigureAwait(false);
}
return outcome;
}
///
/// Sends the chunk as a reader, collects every command's result set in order, and returns the rows affected — the sum of
/// the commands' own counts, read once the reader is closed.
///
private static async Task ExecuteForRowsAsync(DbBatch batch, BatchRowCollector keys, CancellationToken ct)
{
await using (var reader = await batch.ExecuteReaderAsync(ct).ConfigureAwait(false))
await keys.ReadAllAsync(reader, ct).ConfigureAwait(false);
var affected = 0;
foreach (var command in batch.BatchCommands)
affected += Math.Max(command.RecordsAffected, 0);
return affected;
}
private static BatchItemFailedException ChunkFailure(Exception ex, DbBatch batch, int start, int end)
{
var failedCommand = (ex as DbException)?.BatchCommand;
var position = failedCommand is null ? -1 : batch.BatchCommands.IndexOf(failedCommand);
if (position >= 0)
return new BatchItemFailedException(start + position, ex);
ex.Data[FailedChunkKey] = $"{start}..{end - 1}";
return new BatchItemFailedException(start, ex);
}
}
Path: redb-route/redb.Route.Sql/Batch/IBatchWriter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/IBatchWriter.cs
----
namespace redb.Route.Sql.Batch;
/// Writes the items of one batch inside the connection and transaction the batch processor opened.
internal interface IBatchWriter
{
/// Strategy name reported in the header.
string Strategy { get; }
///
/// Writes the items. The item that ends the batch is reported by throwing with the
/// provider's exception inside; cancellation propagates as is.
///
Task WriteAsync(BatchWriteRequest request, CancellationToken ct);
}
Path: redb-route/redb.Route.Sql/Batch/SavepointBatchWriter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/SavepointBatchWriter.cs
----
using System.Data.Common;
using Microsoft.Extensions.Logging;
using redb.Route.Sql.Mapping;
namespace redb.Route.Sql.Batch;
///
/// Continue-past-errors batch (breakBatchOnError=false ). Every item runs under its own savepoint: a failed item is
/// rolled back to it and reported, the others stay. Whether savepoints work is learnt by using them — providers under-report
/// (SqlClient says false and supports them). When rolling back to the
/// savepoint fails, the server has already ended the transaction; SQL Server would then run the next statement in
/// autocommit, so the batch stops at that item instead of sending anything more. The items share one command whose
/// parameter values are replaced per item; a DbBatch is never used here, since it cannot go on past a failed command.
/// A failure of the source itself is not an item error: it ends the batch. Rows a failed item returned are dropped with it.
///
internal sealed class SavepointBatchWriter(SqlEndpointOptions options, ILogger? logger) : IBatchWriter
{
/// Name of the per-item savepoint.
internal const string SavepointName = "redb_batch_item";
///
public string Strategy => "Savepoints";
///
public async Task WriteAsync(BatchWriteRequest request, CancellationToken ct)
{
var transaction = request.Transaction
?? throw new InvalidOperationException("Continuing past a failed batch item needs a local transaction.");
var outcome = new BatchOutcome();
await using var command = new BatchItemCommand(request, options);
while (await request.Items.ReadAsync().ConfigureAwait(false))
{
var index = request.Items.Index;
await SaveAsync(request, transaction, ct).ConfigureAwait(false);
var keysBefore = request.Keys?.Count ?? 0;
int affected;
try
{
affected = await command.ExecuteAsync(request.Items.Current, index, ct).ConfigureAwait(false);
}
// A returned row that cannot be mapped is the endpoint's configuration, not this item's failure: it goes up as is.
catch (Exception ex) when (ex is not OperationCanceledException && !ct.IsCancellationRequested && ex is not SqlRowMappingException)
{
if (!await TryRollbackToSavepointAsync(transaction, index).ConfigureAwait(false))
throw new BatchItemFailedException(index, ex);
request.Keys?.Truncate(keysBefore);
outcome.Errors.Add(new SqlBatchItemError(index, ex.Message, (ex as DbException)?.SqlState));
continue;
}
await transaction.ReleaseAsync(SavepointName, ct).ConfigureAwait(false);
outcome.RowsAffected += affected;
outcome.ItemsWritten++;
}
return outcome;
}
private static async Task SaveAsync(BatchWriteRequest request, DbTransaction transaction, CancellationToken ct)
{
try
{
await transaction.SaveAsync(SavepointName, ct).ConfigureAwait(false);
}
catch (NotSupportedException ex)
{
throw new InvalidOperationException(
$"breakBatchOnError=false undoes a failed item to a savepoint, and {request.Connection.GetType().Name} does not " +
"support savepoints. Use breakBatchOnError=true: the whole batch then rolls back on the first error.", ex);
}
}
private async Task TryRollbackToSavepointAsync(DbTransaction transaction, int index)
{
try
{
await transaction.RollbackAsync(SavepointName, CancellationToken.None).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
// Not swallowed: the caller stops the batch and rethrows the item's own error; this records why.
logger?.LogWarning(ex,
"SQL batch item {Index} failed and its savepoint can no longer be rolled back to; the transaction has ended, the batch stops",
index);
return false;
}
}
}
Path: redb-route/redb.Route.Sql/Batch/SqlBatchProcessor.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Batch/SqlBatchProcessor.cs
----
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.ExceptionServices;
using System.Transactions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
namespace redb.Route.Sql.Batch;
///
/// Runs one batch over a reader of its items. The first item is read before anything else: an empty source writes nothing
/// and opens no connection. Otherwise all items share one connection and — unless the route already runs in an ambient
/// transaction — one local transaction. Breaking on the first error (the default, as in Apache Camel) sends the items in
/// DbBatch chunks of when the connection can create one, and through one
/// reused command otherwise; it rolls the whole batch back and rethrows the provider's own exception, with the failed item's
/// index in and in a header. Continuing past errors undoes each failed item to a savepoint and
/// reports it; it is refused before any write where savepoints cannot exist, and it stops when the transaction is gone. A
/// failure of the source itself ends the batch in either mode, reported the same way with the number of items read. No
/// option picks the strategy: as in Camel, the driver decides. With an outputType that reads rows, the rows the
/// statements return are collected into ; the batch tags the sql.execute span.
///
internal sealed class SqlBatchProcessor(SqlEndpoint endpoint, SqlEndpointOptions options, ILogger? logger)
{
///
/// Writes the items of with , sets the batch headers and tags
/// . The caller owns the reader and disposes it.
///
internal async Task ProcessAsync(IExchange exchange, BatchItemReader items, string sql, Activity? activity, CancellationToken ct)
{
var stopwatch = Stopwatch.StartNew();
var keys = BatchRowCollector.Create(options, endpoint.OutputMapping, sql);
ClearResultHeaders(exchange);
bool hasItems;
try
{
hasItems = await items.HasItemsAsync().ConfigureAwait(false);
}
catch (BatchItemFailedException failure)
{
ThrowItemFailure(exchange, activity, failure, strategy: "None", items.ItemsRead);
throw;
}
if (!hasItems)
{
SetHeaders(exchange, activity, sql, "None", new BatchOutcome(), keys, stopwatch, transaction: null);
return;
}
var ambient = Transaction.Current is not null;
if (!options.BreakBatchOnError && ambient)
{
throw new InvalidOperationException(
"breakBatchOnError=false undoes a failed item to a savepoint of a local transaction, but this batch runs inside an " +
"ambient transaction (a transacted route), where the connector has no savepoints. Use breakBatchOnError=true: " +
"the route transaction then rolls back on the first error.");
}
var plan = SqlParameterPlan.Create(sql, options.ExplicitParameters, options.PlaceholderStyle, options.BackslashEscapes);
var factory = endpoint.ResolveConnectionFactory();
if (!options.BreakBatchOnError && factory.LendsConnection)
{
throw new InvalidOperationException(
$"breakBatchOnError=false undoes a failed item to a savepoint of the batch's own transaction, and " +
$"dataSource={options.DataSource} lends a connection whose transaction is not the batch's. Use " +
"breakBatchOnError=true: inside a transacted route the route transaction then rolls back on the first error.");
}
// A lent connection (dataSource=redb) is the lender's: no transaction of the batch's own, items bound to the lender's.
await using var lease = await SqlConnections.OpenAsync(factory, exchange, readOnly: false, ct).ConfigureAwait(false);
var connection = lease.Connection;
var writer = ChooseWriter(connection);
DbTransaction? transaction = null;
var committed = false;
try
{
if (!ambient && !lease.IsBorrowed)
{
transaction = options.IsolationLevel.HasValue
? await connection.BeginTransactionAsync(options.IsolationLevel.Value, ct).ConfigureAwait(false)
: await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
}
BatchOutcome outcome;
try
{
outcome = await writer
.WriteAsync(new BatchWriteRequest(connection, transaction ?? lease.Transaction, plan, items, exchange, keys), ct)
.ConfigureAwait(false);
}
catch (BatchItemFailedException failure)
{
// The rollback runs in finally; the route sees the original exception with its original stack.
ThrowItemFailure(exchange, activity, failure, writer.Strategy, items.ItemsRead);
throw;
}
if (transaction is not null)
await transaction.CommitAsync(ct).ConfigureAwait(false);
committed = true;
SetHeaders(exchange, activity, sql, writer.Strategy, outcome, keys, stopwatch, transaction);
}
finally
{
if (transaction is not null)
{
if (!committed)
await BatchRollback.RunAsync(transaction, logger).ConfigureAwait(false);
await transaction.DisposeAsync().ConfigureAwait(false);
}
}
}
///
/// Continuing past errors needs savepoints, and a DbBatch cannot go on past a failed command; breaking on the first
/// error uses a DbBatch wherever the connection can create one.
///
private IBatchWriter ChooseWriter(DbConnection connection)
{
if (!options.BreakBatchOnError)
return new SavepointBatchWriter(options, logger);
return connection.CanCreateBatch ? new DbBatchWriter(options) : new CommandsBatchWriter(options);
}
/// Records the failed item's index on the exception, the exchange and the span, then rethrows the original exception.
[DoesNotReturn]
private void ThrowItemFailure(IExchange exchange, Activity? activity, BatchItemFailedException failure, string strategy, int itemsRead)
{
var original = failure.InnerException!;
logger?.LogError(original, "SQL batch stopped at item {Index}: dataSource={DataSource}, strategy={Strategy}",
failure.Index, options.DataSource, strategy);
original.Data[SqlHeaders.BatchFailedIndex] = failure.Index;
exchange.In.Headers[SqlHeaders.BatchFailedIndex] = failure.Index;
// The strategy tells a handler how to read the index: for a DbBatch whose driver names no command it is the chunk's start.
exchange.In.Headers[SqlHeaders.BatchStrategy] = strategy;
TagSpan(activity, strategy, itemsRead, chunks: null, failedIndex: failure.Index);
ExceptionDispatchInfo.Capture(original).Throw();
}
///
/// A batch describes only its own run: what an earlier attempt on the same exchange (a redelivery, an earlier sql:
/// step) left behind is removed before this one writes its result.
///
private static void ClearResultHeaders(IExchange exchange)
{
var headers = exchange.In.Headers;
headers.Remove(SqlHeaders.BatchFailedIndex);
headers.Remove(SqlHeaders.BatchErrors);
headers.Remove(SqlHeaders.Error);
headers.Remove(SqlHeaders.BatchStrategy);
headers.Remove(SqlHeaders.BatchChunkCount);
headers.Remove(SqlHeaders.GeneratedKeys);
headers.Remove(SqlHeaders.GeneratedKeysRowCount);
}
private void SetHeaders(
IExchange exchange, Activity? activity, string sql, string strategy, BatchOutcome outcome, BatchRowCollector? keys,
Stopwatch stopwatch, DbTransaction? transaction)
{
var headers = exchange.In.Headers;
headers[SqlHeaders.UpdateCount] = outcome.RowsAffected;
headers[SqlHeaders.RowCount] = outcome.ItemsWritten;
headers[SqlHeaders.BatchItemCount] = outcome.ItemsWritten;
headers[SqlHeaders.BatchStrategy] = strategy;
if (outcome.ChunkCount is { } chunks)
headers[SqlHeaders.BatchChunkCount] = chunks;
if (outcome.Errors.Count > 0)
{
headers[SqlHeaders.BatchErrors] = outcome.Errors.AsReadOnly();
headers[SqlHeaders.Error] = $"{outcome.Errors.Count} batch error(s): {outcome.Errors[0].Message}";
}
if (keys is not null)
{
headers[SqlHeaders.GeneratedKeys] = keys.Rows;
headers[SqlHeaders.GeneratedKeysRowCount] = keys.Count;
}
if (transaction is not null)
headers[SqlHeaders.TransactionId] = transaction.GetHashCode().ToString();
TagSpan(activity, strategy, outcome.ItemsWritten + outcome.Errors.Count, outcome.ChunkCount, failedIndex: null);
SqlExchangeHeaders.SetCommon(exchange, options, sql, stopwatch.ElapsedMilliseconds);
}
///
/// Batch tags on the sql.execute span. db.operation.batch.size follows the OpenTelemetry database conventions,
/// which count an operation as a batch only from two statements. No parameter value is ever tagged.
///
private static void TagSpan(Activity? activity, string strategy, int itemCount, int? chunks, int? failedIndex)
{
if (activity is null)
return;
activity.SetTag("redb.sql.batch.strategy", strategy);
if (itemCount >= 2)
activity.SetTag("db.operation.batch.size", itemCount);
if (chunks is { } roundTrips)
activity.SetTag("redb.sql.batch.chunks", roundTrips);
if (failedIndex is { } index)
activity.SetTag("redb.sql.batch.failed_index", index);
}
}
Path: redb-route/redb.Route.Sql/Connection/ISqlConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/ISqlConnectionFactory.cs
----
using System.Data.Common;
using redb.Route.Abstractions;
namespace redb.Route.Sql.Connection;
///
/// Abstraction for creating instances.
/// Implementations may provide pooling, read/write splitting, or failover.
///
///
/// The sql: producers take their connection through . Its default body opens a connection
/// of the endpoint's own with , so a factory that implements only that method works as
/// before. A factory that lends a connection someone else owns (dataSource=redb : the connection a redb service
/// works on, in the transaction redb's commands run in) implements and
/// .
///
public interface ISqlConnectionFactory
{
/// Creates an opened database connection.
/// Hint for read/write split: true = read replica, false = primary.
/// Cancellation token.
/// An opened .
Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default);
///
/// True when lends a connection the endpoint does not own. The endpoint then begins no
/// transaction of its own (it runs in the lender's transaction, or in autocommit when there is none), keeps no reader
/// open past the step (outputType=StreamList is refused), and is refused where no exchange holds the lease (the
/// polling consumer, the idempotent and claim-check repositories). Default: false.
///
bool LendsConnection => false;
///
/// The factory a data source name with a qualifier stands for: dataSource=redb:orders finds the factory
/// registered under redb and asks it for orders . Called when the endpoint resolves its factory (the
/// producer's start, and every exchange), with null for the bare name. Throws when the qualifier names nothing the
/// factory knows, so a wrong name fails at start. Default: this factory for the bare name, a refusal for a qualifier.
///
/// The part of the data source name after the first : ; null for the bare name.
ISqlConnectionFactory ForQualifier(string? qualifier)
=> qualifier is null
? this
: throw new InvalidOperationException(
$"{GetType().Name} takes no qualifier, and the data source name asks for '{qualifier}'. Register a " +
$"connection factory under the whole name, or remove ':{qualifier}' from the data source.");
///
/// The connection one sql: step runs on, given back when the lease is disposed. Default: a connection of the
/// step's own from , closed when the lease is disposed.
///
/// The exchange the step runs for; a lending factory finds the lender through it.
/// Hint for read/write split, as in .
/// Cancellation token.
async Task LeaseAsync(IExchange exchange, bool readOnly = false, CancellationToken ct = default)
=> SqlConnectionLease.Owned(await CreateConnectionAsync(readOnly, ct).ConfigureAwait(false));
}
Path: redb-route/redb.Route.Sql/Connection/SqlAmbientTransaction.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/SqlAmbientTransaction.cs
----
using System.Data.Common;
using System.Globalization;
using System.Transactions;
namespace redb.Route.Sql.Connection;
///
/// A sql: step inside a .Transacted() block writes through the block's transaction only if its connection
/// enlists in it. Npgsql, SqlClient, MySqlConnector and the Oracle provider do so by default; the Firebird client only
/// with Enlist=true ; Microsoft.Data.Sqlite never does; and any provider with Enlist=false or
/// AutoEnlist=false in its connection string opts out.
/// Such a connection would run the statement in autocommit and a rolled-back block would leave its rows behind, so the
/// step refuses before it writes.
///
internal static class SqlAmbientTransaction
{
///
/// The refusal to throw when an ambient transaction is running and stays out of it;
/// null when the step may write. The caller disposes the connection before it throws.
///
public static InvalidOperationException? Refusal(DbConnection connection)
{
if (Transaction.Current is null || Joins(connection))
return null;
return new InvalidOperationException(
$"This sql: step runs inside a .Transacted() block, and its {connection.GetType().Name} connection does not join " +
"the block's transaction: the statement would commit on its own and stay when the block rolls back. Use a " +
"provider that enlists in System.Transactions (PostgreSQL, SQL Server), remove Enlist=false from the connection " +
"string, or run the step outside the block.");
}
private static bool Joins(DbConnection connection)
{
// Microsoft.Data.Sqlite has no System.Transactions support at all.
if (connection.GetType().FullName == "Microsoft.Data.Sqlite.SqliteConnection")
return false;
var settings = new DbConnectionStringBuilder { ConnectionString = connection.ConnectionString };
// The Firebird client enlists only when asked to: Enlist is off by default there.
if (connection.GetType().Name == "FbConnection")
return settings.TryGetValue("Enlist", out var fbEnlist)
&& Convert.ToString(fbEnlist, CultureInfo.InvariantCulture)?.Trim().ToLowerInvariant() is "true" or "yes";
foreach (var key in new[] { "Enlist", "AutoEnlist", "Auto Enlist" })
{
if (settings.TryGetValue(key, out var value)
&& Convert.ToString(value, CultureInfo.InvariantCulture)?.Trim().ToLowerInvariant() is "false" or "no")
return false;
}
return true;
}
}
Path: redb-route/redb.Route.Sql/Connection/SqlConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/SqlConnectionFactory.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Connection;
///
/// Default connection factory. Resolves from the provider
/// registry and creates connections from a connection string.
/// Supports optional read/write splitting and connection validation on borrow.
///
public sealed class SqlConnectionFactory : ISqlConnectionFactory
{
private readonly SqlConnectionOptions _options;
private readonly DbProviderFactory _providerFactory;
/// Creates a connection factory from the given options.
/// Connection configuration.
public SqlConnectionFactory(SqlConnectionOptions options)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
_providerFactory = options.ProviderFactory
?? ResolveProviderFactory(options.ProviderName);
}
///
public async Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default)
{
var connectionString = readOnly && !string.IsNullOrEmpty(_options.ReadConnectionString)
? _options.ReadConnectionString
: _options.ConnectionString;
var attempts = 0;
var maxAttempts = _options.EnableRetryOnFailure ? _options.MaxRetries + 1 : 1;
while (true)
{
attempts++;
DbConnection? connection = null;
try
{
connection = _providerFactory.CreateConnection()
?? throw new InvalidOperationException(
$"DbProviderFactory ({_options.ProviderName}) returned null from CreateConnection().");
connection.ConnectionString = connectionString;
await connection.OpenAsync(ct).ConfigureAwait(false);
if (_options.TestOnBorrow)
{
await ValidateConnectionAsync(connection, ct).ConfigureAwait(false);
}
return connection;
}
catch (OperationCanceledException) { connection?.Dispose(); throw; }
catch
{
connection?.Dispose();
if (attempts >= maxAttempts)
throw;
await Task.Delay(_options.RetryDelay, ct).ConfigureAwait(false);
}
}
}
private async Task ValidateConnectionAsync(DbConnection connection, CancellationToken ct)
{
using var cmd = connection.CreateCommand();
cmd.CommandText = _options.ValidationQuery;
cmd.CommandTimeout = _options.ValidationTimeout;
await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
}
private static DbProviderFactory ResolveProviderFactory(string providerName)
{
if (string.IsNullOrEmpty(providerName))
throw new ArgumentException(
"Either ProviderFactory or ProviderName must be specified in SqlConnectionOptions.");
if (!DbProviderFactories.TryGetFactory(providerName, out var factory))
throw new InvalidOperationException(
$"ADO.NET provider '{providerName}' is not registered. " +
"Call DbProviderFactories.RegisterFactory() or set ProviderFactory explicitly.");
return factory;
}
}
Path: redb-route/redb.Route.Sql/Connection/SqlConnectionLease.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/SqlConnectionLease.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Connection;
///
/// The connection one sql: step runs on: an open connection, the transaction its commands must be bound to, and
/// how it is given back. wraps a connection of the step's own, closed on release;
/// wraps a connection someone else owns (redb's, through dataSource=redb ), handed back on release and never closed.
///
public sealed class SqlConnectionLease : IAsyncDisposable
{
private readonly Func _release;
private int _released;
private SqlConnectionLease(DbConnection connection, DbTransaction? transaction, bool isBorrowed, Func release)
{
Connection = connection;
Transaction = transaction;
IsBorrowed = isBorrowed;
_release = release;
}
/// A connection of the step's own: disposes it.
/// The opened connection.
public static SqlConnectionLease Owned(DbConnection connection)
{
ArgumentNullException.ThrowIfNull(connection);
return new SqlConnectionLease(connection, null, isBorrowed: false, connection.DisposeAsync);
}
///
/// A connection the step does not own. gives it back once and must not close it. The step
/// begins no transaction of its own on it, binds every command to , and keeps no reader
/// open past the release.
///
/// The open connection.
/// The transaction the commands must be bound to; null when the driver runs them in the
/// connection's transaction by itself (an enlisted connection) or none is active (autocommit).
/// Gives the connection back; called once by .
public static SqlConnectionLease Borrowed(DbConnection connection, DbTransaction? transaction, Func release)
{
ArgumentNullException.ThrowIfNull(connection);
ArgumentNullException.ThrowIfNull(release);
return new SqlConnectionLease(connection, transaction, isBorrowed: true, release);
}
/// The open connection.
public DbConnection Connection { get; }
/// The transaction every command must be bound to; null when none is needed. binds it.
public DbTransaction? Transaction { get; }
/// True when the connection is lent ( ): the step neither owns it nor its transaction.
public bool IsBorrowed { get; }
/// A command on , bound to . The caller disposes it.
public DbCommand CreateCommand()
{
if (Volatile.Read(ref _released) != 0)
throw new ObjectDisposedException(nameof(SqlConnectionLease), "The lease was already released.");
var command = Connection.CreateCommand();
command.Transaction = Transaction;
return command;
}
/// Gives the connection back: disposes an owned one, hands a borrowed one back. The second call does nothing.
public ValueTask DisposeAsync()
=> Interlocked.Exchange(ref _released, 1) != 0 ? default : _release();
}
Path: redb-route/redb.Route.Sql/Connection/SqlConnectionOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/SqlConnectionOptions.cs
----
namespace redb.Route.Sql.Connection;
///
/// Configuration options for a named data source connection.
///
public sealed class SqlConnectionOptions
{
/// Primary connection string (used for writes and default reads).
public string ConnectionString { get; set; } = string.Empty;
///
/// Read replica connection string. Used only by endpoints with readOnly=true ( );
/// every other statement, and every statement when this is not set, goes through .
///
public string? ReadConnectionString { get; set; }
///
/// ADO.NET provider invariant name (e.g. "Microsoft.Data.SqlClient", "Npgsql", "MySqlConnector").
/// Used to resolve from the provider registry.
///
public string ProviderName { get; set; } = string.Empty;
///
/// Explicit instance.
/// Takes priority over if both are set.
///
public System.Data.Common.DbProviderFactory? ProviderFactory { get; set; }
/// Minimum connection pool size. Default: 0 (provider default).
public int MinPoolSize { get; set; }
/// Maximum connection pool size. Default: 100.
public int MaxPoolSize { get; set; } = 100;
/// Maximum lifetime of a connection. Default: (unlimited).
public TimeSpan ConnectionLifetime { get; set; } = TimeSpan.Zero;
/// Idle timeout before a pooled connection is closed. Default: 5 minutes.
public TimeSpan ConnectionIdleTimeout { get; set; } = TimeSpan.FromMinutes(5);
/// Validate connection on checkout from pool. Default: false.
public bool TestOnBorrow { get; set; }
/// SQL used to validate a connection. Default: "SELECT 1".
public string ValidationQuery { get; set; } = "SELECT 1";
/// Timeout for validation query in seconds. Default: 5.
public int ValidationTimeout { get; set; } = 5;
/// Timeout for establishing a new connection in seconds. Default: 15.
public int ConnectTimeout { get; set; } = 15;
/// Default command execution timeout in seconds. Default: 30.
public int CommandTimeout { get; set; } = 30;
/// Number of retry attempts for transient failures. Default: 0 (no retry).
public int MaxRetries { get; set; }
/// Delay between retry attempts. Default: 1 second.
public TimeSpan RetryDelay { get; set; } = TimeSpan.FromSeconds(1);
/// Enable automatic retry on transient failures. Default: false.
public bool EnableRetryOnFailure { get; set; }
}
Path: redb-route/redb.Route.Sql/Connection/SqlConnections.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Connection/SqlConnections.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Sql.Connection;
/// How a sql: producer path takes the connection of one exchange.
internal static class SqlConnections
{
///
/// The refusal of outputType=StreamList on a lent connection: the stream would keep a reader open on the
/// lender's connection after the lease is given back.
///
public static InvalidOperationException StreamOnLentConnection(string? dataSource)
=> new(
$"outputType=StreamList keeps a reader open after the endpoint, and dataSource={dataSource} lends a connection " +
"only for the time of the step: the reader would outlive the lease, on a connection that is not this endpoint's. " +
"Use outputType=SelectList, which reads the rows before the connection is given back.");
///
/// Refuses a lending factory (dataSource=redb ) for a repository: a repository is called without an exchange to
/// find the lender through, and it commits its own statements.
///
public static void RefuseLending(ISqlConnectionFactory factory, string repository, string paramName)
{
if (factory.LendsConnection)
throw new ArgumentException(
$"{repository} keeps its rows on a connection of its own and commits them itself, and this connection factory " +
"lends a connection (dataSource=redb) to one sql: step of an exchange. Give the repository a factory with a " +
"connection string of its own (it may name the same database).", paramName);
}
///
/// A lent connection when the factory lends one ( ), otherwise a
/// connection of the step's own from , refused (and closed)
/// when an ambient transaction runs and the connection stays out of it.
///
public static async Task OpenAsync(
ISqlConnectionFactory factory, IExchange exchange, bool readOnly, CancellationToken ct)
{
if (factory.LendsConnection)
return await factory.LeaseAsync(exchange, readOnly, ct).ConfigureAwait(false);
var connection = await factory.CreateConnectionAsync(readOnly, ct).ConfigureAwait(false);
if (SqlAmbientTransaction.Refusal(connection) is { } refusal)
{
await connection.DisposeAsync().ConfigureAwait(false);
throw refusal;
}
return SqlConnectionLease.Owned(connection);
}
}
Path: redb-route/redb.Route.Sql/ConsumerRowStream.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/ConsumerRowStream.cs
----
using System.Data.Common;
using System.Runtime.CompilerServices;
namespace redb.Route.Sql;
/// Creates the body of a streaming poll delivered as one list, for a row type known only at run time.
internal static class ConsumerRowStream
{
/// A stream of rows over a reader positioned on its first row.
internal static object Create(Type elementType, DbDataReader reader, Func map, int maxRows) =>
Activator.CreateInstance(typeof(ConsumerRowStream<>).MakeGenericType(elementType), reader, map, maxRows)!;
}
///
/// The body of a poll with outputType=StreamList and pollDelivery=List : the rows of the consumer's open reader,
/// which is positioned on the first row. The consumer owns the reader and closes it as soon as the route is done, so the rows
/// are read once, while the route runs; at most maxMessagesPerPoll of them.
///
internal sealed class ConsumerRowStream(DbDataReader reader, Func map, int maxRows) : IAsyncEnumerable
{
private int _enumerated;
///
/// The rows were already read, or the route has finished.
public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _enumerated, 1) != 0)
throw new InvalidOperationException(
"The rows of a streaming poll (outputType=StreamList, pollDelivery=List) can be read once: they come from one open reader.");
if (reader.IsClosed)
throw new InvalidOperationException(
"The rows of a streaming poll (outputType=StreamList, pollDelivery=List) are read while the route runs; the reader is closed.");
return ReadRows(cancellationToken).GetAsyncEnumerator(cancellationToken);
}
private async IAsyncEnumerable ReadRows([EnumeratorCancellation] CancellationToken ct)
{
var count = 0;
do
{
if (maxRows >= 0 && count >= maxRows)
yield break;
yield return (T)map(reader);
count++;
}
while (await reader.ReadAsync(ct).ConfigureAwait(false));
}
}
Path: redb-route/redb.Route.Sql/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using redb.Route.Extensions;
using redb.Route.Sql.Connection;
namespace redb.Route.Sql;
///
/// Extension methods for registering the SQL transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that
/// sql: URIs are resolved.
/// Named data sources are registered in the context registry via
/// context.AddToRegistry(name, ISqlConnectionFactory) .
/// The method can be called more than once (one module, one call): every call adds its data sources and named queries
/// to the same component and the same registry.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteSql(sql =>
/// {
/// sql.AddDataSource("main", opts =>
/// {
/// opts.ConnectionString = "Server=...";
/// opts.ProviderName = "Microsoft.Data.SqlClient";
/// });
/// });
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteSql(
this IServiceCollection services,
Action? configure = null)
{
// One registry per container: a later call registers into it instead of replacing it, so the named queries of
// every call resolve. A name registered twice fails right here, in the second call.
var registry = services.FirstOrDefault(d => d.ServiceType == typeof(ISqlNamedQueryRegistry))?.ImplementationInstance
as ISqlNamedQueryRegistry;
if (registry is null)
{
registry = new SqlNamedQueryRegistry();
services.AddSingleton(registry);
}
var builder = new SqlConfigurationBuilder(services, registry);
configure?.Invoke(builder);
services.TryAddSingleton();
// Capture data sources from builder
var dataSources = builder.BuildDataSources();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
if (!context.HasComponent("sql"))
context.AddComponent(sp.GetRequiredService());
// The producer and the consumer resolve ref: queries from the context's services.
context.AddService(typeof(ISqlNamedQueryRegistry), sp.GetRequiredService());
// Register all named data sources in the context registry
foreach (var (name, factory) in dataSources)
context.AddToRegistry(name, factory);
});
return services;
}
}
/// Fluent builder for configuring the SQL connector.
public sealed class SqlConfigurationBuilder
{
private readonly IServiceCollection _services;
private readonly List> _dataSources = [];
private readonly ISqlNamedQueryRegistry _queryRegistry;
internal SqlConfigurationBuilder(IServiceCollection services, ISqlNamedQueryRegistry queryRegistry)
{
_services = services;
_queryRegistry = queryRegistry;
}
/// The service collection.
public IServiceCollection Services => _services;
///
/// Adds a named data source that will be resolved via dataSource=name in SQL URIs.
///
public SqlConfigurationBuilder AddDataSource(string name, Action configure)
{
var options = new SqlConnectionOptions();
configure(options);
var factory = new SqlConnectionFactory(options);
_dataSources.Add(new(name, factory));
return this;
}
///
/// Adds a named data source with a pre-built connection factory.
///
public SqlConfigurationBuilder AddDataSource(string name, ISqlConnectionFactory factory)
{
_dataSources.Add(new(name, factory));
return this;
}
///
/// Registers a named query for reuse via ref:queryName protocol.
///
/// The name is already registered, by this call or an earlier one.
public SqlConfigurationBuilder AddNamedQuery(string name, string sql)
{
_queryRegistry.Register(name, sql);
return this;
}
internal IReadOnlyList> BuildDataSources() => _dataSources;
}
Path: redb-route/redb.Route.Sql/Fluent/SqlDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Fluent/SqlDsl.cs
----
using System.Data;
using System.Globalization;
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.Sql;
///
/// Entry point for the SQL Fluent API. Three methods → three modes.
/// Each returns a for fluent configuration.
///
/// The builder generates a URI string that is fully equivalent to writing the URI manually.
/// Both paths converge in via URI binding → same result.
///
///
///
/// // Fluent:
/// .From(Sql.Poll("SELECT * FROM outbox WHERE processed = 0")
/// .DataSource("main").Delay(5000).Transacted()
/// .OnSuccess("UPDATE outbox SET processed = 1 WHERE id = :#id"))
///
/// // URI (equivalent):
/// .From("sql:SELECT * FROM outbox WHERE processed = 0?mode=Poll&dataSource=main&delay=5000&transacted=true&onSuccess=...")
///
///
///
public static class Sql
{
/// Creates a polling consumer that repeatedly executes a SELECT query.
/// SQL SELECT query or ref:name reference.
public static SqlBuilder Poll(string sql) => new(SqlMode.Poll, sql);
/// Creates a producer that executes INSERT/UPDATE/DELETE/SELECT statements.
/// SQL statement or ref:name reference.
public static SqlBuilder Execute(string sql) => new(SqlMode.Execute, sql);
/// Creates a producer that calls a stored procedure or function.
/// Stored procedure or function name.
public static SqlBuilder Procedure(string name) => new(SqlMode.Procedure, name);
}
///
/// Fluent builder for SQL endpoint URIs. Thin sugar over .
/// Call or use implicit conversion to
/// to get the URI for From() / To() .
///
public sealed class SqlBuilder
{
private readonly SqlMode _mode;
private readonly string _queryOrProcedure;
private string? _dataSource;
private string? _connectionString;
private string? _provider;
private string? _commandTimeout;
private bool _transacted;
private IsolationLevel? _isolationLevel;
private SqlOutputType? _outputType;
private string? _outputClass;
private string? _outputHeader;
private bool _noop;
private string? _delay;
private string? _initialDelay;
private bool _fixedRate;
private string? _repeatCount;
private string? _maxMessagesPerPoll;
private bool _routeEmptyResultSet;
private bool _sendEmptyMessageWhenIdle;
private string? _onSuccess;
private string? _onFailure;
private string? _onBatchComplete;
private string? _batchSize;
private bool? _breakBatchOnError;
private bool _readOnly;
private SqlPlaceholderStyle? _placeholderStyle;
private bool _backslashEscapes;
private bool _asFunction;
private readonly List _procedureParams = [];
private readonly List<(string Name, string Value)> _explicitParams = [];
/// Creates a builder for the given mode and query/procedure name.
internal SqlBuilder(SqlMode mode, string queryOrProcedure)
{
ArgumentException.ThrowIfNullOrWhiteSpace(queryOrProcedure);
_mode = mode;
_queryOrProcedure = queryOrProcedure;
}
// ── Connection ────────────────────────────────────────────────────
/// Sets the named data source (constant name, e.g. "main" ).
public SqlBuilder DataSource(string name) { _dataSource = name; return this; }
///
/// Sets the named data source from a constant expression. The data source is fixed when the endpoint is created: a
/// ${...} expression is refused — as in Apache Camel, a dynamic target is a dynamic endpoint (ToD ).
///
/// The expression is not a constant.
public SqlBuilder DataSource(IExpression name) { _dataSource = ConstantOnly(name, "dataSource"); return this; }
/// Sets a direct connection string.
public SqlBuilder ConnectionString(string cs) { _connectionString = cs; return this; }
/// Sets a direct connection string from a constant expression; a ${...} expression is refused, as for .
/// The expression is not a constant.
public SqlBuilder ConnectionString(IExpression cs) { _connectionString = ConstantOnly(cs, "connectionString"); return this; }
private static string ConstantOnly(IExpression expression, string option)
{
ArgumentNullException.ThrowIfNull(expression);
var text = expression.ToTemplateString();
if (text.Contains("${", StringComparison.Ordinal))
{
throw new ArgumentException(
$"{option} is fixed when the endpoint is created and cannot come from the expression '{text}'. " +
"As in Apache Camel, route to a dynamic endpoint (ToD, RecipientList) instead.", nameof(expression));
}
return text;
}
/// Sets the ADO.NET provider name.
public SqlBuilder Provider(string name) { _provider = name; return this; }
/// Sets the command timeout in seconds.
public SqlBuilder CommandTimeout(int seconds) { _commandTimeout = seconds.ToString(CultureInfo.InvariantCulture); return this; }
/// Sets the command timeout from an expression.
public SqlBuilder CommandTimeout(IExpression seconds) { _commandTimeout = seconds.ToTemplateString(); return this; }
// ── Transaction ───────────────────────────────────────────────────
/// Enables transaction wrapping.
public SqlBuilder Transacted() { _transacted = true; return this; }
///
/// Runs the statement on the data source's read replica. Declare it only for a statement that does not write; a batch, and a
/// poll with lifecycle SQL or a transaction, refuse it (see ).
///
public SqlBuilder ReadOnly() { _readOnly = true; return this; }
///
/// How :#name placeholders are written for the provider: @name (the default), :name (Oracle) or
/// ? (ODBC) — see .
///
public SqlBuilder PlaceholderStyle(SqlPlaceholderStyle style) { _placeholderStyle = style; return this; }
///
/// Reads a backslash inside '…' and "…" as an escape, as MySQL and MariaDB do by default — see
/// .
///
public SqlBuilder BackslashEscapes() { _backslashEscapes = true; return this; }
/// Sets the transaction isolation level.
public SqlBuilder WithIsolationLevel(IsolationLevel level) { _isolationLevel = level; return this; }
// ── Output ────────────────────────────────────────────────────────
/// Sets how query results are mapped.
public SqlBuilder OutputType(SqlOutputType type) { _outputType = type; return this; }
/// Sets the POCO type name for result mapping.
public SqlBuilder OutputClass(string typeName) { _outputClass = typeName; return this; }
/// Sends the result to a header instead of the body.
public SqlBuilder OutputHeader(IExpression headerName) { _outputHeader = headerName.ToTemplateString(); return this; }
/// Enables dry-run mode.
public SqlBuilder Noop() { _noop = true; return this; }
// ── Polling ───────────────────────────────────────────────────────
/// Sets the delay between polls in milliseconds.
public SqlBuilder Delay(int ms) { _delay = ms.ToString(CultureInfo.InvariantCulture); return this; }
/// Sets the delay from an expression.
public SqlBuilder Delay(IExpression ms) { _delay = ms.ToTemplateString(); return this; }
/// Sets the initial delay before the first poll.
public SqlBuilder InitialDelay(int ms) { _initialDelay = ms.ToString(CultureInfo.InvariantCulture); return this; }
/// Sets the initial delay from an expression.
public SqlBuilder InitialDelay(IExpression ms) { _initialDelay = ms.ToTemplateString(); return this; }
/// Enables fixed-rate polling.
public SqlBuilder FixedRate() { _fixedRate = true; return this; }
/// Sets the maximum number of poll cycles.
public SqlBuilder RepeatCount(long count) { _repeatCount = count.ToString(CultureInfo.InvariantCulture); return this; }
/// Sets the repeat count from an expression.
public SqlBuilder RepeatCount(IExpression count) { _repeatCount = count.ToTemplateString(); return this; }
/// Sets the maximum rows per poll.
public SqlBuilder MaxMessagesPerPoll(int max) { _maxMessagesPerPoll = max.ToString(CultureInfo.InvariantCulture); return this; }
/// Sets max messages per poll from an expression.
public SqlBuilder MaxMessagesPerPoll(IExpression max) { _maxMessagesPerPoll = max.ToTemplateString(); return this; }
/// Creates an Exchange even on empty result.
public SqlBuilder RouteEmptyResultSet() { _routeEmptyResultSet = true; return this; }
/// Sends idle notification when nothing to poll.
public SqlBuilder SendEmptyMessageWhenIdle() { _sendEmptyMessageWhenIdle = true; return this; }
// ── Lifecycle SQL ─────────────────────────────────────────────────
/// SQL to execute after each row is successfully processed.
public SqlBuilder OnSuccess(string sql) { _onSuccess = sql; return this; }
/// SQL to execute when processing a row fails.
public SqlBuilder OnFailure(string sql) { _onFailure = sql; return this; }
/// SQL to execute after the entire batch.
public SqlBuilder OnBatchComplete(string sql) { _onBatchComplete = sql; return this; }
private SqlPollDelivery? _pollDelivery;
///
/// How polled rows reach the route: an exchange per row (the default) or one exchange with every row
/// ( , Apache Camel useIterator=false ).
///
public SqlBuilder PollDelivery(SqlPollDelivery delivery) { _pollDelivery = delivery; return this; }
// ── Batch ─────────────────────────────────────────────────────────
/// Enables batch mode for producer mode: a list body is written item by item in one transaction.
public SqlBuilder Batch(int size) { _batchSize = size.ToString(CultureInfo.InvariantCulture); return this; }
///
/// Sets the batch size from an expression. Only constant expressions and {{property}} placeholders are accepted:
/// the value is read when the endpoint is created, and a ${...} expression fails endpoint creation.
///
public SqlBuilder Batch(IExpression size) { _batchSize = size.ToTemplateString(); return this; }
/// Stops the batch on the first error and rolls it back (the default).
public SqlBuilder BreakBatchOnError() { _breakBatchOnError = true; return this; }
///
/// Chooses what a failing batch item does: true stops and rolls the batch back (the default); false undoes
/// the failed item to its savepoint, reports it in and commits the others.
///
public SqlBuilder BreakBatchOnError(bool enabled) { _breakBatchOnError = enabled; return this; }
// ── Explicit Parameters ─────────────────────────────────────────
///
/// Binds a SQL parameter to an explicit value, overriding auto-bind from headers/body.
/// Values containing ${...} are resolved as expressions at runtime.
///
/// Parameter name, bare (id ) or as written in the statement (:#id ).
/// Constant value or expression string.
/// The name starts with @ , which is not a placeholder.
public SqlBuilder Param(string name, object? value)
{
// null → "" → ResolveParamValue → DBNull.Value (SQL NULL)
_explicitParams.Add((ParamName(name), FormatConstant(value)));
return this;
}
///
/// A constant as the database reads it, whatever the culture of the process: numbers with a decimal point, dates and times
/// as ISO 8601 round-trip text.
///
private static string FormatConstant(object? value) => value switch
{
null => "",
string text => text,
DateTime dateTime => dateTime.ToString("O", CultureInfo.InvariantCulture),
DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("O", CultureInfo.InvariantCulture),
DateOnly date => date.ToString("O", CultureInfo.InvariantCulture),
TimeOnly time => time.ToString("O", CultureInfo.InvariantCulture),
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString() ?? "",
};
///
/// Binds a SQL parameter to an expression, resolved at runtime.
///
/// Parameter name, bare (id ) or as written in the statement (:#id ).
/// Expression that produces the parameter value.
/// The name starts with @ , which is not a placeholder.
public SqlBuilder Param(string name, IExpression expression)
{
ArgumentNullException.ThrowIfNull(expression);
_explicitParams.Add((ParamName(name), expression.ToTemplateString()));
return this;
}
private static string ParamName(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
if (name.StartsWith('@'))
{
var bare = name.TrimStart('@');
throw new ArgumentException(
$"SQL parameters are written :#name, and '{name}' starts with '@', which the database keeps for its own variables. " +
$"Use Param(\"{bare}\", ...) or Param(\":#{bare}\", ...).", nameof(name));
}
return name.StartsWith(":#", StringComparison.Ordinal) ? name[2..] : name;
}
// ── Procedure ─────────────────────────────────────────────────────
/// Calls as a function instead of a procedure.
public SqlBuilder AsFunction() { _asFunction = true; return this; }
/// Adds an IN parameter definition.
public SqlBuilder In(string name, DbType type)
{
_procedureParams.Add(new(SqlParamDirection.In, name, type, null));
return this;
}
/// Adds an IN parameter with an expression value.
public SqlBuilder In(string name, DbType type, string expression)
{
_procedureParams.Add(new(SqlParamDirection.In, name, type, expression));
return this;
}
/// Adds an OUT parameter definition.
public SqlBuilder Out(string name, DbType type)
{
_procedureParams.Add(new(SqlParamDirection.Out, name, type, null));
return this;
}
/// Adds an INOUT parameter definition.
public SqlBuilder InOut(string name, DbType type)
{
_procedureParams.Add(new(SqlParamDirection.InOut, name, type, null));
return this;
}
// ── Build ─────────────────────────────────────────────────────────
/// Builds the URI string for use in From() / To() .
public string Build()
{
var sb = new StringBuilder();
sb.Append("sql:");
sb.Append(_queryOrProcedure);
var separator = '?';
void Append(string key, string value)
{
sb.Append(separator);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(value));
separator = '&';
}
void AppendIf(string key, string? value)
{
if (value != null) Append(key, value);
}
void AppendBool(string key, bool value)
{
if (value) Append(key, "true");
}
// Mode (always present)
Append("mode", _mode.ToString());
// Connection
AppendIf("dataSource", _dataSource);
AppendIf("connectionString", _connectionString);
AppendIf("provider", _provider);
AppendIf("commandTimeout", _commandTimeout);
AppendBool("transacted", _transacted);
AppendBool("readOnly", _readOnly);
if (_placeholderStyle.HasValue) Append("placeholderStyle", _placeholderStyle.Value.ToString());
AppendBool("backslashEscapes", _backslashEscapes);
if (_isolationLevel.HasValue) Append("isolationLevel", _isolationLevel.Value.ToString());
// Output
if (_outputType.HasValue) Append("outputType", _outputType.Value.ToString());
AppendIf("outputClass", _outputClass);
AppendIf("outputHeader", _outputHeader);
AppendBool("noop", _noop);
// Polling
AppendIf("delay", _delay);
AppendIf("initialDelay", _initialDelay);
AppendBool("fixedRate", _fixedRate);
AppendIf("repeatCount", _repeatCount);
AppendIf("maxMessagesPerPoll", _maxMessagesPerPoll);
AppendBool("routeEmptyResultSet", _routeEmptyResultSet);
AppendBool("sendEmptyMessageWhenIdle", _sendEmptyMessageWhenIdle);
if (_pollDelivery.HasValue) Append("pollDelivery", _pollDelivery.Value.ToString());
// Lifecycle SQL
AppendIf("onSuccess", _onSuccess);
AppendIf("onFailure", _onFailure);
AppendIf("onBatchComplete", _onBatchComplete);
// Batch
AppendIf("batchSize", _batchSize);
if (_breakBatchOnError.HasValue) Append("breakBatchOnError", _breakBatchOnError.Value ? "true" : "false");
// Explicit parameters
foreach (var (name, value) in _explicitParams)
Append($"param.{name}", value);
// Procedure
AppendBool("asFunction", _asFunction);
if (_procedureParams.Count > 0)
{
var paramStr = string.Join(",", _procedureParams.Select(p => p.Serialize()));
Append("procedureParams", paramStr);
}
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(SqlBuilder builder) => builder.Build();
///
public override string ToString() => Build();
// ── Internal ──────────────────────────────────────────────────────
private readonly record struct ProcedureParamDef(SqlParamDirection Direction, string Name, DbType Type, string? Expression)
{
public string Serialize()
{
var dir = Direction.ToString().ToUpperInvariant();
var result = $"{dir}:{Name}:{Type}";
return Expression != null ? $"{result}:{Expression}" : result;
}
}
}
Path: redb-route/redb.Route.Sql/Mapping/ColumnNameMatcher.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/ColumnNameMatcher.cs
----
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
namespace redb.Route.Sql.Mapping;
///
/// Which property a column or parameter name refers to: a property of that name ignoring case, then a property whose
/// carries the name, then the snake_case name read as PascalCase (user_name →
/// UserName ). Result rows are mapped to objects and batch items to parameters by this one rule.
///
internal static class ColumnNameMatcher
{
/// The property among that refers to, or null.
internal static PropertyInfo? Find(PropertyInfo[] properties, string name)
{
// Direct case-insensitive match
var property = Array.Find(properties, p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (property != null) return property;
// [Column] attribute match
property = Array.Find(properties, p =>
p.GetCustomAttribute()?.Name?.Equals(name, StringComparison.OrdinalIgnoreCase) == true);
if (property != null) return property;
// snake_case → PascalCase: user_name → UserName
var pascal = SnakeToPascal(name);
return Array.Find(properties, p => p.Name.Equals(pascal, StringComparison.OrdinalIgnoreCase));
}
private static string SnakeToPascal(string snake)
{
var parts = snake.Split('_', StringSplitOptions.RemoveEmptyEntries);
return string.Concat(parts.Select(p =>
string.Concat(char.ToUpperInvariant(p[0]).ToString(), p.AsSpan(1))));
}
}
Path: redb-route/redb.Route.Sql/Mapping/DictionaryRowMapper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/DictionaryRowMapper.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Mapping;
///
/// Maps a row to Dictionary<string, object?> .
/// Column names are keys, values are as-is from the provider (DBNull → null).
///
public sealed class DictionaryRowMapper : ISqlRowMapper>
{
///
public Dictionary Map(DbDataReader reader)
{
var fieldCount = reader.FieldCount;
var row = new Dictionary(fieldCount, StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < fieldCount; i++)
{
var name = reader.GetName(i);
var value = reader.IsDBNull(i) ? null : reader.GetValue(i);
row[name] = value;
}
return row;
}
}
Path: redb-route/redb.Route.Sql/Mapping/ISqlRowMapper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/ISqlRowMapper.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Mapping;
///
/// Maps a row to type .
///
/// Target type.
public interface ISqlRowMapper
{
/// Maps the current row of the reader to an object.
/// Positioned reader (ReadAsync already called).
/// Mapped object.
T Map(DbDataReader reader);
}
Path: redb-route/redb.Route.Sql/Mapping/PocoRowMapper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/PocoRowMapper.cs
----
using System.Collections.Concurrent;
using System.Data.Common;
using System.Reflection;
namespace redb.Route.Sql.Mapping;
///
/// Maps a row to a POCO of type
/// via reflection. Caches property accessors per type for performance.
/// Supports case-insensitive and snake_case → PascalCase column matching.
///
///
/// A column without a writable property is skipped. A value reaches its property only when the conversion is lossless and
/// unambiguous (see ); a NULL sets a nullable or reference property to null. Anything else —
/// a NULL for a value type, an overflow, a timestamp without a time zone for a — throws, as
/// Apache Camel's BeanPropertyRowMapper refuses a type mismatch.
///
/// POCO type with a parameterless constructor.
public sealed class PocoRowMapper : ISqlRowMapper where T : new()
{
private static readonly ConcurrentDictionary _propertyCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly PropertyInfo[] _allProps = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
///
///
/// A column's value cannot be assigned to its property without loss or guessing. The message names the column, the
/// property and both types, never the value.
///
public T Map(DbDataReader reader)
{
var obj = new T();
var fieldCount = reader.FieldCount;
for (var i = 0; i < fieldCount; i++)
{
var columnName = reader.GetName(i);
var prop = ResolveProperty(columnName);
if (prop == null || !prop.CanWrite) continue;
if (reader.IsDBNull(i))
{
if (!SqlValueConverter.AcceptsNull(prop.PropertyType))
throw MappingError(columnName, "NULL", prop, "a NULL cannot be assigned to a non-nullable value type; make the property nullable");
prop.SetValue(obj, null);
continue;
}
var value = reader.GetValue(i);
if (!SqlValueConverter.TryConvert(value, prop.PropertyType, out var converted, out var reason))
throw MappingError(columnName, value.GetType().Name, prop, reason);
prop.SetValue(obj, converted);
}
return obj;
}
private static SqlRowMappingException MappingError(string column, string sourceType, PropertyInfo prop, string reason) =>
new($"Column '{column}' ({sourceType}) cannot be assigned to {typeof(T).Name}.{prop.Name} " +
$"({SqlValueConverter.TypeName(prop.PropertyType)}): {reason}.");
private static PropertyInfo? ResolveProperty(string columnName) =>
_propertyCache.GetOrAdd(columnName, name => ColumnNameMatcher.Find(_allProps, name));
}
Path: redb-route/redb.Route.Sql/Mapping/ScalarMapper.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/ScalarMapper.cs
----
using System.Data.Common;
namespace redb.Route.Sql.Mapping;
///
/// Maps the first column of the current row to a scalar value.
/// A is null for a nullable or reference and an error for a value type;
/// other values convert only when that is lossless and unambiguous, as does.
///
/// Scalar value type.
public sealed class ScalarMapper : ISqlRowMapper
{
///
/// The value cannot be read as without loss or guessing.
public T? Map(DbDataReader reader)
{
if (reader.IsDBNull(0))
{
if (!SqlValueConverter.AcceptsNull(typeof(T)))
throw new SqlRowMappingException(
$"Column '{reader.GetName(0)}' is NULL and cannot be read as {SqlValueConverter.TypeName(typeof(T))}: " +
"use a nullable type.");
return default;
}
var value = reader.GetValue(0);
if (!SqlValueConverter.TryConvert(value, typeof(T), out var converted, out var reason))
throw new SqlRowMappingException(
$"Column '{reader.GetName(0)}' ({value.GetType().Name}) cannot be read as {SqlValueConverter.TypeName(typeof(T))}: {reason}.");
return (T?)converted;
}
}
Path: redb-route/redb.Route.Sql/Mapping/SqlRowMapperFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/SqlRowMapperFactory.cs
----
using System.Collections;
using System.Data.Common;
using System.Reflection;
using redb.Route.Abstractions;
namespace redb.Route.Sql.Mapping;
///
/// Resolves the outputClass endpoint option to a .
/// The option carries a type name (assembly-qualified or plain, resolved against loaded
/// assemblies), so the mapper can only be built reflectively — this factory hides that
/// and hands back a non-generic mapping delegate plus the element type, which callers
/// need to build a correctly typed or .
///
/// Nothing is cached here: the endpoint resolves its outputClass once and keeps the mapping, through the type
/// resolver of its route context. A process-wide cache by name handed a module reloaded under the same name the
/// class of its previous version, and kept an unloaded module's type alive.
///
///
internal static class SqlRowMapperFactory
{
/// A resolved POCO mapping: the element type and a row → object mapper.
internal sealed record PocoMapping(Type ElementType, Func Map)
{
/// Creates an empty List<ElementType> to accumulate mapped rows.
public IList CreateList() => (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(ElementType))!;
}
///
/// Resolves to a mapping, or null when the option
/// is not set — in which case the caller keeps the default .
///
///
/// The type cannot be found, or has no public parameterless constructor.
///
public static PocoMapping? Resolve(string? outputClass, IBeanTypeResolver typeResolver)
{
ArgumentNullException.ThrowIfNull(typeResolver);
return string.IsNullOrWhiteSpace(outputClass) ? null : Build(outputClass, typeResolver);
}
private static PocoMapping Build(string outputClass, IBeanTypeResolver typeResolver)
{
// The context's resolver first (a host that loads modules searches the module's assemblies), then a bare
// class name matched across the loaded assemblies.
var type = typeResolver.Resolve(outputClass) ?? ResolveType(outputClass)
?? throw new InvalidOperationException(
$"outputClass '{outputClass}' could not be resolved. Use an assembly-qualified name " +
"(e.g. 'MyApp.Models.Order, MyApp') or make sure the declaring assembly is loaded.");
if (type.GetConstructor(Type.EmptyTypes) == null)
throw new InvalidOperationException(
$"outputClass '{type.FullName}' must have a public parameterless constructor.");
// A typed delegate, built once: a mapping error reaches the route as itself, not wrapped in the
// TargetInvocationException a reflective Invoke per row would add.
var map = (Func)typeof(SqlRowMapperFactory)
.GetMethod(nameof(CreateMap), BindingFlags.NonPublic | BindingFlags.Static)!
.MakeGenericMethod(type)
.Invoke(null, null)!;
return new PocoMapping(type, map);
}
private static Func CreateMap() where T : new()
{
var mapper = new PocoRowMapper();
return reader => mapper.Map(reader)!;
}
private static Type? ResolveType(string name)
{
var direct = Type.GetType(name, throwOnError: false);
if (direct != null) return direct;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var found = assembly.GetType(name, throwOnError: false);
if (found != null) return found;
}
// Last resort: match by short name across loaded assemblies.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] types;
try { types = assembly.GetTypes(); }
catch (ReflectionTypeLoadException ex) { types = ex.Types.Where(t => t != null).ToArray()!; }
var found = Array.Find(types, t => t.Name.Equals(name, StringComparison.Ordinal));
if (found != null) return found;
}
return null;
}
}
Path: redb-route/redb.Route.Sql/Mapping/SqlRowMappingException.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/SqlRowMappingException.cs
----
namespace redb.Route.Sql.Mapping;
///
/// A column of a result row cannot become its property (or the scalar type) without loss or guessing: the endpoint's
/// outputClass does not fit the rows the statement returns. It is the endpoint's configuration, the same for every
/// row, so a batch that goes on past failed items does not treat it as an item's failure: it ends the batch.
///
public sealed class SqlRowMappingException(string message) : InvalidOperationException(message);
Path: redb-route/redb.Route.Sql/Mapping/SqlValueConverter.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Mapping/SqlValueConverter.cs
----
using System.Globalization;
using System.Numerics;
using System.Text.RegularExpressions;
using redb.Route.Core;
namespace redb.Route.Sql.Mapping;
///
/// Converts a database value to a property type only when the conversion is lossless and unambiguous: a number the target
/// holds exactly, a defined enum member, text in the invariant culture and ISO 8601 form, a timestamp that is UTC or carries
/// its offset. Every other combination is refused with a reason. Reasons never quote the value, so a mapping error does not
/// leak row data into a log. Apache Camel's BeanPropertyRowMapper refuses a type mismatch the same way.
///
internal static partial class SqlValueConverter
{
private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture;
/// Whether a NULL column may be assigned to : a reference type or a nullable value type.
internal static bool AcceptsNull(Type type) => !type.IsValueType || Nullable.GetUnderlyingType(type) is not null;
/// A short name of for messages: Int32? for a nullable value type.
internal static string TypeName(Type type) =>
Nullable.GetUnderlyingType(type) is { } underlying ? underlying.Name + "?" : type.Name;
///
/// Converts the non-null to (a nullable type converts to its
/// underlying type); returns false with the reason when the conversion would lose or guess anything.
///
internal static bool TryConvert(object value, Type targetType, out object? result, out string reason)
{
var target = Nullable.GetUnderlyingType(targetType) ?? targetType;
result = null;
reason = "";
if (target.IsInstanceOfType(value))
{
result = value;
return true;
}
if (target.IsEnum)
return TryEnum(value, target, out result, out reason);
if (target == typeof(string))
return TryString(value, out result, out reason);
if (target == typeof(bool))
return TryBool(value, out result, out reason);
if (IsIntegerType(target))
return TryInteger(value, target, out result, out reason);
if (target == typeof(decimal) || target == typeof(double) || target == typeof(float))
return TryReal(value, target, out result, out reason);
if (target == typeof(Guid))
return TryGuid(value, out result, out reason);
if (target == typeof(DateTime))
return TryDateTime(value, out result, out reason);
if (target == typeof(DateTimeOffset))
return TryDateTimeOffset(value, out result, out reason);
if (target == typeof(DateOnly))
return TryDateOnly(value, out result, out reason);
if (target == typeof(TimeOnly))
return TryTimeOnly(value, out result, out reason);
if (target == typeof(TimeSpan))
return TryTimeSpan(value, out result, out reason);
if (target == typeof(char) && value is string { Length: 1 } single)
{
result = single[0];
return true;
}
reason = "there is no lossless conversion between these types";
return false;
}
// ── Numbers ─────────────────────────────────────────────────────
private static bool IsIntegerType(Type type) => Type.GetTypeCode(type) is
TypeCode.SByte or TypeCode.Byte or TypeCode.Int16 or TypeCode.UInt16 or
TypeCode.Int32 or TypeCode.UInt32 or TypeCode.Int64 or TypeCode.UInt64;
private static bool IsInteger(object value) => value is sbyte or byte or short or ushort or int or uint or long or ulong;
private static BigInteger ToBigInteger(object integer) =>
integer is ulong unsigned ? new BigInteger(unsigned) : new BigInteger(Convert.ToInt64(integer, Invariant));
/// The exact integer stands for, if any.
private static bool TryExactInteger(object value, out BigInteger integer, out string reason)
{
integer = default;
reason = "";
switch (value)
{
case sbyte or byte or short or ushort or int or uint or long or ulong:
integer = ToBigInteger(value);
return true;
case decimal d when decimal.Truncate(d) == d:
integer = new BigInteger(d);
return true;
case double f when double.IsFinite(f) && Math.Truncate(f) == f:
integer = new BigInteger(f);
return true;
case float f when float.IsFinite(f) && MathF.Truncate(f) == f:
integer = new BigInteger(f);
return true;
case decimal or double or float:
reason = "the number has a fractional part";
return false;
case string s when BigInteger.TryParse(s, NumberStyles.AllowLeadingSign, Invariant, out var parsed):
integer = parsed;
return true;
case string:
reason = "the text is not an integer";
return false;
default:
reason = "the value is not a number";
return false;
}
}
private static bool TryInteger(object value, Type target, out object? result, out string reason)
{
result = null;
if (!TryExactInteger(value, out var integer, out reason))
return false;
var code = Type.GetTypeCode(target);
var inRange = code switch
{
TypeCode.SByte => integer >= sbyte.MinValue && integer <= sbyte.MaxValue,
TypeCode.Byte => integer >= byte.MinValue && integer <= byte.MaxValue,
TypeCode.Int16 => integer >= short.MinValue && integer <= short.MaxValue,
TypeCode.UInt16 => integer >= ushort.MinValue && integer <= ushort.MaxValue,
TypeCode.Int32 => integer >= int.MinValue && integer <= int.MaxValue,
TypeCode.UInt32 => integer >= uint.MinValue && integer <= uint.MaxValue,
TypeCode.Int64 => integer >= long.MinValue && integer <= long.MaxValue,
_ => integer >= ulong.MinValue && integer <= ulong.MaxValue,
};
if (!inRange)
{
reason = $"the number is outside the range of {target.Name}";
return false;
}
result = code switch
{
TypeCode.SByte => (object)(sbyte)integer,
TypeCode.Byte => (byte)integer,
TypeCode.Int16 => (short)integer,
TypeCode.UInt16 => (ushort)integer,
TypeCode.Int32 => (int)integer,
TypeCode.UInt32 => (uint)integer,
TypeCode.Int64 => (long)integer,
_ => (ulong)integer,
};
return true;
}
private static bool TryReal(object value, Type target, out object? result, out string reason)
{
result = null;
reason = "";
if (value is string text)
return TryParseReal(text, target, out result, out reason);
if (!IsInteger(value) && value is not (decimal or double or float))
{
reason = "the value is not a number";
return false;
}
if (target == typeof(decimal))
{
decimal? exact = value switch
{
double f when double.IsFinite(f) && Math.Abs(f) < 7.9e28 && (double)RouteDecimal.FromDouble(f) == f => RouteDecimal.FromDouble(f),
float f when float.IsFinite(f) && Math.Abs(f) < 7.9e28f && (float)RouteDecimal.FromSingle(f) == f => RouteDecimal.FromSingle(f),
double or float => null,
_ => Convert.ToDecimal(value, Invariant),
};
result = exact;
reason = exact is null ? "the number cannot be held exactly by Decimal" : "";
return exact is not null;
}
if (target == typeof(double))
{
double? exact = value switch
{
float f => f,
decimal d when (decimal)(double)d == d => (double)d,
decimal => null,
_ when IsInteger(value) && new BigInteger((double)ToBigInteger(value)) == ToBigInteger(value) => (double)ToBigInteger(value),
_ => null,
};
result = exact;
reason = exact is null ? "the number cannot be held exactly by Double" : "";
return exact is not null;
}
float? single = value switch
{
double f when !double.IsFinite(f) || (double)(float)f == f => (float)f,
decimal d when (decimal)(float)d == d => (float)d,
_ when IsInteger(value) && new BigInteger((float)ToBigInteger(value)) == ToBigInteger(value) => (float)ToBigInteger(value),
_ => null,
};
result = single;
reason = single is null ? "the number cannot be held exactly by Single" : "";
return single is not null;
}
private static bool TryParseReal(string text, Type target, out object? result, out string reason)
{
result = null;
reason = "the text is not a number";
const NumberStyles styles = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent;
if (target == typeof(decimal) && decimal.TryParse(text, styles, Invariant, out var d))
result = d;
else if (target == typeof(double) && double.TryParse(text, styles, Invariant, out var f) && double.IsFinite(f))
result = f;
else if (target == typeof(float) && float.TryParse(text, styles, Invariant, out var s) && float.IsFinite(s))
result = s;
if (result is null)
return false;
reason = "";
return true;
}
private static bool TryBool(object value, out object? result, out string reason)
{
result = null;
reason = "";
if (value is string text && bool.TryParse(text, out var parsed))
{
result = parsed;
return true;
}
// Any number that is exactly 0 or 1: an integer column, or a numeric one without a fractional part (Oracle NUMBER(1),
// PostgreSQL numeric come as decimal).
if (TryExactInteger(value, out var integer, out _))
{
if (integer == 0 || integer == 1)
{
result = integer == 1;
return true;
}
reason = "only 0 or 1 is a Boolean";
return false;
}
reason = "only 0, 1, 'true' or 'false' is a Boolean";
return false;
}
// ── Enums, text, GUIDs ──────────────────────────────────────────
private static bool TryEnum(object value, Type target, out object? result, out string reason)
{
result = null;
object candidate;
if (value is string text)
{
var name = text.Trim();
if (name.Length == 0 || char.IsDigit(name[0]) || name[0] is '-' or '+' ||
!Enum.TryParse(target, name, ignoreCase: true, out var parsed))
{
reason = $"the text is not the name of a {target.Name} member";
return false;
}
candidate = parsed!;
}
else if (TryExactInteger(value, out _, out _))
{
// An integer column, or a numeric one without a fractional part, as for the integer properties.
if (!TryInteger(value, Enum.GetUnderlyingType(target), out var underlying, out reason))
return false;
candidate = Enum.ToObject(target, underlying!);
}
else
{
reason = $"only a number or a member name is a {target.Name}";
return false;
}
if (!IsMember(target, candidate))
{
reason = $"the value is not a member of {target.Name}";
return false;
}
result = candidate;
reason = "";
return true;
}
private static bool IsMember(Type enumType, object candidate)
{
if (Enum.IsDefined(enumType, candidate))
return true;
if (!enumType.IsDefined(typeof(FlagsAttribute), inherit: false))
return false;
// A [Flags] combination is a member when every bit it sets belongs to a defined value.
var all = Enum.GetValues(enumType).Cast().Aggregate(BigInteger.Zero, (mask, v) => mask | ToBigInteger(Convert.ChangeType(v, Enum.GetUnderlyingType(enumType), Invariant)));
var bits = ToBigInteger(Convert.ChangeType(candidate, Enum.GetUnderlyingType(enumType), Invariant));
return (bits & ~all) == 0;
}
private static bool TryString(object value, out object? result, out string reason)
{
result = null;
reason = "";
if (IsInteger(value) || value is decimal or double or float or bool or char or Guid)
{
result = Convert.ToString(value, Invariant);
return true;
}
reason = value is DateTime or DateTimeOffset or DateOnly or TimeOnly or TimeSpan
? "a date or time has no single text form; map it to a date or time property"
: "the value has no single text form";
return false;
}
private static bool TryGuid(object value, out object? result, out string reason)
{
result = null;
reason = "";
if (value is string text && Guid.TryParse(text, out var parsed))
{
result = parsed;
return true;
}
reason = value is byte[]
? "the byte order of a binary GUID differs between databases; store the key as text or map it to byte[]"
: "the text is not a GUID";
return false;
}
// ── Dates and times ─────────────────────────────────────────────
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d{1,7})?)?)?(?Z|[+-]\d{2}(:\d{2})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex IsoTimestamp();
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$", RegexOptions.CultureInvariant)]
private static partial Regex IsoDate();
[GeneratedRegex(@"^\d{2}:\d{2}(:\d{2}(\.\d{1,7})?)?$", RegexOptions.CultureInvariant)]
private static partial Regex IsoTime();
private const string NoTimeZone =
"the timestamp has no time zone; map it to a DateTime property, or store a type that keeps the offset " +
"(timestamptz, datetimeoffset)";
private static bool TryDateTime(object value, out object? result, out string reason)
{
result = null;
reason = "";
switch (value)
{
case DateOnly date:
result = date.ToDateTime(TimeOnly.MinValue);
return true;
case DateTimeOffset:
reason = "the offset would be lost; map it to a DateTimeOffset property";
return false;
case string text when IsoTimestamp().Match(text) is { Success: true } match:
var zone = match.Groups["zone"].Value;
if (zone.Length > 0 && zone != "Z")
{
reason = "the text carries an offset that a DateTime cannot keep; map it to a DateTimeOffset property";
return false;
}
// The pattern checks the shape only; the ranges (month 13, hour 25) are checked here, without the value.
if (!DateTime.TryParse(text, Invariant, DateTimeStyles.RoundtripKind, out var dateTime))
{
reason = "the text has the shape of an ISO 8601 date and time but is not a valid one";
return false;
}
result = dateTime;
return true;
default:
reason = "only a date, or ISO 8601 text, is a DateTime";
return false;
}
}
private static bool TryDateTimeOffset(object value, out object? result, out string reason)
{
result = null;
reason = "";
switch (value)
{
case DateTime { Kind: DateTimeKind.Utc } utc:
result = new DateTimeOffset(utc, TimeSpan.Zero);
return true;
case DateTime:
reason = NoTimeZone;
return false;
case string text when IsoTimestamp().Match(text) is { Success: true } match:
if (match.Groups["zone"].Value.Length == 0)
{
reason = NoTimeZone;
return false;
}
if (!DateTimeOffset.TryParse(text, Invariant, DateTimeStyles.None, out var dateTimeOffset))
{
reason = "the text has the shape of an ISO 8601 date and time but is not a valid one";
return false;
}
result = dateTimeOffset;
return true;
default:
reason = "only a UTC timestamp, or ISO 8601 text with an offset, is a DateTimeOffset";
return false;
}
}
private static bool TryDateOnly(object value, out object? result, out string reason)
{
result = null;
reason = "";
switch (value)
{
case DateTime dateTime when dateTime.TimeOfDay == TimeSpan.Zero:
result = DateOnly.FromDateTime(dateTime);
return true;
case DateTime:
reason = "the timestamp has a time of day; map it to a DateTime property";
return false;
case string text when IsoDate().IsMatch(text) &&
DateOnly.TryParseExact(text, "yyyy-MM-dd", Invariant, DateTimeStyles.None, out var date):
result = date;
return true;
default:
reason = "only a date, or yyyy-MM-dd text, is a DateOnly";
return false;
}
}
private static bool TryTimeOnly(object value, out object? result, out string reason)
{
result = null;
reason = "";
switch (value)
{
case TimeSpan span when span >= TimeSpan.Zero && span < TimeSpan.FromDays(1):
result = TimeOnly.FromTimeSpan(span);
return true;
case string text when IsoTime().IsMatch(text) && TimeOnly.TryParse(text, Invariant, DateTimeStyles.None, out var time):
result = time;
return true;
default:
reason = "only a time of day, or HH:mm[:ss] text, is a TimeOnly";
return false;
}
}
private static bool TryTimeSpan(object value, out object? result, out string reason)
{
result = null;
reason = "";
switch (value)
{
case TimeOnly time:
result = time.ToTimeSpan();
return true;
case string text when TimeSpan.TryParseExact(text, "c", Invariant, out var span):
result = span;
return true;
default:
reason = "only a time, or [d.]hh:mm:ss text, is a TimeSpan";
return false;
}
}
}
Path: redb-route/redb.Route.Sql/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/README.md
----
# redb.Route.Sql
> Documentation and articles:
SQL database transport for redb.Route. Pure ADO.NET polling consumer, query/batch producer, and stored procedure support. Provider-agnostic — tested end to end against PostgreSQL, SQL Server, SQLite, MySQL, MariaDB, Oracle and Firebird, and works with any `DbConnection` (see [Providers](#providers)).
[](https://www.nuget.org/packages/redb.Route.Sql)
[](../../LICENSE)
## Installation
```bash
dotnet add package redb.Route.Sql
```
No additional dependencies — uses `System.Data.Common` abstractions only.
## URI Format
One scheme — `sql:` — and the mode is chosen by the `mode=` parameter, not by the scheme.
```
sql:?mode=Poll|Execute|Procedure&dataSource=&...
```
| Mode | Role | Required |
|------|------|----------|
| `Execute` (default) | Producer — `To(...)` | `dataSource` or `connectionString` |
| `Procedure` | Producer — `To(...)` | `dataSource` + `procedureName` |
| `Poll` | Consumer — `From(...)` | `dataSource`; **`mode=Poll` is mandatory** |
The path is the SQL text itself and is taken verbatim (it is *not* URL-decoded), so it must not
contain a `?` — the parser splits on the first one.
### Consumer — poll rows
```csharp
From("sql:SELECT id, payload FROM outbox WHERE processed = 0"
+ "?mode=Poll"
+ "&dataSource=#main"
+ "&delay=5000"
+ "&maxMessagesPerPoll=100"
+ "&transacted=true"
+ "&onSuccess=UPDATE outbox SET processed = 1 WHERE id = :#id")
.Log("Processing outbox row ${header.id}")
.To("direct://handle");
```
One Exchange per row; body is a `Dictionary`, and **every column is also copied
into headers** — which is why `onSuccess=... WHERE id = :#id` binds without any extra configuration.
### Producer — execute a statement
```csharp
From("direct://save")
.To("sql:INSERT INTO audit(message, status) VALUES(:#message, :#status)"
+ "?dataSource=#main"
+ "¶m.message=${body}"
+ "¶m.status=${header.mode}");
```
### Producer — call a stored procedure or function
```csharp
// PostgreSQL function: SELECT maintain_partitions(:#tbl, :#keep_days)
From("direct://maintenance")
.To("sql:maintain_partitions"
+ "?mode=Procedure"
+ "&dataSource=#main"
+ "&procedureName=maintain_partitions"
+ "&asFunction=true"
+ "&procedureParams=IN:tbl:String,IN:keep_days:Int32"
+ "¶m.keep_days=90");
```
`asFunction=true` builds `SELECT name(:#p1, :#p2, ...)` from the `IN`/`INOUT` params **in declaration
order** and executes it as a scalar — the result lands in the body. `asFunction=false` (default)
uses `CommandType.StoredProcedure` (`CALL`/`EXEC` semantics of the driver) and executes non-query.
`OUT`/`INOUT` values are written back into headers under their parameter names.
> In `Procedure` mode the URI path is the procedure name; an explicit `procedureName=` wins over it.
`procedureParams` format: `DIR:name:DbType[:expression]`, comma-separated. `DIR` is `IN`, `OUT`
or `INOUT`; `DbType` is a `System.Data.DbType` name (`Int32`, `Int64`, `String`, `Decimal`, …).
### Batch
```csharp
From("direct://bulk")
.To("sql:INSERT INTO logs(message) VALUES(:#message)?dataSource=#main&batchSize=500");
```
With `batchSize` above zero, a list body is a batch: the statement runs once per item, and all items
share one transaction — a local one, or the route's when the route is transacted. Each item binds its
own values (see [Batch item binding](#batch-item-binding)). An empty list writes nothing
(`redbSql.updateCount` is `0`), and a `byte[]` body is a single value, not a batch.
A batch source is any list or other sequence (`HashSet`, a LINQ query, a `yield` method), an `IAsyncEnumerable` of a
reference type — a `StreamList` result from another `sql:` endpoint, say — or a JSON array (`JsonElement`, a `JsonDocument`
whose root is an array, `JsonArray`; what `Unmarshal("application/json")` produces). A string or any other sequence
of characters, a `byte[]` or any other sequence of bytes (`ArraySegment`, `List`), a dictionary or JSON
object, an XML document and an `IAsyncEnumerable` of a value type (`IAsyncEnumerable`) are one value each. Items are
read as they are written — a chunk at a time for `DbBatch`, one at a time otherwise — and the first item is read before a
connection is opened, so an empty stream costs none. A failure of the source itself ends the batch in either error mode, with
the number of items read in `redbSql.batchFailedIndex`. A streamed body is consumed by the batch. On SQLite, a stream read
from a file cannot feed a batch into the same file: the open reader blocks the writer.
`batchSize` is the number of statements sent in one round trip; it does not split the transaction. How the
statements travel is decided by the driver, as in Apache Camel — there is no option to pick it:
| When | Strategy (`redbSql.batchStrategy`) | Over the wire |
|---|---|---|
| `breakBatchOnError=true` and the connection can create a `DbBatch` (PostgreSQL, SQL Server, MySQL, MariaDB) | `DbBatch` | chunks of `batchSize` statements, one round trip each (`redbSql.batchChunkCount`) |
| `breakBatchOnError=true`, no `DbBatch` (SQLite, Oracle, Firebird) | `Commands` | one command, prepared once, runs per item with its parameters reused |
| `breakBatchOnError=false` | `Savepoints` | the same reused command, one item at a time under its savepoint |
What a failing item does is set by `breakBatchOnError`:
| `breakBatchOnError` | On a failing item |
|---|---|
| `true` (default) | The batch stops, the transaction rolls back, and the provider's exception (`SqlException`, `PostgresException`, `SqliteException`, …) is thrown as is, so `OnException` matches it. The item's index is in `exception.Data["redbSql.batchFailedIndex"]` and in the `redbSql.batchFailedIndex` header, with `redbSql.batchStrategy` saying how to read it. |
| `false` | Each item runs under a savepoint. A failed item is undone and listed in `redbSql.batchErrors` (`IReadOnlyList`: index, message, SQLSTATE); the other items commit. If the error ended the server transaction (SQL Server conversion errors or any error under `XACT_ABORT ON`, SQLite `OR ROLLBACK`), the batch stops with that error and nothing is committed. Refused before any write inside a transacted route, and on a driver that does not implement savepoints (`NotSupportedException` from the first savepoint). Savepoints are tried, not looked up: SqlClient and MySqlConnector report `SupportsSavepoints=false` and support them. |
A batch reports only its own run: the result headers an earlier attempt on the same exchange left (a redelivery through
`OnException`, an earlier `sql:` step) are removed before it writes its own. A returned row that `outputClass` cannot hold
is the endpoint's configuration, not an item's failure: the batch ends with a `SqlRowMappingException`
(an `InvalidOperationException`) in either error mode and nothing is committed.
To split a large volume into several transactions, aggregate in front of the batch
(`Aggregate(..., completionSize: 500, completionTimeout: ...)`), the same way as with Apache Camel.
Rows the statements return — `INSERT … RETURNING id` on PostgreSQL, SQLite, MariaDB and Firebird,
`INSERT … OUTPUT inserted.id VALUES …` on SQL Server — are collected when `outputType` reads rows (`SelectList` and the other row modes; under
`Auto` a batch collects nothing, as Apache Camel's `executeBatch` collects no result sets). `redbSql.generatedKeys` holds them in item order, as `List>` or
`List` with `outputClass`, and `redbSql.generatedKeysRowCount` their number; the body stays the list that was written,
as with Apache Camel's `CamelSqlGeneratedKeyRows`. A failed item of a batch that continues past errors returns none.
MySQL's `LAST_INSERT_ID()` and Oracle's `RETURNING … INTO` need a separate statement or OUT parameters and are not
collected in a batch.
The `sql.execute` span of a batch carries `db.operation.batch.size` (from two items, as the OpenTelemetry database
conventions count a batch), `redb.sql.batch.strategy`, `redb.sql.batch.chunks` for a `DbBatch` and
`redb.sql.batch.failed_index` when an item ends the batch. Parameter values are never tagged.
## Parameters and binding
SQL placeholders are written **`:#name`**, as in Apache Camel. `@` belongs to the database — T-SQL variables
(`DECLARE @n int = :#value`), `EXEC proc @arg = :#value` argument names, MySQL user variables, `@@ROWCOUNT` — and reaches
it as written. Placeholders are found only in the SQL itself: `':#x'`, `"col:#x"`, `-- :#x`, `/* :#x */` and PostgreSQL
`$$ … $$` bodies are left alone. There is no implicit `:#body` — a scalar body (string, number) never binds itself into a
parameter; use `param.x=${body}`. Apache Camel's inline expressions `:#${...}` and `:#in:name` lists are refused with a
message; use `param.name=${...}`.
What the provider receives is set by `placeholderStyle`:
| `placeholderStyle` | Sent to the provider | For |
|---|---|---|
| `At` (default) | `@name`, one parameter per name | Npgsql, SqlClient, Microsoft.Data.Sqlite, MySqlConnector, Firebird |
| `Colon` | `:name`, one parameter per occurrence | Oracle (ODP.NET binds by name or by position) |
| `Question` | `?`, one parameter per occurrence, in order | ODBC, OleDb |
On SQL Server with `placeholderStyle=At`, a `:#name` parameter becomes `@name`: do not also declare a variable `@name` in
the same statement. `Colon` adds a parameter for every occurrence, which is what ODP.NET's default positional binding
needs; a provider that binds `:name` by name and refuses two parameters with one name (Microsoft.Data.Sqlite) keeps `At`.
MySQL and MariaDB escape a quote inside a literal with a backslash by default (`'it\'s'`); standard SQL does not, and
`'C:\'` is a complete literal on PostgreSQL, SQL Server, Oracle and SQLite. The connector does not guess from the provider:
where the SQL text uses backslash escapes, set `backslashEscapes=true`, or double the quote (`'it''s'`), which every
database reads. Without the option a `:#name` after `\'` is not found and the provider rejects the statement. MySqlConnector
also reads every `@var` of a statement with parameters as a parameter: MySQL user variables need `AllowUserVariables=true` in
the connection string.
Binding priority for each `:#name` found in the statement:
| # | Source |
|---|--------|
| 0 | `param.=...` from the URI (constant or `${...}` expression) |
| 1 | Exchange header with the same name |
| 2 | Body, if it is a map — a dictionary (`IDictionary`, `IReadOnlyDictionary`, non-generic `IDictionary` such as a CSV row) or a JSON object (`JsonElement`, `JsonDocument`, `JsonObject`) — by key: the key `name`, failing that the one key equal to it ignoring case. As in Apache Camel, a POCO, XML or JSON-text body is not read by name |
| — | *(nothing matched)* → `InvalidOperationException` naming the parameter and the statement |
As in Apache Camel, a placeholder with no value is an error, not a silent `NULL`. A source that is present
binds its value even when the value is null: a header or key set to `null` / `DBNull.Value`, an empty
string, or a `param.*` expression that evaluates to null all bind `NULL`.
Values are normalised before binding: `null` and `""` become `NULL`; JSON values (`JsonElement`,
`JsonNode` — what unmarshalling JSON to `object` produces) become a string, `long` / `decimal` / `double`,
`bool` or `NULL`, and a JSON object or array becomes its JSON text.
In `onSuccess` / `onFailure` / `onBatchComplete` the sources are `param.*`, the polled row's columns and
the exchange headers, under the same rule. The special parameter `:#redbError` always has a value:
`exchange.Exception.Message` in `onFailure`, `NULL` where nothing failed.
In a poll consumer, the poll query's placeholders take their values from `param.*` only, resolved **without an Exchange**
— constants only, `${header...}` expressions will not resolve there — and a placeholder without a `param.*` value is an
error.
### Batch item binding
Each item of a batch binds its own values. Sources, first match wins:
| # | Source |
|---|--------|
| 0 | `param.=...` — a `${...}` expression is evaluated per item: `${body}` is the item, `${header.x}` sees the carrying exchange's headers and the keys of a dictionary item, `${property.x}` the exchange properties |
| 1 | The item's own value for `name`, by item shape (below) |
| 2 | Header of the exchange that carries the batch |
| — | *(nothing matched)* → the item fails: with `breakBatchOnError=true` the batch stops and rolls back (`InvalidOperationException`, index in `redbSql.batchFailedIndex`); with `false` the item is listed in `redbSql.batchErrors` |
| Item shape | How `name` is found |
|---|---|
| `IDictionary`, `IReadOnlyDictionary`, `IDictionary` (CSV rows are `Dictionary`) | the key `name`; failing that, the one key equal to it ignoring case — two such keys match nothing |
| JSON object (`JsonElement`, `JsonObject`, `JsonDocument` with an object root) | the property `name`, same case rule; values normalised as above |
| POCO — a type of the application, anonymous types and records included | public property: the same name ignoring case, `[Column("name")]`, or `snake_case` → `PascalCase` — the rule `outputClass` uses for rows |
| `IExchange` (`AggregationStrategies.GroupedExchange()`) | its own headers, then its body by the shapes above; `param.*` expressions are evaluated on the item exchange; the carrying exchange's headers are not used |
| XML node (`XElement`, `XmlNode` — e.g. a `List` from XPath) | no named values, as in Apache Camel — bind with an expression relative to the item: `param.id=${xpath('@id')}`, `param.name=${xpath('name')}` |
| scalar, string, array, list, any other .NET type (`Uri`, `Stream`, …) | no named values — bind with `param.x=${body}` or an expression; the properties of a .NET type are not record fields |
CSV values are text and are sent as text: a database that does not convert a text parameter to a numeric
column (PostgreSQL) needs a cast in the statement, `CAST(:#id AS int)`, or a typed item (POCO).
## URI parameters
Names are the property names of `SqlEndpointOptions`, case-insensitive. Numeric and enum options take
constants or `{{property}}` placeholders; a `${...}` expression there fails endpoint creation.
| Parameter | Type | Default |
|---|---|---|
| `mode` | `Poll` \| `Execute` \| `Procedure` | `Execute` |
| `dataSource` | registered data source name (a leading `#` is stripped); fixed when the endpoint is created — a dynamic target is a dynamic endpoint (`ToD`), as in Apache Camel; `redb` or `redb:` runs the statement on the connection of a redb service (see Transactions) | — |
| `connectionString` / `provider` | inline connection instead of `dataSource` | — |
| `commandTimeout` | seconds | `30` |
| `transacted` | **consumer only** — SELECT + `onSuccess`/`onFailure` in one transaction | `false` |
| `onFailureAfterRollback` | **consumer only**, with `transacted=true` — a failed row keeps its `onFailure` mark and the poll goes on (see below) | `false` |
| `isolationLevel` | `System.Data.IsolationLevel` | provider default |
| `readOnly` | `true`: run on the data source's read replica (`ReadConnectionString`) — declared by the endpoint's author, never guessed from the SQL; refused with `batchSize` and for a poll with `onSuccess`/`onFailure`/`onBatchComplete` or `transacted` | `false` |
| `placeholderStyle` | how `:#name` reaches the provider: `At` (`@name`) \| `Colon` (`:name`, Oracle) \| `Question` (`?`, ODBC) — see [Parameters and binding](#parameters-and-binding) | `At` |
| `backslashEscapes` | `true`: inside `'…'` and `"…"` a backslash escapes the next character, as MySQL and MariaDB read them by default; `false`: standard SQL, `\` is an ordinary character — see [Parameters and binding](#parameters-and-binding) | `false` |
| `outputType` | `Auto` \| `SelectList` \| `SelectOne` \| `StreamList` \| `Scalar` \| `None` | `Auto` |
| `outputClass` | POCO type name for mapped rows (`SelectList` → `List`, `SelectOne` → `T`, `StreamList` → `IAsyncEnumerable`) | — |
| `outputHeader` | put the result into this header and leave the body untouched; a `${...}` expression names the header per exchange | — |
| `noop` | skip execution (dry run) | `false` |
| `delay` / `initialDelay` | poll interval / first delay, ms | `500` / `1000` |
| `fixedRate` | measure delay from cycle start | `false` |
| `repeatCount` | 0 = forever | `0` |
| `maxMessagesPerPoll` | −1 = no limit | `-1` |
| `routeEmptyResultSet` / `sendEmptyMessageWhenIdle` | emit an Exchange on empty polls | `false` |
| `onSuccess` / `onFailure` / `onBatchComplete` | SQL run after each row / after a failed row / after the cycle | — |
| `pollDelivery` | `PerRow` (an exchange per row) \| `List` (one exchange with every polled row, Apache Camel `useIterator=false`); `List` is refused with `outputType=Scalar` or `SelectOne` | `PerRow` |
| `batchSize` | > 0 turns a list body into a batch, all items in one transaction | `0` |
| `breakBatchOnError` | `true`: stop and roll back on the first failing item; `false`: undo failed items to savepoints and commit the rest | `true` |
| `param.` | explicit parameter value or `${...}` expression | — |
| `procedureName` | required for `mode=Procedure` | — |
| `asFunction` | `SELECT fn(...)` instead of `CALL`/`EXEC`; the result is the scalar, so `OUT`/`INOUT` parameters are refused | `false` |
| `procedureParams` | `DIR:name:DbType[:expr],…` | — |
`outputType=Auto` is decided by what the statement returns when it runs, as Apache Camel's `execute()` asks the driver —
the text is never parsed: a result set (the first one, even an empty one) is delivered as `SelectList`, and a statement
without one leaves the body untouched and sets `redbSql.updateCount` (`None`). A comment before `SELECT`, a `WITH` that
writes and an `INSERT … RETURNING` all come out as what they return; `redbSql.outputType` reports the resolved type. In a
batch `Auto` collects no rows (above).
`outputType=StreamList` gives the route an `IAsyncEnumerable` that reads rows from an open reader. The reader, its
command, transaction and connection are released when the rows are read to the end, when reading stops early, or — as in
Apache Camel — when the exchange ends, whether or not anyone read the stream. The rows can be read once. Inside a route
transaction `StreamList` is refused: the transaction cannot commit while the reader is open, and a later SQL step in the same
transaction would need a second connection and a distributed transaction; use `SelectList` there.
The stream belongs to the exchange that ran the endpoint. A copy of that exchange (WireTap, RecipientList, Threads, a
`seda:` hand-off) shares the body but not the release: disposing the copy leaves the stream alone, and once the original
ends the copy finds the stream released — read it in the segment that produced it, or use `SelectList` where the exchange
is handed to another thread. `Enrich` hands the stream over to the exchange it enriches, as Apache Camel hands over the
resource exchange's completions, so `.Enrich("sql:…?outputType=StreamList")` is read by the enriched route.
A poll consumer with `outputType=StreamList` keeps its reader open while the route processes each row. Where its
`onSuccess` / `onFailure` run follows Apache Camel, which runs `onConsume` through its `JdbcTemplate`:
| Poll | `onSuccess` / `onFailure` run on | PostgreSQL, SQL Server | SQLite (default journal mode) |
|---|---|---|---|
| outside a transaction | a connection of their own to the primary database | works | the open reader blocks the write: use `transacted=true` or WAL |
| `transacted=true` (or an ambient transaction) | the reader's connection, in its transaction | the driver refuses a second command while the reader is open: the failure is logged and the transaction rolls back — use the default mode | works |
The default mode reads the rows first and closes the reader before processing, so SELECT and `onSuccess` share one
connection and transaction on every provider. A failing `onSuccess` is logged in every mode.
A row fails, and gets `onFailure` instead of `onSuccess`, when a failure escapes the route, when the route leaves one on
the exchange (an `onException` with `handled="false"`), or when the route marks the exchange rollback-only. A failure an
`onException` handles (`handled="true"`) completes the row.
With `transacted=true` the poll cycle is one transaction. The first failed row runs `onFailure` inside it, then the
transaction rolls back, `onFailure` included, and the cycle ends: that row keeps the state it had and is read again on the
next poll, and the rows after it wait. A row that fails every time therefore holds up the rows behind it, as in Apache
Camel. `onFailureAfterRollback=true` keeps the mark: with one exchange per row each row runs under a savepoint, a failed row
is rolled back to it, gets `onFailure` in the poll's transaction and the cycle goes on with the next row; with one exchange
per poll (`pollDelivery=List`, `Scalar`, `SelectOne`) the transaction rolls back and `onFailure` runs in a short transaction
of its own. It needs `transacted=true` and a provider with savepoints, and is refused with `outputType=StreamList`. Without
`transacted` each row's `onSuccess` or `onFailure` commits on its own anyway.
With `pollDelivery=List` the poll is one exchange, as Apache Camel's `useIterator=false`: the body is the list of rows
(`List>`, or `List` with `outputClass`), limited by `maxMessagesPerPoll`; with
`outputType=StreamList` it is the open stream itself, for the route to read — straight into a `sql:` batch, say.
`onSuccess` / `onFailure` and `onBatchComplete` run once, after the route and after the reader is closed, on the
consumer's connection and transaction; their values come from headers and `param.*`, since a list has no row columns.
`routeEmptyResultSet=true` delivers an empty list.
`outputClass` resolves an assembly-qualified or loaded type name and maps columns to properties (case-insensitive,
`[Column]`, `snake_case` → `PascalCase`); a column without a property is skipped, and without `outputClass` rows are
`Dictionary`. A value reaches a property only when the conversion is lossless and unambiguous — as Apache
Camel's `BeanPropertyRowMapper` refuses a type mismatch. Anything else fails the exchange with an
`InvalidOperationException` naming the column, the property and both types (never the value):
| Property | Accepted column values |
|---|---|
| any | a value of the property's own type |
| nullable (`int?`) or reference (`string`) | `NULL` sets `null`; for any other value type `NULL` is an error |
| integer types | integers in range, `REAL` / `decimal` without a fractional part, integer text |
| `decimal`, `double`, `float` | numbers the property holds exactly, numeric text |
| `bool` | `0` / `1`, `true` / `false` text |
| `enum` | the number or the name (case-insensitive) of a defined member |
| `Guid` | text |
| `string` | text, numbers, `bool`, `Guid`; a date or time is an error — use a date/time property |
| `DateTime` | ISO 8601 text; a `DateTimeOffset` is an error — the offset would be lost |
| `DateTimeOffset` | a UTC `DateTime` (PostgreSQL `timestamptz`), text with an offset; a timestamp without a time zone (`timestamp`, `datetime2`) is an error — use `DateTime` |
| `DateOnly` | a `DateTime` at midnight (`date`), date text |
| `TimeOnly`, `TimeSpan` | a `TimeSpan` (`time`), time text |
Text is parsed with the invariant culture, whatever the culture of the process. `ScalarMapper` follows the same rules.
## Headers written back
All prefixed with `redbSql.`: `query`, `updateCount`, `rowCount`, `dataSource`, `outputType` (the type `Auto` resolved
to), `error`, `transactionId`, `storedProcedure`, `executionTime` (ms: resolving, binding and executing the statement and
reading its result; for `StreamList`, until the reader is open). Batch mode adds `batchStrategy`
(`None` / `DbBatch` / `Commands` / `Savepoints`, on failure too), `batchItemCount`, `batchChunkCount` (round trips of a
`DbBatch`), `batchFailedIndex` and `batchErrors`, and — with an `outputType` that reads rows — `generatedKeys` and
`generatedKeysRowCount`. When the driver does not name the failed command of a `DbBatch`,
`batchFailedIndex` is the first item of the failed chunk and `exception.Data["redbSql.batchFailedChunk"]` holds its
range (`"500..999"`).
## Transactions
Producers (`Execute` and `Procedure`) **always** open a local transaction when there is no ambient
one (except on the borrowed connection of `dataSource=redb`, below) — write atomicity does not need `transacted=true`, and the option is a no-op there. The consumer
is the only place that reads `transacted`. A route-level `.Transacted()` wraps the pipeline in a
`TransactionScope`; the connector then detects the ambient transaction, skips its local one, and
enlists the connection. Two `sql:` steps in one block share the transaction (PostgreSQL and SQL Server hand the
same enlisted connection back from the pool).
A connection that does not join the block's transaction would commit on its own and keep its rows when the block
rolls back. Such a step is refused before it writes: Microsoft.Data.Sqlite, which has no System.Transactions
support; Firebird without `Enlist=true` (its client enlists only when asked); and any provider whose connection
string says `Enlist=false` or `AutoEnlist=false`. Other providers are taken at their own enlistment defaults.
With a data source of its own the connector opens its own connection. Inside a transacted route that also writes
through `redb` to the **same** database that is a second connection in the transaction, which SQL Server refuses (a
distributed transaction), PostgreSQL cannot commit and SQLite runs in autocommit. For that case use `dataSource=redb`.
### One transaction with redb: `dataSource=redb`
`dataSource=redb` runs the statement on the connection the exchange's default redb service works on;
`dataSource=redb:orders` on the connection of the redb service registered as `orders`. The service is the one the
redb steps of the same exchange (`.RedbSave()`, `ProcessWithRedb`) get, and the connection is borrowed for the time of
the statement only.
```csharp
From("direct://order")
.Transacted()
.To("sql:INSERT INTO order_audit (order_no) VALUES (:#orderNo)?dataSource=redb&outputType=None")
.Process(e => e.In.Body = BuildOrder(e))
.RedbSave()
.End();
```
A route in XML takes the same option, here with the named service:
```xml
```
- Inside `.Transacted()` the statement and the redb steps of the block commit or roll back together, on one connection:
no distributed transaction on SQL Server or PostgreSQL, and on SQLite the statement runs in the transaction redb
keeps on the block's connection.
- Outside a transaction the statement runs in autocommit: the step begins no transaction of its own on redb's connection.
- `Execute` and `Procedure` producers and batches take the data source. `readOnly=true` is ignored: the statement runs
where redb works.
- Refused, with a message naming the reason: `outputType=StreamList` (the reader would outlive the borrowed
connection; `SelectList` reads the rows first), a batch with `breakBatchOnError=false` (its savepoints need a
transaction of the batch's own), and the polling consumer (it polls outside any exchange; its route is marked
errored at start).
- The SQL idempotent and claim-check repositories refuse it in their constructors: they are called without an exchange
and commit their own rows, so they keep a data source with a connection string. For idempotent keys that commit
with redb work use `RedbIdempotentRepository` from redb.Route.Core.
- The data source comes with redb.Route.Core: `services.AddRedbRouteCore()` registers it on the context the host
starts, `context.AddRedbSqlDataSource()` on a context built by hand. A context without a redb service, or a name that
is not registered, fails when the context starts the endpoint (logged, the context reports degraded mode) and again
at the first exchange.
- Inside a step the statement holds redb's connection: the statement must not commit, roll back or change session
settings. A failed statement fails the step; on PostgreSQL the failure aborts the transaction for every later
command, so the block rolls back.
## Register data sources
```csharp
DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance); // required
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteSql(sql =>
{
sql.AddDataSource("main", opts =>
{
opts.ConnectionString = "Host=localhost;Database=demo;Username=postgres;Password=***";
opts.ProviderName = "Npgsql";
});
sql.AddNamedQuery("pendingOrders", "SELECT * FROM orders WHERE processed = 0");
// → "sql:ref:pendingOrders?mode=Poll&dataSource=#main"
});
});
```
Inside a Tsak module the same thing without DI:
```csharp
context.AddComponent(new SqlComponent());
context.AddToRegistry("main", (ISqlConnectionFactory)new SqlConnectionFactory(
new SqlConnectionOptions { ConnectionString = conn, ProviderName = "Npgsql" }));
```
`SqlConnectionOptions` also carries `ReadConnectionString` (a read replica, used only by endpoints with `readOnly=true`),
`TestOnBorrow` / `ValidationQuery`, and `EnableRetryOnFailure` / `MaxRetries` / `RetryDelay`. Instead of a registered
`ProviderName`, `ProviderFactory` takes the driver's factory directly (`opts.ProviderFactory = MySqlConnectorFactory.Instance`)
and wins when both are set.
## Providers
The connector itself has no provider-specific code: what differs is the driver and the SQL dialect, and the options below
are how a route states it. Every database in the table is covered by end-to-end tests against a real server — batches that
stop and that go on past errors, returned keys, parameters, literals and polling.
| Database (tested) | Driver, factory | `placeholderStyle` | Batch with `breakBatchOnError=true` | Keys of a batch |
|---|---|---|---|---|
| PostgreSQL 18 | Npgsql 9.0.3, `NpgsqlFactory.Instance` | `At` | `DbBatch`; the driver names the failed item | `RETURNING` |
| SQL Server | Microsoft.Data.SqlClient 7.0.3, `SqlClientFactory.Instance` | `At` | `DbBatch`; the driver names the failed item | `OUTPUT inserted.*` |
| SQLite | Microsoft.Data.Sqlite 10.0.0, `SqliteFactory.Instance` | `At` | `Commands` | `RETURNING` (SQLite 3.35+) |
| MySQL 8.4 | MySqlConnector 2.6.2, `MySqlConnectorFactory.Instance` | `At` | `DbBatch`; the driver does not name the failed item | not collected: no `RETURNING` |
| MariaDB 11 | MySqlConnector 2.6.2, `MySqlConnectorFactory.Instance` | `At` | as MySQL | `RETURNING` |
| Oracle Database 23 (Free) | Oracle.ManagedDataAccess.Core 23.26.301, `OracleClientFactory.Instance` | **`Colon`** | `Commands` | not collected: `RETURNING … INTO` needs OUT parameters |
| Firebird 5 | FirebirdSql.Data.FirebirdClient 10.3.4, `FirebirdClientFactory.Instance` | `At` | `Commands` | `RETURNING` |
| any other `DbConnection` | `ProviderFactory`, or a factory registered under `ProviderName` | `At`; `Question` for ODBC / OleDb | `DbBatch` when `CanCreateBatch`, otherwise `Commands` | the rows the statement returns |
`breakBatchOnError=false` runs with savepoints on every tested database.
What a failed statement does to its transaction decides how much of a batch survives it:
| Database | A failed statement inside a transaction |
|---|---|
| PostgreSQL | aborts the transaction block, whatever the error; each item's savepoint brings it back, so a batch that goes on past errors still commits the other items |
| SQL Server | a duplicate key is undone alone; a conversion error (245), any error under `XACT_ABORT ON` and a deadlock victim end the transaction — a batch that goes on past errors stops there, nothing committed |
| SQLite | a constraint violation is undone alone; `INSERT OR ROLLBACK` ends the transaction |
| MySQL, MariaDB | undone alone (duplicate key, a value strict `sql_mode` refuses); a deadlock ends the transaction |
| Oracle, Firebird | undone alone |
What to know per database:
- **PostgreSQL** — `$$ … $$` and `$tag$ … $tag$` bodies are not searched for placeholders; `$1` is not a dollar quote.
CSV text needs a cast into a numeric column: `CAST(:#id AS int)`.
- **SQL Server** — `:#name` becomes `@name` with `At`: do not declare a variable of the same name in the statement.
T-SQL variables and `EXEC proc @arg = :#value` work as written.
- **SQLite** — the driver binds `:name` by name and refuses two parameters with one name, so a repeated placeholder needs
`At`, not `Colon`. An open reader blocks writers in the default journal mode: a stream read from a file cannot feed a
batch into the same file, and a streaming poll outside a transaction needs `transacted=true` or WAL for `onSuccess`.
- **MySQL, MariaDB** — the driver does not report which command of a `DbBatch` failed: `redbSql.batchFailedIndex` is the
first item of the failed chunk and `exception.Data["redbSql.batchFailedChunk"]` holds the chunk's range; a smaller
`batchSize` narrows it. Literals written with backslash escapes (`'it\'s'`) need `backslashEscapes=true`, or double the
quote (`'it''s'`). User variables (`SET @u = 5`) in a statement with parameters need `AllowUserVariables=true` in the
connection string, or MySqlConnector refuses `@u` as an undefined parameter. `#` comments are not recognised by the
placeholder scanner: a comment that contains `:#` is written with `--` or `/* */`.
- **Oracle** — set `placeholderStyle=Colon`. ODP.NET binds by position by default, so the connector sends one parameter
per occurrence and a repeated `:#x` works. A `SELECT` without a table needs `FROM DUAL`.
- **Firebird** — `SELECT` without a table needs `FROM RDB$DATABASE`; a repeated `:#x` is bound by name.
## Fluent DSL
`Sql.Poll(...)` / `Sql.Execute(...)` compile to exactly the URI strings above and are equivalent:
```csharp
using redb.Route.Sql;
From(Sql.Poll("SELECT * FROM orders WHERE processed = 0")
.DataSource("main")
.Delay(5000)
.OnSuccess("UPDATE orders SET processed = 1 WHERE id = :#id")
.MaxMessagesPerPoll(100))
.To("direct://handle");
```
`Sql.Procedure("name")` writes the name into the URI path, which is the procedure name in `Procedure` mode.
A batch, and a database that needs its own options:
```csharp
From("direct://bulk")
.To(Sql.Execute("INSERT INTO logs(id, message) VALUES(:#id, :#message)")
.DataSource("oracle")
.PlaceholderStyle(SqlPlaceholderStyle.Colon)
.Batch(500)
.BreakBatchOnError(false));
```
`CommandTimeout`, `Delay`, `InitialDelay`, `RepeatCount`, `MaxMessagesPerPoll`, `Batch`, `Param` and `OutputHeader` accept
both constants and `IExpression` for runtime resolution; `DataSource` and `ConnectionString` take a constant only — an
`IExpression` that is not a constant is refused, since the endpoint is fixed when it is created. A constant given to `Param`
as a number or a date is written invariantly (`12.5`, `2026-09-16T10:00:00.0000000Z`), whatever the culture of the process.
| Builder method | URI parameter |
|---|---|
| `Batch(n)`, `BreakBatchOnError()` / `BreakBatchOnError(bool)` | `batchSize`, `breakBatchOnError` |
| `ReadOnly()` | `readOnly=true` |
| `PlaceholderStyle(SqlPlaceholderStyle)` | `placeholderStyle` |
| `BackslashEscapes()` | `backslashEscapes=true` |
| `PollDelivery(SqlPollDelivery)` | `pollDelivery` |
| `Param("x", value)` / `Param("x", expression)` | `param.x` — the name is written `x` or `:#x`; `@x` is refused with an `ArgumentException` |
| `AsFunction()`, `In(...)`, `Out(...)`, `InOut(...)` | `asFunction`, `procedureParams` |
A default is not written into the URI: an option left unset keeps the default of `SqlEndpointOptions`.
## Part of
[redb.Route](../README.md) — ESB & EIP Framework for .NET
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `db.system` = the scheme and
`redb.route.endpoint`:
- **Consumer.** One `Consumer` span, `sql.receive`, per routed exchange: a row, or the list of a batch
(`pollDelivery=List`). A row carries no trace context, so the span is a root, never a child of the activity the poll
runs under. A poll that routes nothing opens none; one that routes an empty exchange (`routeEmptyResultSet`,
`sendEmptyMessageWhenIdle`) opens one for it. A failed route marks it an error; our own stop does not.
- **Producers.** `sql.execute` and `sql.procedure`, `Client` spans; an error when the statement fails, unless our own
token cancelled it.
- `RouteEngineOptions.EnableTelemetry = false` opens none of these spans.
Path: redb-route/redb.Route.Sql/Repositories/SqlClaimCheckOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Repositories/SqlClaimCheckOptions.cs
----
using System;
using System.Text.RegularExpressions;
namespace redb.Route.Sql.Repositories;
///
/// Configuration options for .
///
public sealed class SqlClaimCheckOptions
{
private static readonly Regex ValidTableName = new(@"^[a-zA-Z_][a-zA-Z0-9_.]*$", RegexOptions.Compiled);
private string _tableName = "redb_claim_check";
/// Table name for claim check entries (default: "redb_claim_check").
public string TableName
{
get => _tableName;
set
{
if (string.IsNullOrWhiteSpace(value) || !ValidTableName.IsMatch(value))
throw new ArgumentException($"Invalid table name: '{value}'. Must match [a-zA-Z_][a-zA-Z0-9_.]*", nameof(value));
_tableName = value;
}
}
/// Default TTL for entries. Zero or null means no expiry.
public TimeSpan? DefaultTtl { get; set; }
/// Auto-create the table on first use (default: true).
public bool CreateTable { get; set; } = true;
///
/// Run cleanup of expired rows every N Store operations. Zero disables automatic cleanup.
///
public int CleanupInterval { get; set; } = 100;
}
Path: redb-route/redb.Route.Sql/Repositories/SqlClaimCheckRepository.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Repositories/SqlClaimCheckRepository.cs
----
using System;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
namespace redb.Route.Sql.Repositories;
///
/// SQL-backed implementation of .
/// Uses raw ADO.NET with — works with any DbProvider
/// (SQLite, PostgreSQL, MSSQL, MySQL).
/// Auto-creates the table on first use. Supports TTL-based lazy cleanup.
///
public sealed class SqlClaimCheckRepository : IClaimCheckRepository
{
private readonly ISqlConnectionFactory _connectionFactory;
private readonly SqlClaimCheckOptions _options;
private volatile bool _tableCreated;
private int _storeCounter;
///
/// Creates a new SQL-backed claim check repository.
///
/// Factory for creating database connections.
/// Repository options.
public SqlClaimCheckRepository(ISqlConnectionFactory connectionFactory, SqlClaimCheckOptions options)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
_options = options ?? throw new ArgumentNullException(nameof(options));
SqlConnections.RefuseLending(connectionFactory, nameof(SqlClaimCheckRepository), nameof(connectionFactory));
}
///
public async Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
var key = Guid.NewGuid().ToString("N");
await StoreInternal(key, data, ttl, ct).ConfigureAwait(false);
return key;
}
///
public async Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await StoreInternal(key, data, ttl, ct).ConfigureAwait(false);
}
///
public async Task Retrieve(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(readOnly: true, ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
SELECT data FROM {_options.TableName}
WHERE claim_key = @key
AND (expires_at IS NULL OR expires_at > @now)
""";
AddParam(cmd, "key", key);
AddParam(cmd, "now", DateTimeOffset.UtcNow.ToString("O"));
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
return result as byte[];
}
///
public async Task RetrieveAndRemove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureTableAsync(ct).ConfigureAwait(false);
// SELECT + DELETE inside a transaction for atomicity
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var tx = await conn.BeginTransactionAsync(ct).ConfigureAwait(false);
try
{
// Read
byte[]? data;
await using (var readCmd = conn.CreateCommand())
{
readCmd.Transaction = tx;
readCmd.CommandText = $"""
SELECT data FROM {_options.TableName}
WHERE claim_key = @key
AND (expires_at IS NULL OR expires_at > @now)
""";
AddParam(readCmd, "key", key);
AddParam(readCmd, "now", DateTimeOffset.UtcNow.ToString("O"));
data = await readCmd.ExecuteScalarAsync(ct).ConfigureAwait(false) as byte[];
}
if (data is null)
{
await tx.RollbackAsync(ct).ConfigureAwait(false);
return null;
}
// Delete
await using (var delCmd = conn.CreateCommand())
{
delCmd.Transaction = tx;
delCmd.CommandText = $"DELETE FROM {_options.TableName} WHERE claim_key = @key";
AddParam(delCmd, "key", key);
await delCmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
await tx.CommitAsync(ct).ConfigureAwait(false);
return data;
}
catch
{
await tx.RollbackAsync(ct).ConfigureAwait(false);
throw;
}
}
///
public async Task Remove(string key, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"DELETE FROM {_options.TableName} WHERE claim_key = @key";
AddParam(cmd, "key", key);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
private async Task StoreInternal(string key, ReadOnlyMemory data, TimeSpan? ttl, CancellationToken ct)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await CleanupIfNeededAsync(ct).ConfigureAwait(false);
var effectiveTtl = ttl ?? _options.DefaultTtl;
var expiresAt = effectiveTtl.HasValue && effectiveTtl.Value > TimeSpan.Zero
? DateTimeOffset.UtcNow + effectiveTtl.Value
: (DateTimeOffset?)null;
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
// Upsert: delete existing then insert (portable across DBs)
await using (var delCmd = conn.CreateCommand())
{
delCmd.CommandText = $"DELETE FROM {_options.TableName} WHERE claim_key = @key";
AddParam(delCmd, "key", key);
await delCmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
await using (var insCmd = conn.CreateCommand())
{
insCmd.CommandText = $"""
INSERT INTO {_options.TableName} (claim_key, data, created_at, expires_at)
VALUES (@key, @data, @now, @exp)
""";
AddParam(insCmd, "key", key);
AddParam(insCmd, "data", data.ToArray());
AddParam(insCmd, "now", DateTimeOffset.UtcNow.ToString("O"));
AddParam(insCmd, "exp", expiresAt.HasValue ? expiresAt.Value.ToString("O") : DBNull.Value);
await insCmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
Interlocked.Increment(ref _storeCounter);
}
private async Task EnsureTableAsync(CancellationToken ct)
{
if (_tableCreated || !_options.CreateTable) return;
// The table is the repository's, not the message's: the first call may run inside the transaction of whatever
// message came first, and DDL there would go with its rollback (PostgreSQL, SQL Server) or commit it implicitly
// (MySQL, Oracle). As Apache Camel creates the table outside any exchange, it is created outside the transaction.
using var outsideTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = BuildCreateTableDdl(conn, _options.TableName);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
outsideTransaction.Complete();
_tableCreated = true;
}
///
/// Returns the CREATE TABLE statement for the connection's dialect. SQL Server (no
/// CREATE TABLE IF NOT EXISTS ) gets a guarded T-SQL statement with NVARCHAR /
/// VARBINARY(MAX) ; the binary column type also differs by dialect
/// (BYTEA on PostgreSQL, LONGBLOB on MySQL and MariaDB, BLOB on SQLite), and the
/// key column is a sized VARCHAR(255) everywhere. Detection is by
/// exact connection class name so siblings like MySqlConnection are not misread as SQL Server.
///
private static string BuildCreateTableDdl(DbConnection conn, string table)
{
var name = conn.GetType().Name;
if (string.Equals(name, "SqlConnection", StringComparison.Ordinal))
return $"""
IF OBJECT_ID(N'{table}', N'U') IS NULL
CREATE TABLE {table} (
claim_key NVARCHAR(255) NOT NULL PRIMARY KEY,
data VARBINARY(MAX) NOT NULL,
created_at NVARCHAR(64) NOT NULL,
expires_at NVARCHAR(64) NULL
)
""";
var blob = name switch
{
"NpgsqlConnection" => "BYTEA",
"MySqlConnection" => "LONGBLOB",
_ => "BLOB" // SQLite and other providers
};
// The key column is sized: MySQL and MariaDB refuse a TEXT column in a primary key (error 1170).
return $"""
CREATE TABLE IF NOT EXISTS {table} (
claim_key VARCHAR(255) NOT NULL PRIMARY KEY,
data {blob} NOT NULL,
created_at VARCHAR(64) NOT NULL,
expires_at VARCHAR(64) NULL
)
""";
}
private async Task CleanupIfNeededAsync(CancellationToken ct)
{
if (_options.CleanupInterval <= 0) return;
if (_storeCounter % _options.CleanupInterval != 0) return;
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
DELETE FROM {_options.TableName}
WHERE expires_at IS NOT NULL AND expires_at < @now
""";
AddParam(cmd, "now", DateTimeOffset.UtcNow.ToString("O"));
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
private static void AddParam(DbCommand cmd, string name, object value)
{
var p = cmd.CreateParameter();
p.ParameterName = name;
p.Value = value;
cmd.Parameters.Add(p);
}
}
Path: redb-route/redb.Route.Sql/Repositories/SqlIdempotentOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Repositories/SqlIdempotentOptions.cs
----
using System.Text.RegularExpressions;
namespace redb.Route.Sql.Repositories;
///
/// Configuration for .
///
public sealed class SqlIdempotentOptions
{
private static readonly Regex ValidTableName = new(@"^[a-zA-Z_][a-zA-Z0-9_.]*$", RegexOptions.Compiled);
private string _tableName = "redb_idempotent";
/// Named data source from the registry.
public string DataSource { get; set; } = string.Empty;
///
/// Table name for storing idempotent keys. Default: "redb_idempotent". The name goes into DDL and statements as written,
/// so only an identifier (letters, digits, _ , . ) is accepted.
///
/// The value is not an identifier.
public string TableName
{
get => _tableName;
set
{
if (string.IsNullOrWhiteSpace(value) || !ValidTableName.IsMatch(value))
throw new ArgumentException($"Invalid table name: '{value}'. Must match [a-zA-Z_][a-zA-Z0-9_.]*", nameof(value));
_tableName = value;
}
}
/// Scope identifier (route id). Allows multiple routes to share one table.
public string ProcessorName { get; set; } = string.Empty;
/// Auto-cleanup: delete entries older than TTL. Null = no cleanup.
public TimeSpan? Ttl { get; set; }
/// Auto-create the table on first use. Default: true.
public bool CreateTable { get; set; } = true;
}
Path: redb-route/redb.Route.Sql/Repositories/SqlIdempotentRepository.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/Repositories/SqlIdempotentRepository.cs
----
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Transactions;
using redb.Route.Abstractions;
using redb.Route.Sql.Connection;
namespace redb.Route.Sql.Repositories;
///
/// Idempotent repository backed by a raw ADO.NET table.
/// For autonomous use of redb.Route without redb.Core dependency.
/// Supports auto-create table and TTL-based cleanup.
///
/// Schema bootstrap: when is true (default),
/// the table is created on first operation with dialect-aware DDL: SQLite/PostgreSQL/MySQL/MariaDB use
/// CREATE TABLE IF NOT EXISTS with VARCHAR key columns (128 for the processor name, 255 for
/// the message key — MySQL refuses TEXT in a key); SQL Server (which has no such syntax) is detected
/// from the live connection and gets a guarded IF OBJECT_ID(...) IS NULL CREATE TABLE with
/// NVARCHAR /INT columns of the same sizes, inside the 900-byte clustered key limit. Set
/// = false to manage the schema yourself.
///
///
/// Cleanup: when is set, every
/// runs a best-effort DELETE WHERE created_at < cutoff . This adds latency to the hot
/// path; for high-throughput scenarios prefer running cleanup out-of-band on a schedule.
///
///
public sealed class SqlIdempotentRepository : IIdempotentRepository
{
private readonly ISqlConnectionFactory _connectionFactory;
private readonly SqlIdempotentOptions _options;
private readonly SemaphoreSlim _ddlLock = new(1, 1);
private bool _tableCreated;
private bool _claimIdColumnSeen;
// What the connections of this repository do in an ambient transaction: 0 until the first one is seen.
private const int Joins = 1;
private const int StaysOutside = 2;
private int _ambientBehaviour;
/// Creates an idempotent repository with the given connection factory and options.
/// Factory for creating database connections.
/// Repository configuration.
public SqlIdempotentRepository(ISqlConnectionFactory connectionFactory, SqlIdempotentOptions options)
{
ArgumentNullException.ThrowIfNull(connectionFactory);
ArgumentNullException.ThrowIfNull(options);
SqlConnections.RefuseLending(connectionFactory, nameof(SqlIdempotentRepository), nameof(connectionFactory));
_connectionFactory = connectionFactory;
_options = options;
}
///
/// True when the repository's connections enlist in an ambient transaction, so that inside a
/// .Transacted() block is rolled back with it: Npgsql (PostgreSQL) and SqlClient (SQL Server), unless the
/// connection string sets Enlist=false . False for other providers (Microsoft.Data.Sqlite does not enlist) and
/// with Enlist=false ; the idempotent consumer then removes the key itself after a rollback. It is learnt from the
/// connection opens, and the consumer reads it after ; before the first connection it
/// is false.
///
public bool JoinsAmbientTransaction => Volatile.Read(ref _ambientBehaviour) == Joins;
///
///
/// An insert that loses the key to another one at the same moment (an error on PostgreSQL, and on SQL Server when both
/// pass the existence check) answers false : the key is held, the message is a duplicate.
///
public Task Add(string key, CancellationToken ct = default) => AddRacingAsync(key, restampAfter: null, claimId: null, ct);
///
/// ; with , an insert that took longer than
/// that is stamped again, in the same transaction, before it commits: a claim stamped before an insert that then waits on
/// a lock would otherwise look abandoned the moment it became visible. Inside an ambient transaction the row stays
/// invisible until the caller commits, so it is not stamped again there. A goes into the
/// claim_id column; without one the row is written as before 4.8.0, with no claim id.
///
private async Task Add(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await CleanupIfNeededAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
var enlists = EnlistsInAmbientTransaction(conn);
if (Volatile.Read(ref _ambientBehaviour) == 0)
Volatile.Write(ref _ambientBehaviour, enlists ? Joins : StaysOutside);
await using var tx = restampAfter is not null && !(enlists && Transaction.Current is not null)
? await conn.BeginTransactionAsync(ct).ConfigureAwait(false)
: null;
await using var cmd = conn.CreateCommand();
cmd.Transaction = tx;
var (claimColumn, claimValue) = claimId is null ? ("", "") : (", claim_id", ", @claim");
cmd.CommandText = $"""
INSERT INTO {_options.TableName} (processor_name, message_key, created_at, confirmed{claimColumn})
SELECT @processor, @key, {UtcText(cmd, conn, TimeSpan.Zero)}, 0{claimValue}
WHERE NOT EXISTS (
SELECT 1 FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key
)
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
if (claimId is not null)
AddParam(cmd, "claim", claimId);
var started = Stopwatch.GetTimestamp();
var rows = await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
if (rows > 0 && tx is not null && Stopwatch.GetElapsedTime(started) > restampAfter)
{
await using var restamp = conn.CreateCommand();
restamp.Transaction = tx;
restamp.CommandText = $"""
UPDATE {_options.TableName} SET created_at = {UtcText(restamp, conn, TimeSpan.Zero)}
WHERE processor_name = @processor AND message_key = @key
""";
AddParam(restamp, "processor", _options.ProcessorName);
AddParam(restamp, "key", key);
await restamp.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
if (tx is not null)
await tx.CommitAsync(ct).ConfigureAwait(false);
return rows > 0;
}
///
public async Task Confirm(string key, CancellationToken ct = default)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
UPDATE {_options.TableName}
SET confirmed = 1
WHERE processor_name = @processor AND message_key = @key
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
///
public async Task Remove(string key, CancellationToken ct = default)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
DELETE FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
///
/// Sets confirmed on the row only while its claim_id is .
public async Task Confirm(string key, string? token, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
if (token is null)
{
await Confirm(key, ct).ConfigureAwait(false);
return true;
}
await EnsureTableAsync(ct).ConfigureAwait(false);
await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
UPDATE {_options.TableName}
SET confirmed = 1
WHERE processor_name = @processor AND message_key = @key AND claim_id = @claim
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
AddParam(cmd, "claim", token);
return await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0;
}
///
/// Deletes the row only while its claim_id is .
public async Task Release(string key, string? token, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
if (token is null)
{
await Remove(key, ct).ConfigureAwait(false);
return true;
}
await EnsureTableAsync(ct).ConfigureAwait(false);
await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
DELETE FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key AND claim_id = @claim
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
AddParam(cmd, "claim", token);
return await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0;
}
///
public async Task Contains(string key, CancellationToken ct = default)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
SELECT COUNT(1) FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key
""";
AddParam(cmd, "processor", _options.ProcessorName);
AddParam(cmd, "key", key);
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
return Convert.ToInt32(result) > 0;
}
///
public async Task Clear(CancellationToken ct = default)
{
await EnsureTableAsync(ct).ConfigureAwait(false);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"DELETE FROM {_options.TableName} WHERE processor_name = @processor";
AddParam(cmd, "processor", _options.ProcessorName);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
///
public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) =>
(await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome;
///
///
/// Answered from the row's confirmed flag and created_at ; the claim's token is a new random id written
/// to the row's claim_id . An abandoned claim is taken over by deleting the row only while it is still
/// unconfirmed and older than the cutoff, then inserting a new one: of two callers that saw the same stale row, one
/// deletes it and the other deletes nothing and finds the new claim in flight. Inside an ambient transaction the
/// statements run on the transaction's connection, as does. A row without
/// a claim_id (written by or before 4.8.0) is answered and taken
/// over the same way.
///
/// Both the stamp and the cutoff are the database's clock (created_at keeps its ISO 8601 UTC text, so a row
/// written with the application's clock compares as before), and an insert that waits on locks for longer than a tenth
/// of is stamped again before it commits.
///
///
public async Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(key);
await EnsureTableAsync(ct).ConfigureAwait(false);
await EnsureClaimIdColumnAsync(ct).ConfigureAwait(false);
TimeSpan? restamp = abandonedAfter is { } after ? after / 10 : null;
var token = Guid.NewGuid().ToString("N");
var claim = await ClaimAsync(key, abandonedAfter, restamp, token, ct).ConfigureAwait(false);
return new IdempotentLease(claim, claim is IdempotentClaim.Claimed or IdempotentClaim.TakenOver ? token : null);
}
private async Task ClaimAsync(string key, TimeSpan? abandonedAfter, TimeSpan? restamp, string token, CancellationToken ct)
{
if (await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false))
return IdempotentClaim.Claimed;
if (abandonedAfter is { } age)
{
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var takeOver = conn.CreateCommand();
takeOver.CommandText = $"""
DELETE FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key AND confirmed = 0
AND created_at < {UtcText(takeOver, conn, age)}
""";
AddParam(takeOver, "processor", _options.ProcessorName);
AddParam(takeOver, "key", key);
if (await takeOver.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0)
return await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight;
}
return await ReadConfirmedAsync(key, ct).ConfigureAwait(false) switch
{
true => IdempotentClaim.Confirmed,
false => IdempotentClaim.InFlight,
// Released between the insert and the read: claim it again.
null => await AddRacingAsync(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.Claimed : IdempotentClaim.InFlight,
};
}
/// The row's confirmed flag, or null when there is no row.
private async Task ReadConfirmedAsync(string key, CancellationToken ct)
{
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var read = conn.CreateCommand();
read.CommandText = $"""
SELECT confirmed FROM {_options.TableName}
WHERE processor_name = @processor AND message_key = @key
""";
AddParam(read, "processor", _options.ProcessorName);
AddParam(read, "key", key);
var confirmed = await read.ExecuteScalarAsync(ct).ConfigureAwait(false);
return confirmed is null or DBNull ? null : Convert.ToInt32(confirmed, CultureInfo.InvariantCulture) != 0;
}
///
/// where another caller may insert the same key at the
/// same moment: the primary key lets one row through, and a statement that loses on it (an error on some databases, no
/// row on others) means the key is held.
///
private async Task AddRacingAsync(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct)
{
try
{
return await Add(key, restampAfter, claimId, ct).ConfigureAwait(false);
}
catch (DbException)
{
if (await ReadConfirmedAsync(key, ct).ConfigureAwait(false) is not null)
return false;
throw;
}
}
private async Task EnsureTableAsync(CancellationToken ct)
{
if (_tableCreated || !_options.CreateTable) return;
await _ddlLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_tableCreated) return;
// The table is the repository's, not the message's: the first call may run inside the transaction of whatever
// message came first, and DDL there would go with its rollback (PostgreSQL, SQL Server) or commit it implicitly
// (MySQL, Oracle). As Apache Camel creates the table outside any exchange, it is created outside the transaction.
using var outsideTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
// Dialect-aware bootstrap. SQL Server has no CREATE TABLE IF NOT EXISTS, so it gets a
// guarded T-SQL statement; SQLite/PostgreSQL/MySQL keep the portable form. Both are
// idempotent at the SQL level, so even concurrent first-callers won't error — but we
// serialize via _ddlLock to avoid burning round-trips and keep the
// "set _tableCreated only after success" logic linear.
cmd.CommandText = BuildCreateTableDdl(conn, _options.TableName);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
// A table created before 4.8.0 has no claim_id column: added here, before any claim needs it.
if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false))
await AddClaimIdColumnAsync(conn, ct).ConfigureAwait(false);
outsideTransaction.Complete();
_claimIdColumnSeen = true;
_tableCreated = true;
}
finally
{
_ddlLock.Release();
}
}
///
/// Makes sure the table has the claim_id column and the token methods use. With
/// it was added with the table; without it a table that lacks the
/// column fails here with the statement that adds it. does not need it.
///
private async Task EnsureClaimIdColumnAsync(CancellationToken ct)
{
if (_claimIdColumnSeen) return;
await _ddlLock.WaitAsync(ct).ConfigureAwait(false);
try
{
if (_claimIdColumnSeen) return;
using var outsideTransaction = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled);
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false))
throw new InvalidOperationException(
$"The idempotent table {_options.TableName} has no claim_id column, which claims use since redb.Route 4.8.0, " +
$"and CreateTable is off, so the repository does not change the schema. Add it, then start the node: " +
$"{AddClaimIdColumnDdl(conn, _options.TableName)}");
outsideTransaction.Complete();
_claimIdColumnSeen = true;
}
finally
{
_ddlLock.Release();
}
}
/// Whether the table has a claim_id column: a query that names it, and returns no row, succeeds.
private async Task HasClaimIdColumnAsync(DbConnection conn, CancellationToken ct)
{
await using var probe = conn.CreateCommand();
probe.CommandText = $"SELECT claim_id FROM {_options.TableName} WHERE 1 = 0";
try
{
await using var reader = await probe.ExecuteReaderAsync(ct).ConfigureAwait(false);
return true;
}
catch (DbException)
{
return false;
}
}
/// Adds the claim_id column; when another node added it at the same moment, its column is taken.
private async Task AddClaimIdColumnAsync(DbConnection conn, CancellationToken ct)
{
await using var alter = conn.CreateCommand();
alter.CommandText = AddClaimIdColumnDdl(conn, _options.TableName);
try
{
await alter.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
catch (DbException)
{
if (!await HasClaimIdColumnAsync(conn, ct).ConfigureAwait(false))
throw;
}
}
///
/// The statement that adds the nullable claim_id column to a table created before 4.8.0: rows written before
/// keep a null claim id.
///
private static string AddClaimIdColumnDdl(DbConnection conn, string table) => IsSqlServer(conn)
? $"ALTER TABLE {table} ADD claim_id NVARCHAR(36) NULL"
: $"ALTER TABLE {table} ADD COLUMN claim_id VARCHAR(36) NULL";
/// True when the live connection is a SQL Server connection (exact class-name match,
/// so MySqlConnection /NpgsqlConnection /SqliteConnection are not misdetected).
private static bool IsSqlServer(DbConnection conn) =>
string.Equals(conn.GetType().Name, "SqlConnection", StringComparison.Ordinal);
///
/// Whether enlists in an ambient transaction. Npgsql and SqlClient do by default (Enlist is
/// on) and are the providers this is established for; any other provider, and Enlist=false or no , is taken as
/// staying outside, so the consumer removes the key itself rather than leave one whose work never committed.
///
private static bool EnlistsInAmbientTransaction(DbConnection conn)
{
if (conn.GetType().Name is not ("NpgsqlConnection" or "SqlConnection"))
return false;
var settings = new DbConnectionStringBuilder { ConnectionString = conn.ConnectionString };
return !settings.TryGetValue("Enlist", out var enlist)
|| Convert.ToString(enlist, CultureInfo.InvariantCulture)?.Trim().ToLowerInvariant() is not ("false" or "no");
}
///
/// Returns the CREATE TABLE statement for the connection's dialect. The key columns are sized: MySQL and MariaDB refuse a
/// TEXT column in a primary key (error 1170), and on SQL Server a clustered key is limited to 900 bytes — a
/// processor name of 128 and a message key of 255 characters (766 bytes as NVARCHAR ) stay inside it.
///
private static string BuildCreateTableDdl(DbConnection conn, string table) => IsSqlServer(conn)
? $"""
IF OBJECT_ID(N'{table}', N'U') IS NULL
CREATE TABLE {table} (
processor_name NVARCHAR(128) NOT NULL,
message_key NVARCHAR(255) NOT NULL,
created_at NVARCHAR(64) NOT NULL,
confirmed INT NOT NULL DEFAULT 0,
claim_id NVARCHAR(36) NULL,
PRIMARY KEY (processor_name, message_key)
)
"""
: $"""
CREATE TABLE IF NOT EXISTS {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,
claim_id VARCHAR(36) NULL,
PRIMARY KEY (processor_name, message_key)
)
""";
private async Task CleanupIfNeededAsync(CancellationToken ct)
{
if (_options.Ttl is not { } ttl) return;
await using var conn = await _connectionFactory.CreateConnectionAsync(ct: ct).ConfigureAwait(false);
await using var cmd = conn.CreateCommand();
cmd.CommandText = $"""
DELETE FROM {_options.TableName}
WHERE processor_name = @processor AND created_at < {UtcText(cmd, conn, ttl)}
""";
AddParam(cmd, "processor", _options.ProcessorName);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
///
/// The current UTC time minus , as SQL for (its parameter is added): the
/// created_at text, ISO 8601 with seven fraction digits and +00:00 , the round-trip form of a
/// in UTC, so the text orders as the time does whichever clock wrote it. The database's
/// clock on SQL Server, PostgreSQL, SQLite and MySQL/MariaDB, so the nodes' clocks do not enter; on another database
/// the application's, as before (the stamp, the re-stamp and the cutoff then all take it).
///
private static string UtcText(DbCommand cmd, DbConnection conn, TimeSpan age)
{
var sql = conn.GetType().Name switch
{
"SqlConnection" =>
"FORMAT(DATEADD(SECOND, -CAST(@ageMs / 1000 AS INT), DATEADD(MILLISECOND, -CAST(@ageMs % 1000 AS INT), SYSUTCDATETIME())), " +
"'yyyy-MM-dd''T''HH:mm:ss.fffffff', 'en-US') + '+00:00'",
"NpgsqlConnection" =>
"to_char((clock_timestamp() AT TIME ZONE 'UTC') - @ageMs * interval '1 millisecond', 'YYYY-MM-DD\"T\"HH24:MI:SS.US') || '0+00:00'",
"SqliteConnection" =>
"strftime('%Y-%m-%dT%H:%M:%f', 'now', '-' || (@ageMs / 1000.0) || ' seconds') || '0000+00:00'",
"MySqlConnection" =>
"CONCAT(DATE_FORMAT(UTC_TIMESTAMP(6) - INTERVAL (@ageMs * 1000) MICROSECOND, '%Y-%m-%dT%H:%i:%s.%f'), '0+00:00')",
_ => null,
};
if (sql is null)
{
AddParam(cmd, "clock", DateTimeOffset.UtcNow.Subtract(age).ToString("O"));
return "@clock";
}
AddParam(cmd, "ageMs", (long)age.TotalMilliseconds);
return sql;
}
private static void AddParam(DbCommand cmd, string name, object value)
{
var p = cmd.CreateParameter();
p.ParameterName = name;
p.Value = value;
cmd.Parameters.Add(p);
}
}
Path: redb-route/redb.Route.Sql/SqlBatchItemError.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlBatchItemError.cs
----
namespace redb.Route.Sql;
///
/// A batch item that failed in a batch configured with breakBatchOnError=false : its statement was undone to the
/// item's savepoint and the batch went on. The failed items of a batch are carried in the
/// header.
///
/// Zero-based position of the item in the batch source.
/// The provider's error message.
///
/// The SQLSTATE code when the provider reports one ( ), otherwise null.
///
public sealed record SqlBatchItemError(int Index, string Message, string? SqlState);
Path: redb-route/redb.Route.Sql/SqlComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql.Connection;
namespace redb.Route.Sql;
///
/// SQL component. Scheme: sql .
/// Provides database polling (consumer) and query execution (producer)
/// over any ADO.NET provider via .
///
/// URI examples:
///
/// sql:SELECT * FROM orders?mode=Poll&dataSource=main&delay=5000
/// sql:INSERT INTO audit(msg) VALUES(:#msg)?dataSource=main
/// sql:sp_Calculate?mode=Procedure&dataSource=main
///
///
///
public class SqlComponent : ComponentBase
{
///
public override string Scheme => "sql";
/// The path of a sql: URI IS the query text — the structured XML form takes it from CDATA content.
public override bool PathIsText => true;
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new SqlEndpointOptions();
options.BindFromUri(uri.RawParameters);
// In Procedure mode the URI path IS the procedure name (same as the query text is in the
// other modes). Without this, every procedure URI had to repeat the name in procedureName=,
// and the fluent builder — which only ever emits the path — produced a URI that failed
// validation. An explicit procedureName= still wins.
if (options.Mode == SqlMode.Procedure && string.IsNullOrEmpty(options.ProcedureName))
options.ProcedureName = uri.Path;
options.Validate();
return new SqlEndpoint(uri, this, options);
}
}
///
/// SQL endpoint. Creates a consumer (polling) or producer (execute/procedure)
/// based on the in options.
/// The path part of the URI is the SQL query or stored procedure name.
///
public class SqlEndpoint : EndpointBase
{
/// Creates a SQL endpoint.
/// Parsed endpoint URI.
/// The SQL component that created this endpoint.
/// Bound and validated endpoint options.
public SqlEndpoint(EndpointUri uri, SqlComponent component, SqlEndpointOptions options)
: base(uri, component, options)
{
_outputMapping = new Lazy(() => Mapping.SqlRowMapperFactory.Resolve(
Options.OutputClass,
component.Context?.GetService() ?? redb.Route.Components.Bean.DefaultBeanTypeResolver.Instance));
}
private readonly Lazy _outputMapping;
///
/// The POCO mapping of outputClass , or null without one: resolved once for this endpoint, through the type
/// resolver of its route context, on first use (a type that cannot be resolved fails the first exchange).
///
internal Mapping.SqlRowMapperFactory.PocoMapping? OutputMapping => _outputMapping.Value;
/// Gets the SQL component that owns this endpoint.
internal SqlComponent SqlComponent => (SqlComponent)Component;
/// Gets the endpoint options for access by consumer/producer.
internal SqlEndpointOptions EndpointOptions => Options;
///
/// The SQL query or procedure name from the URI path.
/// This is the raw text after sql: and before ? .
///
public string QueryOrProcedure => Uri.Path;
///
/// Resolves a data source whose factory is registered already, so dataSource=redb on a context without redb, or
/// dataSource=redb:<name> naming no service, fails when the context starts the endpoint (the context logs it
/// and reports degraded mode) instead of at the first exchange.
///
public override Task Start(CancellationToken ct = default)
{
ResolveRegisteredFactoryAtStart();
return base.Start(ct);
}
///
public override IProducer CreateProducer()
{
return Options.Mode switch
{
SqlMode.Procedure => new SqlProcedureProducer(this, Options),
_ => new SqlProducer(this, Options)
};
}
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
if (Options.Mode != SqlMode.Poll)
throw new InvalidOperationException(
$"SQL consumer requires Mode=Poll, but Mode={Options.Mode}. " +
"Use Sql.Poll() or add mode=Poll to the URI.");
return new SqlConsumer(this, processor, Options);
}
///
/// Resolves using registry lookup:
///
/// - Context registry:
context.GetFromRegistry<ISqlConnectionFactory>(dataSource)
/// - A name with a qualifier (
redb:orders ) no factory is registered under: the factory under the part
/// before the first : , asked for the rest ( )
/// - Inline
connectionString from the URI
///
/// A factory that lends its connection is asked for the bare name too, so it can refuse a lender that is not there.
///
internal ISqlConnectionFactory ResolveConnectionFactory()
=> TryResolveRegisteredFactory() ?? ResolveUnregisteredFactory();
///
/// The endpoint's and the consumer's start: resolves a data source whose factory is registered already, so a lending
/// factory refuses a missing lender before the first exchange. A data source not registered yet is resolved per
/// exchange, as before.
///
/// The factory, or null when the data source is not registered yet (or a connection string is used).
internal ISqlConnectionFactory? ResolveRegisteredFactoryAtStart() => TryResolveRegisteredFactory();
private ISqlConnectionFactory? TryResolveRegisteredFactory()
{
if (Options.DataSource is not { } dataSource || SqlComponent.Context is not { } context)
return null;
if (context.GetFromRegistry(dataSource) is { } factory)
return factory.LendsConnection ? factory.ForQualifier(null) : factory;
var colon = dataSource.IndexOf(':');
if (colon > 0 && colon < dataSource.Length - 1
&& context.GetFromRegistry(dataSource[..colon]) is { } qualified)
return qualified.ForQualifier(dataSource[(colon + 1)..]);
return null;
}
private ISqlConnectionFactory ResolveUnregisteredFactory()
{
if (Options.DataSource != null)
{
throw new InvalidOperationException(
$"DataSource '{Options.DataSource}' is not found in context registry. " +
"Register it via context.AddToRegistry(name, ISqlConnectionFactory). dataSource=redb and " +
"dataSource=redb: come with redb.Route.Core: services.AddRedbRouteCore() or context.AddRedbSqlDataSource().");
}
if (Options.ConnectionString != null)
{
return new SqlConnectionFactory(new SqlConnectionOptions
{
ConnectionString = Options.ConnectionString,
ProviderName = Options.Provider ?? string.Empty
});
}
throw new InvalidOperationException("Either DataSource or ConnectionString must be configured.");
}
}
Path: redb-route/redb.Route.Sql/SqlConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlConsumer.cs
----
using System.Data.Common;
using System.Diagnostics;
using System.Transactions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Mapping;
using redb.Route.Telemetry;
namespace redb.Route.Sql;
///
/// Polling consumer for SQL. Periodically executes a SELECT query and emits
/// an per row (or batch). Supports OnSuccess/OnFailure
/// lifecycle SQL and named query references.
///
///
/// Transaction behavior: by default runs without a local transaction (SELECT is
/// idempotent). Set ?transacted=true to wrap SELECT + OnSuccess/OnFailure in a
/// single — useful when SELECT + OnSuccess
/// UPDATE must be atomic (e.g. outbox pattern).
/// If an ambient exists (e.g. from
/// BeginTransaction() DSL), the local transaction is skipped and the connection
/// auto-enlists in the ambient .
///
internal sealed class SqlConsumer : DrainableConsumer
{
private readonly SqlEndpoint _endpoint;
private readonly SqlEndpointOptions _options;
private long _pollCount;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => "sql";
internal SqlConsumer(SqlEndpoint endpoint, IProcessor processor, SqlEndpointOptions options)
: base(processor)
{
_endpoint = endpoint;
_options = options;
}
///
/// Refuses a data source that lends its connection (dataSource=redb ): the consumer polls outside any exchange,
/// so no exchange holds the lease, and its poll and onConsume statements need a transaction of its own.
///
protected override Task OnStarting(CancellationToken ct)
{
if (_endpoint.ResolveRegisteredFactoryAtStart() is { LendsConnection: true })
throw new InvalidOperationException(
$"The sql: consumer polls outside any exchange and runs its poll and onConsume statements in a transaction of " +
$"its own, and dataSource={_options.DataSource} lends the connection of a redb service to one step of an " +
"exchange. Poll through a data source with a connection string of its own (it may name the same database).");
return Task.CompletedTask;
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
if (_options.InitialDelay > 0)
await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false);
var delay = TimeSpan.FromMilliseconds(_options.Delay);
while (!pollCt.IsCancellationRequested)
{
var sw = Stopwatch.StartNew();
try
{
await Poll(processingCt).ConfigureAwait(false);
}
catch (OperationCanceledException) when (pollCt.IsCancellationRequested || processingCt.IsCancellationRequested) { break; }
catch (Exception ex)
{
Logger?.LogError(ex, "SQL consumer poll failed: dataSource={DataSource}",
_options.DataSource);
}
_pollCount++;
if (_options.RepeatCount > 0 && _pollCount >= _options.RepeatCount)
break;
try
{
if (_options.FixedRate)
{
var remaining = delay - sw.Elapsed;
if (remaining > TimeSpan.Zero)
await Task.Delay(remaining, pollCt).ConfigureAwait(false);
}
else
{
await Task.Delay(delay, pollCt).ConfigureAwait(false);
}
}
catch (OperationCanceledException) { break; }
}
}
internal async Task Poll(CancellationToken ct)
{
var factory = ResolveConnectionFactory();
// Measured until the statement has run and its result is read (for a stream, until the reader is open): each poll
// strategy reads the stopwatch at that point.
var sw = Stopwatch.StartNew();
// The replica only with readOnly=true, which Validate refuses for a poll that marks or locks its rows.
await using var connection = await factory.CreateConnectionAsync(readOnly: _options.ReadOnly, ct).ConfigureAwait(false);
var hasAmbientTx = Transaction.Current != null;
DbTransaction? tx = null;
if (!hasAmbientTx && _options.Transacted)
{
tx = _options.IsolationLevel.HasValue
? await connection.BeginTransactionAsync(_options.IsolationLevel.Value, ct).ConfigureAwait(false)
: await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
}
try
{
var sql = ResolveQuery(null);
await using var cmd = connection.CreateCommand();
cmd.CommandText = sql;
cmd.CommandTimeout = _options.CommandTimeout;
if (tx != null) cmd.Transaction = tx;
BindPollParameters(cmd);
switch (_options.OutputType)
{
case SqlOutputType.Scalar:
await PollScalar(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
break;
case SqlOutputType.SelectOne:
await PollSelectOne(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
break;
case SqlOutputType.StreamList when _options.PollDelivery == SqlPollDelivery.List:
await PollStreamAsList(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
break;
case SqlOutputType.StreamList:
await PollStreamPerRow(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
break;
default:
if (_options.PollDelivery == SqlPollDelivery.List)
await PollAsList(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
else
await PollPerRow(cmd, connection, tx, sql, sw, ct).ConfigureAwait(false);
break;
}
}
catch (Exception ex)
{
// A stop (cancellation of this poll's token) is not a failure; anything else is logged here, whatever the caller does.
if (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
Logger?.LogError(ex, "SQL consumer execution failed: dataSource={DataSource}",
_options.DataSource);
}
if (tx != null)
{
// The rollback is not interruptible: a cancelled token would only turn it into a "rollback failed" log.
try { await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false); }
catch (Exception rbEx) { Logger?.LogError(rbEx, "SQL transaction rollback failed"); }
}
throw;
}
finally
{
if (tx != null)
await tx.DisposeAsync().ConfigureAwait(false);
}
}
// ── Poll strategies by OutputType ─────────────────────────────
/// Default mode: read all rows, emit one exchange per row with lifecycle SQL.
private async Task PollPerRow(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var rows = new List>();
var bodies = new List();
var mapper = new DictionaryRowMapper();
var poco = _endpoint.OutputMapping;
await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false))
{
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
if (_options.MaxMessagesPerPoll >= 0 && rows.Count >= _options.MaxMessagesPerPoll)
break;
// The dictionary is mapped even when outputClass is set: headers and the
// OnSuccess/OnFailure parameter auto-bind are driven off the raw columns,
// and a POCO would silently drop any column it has no property for.
rows.Add(mapper.Map(reader));
bodies.Add(poco?.Map(reader));
}
}
var executionMs = stopwatch.ElapsedMilliseconds;
// onFailureAfterRollback: every row under a savepoint, so a failed row is undone alone and the cycle goes on.
var perRowSavepoint = tx != null && _options.OnFailureAfterRollback;
for (var i = 0; i < rows.Count; i++)
{
var row = rows[i];
var exchange = CreateExchange(bodies[i] ?? row, row, sql, rows.Count, executionMs);
using var span = StartReceiveSpan();
IncrementInflight();
try
{
if (perRowSavepoint)
await SaveRowAsync(tx!, ct).ConfigureAwait(false);
await Processor.Process(exchange, ct).ConfigureAwait(false);
// A failure the route left on the exchange (onException handled="false", rollback-only) fails the row too.
exchange.ThrowIfUnhandledFailure();
await ExecuteOnSuccessAsync(connection, tx, row, exchange, ct).ConfigureAwait(false);
}
// A stop is not a failure of the row: a cancellation of this poll's token goes up, onFailure does not run.
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
exchange.Exception = ex;
if (perRowSavepoint)
{
if (await TryRollbackRowAsync(tx!, i).ConfigureAwait(false))
{
// The row's own work is undone; its mark stays in the poll's transaction, and the next row goes on.
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
continue;
}
// The server has ended the transaction: nothing more can be written in it.
await RollbackQuietlyAsync(tx!).ConfigureAwait(false);
return;
}
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
if (tx != null) { await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false); return; }
}
finally
{
RecordOutcome(span, exchange, ct);
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
if (rows.Count == 0)
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
///
/// Streaming mode: reads rows lazily from
/// without buffering all rows in memory. Each row is processed while the reader stays open.
///
/// Where onSuccess / onFailure run follows Apache Camel, which runs onConsume through its
/// JdbcTemplate : inside a transaction (transacted=true or an ambient one) on the reader's connection and
/// transaction; outside one on a connection of their own to the primary database, opened on first use and closed with the
/// cycle. The consequences are the drivers': PostgreSQL and SQL Server refuse a second command on the reader's connection
/// (a failing onSuccess is logged and the transaction rolls back), and SQLite in its default journal mode blocks a
/// write on another connection while the reader is open. onBatchComplete runs after the reader is closed, on the
/// reader's connection and transaction.
///
///
private async Task PollStreamPerRow(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var mapper = new DictionaryRowMapper();
var poco = _endpoint.OutputMapping;
var rowCount = 0;
var inTransaction = tx != null || Transaction.Current != null;
long executionMs = 0;
DbConnection? rowStatementConnection = null;
// Inside a transaction the reader's connection and transaction; outside one a connection of their own, on first use.
async Task RowStatementConnectionAsync() =>
inTransaction ? connection : (rowStatementConnection ??= await OpenRowStatementConnectionAsync(ct).ConfigureAwait(false));
var rowStatementTransaction = inTransaction ? tx : null;
var rollbackAfterReader = false;
try
{
await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false))
{
// A stream is measured until its reader is open; the rows are read while the route runs.
executionMs = stopwatch.ElapsedMilliseconds;
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
if (_options.MaxMessagesPerPoll >= 0 && rowCount >= _options.MaxMessagesPerPoll)
break;
var row = mapper.Map(reader);
var body = poco?.Map(reader) ?? row;
rowCount++;
var exchange = CreateExchange(body, row, sql, -1, executionMs);
using var span = StartReceiveSpan();
IncrementInflight();
try
{
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
if (!string.IsNullOrEmpty(_options.OnSuccess))
{
var statementConnection = await RowStatementConnectionAsync().ConfigureAwait(false);
await ExecuteOnSuccessAsync(statementConnection, rowStatementTransaction, row, exchange, ct).ConfigureAwait(false);
}
}
// A stop is not a failure of the row: a cancellation of this poll's token goes up, onFailure does not run.
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
exchange.Exception = ex;
if (!string.IsNullOrEmpty(_options.OnFailure))
{
var statementConnection = await RowStatementConnectionAsync().ConfigureAwait(false);
await ExecuteLifecycleSql(statementConnection, rowStatementTransaction, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
}
if (tx != null) { rollbackAfterReader = true; break; }
}
finally
{
RecordOutcome(span, exchange, ct);
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
}
if (rollbackAfterReader)
{
// After the reader is closed: PostgreSQL and SQL Server refuse even a rollback while it is open.
await tx!.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
return;
}
}
finally
{
if (rowStatementConnection is not null)
await rowStatementConnection.DisposeAsync().ConfigureAwait(false);
}
if (rowCount == 0)
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
///
/// List delivery (pollDelivery=List , Apache Camel useIterator=false ): reads the rows first, closes the reader,
/// then hands the route one exchange with all of them (List<T> with outputClass ). An empty result is
/// delivered as an empty list when routeEmptyResultSet is set.
///
private async Task PollAsList(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var poco = _endpoint.OutputMapping;
var mapper = new DictionaryRowMapper();
var rows = poco?.CreateList() ?? new List>();
await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false))
{
while (await reader.ReadAsync(ct).ConfigureAwait(false))
{
if (_options.MaxMessagesPerPoll >= 0 && rows.Count >= _options.MaxMessagesPerPoll)
break;
rows.Add(poco != null ? poco.Map(reader) : mapper.Map(reader));
}
}
var executionMs = stopwatch.ElapsedMilliseconds;
if (rows.Count > 0 || _options.RouteEmptyResultSet)
{
var exchange = CreateExchange(rows, null, sql, rows.Count, executionMs);
if (await RunListExchangeAsync(exchange, connection, tx, static () => ValueTask.CompletedTask, ct).ConfigureAwait(false))
return;
}
else
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
///
/// Streaming list delivery (outputType=StreamList , pollDelivery=List ; Apache Camel useIterator=false
/// with a result set iterator): the route gets the open stream as the body and reads the rows while it runs. The reader
/// is closed as soon as the route is done, so onSuccess / onFailure and onBatchComplete then share
/// the consumer's connection and transaction on every driver.
///
private async Task PollStreamAsList(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var poco = _endpoint.OutputMapping;
var mapper = new DictionaryRowMapper();
var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
var executionMs = stopwatch.ElapsedMilliseconds;
var readerClosed = false;
async ValueTask CloseReaderAsync()
{
if (readerClosed)
return;
readerClosed = true;
await reader.DisposeAsync().ConfigureAwait(false);
}
try
{
if (await reader.ReadAsync(ct).ConfigureAwait(false))
{
Func map = poco != null ? poco.Map : r => mapper.Map(r);
var stream = ConsumerRowStream.Create(
poco?.ElementType ?? typeof(Dictionary), reader, map, _options.MaxMessagesPerPoll);
var exchange = CreateExchange(stream, null, sql, -1, executionMs);
if (await RunListExchangeAsync(exchange, connection, tx, CloseReaderAsync, ct).ConfigureAwait(false))
return;
}
else
{
await CloseReaderAsync().ConfigureAwait(false);
if (_options.RouteEmptyResultSet)
{
var empty = poco?.CreateList() ?? new List>();
var exchange = CreateExchange(empty, null, sql, 0, executionMs);
if (await RunListExchangeAsync(exchange, connection, tx, static () => ValueTask.CompletedTask, ct).ConfigureAwait(false))
return;
}
else
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
}
}
finally
{
await CloseReaderAsync().ConfigureAwait(false);
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
///
/// Processes the one exchange of a list delivery: the route, then (closing a streamed list's
/// reader), then onSuccess — or, on any failure, onFailure and a rollback. Values of the statements come from
/// headers and param.* .
///
/// True when the consumer transaction was rolled back and the poll cycle ends.
private async Task RunListExchangeAsync(
Exchange exchange, DbConnection connection, DbTransaction? tx, Func afterRoute, CancellationToken ct)
{
using var span = StartReceiveSpan();
IncrementInflight();
try
{
try
{
try
{
await Processor.Process(exchange, ct).ConfigureAwait(false);
}
finally
{
await afterRoute().ConfigureAwait(false);
}
exchange.ThrowIfUnhandledFailure();
await ExecuteOnSuccessAsync(connection, tx, null, exchange, ct).ConfigureAwait(false);
}
// A stop is not a failure of the row: a cancellation of this poll's token goes up, onFailure does not run.
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
exchange.Exception = ex;
if (tx != null)
{
await FailInTransactionAsync(connection, tx, null, exchange, ct).ConfigureAwait(false);
return true;
}
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, null, exchange, ct).ConfigureAwait(false);
}
}
finally
{
RecordOutcome(span, exchange, ct);
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
return false;
}
/// Name of the savepoint each row of an onFailureAfterRollback poll runs under.
internal const string RowSavepointName = "redb_poll_row";
private static async Task SaveRowAsync(DbTransaction tx, CancellationToken ct)
{
try
{
await tx.SaveAsync(RowSavepointName, ct).ConfigureAwait(false);
}
catch (NotSupportedException ex)
{
throw new InvalidOperationException(
$"onFailureAfterRollback=true undoes a failed row to a savepoint, and {tx.Connection?.GetType().Name} does not support " +
"savepoints. Remove the option: a failure then rolls back the whole poll and the row is read again.", ex);
}
}
private async Task TryRollbackRowAsync(DbTransaction tx, int index)
{
try
{
await tx.RollbackAsync(RowSavepointName, CancellationToken.None).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
Logger?.LogWarning(ex,
"SQL poll row {Index} failed and its savepoint can no longer be rolled back to; the transaction has ended, the cycle stops",
index);
return false;
}
}
private async Task RollbackQuietlyAsync(DbTransaction tx)
{
try { await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false); }
catch (Exception ex) { Logger?.LogDebug(ex, "SQL poll transaction was already ended by the server"); }
}
///
/// The failure of the one exchange of a poll (a list, a scalar, a single row) inside the poll's transaction. By default
/// onFailure runs in it and the transaction rolls back with it. With onFailureAfterRollback the transaction
/// rolls back first, then onFailure runs in a short transaction of its own on the same connection, so the mark stays.
///
private async Task FailInTransactionAsync(
DbConnection connection, DbTransaction tx, Dictionary? row, IExchange exchange, CancellationToken ct)
{
if (!_options.OnFailureAfterRollback)
{
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
return;
}
await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
if (string.IsNullOrEmpty(_options.OnFailure))
return;
await using var own = await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
await ExecuteLifecycleSql(connection, own, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
await own.CommitAsync(ct).ConfigureAwait(false);
}
/// A connection to the primary database for the row statements of a streaming poll.
private Task OpenRowStatementConnectionAsync(CancellationToken ct) =>
ResolveConnectionFactory().CreateConnectionAsync(readOnly: false, ct);
/// Scalar: ExecuteScalarAsync → single exchange. Ideal for FOR XML / FOR JSON.
private async Task PollScalar(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
var executionMs = stopwatch.ElapsedMilliseconds;
if (result == DBNull.Value) result = null;
if (result == null)
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
else
{
var exchange = CreateExchange(result, null, sql, 1, executionMs);
using var span = StartReceiveSpan();
IncrementInflight();
try
{
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
await ExecuteOnSuccessAsync(connection, tx, null, exchange, ct).ConfigureAwait(false);
}
// A stop is not a failure of the row: a cancellation of this poll's token goes up, onFailure does not run.
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
exchange.Exception = ex;
if (tx != null) { await FailInTransactionAsync(connection, tx, null, exchange, ct).ConfigureAwait(false); return; }
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, null, exchange, ct).ConfigureAwait(false);
}
finally
{
RecordOutcome(span, exchange, ct);
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
/// SelectOne: first row only → single exchange.
private async Task PollSelectOne(
DbCommand cmd, DbConnection connection, DbTransaction? tx,
string sql, Stopwatch stopwatch, CancellationToken ct)
{
var mapper = new DictionaryRowMapper();
var poco = _endpoint.OutputMapping;
Dictionary? row = null;
object? body = null;
await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false))
{
if (await reader.ReadAsync(ct).ConfigureAwait(false))
{
row = mapper.Map(reader);
body = poco?.Map(reader) ?? row;
}
}
var executionMs = stopwatch.ElapsedMilliseconds;
if (row == null)
{
await ProcessEmptyResult(sql, executionMs, ct).ConfigureAwait(false);
}
else
{
var exchange = CreateExchange(body, row, sql, 1, executionMs);
using var span = StartReceiveSpan();
IncrementInflight();
try
{
await Processor.Process(exchange, ct).ConfigureAwait(false);
exchange.ThrowIfUnhandledFailure();
await ExecuteOnSuccessAsync(connection, tx, row, exchange, ct).ConfigureAwait(false);
}
// A stop is not a failure of the row: a cancellation of this poll's token goes up, onFailure does not run.
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
exchange.Exception = ex;
if (tx != null) { await FailInTransactionAsync(connection, tx, row, exchange, ct).ConfigureAwait(false); return; }
await ExecuteLifecycleSql(connection, tx, _options.OnFailure, row, exchange, ct).ConfigureAwait(false);
}
finally
{
RecordOutcome(span, exchange, ct);
DecrementInflight();
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
await ExecuteLifecycleSql(connection, tx, _options.OnBatchComplete, null, null, ct).ConfigureAwait(false);
if (tx != null) await tx.CommitAsync(ct).ConfigureAwait(false);
}
/// Handles empty result for RouteEmptyResultSet / SendEmptyMessageWhenIdle.
private async Task ProcessEmptyResult(string sql, long executionMs, CancellationToken ct)
{
if (_options.RouteEmptyResultSet)
{
var empty = new Dictionary();
var emptyExchange = CreateExchange(empty, empty, sql, 0, executionMs);
// An exchange the route runs has its span, an empty one too; only a poll that routes nothing has none.
using var span = StartReceiveSpan();
try { await Processor.Process(emptyExchange, ct).ConfigureAwait(false); }
finally
{
RecordOutcome(span, emptyExchange, ct);
await emptyExchange.DisposeAsync().ConfigureAwait(false);
}
}
else if (_options.SendEmptyMessageWhenIdle)
{
var idleExchange = Exchange.Create(new Message(null), _endpoint.ScopeFactory);
idleExchange.In.Headers[SqlHeaders.Query] = sql;
idleExchange.In.Headers[SqlHeaders.RowCount] = 0;
using var span = StartReceiveSpan();
try { await Processor.Process(idleExchange, ct).ConfigureAwait(false); }
finally
{
RecordOutcome(span, idleExchange, ct);
await idleExchange.DisposeAsync().ConfigureAwait(false);
}
}
}
// ── Parameter binding for poll query ────────────────────────────
///
/// Binds the :#name placeholders of the poll query. The query has no exchange, so its values come from
/// param.* only (constants and context placeholders); a placeholder without one is an error, as everywhere else.
///
private void BindPollParameters(DbCommand cmd)
{
var plan = SqlParameterPlan.Create(cmd.CommandText, _options.ExplicitParameters, _options.PlaceholderStyle, _options.BackslashEscapes);
var values = new object?[plan.Names.Count];
for (var index = 0; index < plan.Names.Count; index++)
{
var name = plan.Names[index];
if (!plan.TryGetExplicit(name, out var explicitParameter))
{
throw new InvalidOperationException(SqlParameterBinder.MissingValueMessage(name, plan.SourceSql,
$"a poll query has no exchange to take values from, and there is no param.{name} option"));
}
// Without an exchange an expression cannot be evaluated, and its text must not be bound as the value.
if (explicitParameter.IsExpression)
{
throw new InvalidOperationException(
$"SQL parameter ':#{name}' of the poll query is set to '{explicitParameter.Value}', a ${{...}} expression, and a " +
$"poll query has no exchange to evaluate it in. Give param.{name} a constant or a {{{{property}}}} placeholder. " +
$"Query: {plan.SourceSql}");
}
values[index] = explicitParameter.Resolve(null);
}
AddPlanParameters(cmd, plan, values);
}
// ── Exchange creation ───────────────────────────────────────────
///
/// Creates the exchange for one polled row.
///
///
/// What the route sees as the message body — the raw row dictionary, or the mapped POCO
/// when outputClass is set, or a scalar in Scalar mode.
///
///
/// The raw columns of the row, independent of . Used for the header
/// copy that OnSuccess/OnFailure parameter binding relies on. Null when there is no row
/// (Scalar mode).
///
/// The resolved poll query, echoed into the redbSql.query header.
/// Rows in this poll cycle; -1 when streaming (not known upfront).
/// Query execution time in milliseconds.
///
/// The span of one exchange a poll routes — a row, or the list of a batch. A row carries no trace context, so it is a
/// root, never a child of the activity the poll loop holds. A poll that routes no exchange opens none.
///
private TransportSpan StartReceiveSpan() => RouteTelemetryExtensions.StartConsumerSpan(
(_endpoint.Component as ComponentBase)?.Context,
"sql.receive", ActivityKind.Consumer, "db.system", _endpoint.Component.Scheme, _endpoint.Uri.NormalizedKey,
null, static (_, _) => null);
/// Marks the span failed when the exchange failed; our own stop (the poll's token) is not a failure.
private static void RecordOutcome(TransportSpan span, IExchange exchange, CancellationToken ct)
{
if (exchange.Exception is { } failure && !exchange.ExceptionHandled
&& (failure is not OperationCanceledException || !ct.IsCancellationRequested))
span.Activity.RecordFailure(failure);
}
private Exchange CreateExchange(object? body, Dictionary? row, string sql, int rowCount, long executionTimeMs)
{
var exchange = Exchange.Create(new Message(body), _endpoint.ScopeFactory);
exchange.In.Headers[SqlHeaders.Query] = sql;
exchange.In.Headers[SqlHeaders.RowCount] = rowCount;
exchange.In.Headers[SqlHeaders.ExecutionTime] = executionTimeMs;
exchange.In.Headers[SqlHeaders.OutputType] = _options.OutputType.ToString();
if (_options.DataSource != null)
exchange.In.Headers[SqlHeaders.DataSource] = _options.DataSource;
// Copy row fields to headers for auto-bind in OnSuccess/OnFailure
if (row != null)
{
foreach (var (key, value) in row)
exchange.In.Headers[key] = value;
}
return exchange;
}
///
/// Runs onSuccess for a processed row. A failure is logged and rethrown: the row's failure handling
/// (onFailure , rollback) still sees it, and without onFailure the unmarked row — processed again on the next
/// poll — would otherwise pass unnoticed.
///
private async Task ExecuteOnSuccessAsync(
DbConnection connection, DbTransaction? tx, Dictionary? row, IExchange exchange, CancellationToken ct)
{
try
{
await ExecuteLifecycleSql(connection, tx, _options.OnSuccess, row, exchange, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Logger?.LogError(ex,
"SQL consumer onSuccess failed; the row stays unmarked and will be polled again: dataSource={DataSource}",
_options.DataSource);
throw;
}
}
private async Task ExecuteLifecycleSql(
DbConnection connection,
DbTransaction? tx,
string? sql,
Dictionary? row,
IExchange? exchange,
CancellationToken ct)
{
if (string.IsNullOrEmpty(sql)) return;
var resolved = ResolveNamedQuery(sql);
await using var cmd = connection.CreateCommand();
cmd.CommandText = resolved;
cmd.CommandTimeout = _options.CommandTimeout;
if (tx != null) cmd.Transaction = tx;
BindParameters(cmd, row, exchange);
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
private void BindParameters(DbCommand cmd, Dictionary? row, IExchange? exchange)
{
var plan = SqlParameterPlan.Create(cmd.CommandText, _options.ExplicitParameters, _options.PlaceholderStyle, _options.BackslashEscapes);
var values = new object?[plan.Names.Count];
for (var index = 0; index < plan.Names.Count; index++)
{
var name = plan.Names[index];
var isRedbError = name.Equals("redbError", StringComparison.OrdinalIgnoreCase);
// Special: :#redbError → exception message
if (isRedbError && exchange?.Exception != null)
{
values[index] = exchange.Exception.Message;
}
// Priority 0: explicit param from .Param()
else if (plan.TryGetExplicit(name, out var explicitParameter))
{
values[index] = explicitParameter.Resolve(exchange);
}
// Priority 1: row data
else if (row != null && row.TryGetValue(name, out var rowVal))
{
values[index] = rowVal ?? DBNull.Value;
}
// Priority 2: exchange headers
else if (exchange?.In.Headers.TryGetValue(name, out var headerVal) == true)
{
values[index] = headerVal ?? DBNull.Value;
}
// :#redbError always has a value: NULL when nothing failed
else if (isRedbError)
{
values[index] = DBNull.Value;
}
// As in Apache Camel: a placeholder with no value is an error, not a silent NULL
else
{
throw new InvalidOperationException(SqlParameterBinder.MissingValueMessage(name, plan.SourceSql,
$"no param.{name} option, no '{name}' column in the polled row and no '{name}' header"));
}
}
AddPlanParameters(cmd, plan, values);
}
///
/// Writes the command text in the provider's placeholder style and adds one parameter per slot of the plan, each value
/// normalised as the producer normalises its own ( ).
///
private static void AddPlanParameters(DbCommand cmd, SqlParameterPlan plan, object?[] values)
{
cmd.CommandText = plan.Sql;
for (var slot = 0; slot < plan.Slots.Count; slot++)
SqlParameterBinder.Add(cmd, plan.ParameterName(slot), values[plan.Slots[slot]]);
}
private string ResolveQuery(IExchange? exchange)
{
// First try URI path (the SQL after "sql:" scheme)
var rawSql = _endpoint.QueryOrProcedure;
// If DynamicValue Query is set in options, use that instead
if (_options.Query is { } dv)
{
// A poll has no exchange: an expression cannot be resolved, and falling back to the path would hide it.
if (exchange == null && dv.IsDynamic)
{
throw new InvalidOperationException(
"The query option is a ${...} expression, and a poll has no exchange to resolve it against. Give the poll " +
"query as the URI path, a constant query option or a ref:name.");
}
var resolved = exchange != null ? dv.Resolve(exchange) : dv.Resolve(new Exchange());
if (resolved != null)
rawSql = resolved;
}
return ResolveNamedQuery(rawSql);
}
private string ResolveNamedQuery(string sql)
{
if (!sql.StartsWith(SqlNamedQueryRegistry.RefPrefix, StringComparison.OrdinalIgnoreCase))
return sql;
var registry = GetNamedQueryRegistry();
if (registry != null)
return registry.ResolveRef(sql);
throw new InvalidOperationException(
$"Named query reference '{sql}' cannot be resolved — no ISqlNamedQueryRegistry is registered.");
}
private ISqlNamedQueryRegistry? GetNamedQueryRegistry()
{
return _endpoint.SqlComponent.Context?.GetService();
}
private ISqlConnectionFactory ResolveConnectionFactory() => _endpoint.ResolveConnectionFactory();
}
Path: redb-route/redb.Route.Sql/SqlEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlEndpointOptions.cs
----
using redb.Route.Sql.Connection;
using System.Data;
using redb.Route.Core;
namespace redb.Route.Sql;
///
/// Options for the SQL endpoint. Inherits for automatic
/// URI parameter binding via .
///
/// This is the single source of truth — both Fluent API ( )
/// and URI strings converge here through BindFromUri() .
///
///
[LenientProperties]
public sealed class SqlEndpointOptions : EndpointOptions
{
// ── Mode ──────────────────────────────────────────────────────────
/// Operating mode: Poll (consumer), Execute (producer), Procedure (producer).
public SqlMode Mode { get; set; } = SqlMode.Execute;
// ── Connection ────────────────────────────────────────────────────
///
/// Named DataSource from the registry (configured via AddDataSource ). redb or redb:<name> : the
/// connection of a redb service, lent to the step (registered by redb.Route.Core).
///
[RegistryReference(typeof(ISqlConnectionFactory))]
public string? DataSource { get; set; }
/// Direct connection string (used if is not set).
[Sensitive]
public string? ConnectionString { get; set; }
/// ADO.NET provider name (e.g. "Microsoft.Data.SqlClient", "Npgsql").
public string? Provider { get; set; }
/// Command execution timeout in seconds. Default: 30.
public int CommandTimeout { get; set; } = 30;
/// Whether to wrap execution in a .
public bool Transacted { get; set; }
/// Transaction isolation level. Null = provider default.
public IsolationLevel? IsolationLevel { get; set; }
///
/// Runs the statement on the data source's read replica ( ),
/// in , and . False, the default: the
/// primary database, whatever the statement. Only the endpoint's author knows that a statement does not write — a SELECT
/// can call a function that writes, advance a sequence or take a lock — so nothing is guessed from the SQL text. A replica
/// may lag behind the primary.
///
/// Refused with above zero, and for a poll with , ,
/// or : rows read on a lagging replica and marked on the primary would
/// be delivered again.
///
///
public bool ReadOnly { get; set; }
///
/// How the :#name placeholders of a statement are written for the provider:
/// (@name , the default), (:name , Oracle) or
/// (? , ODBC). Applies to every statement the endpoint sends — the query,
/// a batch, / / , a function call with
/// ; a stored procedure called by name has no text to rewrite.
///
public SqlPlaceholderStyle PlaceholderStyle { get; set; } = SqlPlaceholderStyle.At;
///
/// Inside '…' and "…" of a statement a backslash escapes the next character, as MySQL and MariaDB read them
/// unless the server's sql_mode has NO_BACKSLASH_ESCAPES . False, the default: standard SQL, where a backslash
/// is an ordinary character and 'C:\' is a complete literal. Nothing is guessed from the provider — the same text
/// means different things on different databases, and on MySQL it depends on the server's mode. Without it, a
/// :#name after \' is not found; doubling the quote ('' ) works everywhere. Applies to every statement
/// applies to.
///
public bool BackslashEscapes { get; set; }
// ── Query ─────────────────────────────────────────────────────────
///
/// SQL query or ref:name reference to a named query.
/// Supports ${...} expressions via .
///
public DynamicValue? Query { get; set; }
///
/// How the result set is mapped to the Exchange body. The default, , is decided by what the
/// statement returns when it runs — as Apache Camel's execute() asks the driver, never by the text: a result set
/// is delivered as , a statement without one sets the rows affected
/// ( ). In a batch Auto collects no rows.
///
public SqlOutputType OutputType { get; set; } = SqlOutputType.Auto;
/// POCO type name for . Null = Dictionary mapping.
public string? OutputClass { get; set; }
/// If set, result goes to this header instead of the Exchange body.
public string? OutputHeader { get; set; }
/// Dry-run mode: logs the query without executing it.
public bool Noop { get; set; }
// ── Polling (Mode = Poll) ─────────────────────────────────────────
/// Delay between polls in milliseconds. Default: 500.
public int Delay { get; set; } = 500;
/// Initial delay before the first poll in milliseconds. Default: 1000.
public int InitialDelay { get; set; } = 1000;
/// Fixed-rate polling (delay is measured from start of poll, not end).
public bool FixedRate { get; set; }
/// Maximum number of poll cycles. 0 = unlimited.
public long RepeatCount { get; set; }
/// Maximum rows to process per poll. -1 = unlimited.
public int MaxMessagesPerPoll { get; set; } = -1;
/// Create an Exchange even when the result set is empty.
public bool RouteEmptyResultSet { get; set; }
/// Send an empty message when there is nothing to poll (idle notification).
public bool SendEmptyMessageWhenIdle { get; set; }
/// SQL to execute after each row is successfully processed.
public string? OnSuccess { get; set; }
/// SQL to execute when processing a row fails.
public string? OnFailure { get; set; }
///
/// With : keep the mark of a failed row. By default (false) a failure
/// rolls the poll's transaction back with its onFailure and ends the cycle, so the row is read again on the next
/// poll, as in Apache Camel. With true, one exchange per row: each row runs under a savepoint, a failed row is rolled back
/// to it, gets onFailure in the poll's transaction and the cycle goes on with the next row; one exchange for the
/// poll (pollDelivery=List , Scalar , SelectOne ): the transaction rolls back, then onFailure runs in a
/// short transaction of its own. Either way a row that fails every time is marked once instead of holding up the rows
/// behind it.
///
public bool OnFailureAfterRollback { get; set; }
/// SQL to execute after the entire batch is processed.
public string? OnBatchComplete { get; set; }
///
/// How polled rows reach the route. (the default): an exchange per row.
/// (Apache Camel useIterator=false ): one exchange whose body is the list of rows —
/// or, with , the open stream the route reads — with /
/// and run once, after the reader is closed; their values come from
/// headers and param.* .
///
public SqlPollDelivery PollDelivery { get; set; } = SqlPollDelivery.PerRow;
// ── Batch ─────────────────────────────────────────────────────────
///
/// Batch mode for the producer. A value above zero makes a list body a batch: the statement runs once per item and all
/// items share one transaction (the route's, when the route is transacted). Zero, the default, runs the statement once
/// with the body as it is. An empty list writes nothing.
///
/// The value is the number of statements sent in one round trip where the connection can create a
/// and the batch breaks on the first error; it never splits the transaction.
///
///
public int BatchSize { get; set; }
///
/// What a failing batch item does.
///
/// true (the default, as in Apache Camel): the batch stops, the whole transaction rolls back and the provider's own
/// exception is thrown, with the item's index in under .
///
///
/// false : every item runs under a savepoint; a failed item is undone and reported in
/// , and the other items commit. This needs a local transaction with savepoints, so it
/// is refused before anything is written inside a transacted route or on a provider without savepoints; and when the
/// server has ended the transaction (an error that aborts it), the batch still stops with that item's error.
///
///
public bool BreakBatchOnError { get; set; } = true;
// ── Explicit Parameters ─────────────────────────────────────────
private IReadOnlyDictionary? _explicitParameters;
///
/// Explicit parameter bindings from .Param() calls.
/// Extracted from URI parameters with param. prefix.
/// Values may contain ${...} expressions resolved at runtime.
///
internal IReadOnlyDictionary ExplicitParameters =>
_explicitParameters ??= ParseExplicitParameters();
private IReadOnlyDictionary ParseExplicitParameters()
{
var dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (key, value) in UnmappedParameters)
{
if (key.StartsWith("param.", StringComparison.OrdinalIgnoreCase))
dict[key["param.".Length..]] = value;
}
return dict;
}
// ── Procedure ─────────────────────────────────────────────────────
/// Stored procedure or function name (for ).
public string? ProcedureName { get; set; }
/// Call as a function (SELECT function_name(...) ) instead of EXEC/CALL .
public bool AsFunction { get; set; }
///
/// Serialized procedure parameter definitions.
/// Format: IN:name:DbType,OUT:name:DbType,INOUT:name:DbType .
///
public string? ProcedureParams { get; set; }
// ── Validation ────────────────────────────────────────────────────
///
public override void Validate()
{
if (DataSource is null && ConnectionString is null)
throw new ArgumentException("Either DataSource or ConnectionString is required.");
if (Mode == SqlMode.Procedure && string.IsNullOrEmpty(ProcedureName))
throw new ArgumentException("ProcedureName is required for Procedure mode.");
if (AsFunction && ProcedureParams is { } definitions && definitions.Split(',').Any(definition =>
definition.TrimStart().StartsWith("OUT:", StringComparison.OrdinalIgnoreCase) ||
definition.TrimStart().StartsWith("INOUT:", StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(
"asFunction=true runs SELECT name(...) and takes its result as the scalar: an OUT or INOUT parameter has no place " +
"in that statement, and under a positional placeholder style it would shift the other parameters. Declare the " +
"parameters IN, or call the procedure with asFunction=false.");
if (Mode == SqlMode.Poll && PollDelivery == SqlPollDelivery.List && OutputType is SqlOutputType.Scalar or SqlOutputType.SelectOne)
throw new ArgumentException(
$"pollDelivery=List delivers the polled rows as one list, and outputType={OutputType} reads a single value. " +
"Use outputType=SelectList or StreamList with pollDelivery=List, or pollDelivery=PerRow.");
if (OnFailureAfterRollback && !Transacted)
throw new ArgumentException(
"onFailureAfterRollback=true changes what a failure does to the poll's transaction, so it needs transacted=true. " +
"Without it every onSuccess and onFailure already commits on its own.");
if (OnFailureAfterRollback && OutputType == SqlOutputType.StreamList)
throw new ArgumentException(
"onFailureAfterRollback=true marks a failed row while the poll goes on, and outputType=StreamList keeps the reader " +
"open on the poll's connection, where PostgreSQL and SQL Server take no other command. Use outputType=SelectList.");
if (CommandTimeout < 0)
throw new ArgumentException("CommandTimeout must be non-negative.");
if (Delay < 0)
throw new ArgumentException("Delay must be non-negative.");
if (BatchSize < 0)
throw new ArgumentException("BatchSize must be non-negative.");
if (ReadOnly && BatchSize > 0)
throw new ArgumentException(
"readOnly=true sends the statement to the read replica, and batchSize makes it a batch that writes. " +
"Remove readOnly or batchSize.");
if (ReadOnly && Mode == SqlMode.Poll && (Transacted || !string.IsNullOrEmpty(OnSuccess) ||
!string.IsNullOrEmpty(OnFailure) || !string.IsNullOrEmpty(OnBatchComplete)))
throw new ArgumentException(
"readOnly=true polls the read replica, where onSuccess / onFailure / onBatchComplete and transacted=true cannot " +
"mark or lock the rows; rows read on a lagging replica and marked on the primary would be delivered again. " +
"Poll the primary database (no readOnly) when the poll marks its rows.");
}
}
Path: redb-route/redb.Route.Sql/SqlEnums.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlEnums.cs
----
namespace redb.Route.Sql;
///
/// Operating mode for the SQL endpoint.
/// Determines whether the endpoint acts as a polling consumer or a producer.
///
public enum SqlMode
{
/// Polling consumer: periodically executes SELECT and emits an Exchange per row.
Poll,
/// Producer: executes INSERT/UPDATE/DELETE/SELECT statements.
Execute,
/// Producer: calls a stored procedure or function with IN/OUT/INOUT parameters.
Procedure
}
///
/// Determines how SQL query results are mapped to the Exchange body.
///
public enum SqlOutputType
{
///
/// Auto-detect based on the SQL statement: SELECT/WITH → ,
/// INSERT/UPDATE/DELETE/MERGE → .
///
Auto,
/// All rows → List<Dictionary<string, object>> .
SelectList,
/// First row only → Dictionary<string, object> (or mapped POCO).
SelectOne,
/// Streaming: IAsyncEnumerable<Dictionary<string, object>> .
StreamList,
/// First column of first row (scalar value).
Scalar,
/// No result body. Affected rows count goes to header redbSql.updateCount .
None
}
///
/// How a poll consumer hands the polled rows to the route.
///
public enum SqlPollDelivery
{
/// An exchange per row; onSuccess / onFailure run for each row.
PerRow,
///
/// One exchange with every polled row (Apache Camel useIterator=false ): a list, or with
/// the open stream; onSuccess / onFailure run once for it.
///
List
}
///
/// Direction of a stored procedure parameter.
///
public enum SqlParamDirection
{
/// Input-only parameter.
In,
/// Output-only parameter (value set by the procedure).
Out,
/// Bi-directional parameter (input and output).
InOut
}
///
/// How a :#name placeholder is written in the statement the connector sends to the provider.
///
public enum SqlPlaceholderStyle
{
/// @name , one parameter per name: Npgsql, SqlClient, Microsoft.Data.Sqlite, MySqlConnector, Firebird.
At,
/// :name , one parameter per occurrence, so binding by name and by position both work: Oracle (ODP.NET).
Colon,
/// ? , one parameter per occurrence, in order: ODBC and OleDb providers.
Question
}
Path: redb-route/redb.Route.Sql/SqlExchangeHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlExchangeHeaders.cs
----
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Sql;
/// Headers every SQL producer path writes after it ran a statement.
internal static class SqlExchangeHeaders
{
///
/// The header outputHeader names on this exchange: the option as written, or — when it is a ${...}
/// expression — its value on the exchange.
///
/// The expression yields no name.
internal static string ResolveOutputHeader(string outputHeader, IExchange exchange)
{
if (!outputHeader.Contains("${", StringComparison.Ordinal))
return outputHeader;
var name = ExpressionResolver.ResolveTypedOrTemplate(outputHeader, exchange)?.ToString();
if (string.IsNullOrEmpty(name))
throw new InvalidOperationException($"outputHeader '{outputHeader}' yields no header name on this exchange.");
return name;
}
///
/// Writes query text, execution time, data source and output type — the type the statement resolved to when
/// is given (Auto becomes what the driver returned), the option otherwise.
///
internal static void SetCommon(
IExchange exchange, SqlEndpointOptions options, string sql, long executionMs, SqlOutputType? resolvedOutputType = null)
{
exchange.In.Headers[SqlHeaders.Query] = sql;
exchange.In.Headers[SqlHeaders.ExecutionTime] = executionMs;
if (options.DataSource != null)
exchange.In.Headers[SqlHeaders.DataSource] = options.DataSource;
exchange.In.Headers[SqlHeaders.OutputType] = (resolvedOutputType ?? options.OutputType).ToString();
}
}
Path: redb-route/redb.Route.Sql/SqlHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlHeaders.cs
----
namespace redb.Route.Sql;
///
/// Constants for exchange headers set by the SQL component.
/// All prefixed with "redbSql." to avoid collisions with other connectors.
///
public static class SqlHeaders
{
/// Common prefix for all SQL component headers.
public const string Prefix = "redbSql.";
// ── Query metadata ────────────────────────────────────────────────
/// The SQL statement that was executed.
public const string Query = "redbSql.query";
/// Number of rows affected by INSERT/UPDATE/DELETE.
public const string UpdateCount = "redbSql.updateCount";
/// Number of rows returned by SELECT.
public const string RowCount = "redbSql.rowCount";
/// Name of the DataSource used for the query.
public const string DataSource = "redbSql.dataSource";
/// Output type used for result mapping.
public const string OutputType = "redbSql.outputType";
// ── INSERT keys ───────────────────────────────────────────────────
///
/// Rows the statements of a batch returned (INSERT … RETURNING , OUTPUT inserted.* ), in item order, when
/// outputType reads rows: a List<Dictionary<string, object?>> , or List<T> with
/// outputClass (Apache Camel CamelSqlGeneratedKeyRows ). The body is left alone.
///
public const string GeneratedKeys = "redbSql.generatedKeys";
/// Number of rows in (Apache Camel CamelSqlGeneratedKeysRowCount ).
public const string GeneratedKeysRowCount = "redbSql.generatedKeysRowCount";
// ── Error ─────────────────────────────────────────────────────────
/// Error message when the query failed (if not thrown).
public const string Error = "redbSql.error";
// ── Transaction ───────────────────────────────────────────────────
/// Transaction identifier when transacted=true .
public const string TransactionId = "redbSql.transactionId";
// ── Stored procedure ──────────────────────────────────────────────
/// Name of the stored procedure that was called.
public const string StoredProcedure = "redbSql.storedProcedure";
// ── Performance ───────────────────────────────────────────────────
/// Query execution time in milliseconds.
public const string ExecutionTime = "redbSql.executionTime";
// ── Batch ─────────────────────────────────────────────────────────
///
/// Batch strategy that ran: None (empty batch source, nothing executed), DbBatch (break on the first error,
/// chunks of batchSize statements per round trip), Commands (break on the first error, the connection has no
/// DbBatch ) or Savepoints (continue past errors). The driver's capability decides, not an option.
///
public const string BatchStrategy = "redbSql.batchStrategy";
/// Round trips of a DbBatch batch ( DbBatch ); absent for other strategies.
public const string BatchChunkCount = "redbSql.batchChunkCount";
/// Batch items written successfully; in batch mode carries the same value.
public const string BatchItemCount = "redbSql.batchItemCount";
///
/// Zero-based index of the item that ended a batch. The thrown provider exception carries the same value in its
/// under this key.
///
public const string BatchFailedIndex = "redbSql.batchFailedIndex";
///
/// Items that failed and were undone to their savepoint in a batch that continues past errors
/// (breakBatchOnError=false ): an IReadOnlyList<SqlBatchItemError> .
///
public const string BatchErrors = "redbSql.batchErrors";
}
Path: redb-route/redb.Route.Sql/SqlNamedQueryRegistry.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlNamedQueryRegistry.cs
----
using System.Collections.Concurrent;
namespace redb.Route.Sql;
///
/// Registry for named SQL queries. Queries are registered at startup and referenced
/// by name using the ref:name syntax in SQL properties.
/// Thread-safe via .
///
public interface ISqlNamedQueryRegistry
{
/// Registers a named query.
/// Query name (case-insensitive).
/// SQL text.
void Register(string name, string sql);
/// Resolves a named query. Throws if not found.
/// Query name.
/// SQL text.
string Resolve(string name);
/// Attempts to resolve a named query.
/// Query name.
/// SQL text if found.
/// True if the query was found.
bool TryResolve(string name, out string? sql);
/// Returns all registered queries.
IReadOnlyDictionary GetAll();
///
/// Resolves a SQL string that may contain a ref:name reference.
/// If the string starts with "ref:", resolves to the registered query.
/// Otherwise, returns the original string unchanged.
///
/// SQL or ref:name reference.
/// Resolved SQL text.
string ResolveRef(string sql);
}
///
/// Default named query registry. Thread-safe, case-insensitive name matching.
///
public sealed class SqlNamedQueryRegistry : ISqlNamedQueryRegistry
{
/// Prefix for named query references in SQL properties.
public const string RefPrefix = "ref:";
private readonly ConcurrentDictionary _queries = new(StringComparer.OrdinalIgnoreCase);
///
public void Register(string name, string sql)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
ArgumentException.ThrowIfNullOrWhiteSpace(sql);
if (!_queries.TryAdd(name, sql))
throw new ArgumentException($"Named query '{name}' is already registered.");
}
///
public string Resolve(string name)
{
if (_queries.TryGetValue(name, out var sql))
return sql;
throw new KeyNotFoundException(
$"Named query '{name}' is not registered. " +
"Register it via AddNamedQuery() in AddRedbRouteSql() configuration.");
}
///
public bool TryResolve(string name, out string? sql) =>
_queries.TryGetValue(name, out sql);
///
public IReadOnlyDictionary GetAll() =>
_queries.ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);
///
/// Resolves a SQL string that may contain a ref:name reference.
/// If the string starts with "ref:", resolves to the registered query.
/// Otherwise, returns the original string unchanged.
///
/// SQL or ref:name reference.
/// Resolved SQL text.
public string ResolveRef(string sql)
{
if (sql.StartsWith(RefPrefix, StringComparison.OrdinalIgnoreCase))
return Resolve(sql[RefPrefix.Length..]);
return sql;
}
}
Path: redb-route/redb.Route.Sql/SqlParameterBinder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlParameterBinder.cs
----
using System.Data.Common;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using redb.Route.Abstractions;
using redb.Route.Expressions;
using redb.Route.Sql.Batch;
namespace redb.Route.Sql;
///
/// Binds the @name placeholders of a statement to values taken from an exchange. One implementation serves the
/// single-statement producer, batch items, the poll consumer and the procedure producer, so the value sources and their
/// normalisation cannot drift apart between them.
///
internal static class SqlParameterBinder
{
private static readonly JsonSerializerOptions RawJson = new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
///
/// Rewrites the command text into the provider's and adds its parameters — one per distinct
/// :#name , or one per occurrence for a positional style. Sources, first match wins: explicit param.name
/// (constant or ${...} expression), exchange header, key of a map body (a dictionary or a JSON object — as in Apache
/// Camel, a POCO, XML or text body is not read by name). A placeholder found in none of them is an error, as in Camel; a
/// source that is present with a null value binds NULL.
///
/// A placeholder has no value in any source, or its form is not supported.
internal static void Bind(
DbCommand command, IExchange exchange, IReadOnlyDictionary explicitParameters, SqlPlaceholderStyle style,
bool backslashEscapes)
{
var plan = SqlParameterPlan.Create(command.CommandText, explicitParameters, style, backslashEscapes);
var values = new object?[plan.Names.Count];
for (var index = 0; index < plan.Names.Count; index++)
{
var name = plan.Names[index];
if (plan.TryGetExplicit(name, out var explicitParameter))
{
values[index] = explicitParameter.Resolve(exchange);
}
else if (!TryGetExchangeValue(exchange, name, out values[index]))
{
throw new InvalidOperationException(MissingValueMessage(name, plan.SourceSql,
$"no param.{name} option, no '{name}' header and no '{name}' key in the message body"));
}
}
command.CommandText = plan.Sql;
for (var slot = 0; slot < plan.Slots.Count; slot++)
Add(command, plan.ParameterName(slot), values[plan.Slots[slot]]);
}
/// Adds the parameter with normalised for the provider.
internal static void Add(DbCommand command, string name, object? value)
{
var parameter = command.CreateParameter();
parameter.ParameterName = name;
parameter.Value = NormalizeForDb(value);
command.Parameters.Add(parameter);
}
/// The message for a placeholder that has no value: where it was looked for, and the statement.
internal static string MissingValueMessage(string name, string sql, string lookedAt) =>
$"SQL parameter ':#{name}' has no value: {lookedAt}. Set param.{name}=... or supply the value; a value that is present " +
$"but null binds NULL. Query: {sql}";
///
/// Normalises C# values for ADO.NET parameter binding:
///
/// null → .
/// - Empty string (
"" ) → . A null upstream value
/// (e.g. an OAuth client_id absent from a logout request) is sometimes
/// serialised through string-typed plumbing (header, query-string, JSON DTO) as
/// ; if we bind that literally, audit columns receive
/// "" instead of NULL and downstream WHERE ... IS NULL
/// predicates miss the rows. Treating empty string as NULL at the parameter layer
/// keeps schema invariants honest (NULL = "not specified") without forcing every
/// caller to convert.
/// - JSON values (
, — what unmarshalling JSON to object
/// produces), which providers cannot bind: a string, number (long , else decimal , else double ) or
/// boolean becomes that CLR value, JSON null becomes , an object or array becomes its JSON text.
/// - Everything else passes through unchanged.
///
///
internal static object NormalizeForDb(object? value) => value switch
{
null => DBNull.Value,
string { Length: 0 } => DBNull.Value,
JsonElement element => FromJson(element),
JsonValue node when node.TryGetValue(out var element) => FromJson(element),
JsonValue node => NormalizeForDb(node.GetValue()),
JsonNode node => node.ToJsonString(RawJson),
_ => value
};
/// Resolves an explicit parameter value: ${...} is evaluated against the exchange; empty means NULL.
internal static object ResolveParamValue(string value, IExchange? exchange)
{
if (value.Contains("${") && exchange != null)
{
return ExpressionResolver.ResolveTypedOrTemplate(value, exchange) ?? DBNull.Value;
}
return string.IsNullOrEmpty(value) ? DBNull.Value : (object)value;
}
private static bool TryGetExchangeValue(IExchange exchange, string name, out object? value)
{
if (exchange.In.Headers.TryGetValue(name, out value))
return true;
return BatchItemAccessor.FindByKey(exchange.In.Body, name, out value) == ItemLookup.Found;
}
private static object FromJson(JsonElement element)
{
switch (element.ValueKind)
{
case JsonValueKind.String:
return NormalizeForDb(element.GetString());
case JsonValueKind.Number:
if (element.TryGetInt64(out var integer))
return integer;
if (element.TryGetDecimal(out var number))
return number;
if (element.TryGetDouble(out var real))
return real;
return element.GetRawText();
case JsonValueKind.True:
return true;
case JsonValueKind.False:
return false;
case JsonValueKind.Null:
case JsonValueKind.Undefined:
return DBNull.Value;
default:
return element.GetRawText();
}
}
}
Path: redb-route/redb.Route.Sql/SqlParameterParser.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlParameterParser.cs
----
using System.Text;
namespace redb.Route.Sql;
/// A :#name placeholder found in a statement: its name and where it stands in the text.
/// The name, without :# .
/// Index of the placeholder's : in the statement.
/// Length of the placeholder text, :# included.
internal readonly record struct SqlPlaceholder(string Name, int Offset, int Length);
///
/// Finds the :#name placeholders of a statement — the way Apache Camel writes named parameters — and rewrites them for
/// the provider. The statement is scanned, not matched: text inside single-quoted literals ('' escapes), double-quoted
/// and back-quoted identifiers, -- and /* */ comments and PostgreSQL dollar quotes ($$ … $$ ,
/// $tag$ … $tag$ ) is not searched. @ is never a placeholder: it belongs to the database — T-SQL variables and
/// EXEC argument names, MySQL user variables, @@IDENTITY . A backslash is an ordinary character unless the caller
/// asks for backslash escapes (MySQL, MariaDB): then it escapes the next character inside '…' and "…" .
///
internal static class SqlParameterParser
{
/// The placeholders of , in order, repeats included.
/// The statement.
///
/// A backslash inside '…' and "…" escapes the next character, as MySQL and MariaDB read them by default.
///
///
/// :# is not followed by a name, or starts an Apache Camel :#in:name list; neither is supported.
///
public static IReadOnlyList FindPlaceholders(string? sql, bool backslashEscapes = false)
{
if (string.IsNullOrEmpty(sql))
return [];
List? found = null;
var i = 0;
while (i < sql.Length)
{
var c = sql[i];
if (c is '\'' or '"' or '`')
{
i = SkipQuoted(sql, i, c, backslashEscapes && c != '`');
}
else if (c == '-' && At(sql, i + 1) == '-')
{
i = SkipLineComment(sql, i);
}
else if (c == '/' && At(sql, i + 1) == '*')
{
i = SkipBlockComment(sql, i);
}
else if (c == '$' && TryReadDollarTag(sql, i, out var tag))
{
i = SkipDollarQuoted(sql, i, tag);
}
else if (c == ':' && At(sql, i + 1) == '#')
{
var placeholder = ReadPlaceholder(sql, i);
(found ??= []).Add(placeholder);
i += placeholder.Length;
}
else
{
i++;
}
}
return found is null ? [] : found;
}
/// Distinct placeholder names of , without :# , in the order they first appear; case is ignored.
public static IReadOnlyList ExtractParameterNames(string? sql)
{
var names = new List();
var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var placeholder in FindPlaceholders(sql))
{
if (seen.Add(placeholder.Name))
names.Add(placeholder.Name);
}
return names;
}
///
/// The statement as the provider takes it: every placeholder written in — @name ,
/// :name or ? — and everything else, literals and comments included, unchanged.
///
public static string Rewrite(string sql, IReadOnlyList placeholders, SqlPlaceholderStyle style)
{
if (placeholders.Count == 0)
return sql;
var text = new StringBuilder(sql.Length);
var last = 0;
foreach (var placeholder in placeholders)
{
text.Append(sql, last, placeholder.Offset - last);
text.Append(style switch
{
SqlPlaceholderStyle.Colon => ":" + placeholder.Name,
SqlPlaceholderStyle.Question => "?",
_ => "@" + placeholder.Name,
});
last = placeholder.Offset + placeholder.Length;
}
text.Append(sql, last, sql.Length - last);
return text.ToString();
}
private static char At(string sql, int index) => index < sql.Length ? sql[index] : '\0';
private static bool IsNameStart(char c) => c is >= 'A' and <= 'Z' or >= 'a' and <= 'z' or '_';
private static bool IsNamePart(char c) => char.IsLetterOrDigit(c) || c == '_';
private static SqlPlaceholder ReadPlaceholder(string sql, int start)
{
var nameStart = start + 2;
if (!IsNameStart(At(sql, nameStart)))
{
throw new InvalidOperationException(
$"SQL placeholder ':#' at position {start} is not followed by a name: write :#name. Apache Camel's inline " +
$"expressions (:#${{...}}) are not supported; use param.name=${{...}}. Query: {sql}");
}
var end = nameStart + 1;
while (end < sql.Length && IsNamePart(sql[end]))
end++;
var name = sql[nameStart..end];
if (name.Equals("in", StringComparison.OrdinalIgnoreCase) && At(sql, end) == ':' && At(sql, end + 1) != ':')
{
throw new InvalidOperationException(
$"SQL placeholder ':#in:' at position {start} is an Apache Camel IN list, which is not supported; bind each value " +
$"as its own :#name. Query: {sql}");
}
return new SqlPlaceholder(name, start, end - start);
}
///
/// Index after the quoted run that starts at ; a doubled quote stays inside, and with
/// so does the character after a backslash. Unterminated: the end.
///
private static int SkipQuoted(string sql, int start, char quote, bool backslashEscapes)
{
var i = start + 1;
while (i < sql.Length)
{
if (backslashEscapes && sql[i] == '\\')
{
i += 2;
continue;
}
if (sql[i] == quote)
{
if (At(sql, i + 1) != quote)
return i + 1;
i += 2;
continue;
}
i++;
}
return sql.Length;
}
private static int SkipLineComment(string sql, int start)
{
var end = sql.IndexOf('\n', start + 2);
return end < 0 ? sql.Length : end + 1;
}
private static int SkipBlockComment(string sql, int start)
{
var end = sql.IndexOf("*/", start + 2, StringComparison.Ordinal);
return end < 0 ? sql.Length : end + 2;
}
///
/// A PostgreSQL dollar-quote opener at : $$ or $tag$ , not preceded by a name
/// character — so neither the positional parameter $1 nor a$b .
///
private static bool TryReadDollarTag(string sql, int start, out string tag)
{
tag = "";
if (start > 0 && IsNamePart(sql[start - 1]))
return false;
var i = start + 1;
if (At(sql, i) == '$')
{
tag = "$$";
return true;
}
if (!IsNameStart(At(sql, i)))
return false;
while (i < sql.Length && IsNamePart(sql[i]))
i++;
if (At(sql, i) != '$')
return false;
tag = sql[start..(i + 1)];
return true;
}
private static int SkipDollarQuoted(string sql, int start, string tag)
{
var end = sql.IndexOf(tag, start + tag.Length, StringComparison.Ordinal);
return end < 0 ? sql.Length : end + tag.Length;
}
}
Path: redb-route/redb.Route.Sql/SqlParameterPlan.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlParameterPlan.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Sql;
///
/// The parameters of one statement, worked out once: its distinct :#name placeholders, the explicit param.name
/// value each uses, the text in the provider's placeholder style and the parameters that text takes. A batch builds the plan
/// once and binds every item with it.
///
internal sealed class SqlParameterPlan
{
private readonly Dictionary _explicit;
private SqlParameterPlan(
string sourceSql, string sql, IReadOnlyList names, IReadOnlyList slots,
Dictionary explicitParameters)
{
SourceSql = sourceSql;
Sql = sql;
Names = names;
Slots = slots;
_explicit = explicitParameters;
HasExpressions = explicitParameters.Values.Any(p => p.IsExpression);
}
/// The statement as written, with :#name placeholders.
internal string SourceSql { get; }
/// The statement sent to the provider: placeholders in its style, everything else as written.
internal string Sql { get; }
/// Distinct placeholder names, without :# , in the order they first appear.
internal IReadOnlyList Names { get; }
///
/// The parameters of , in order: parameter i carries the value of Names[Slots[i]] . One per
/// name for ; one per occurrence for the positional styles.
///
internal IReadOnlyList Slots { get; }
/// At least one explicit value is a ${...} expression, so binding needs an exchange to evaluate it in.
internal bool HasExpressions { get; }
///
/// Parses (with , as MySQL reads its literals), picks the explicit
/// values its placeholders use and writes it in .
///
/// A :# placeholder form that is not supported.
internal static SqlParameterPlan Create(
string sql, IReadOnlyDictionary explicitParameters, SqlPlaceholderStyle style = SqlPlaceholderStyle.At,
bool backslashEscapes = false)
{
var placeholders = SqlParameterParser.FindPlaceholders(sql, backslashEscapes);
var names = new List();
var indexByName = new Dictionary(StringComparer.OrdinalIgnoreCase);
var occurrences = new List(placeholders.Count);
// Names are compared ignoring case, and the text sent to the provider spells every occurrence the way the name was
// first written: a provider that binds names case-sensitively (SQLite) must see one name for the one parameter.
var canonical = new SqlPlaceholder[placeholders.Count];
for (var i = 0; i < placeholders.Count; i++)
{
var placeholder = placeholders[i];
if (!indexByName.TryGetValue(placeholder.Name, out var index))
{
index = names.Count;
indexByName[placeholder.Name] = index;
names.Add(placeholder.Name);
}
occurrences.Add(index);
canonical[i] = placeholder with { Name = names[index] };
}
var used = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var name in names)
{
if (explicitParameters.TryGetValue(name, out var value))
used[name] = new ExplicitSqlParameter(value);
}
IReadOnlyList slots = style == SqlPlaceholderStyle.At ? Enumerable.Range(0, names.Count).ToArray() : occurrences;
return new SqlParameterPlan(sql, SqlParameterParser.Rewrite(sql, canonical, style), names, slots, used);
}
/// The name of the parameter at of .
internal string ParameterName(int slot) => Names[Slots[slot]];
/// The explicit param.name value for , if one is configured.
internal bool TryGetExplicit(string name, out ExplicitSqlParameter parameter) => _explicit.TryGetValue(name, out parameter);
}
/// An explicit param.name value: a constant, or a ${...} expression evaluated per exchange.
internal readonly struct ExplicitSqlParameter(string value)
{
/// The configured text.
internal string Value { get; } = value;
/// The value contains a ${...} expression.
internal bool IsExpression { get; } = value.Contains("${", StringComparison.Ordinal);
///
/// The value to bind; an expression is evaluated against . An explicit parameter always has a
/// value: an expression that yields null, or an empty constant, binds NULL.
///
internal object Resolve(IExchange? exchange) => SqlParameterBinder.ResolveParamValue(Value, exchange);
}
Path: redb-route/redb.Route.Sql/SqlProcedureProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlProcedureProducer.cs
----
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Transactions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Expressions;
using redb.Route.Sql.Connection;
using redb.Route.Telemetry;
namespace redb.Route.Sql;
///
/// Producer for SQL Procedure mode. Calls stored procedures or functions
/// with IN/OUT/INOUT parameters. OUT parameters are written to Exchange headers.
///
///
/// Transaction behavior: always wraps execution in a local .
/// If an ambient exists (e.g. from
/// BeginTransaction() DSL), the local transaction is skipped and the connection
/// auto-enlists in the ambient .
///
internal sealed class SqlProcedureProducer : IProducer
{
private readonly SqlEndpoint _endpoint;
private readonly SqlEndpointOptions _options;
private ILogger? _logger;
internal SqlProcedureProducer(SqlEndpoint endpoint, SqlEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
_logger = (endpoint.Component as ComponentBase)?.Logger;
}
///
public Task Start(CancellationToken ct = default)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("SQL procedure producer started");
return Task.CompletedTask;
}
///
public Task Stop(CancellationToken ct = default)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("SQL procedure producer stopped");
return Task.CompletedTask;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
"sql.procedure", ActivityKind.Client,
"db.system", _endpoint.Component.Scheme,
_endpoint.Uri.NormalizedKey,
destination: _options.ProcedureName);
if (_options.Noop)
{
exchange.In.Headers[SqlHeaders.StoredProcedure] = _options.ProcedureName;
return;
}
var factory = ResolveConnectionFactory();
var sw = Stopwatch.StartNew();
// A lent connection (dataSource=redb) is the lender's: no transaction of this step's own, commands bound to the lender's.
await using var lease = await SqlConnections.OpenAsync(factory, exchange, _options.ReadOnly, ct).ConfigureAwait(false);
var connection = lease.Connection;
var hasAmbientTx = Transaction.Current != null;
DbTransaction? tx = null;
if (!hasAmbientTx && !lease.IsBorrowed)
{
tx = _options.IsolationLevel.HasValue
? await connection.BeginTransactionAsync(_options.IsolationLevel.Value, ct).ConfigureAwait(false)
: await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
}
try
{
await using var cmd = lease.CreateCommand();
cmd.CommandTimeout = _options.CommandTimeout;
if (tx != null) cmd.Transaction = tx;
var procedureName = _options.ProcedureName!;
if (_options.AsFunction)
{
// Call as function: SELECT function_name(params)
cmd.CommandType = CommandType.Text;
cmd.CommandText = BuildFunctionCall(procedureName);
}
else
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procedureName;
}
var outParams = BindProcedureParameters(cmd, exchange);
if (_options.AsFunction)
{
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
if (result == DBNull.Value) result = null;
// outputHeader keeps the incoming body intact and parks the function result
// in a header instead — the same contract as in SqlProducer.
if (!string.IsNullOrEmpty(_options.OutputHeader))
exchange.In.Headers[SqlExchangeHeaders.ResolveOutputHeader(_options.OutputHeader, exchange)] = result;
else
exchange.In.Body = result;
}
else
{
await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
sw.Stop();
// Read OUT/INOUT parameter values back to headers
foreach (var (paramName, dbParam) in outParams)
{
var value = dbParam.Value;
if (value == DBNull.Value) value = null;
exchange.In.Headers[paramName] = value;
}
// Set standard headers
exchange.In.Headers[SqlHeaders.StoredProcedure] = procedureName;
exchange.In.Headers[SqlHeaders.ExecutionTime] = sw.ElapsedMilliseconds;
if (_options.DataSource != null)
exchange.In.Headers[SqlHeaders.DataSource] = _options.DataSource;
if (tx != null)
{
exchange.In.Headers[SqlHeaders.TransactionId] = tx.GetHashCode().ToString();
await tx.CommitAsync(ct).ConfigureAwait(false);
}
}
catch (Exception ex)
{
if (ex is not OperationCanceledException || !ct.IsCancellationRequested)
activity.RecordFailure(ex);
_logger?.LogError(ex, "SQL procedure execution failed: procedure={Procedure}, dataSource={DataSource}",
_options.ProcedureName, _options.DataSource);
if (tx != null)
{
// The rollback is not interruptible: a cancelled token would only turn it into a "rollback failed" log.
try { await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false); }
catch (Exception rbEx) { _logger?.LogError(rbEx, "SQL procedure transaction rollback failed"); }
}
throw;
}
finally
{
if (tx != null)
await tx.DisposeAsync().ConfigureAwait(false);
}
}
private List<(string Name, DbParameter Param)> BindProcedureParameters(DbCommand cmd, IExchange exchange)
{
var outParams = new List<(string, DbParameter)>();
var paramDefs = ParseProcedureParams();
var explicitParams = _options.ExplicitParameters;
foreach (var def in paramDefs)
{
var param = cmd.CreateParameter();
param.ParameterName = def.Name;
param.DbType = def.DbType;
param.Direction = def.Direction switch
{
SqlParamDirection.In => ParameterDirection.Input,
SqlParamDirection.Out => ParameterDirection.Output,
SqlParamDirection.InOut => ParameterDirection.InputOutput,
_ => ParameterDirection.Input
};
if (def.Direction is SqlParamDirection.In or SqlParamDirection.InOut)
{
// Resolve value: expression > explicit param > header > body
if (def.Expression != null)
{
param.Value = SqlParameterBinder.ResolveParamValue(def.Expression, exchange);
}
else if (explicitParams.TryGetValue(def.Name, out var explicitVal))
{
param.Value = SqlParameterBinder.ResolveParamValue(explicitVal, exchange);
}
else if (exchange.In.Headers.TryGetValue(def.Name, out var headerVal))
{
param.Value = headerVal ?? DBNull.Value;
}
else if (exchange.In.Body is Dictionary dict &&
dict.TryGetValue(def.Name, out var bodyVal))
{
param.Value = bodyVal ?? DBNull.Value;
}
else
{
param.Value = DBNull.Value;
}
}
cmd.Parameters.Add(param);
if (def.Direction is SqlParamDirection.Out or SqlParamDirection.InOut)
outParams.Add((def.Name, param));
}
return outParams;
}
private List ParseProcedureParams()
{
var result = new List();
if (string.IsNullOrEmpty(_options.ProcedureParams))
return result;
// Format: "IN:name:DbType,OUT:name:DbType,INOUT:name:DbType:expression"
var parts = _options.ProcedureParams.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
var segments = part.Split(':', 4);
if (segments.Length < 3) continue;
var direction = Enum.Parse(segments[0], ignoreCase: true);
var name = segments[1];
var dbType = Enum.Parse(segments[2], ignoreCase: true);
var expression = segments.Length > 3 ? segments[3] : null;
result.Add(new ProcedureParamDef(direction, name, dbType, expression));
}
return result;
}
/// SELECT name(:#p1, :#p2, …) from the IN / INOUT parameters, in the provider's placeholder style.
private string BuildFunctionCall(string functionName)
{
var paramDefs = ParseProcedureParams();
var paramList = string.Join(", ", paramDefs
.Where(p => p.Direction is SqlParamDirection.In or SqlParamDirection.InOut)
.Select(p => $":#{p.Name}"));
var call = $"SELECT {functionName}({paramList})";
return SqlParameterParser.Rewrite(call, SqlParameterParser.FindPlaceholders(call, _options.BackslashEscapes), _options.PlaceholderStyle);
}
private ISqlConnectionFactory ResolveConnectionFactory() => _endpoint.ResolveConnectionFactory();
private readonly record struct ProcedureParamDef(SqlParamDirection Direction, string Name, DbType DbType, string? Expression);
}
Path: redb-route/redb.Route.Sql/SqlProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/SqlProducer.cs
----
using System.Data.Common;
using System.Diagnostics;
using System.Transactions;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Sql.Batch;
using redb.Route.Sql.Connection;
using redb.Route.Sql.Mapping;
using redb.Route.Telemetry;
namespace redb.Route.Sql;
///
/// Producer for SQL Execute mode. Executes INSERT/UPDATE/DELETE/SELECT statements
/// with auto-bind parameters from Exchange headers and body.
/// Supports all mappings; a list body with batchSize set is written as a batch
/// by .
///
///
/// Transaction behavior: always wraps execution in a local .
/// If an ambient exists (e.g. from
/// BeginTransaction() DSL), the local transaction is skipped and the connection
/// auto-enlists in the ambient .
/// This guarantees write atomicity (like EF SaveChanges ) without requiring
/// an explicit ?transacted=true option. A connection a factory lends (dataSource=redb ) is the lender's:
/// the step begins no transaction on it and binds its command to the lender's transaction, if any.
///
internal sealed class SqlProducer : IProducer
{
private readonly SqlEndpoint _endpoint;
private readonly SqlEndpointOptions _options;
private ILogger? _logger;
internal SqlProducer(SqlEndpoint endpoint, SqlEndpointOptions options)
{
_endpoint = endpoint;
_options = options;
_logger = (endpoint.Component as ComponentBase)?.Logger;
}
///
public Task Start(CancellationToken ct = default)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("SQL producer started");
return Task.CompletedTask;
}
///
public Task Stop(CancellationToken ct = default)
{
_logger ??= (_endpoint.Component as ComponentBase)?.Logger;
_logger?.LogInformation("SQL producer stopped");
return Task.CompletedTask;
}
///
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
"sql.execute", ActivityKind.Client,
"db.system", _endpoint.Component.Scheme,
_endpoint.Uri.NormalizedKey);
if (_options.Noop)
{
exchange.In.Headers[SqlHeaders.Query] = ResolveQuery(exchange);
return;
}
// The statement that runs: the URI path, the query option or the named query either refers to. It is resolved before
// anything is opened, so a failing query leaves a streamed body unread and released with the exchange.
var sql = ResolveQuery(exchange);
// Batch mode: a list, sequence, stream or JSON array body is written item by item through one statement.
if (_options.BatchSize > 0 && BatchSource.TryOpen(exchange.In.Body, ct, out var items))
{
await using (items.ConfigureAwait(false))
{
await new SqlBatchProcessor(_endpoint, _options, _logger)
.ProcessAsync(exchange, items, sql, activity, ct)
.ConfigureAwait(false);
}
return;
}
var factory = ResolveConnectionFactory();
var sw = Stopwatch.StartNew();
// Auto is decided by what the statement returns when it runs — as Apache Camel's execute() asks the driver — never by
// its text; it resolves below, and until then it is not a stream.
var outputType = _options.OutputType;
// Measured on PostgreSQL and SQL Server: a transaction does not commit while a reader is open on its connection, and
// a second connection in the same transaction needs a distributed one. A stream would outlive this endpoint inside
// the route's transaction, so it is refused before any connection is opened.
if (outputType == SqlOutputType.StreamList && Transaction.Current != null)
{
throw new InvalidOperationException(
"outputType=StreamList keeps a reader open after the endpoint, and this exchange runs inside a transaction " +
"(a transacted route). The transaction cannot commit while that reader is open, and a later SQL step in the " +
"same transaction would need a second connection and a distributed transaction. Use outputType=SelectList " +
"inside the transaction, or read the stream outside it.");
}
if (outputType == SqlOutputType.StreamList && factory.LendsConnection)
throw SqlConnections.StreamOnLentConnection(_options.DataSource);
// The replica only when the endpoint's author declares the statement read-only: the SQL text cannot tell. A lent
// connection (dataSource=redb) is the lender's: no transaction of this step's own, commands bound to the lender's.
var lease = await SqlConnections.OpenAsync(factory, exchange, _options.ReadOnly, ct).ConfigureAwait(false);
var connection = lease.Connection;
// From here the connection is owned resource: everything that can throw — starting the
// transaction included, since a dropped socket or a cancellation surfaces exactly there —
// runs under the finally that returns it to the pool. This is the hot path for audit and
// usage writes, and those failure modes come in bursts, so a leak here drains the pool
// rather than dripping.
var hasAmbientTx = Transaction.Current != null;
DbTransaction? tx = null;
DbCommand? cmd = null;
var streamOwnsResources = false;
try
{
// If ambient TransactionScope exists (route-level .Transacted()), the connection
// auto-enlists — no local DbTransaction needed. Otherwise always wrap in a
// local transaction for atomicity (like EF SaveChanges).
if (!hasAmbientTx && !lease.IsBorrowed)
{
tx = _options.IsolationLevel.HasValue
? await connection.BeginTransactionAsync(_options.IsolationLevel.Value, ct).ConfigureAwait(false)
: await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
}
cmd = lease.CreateCommand();
cmd.CommandText = sql;
cmd.CommandTimeout = _options.CommandTimeout;
if (tx != null) cmd.Transaction = tx;
SqlParameterBinder.Bind(cmd, exchange, _options.ExplicitParameters, _options.PlaceholderStyle, _options.BackslashEscapes);
// redbSql.executionTime covers executing the statement and reading its result; for a stream, opening the reader.
switch (outputType)
{
case SqlOutputType.Auto:
outputType = await ExecuteAuto(cmd, exchange, ct).ConfigureAwait(false);
break;
case SqlOutputType.SelectList:
await ExecuteSelectList(cmd, exchange, ct).ConfigureAwait(false);
break;
case SqlOutputType.SelectOne:
await ExecuteSelectOne(cmd, exchange, ct).ConfigureAwait(false);
break;
case SqlOutputType.Scalar:
await ExecuteScalar(cmd, exchange, ct).ConfigureAwait(false);
break;
case SqlOutputType.StreamList:
// StreamList hands connection, cmd and tx to the stream, which disposes them
// as the enumerator is disposed (fully consumed or abandoned early — the
// iterators hold them in `await using`). The flag, not the option value,
// decides who cleans up: an error before this line — the reader failing to
// open, say — means ownership never left this method.
await ExecuteStreamList(cmd, exchange, connection, tx, ct).ConfigureAwait(false);
streamOwnsResources = true;
SqlExchangeHeaders.SetCommon(exchange, _options, sql, sw.ElapsedMilliseconds, outputType);
return;
case SqlOutputType.None:
default:
await ExecuteNonQuery(cmd, exchange, ct).ConfigureAwait(false);
break;
}
SqlExchangeHeaders.SetCommon(exchange, _options, sql, sw.ElapsedMilliseconds, outputType);
if (tx != null)
{
exchange.In.Headers[SqlHeaders.TransactionId] = tx.GetHashCode().ToString();
await tx.CommitAsync(ct).ConfigureAwait(false);
}
}
catch (Exception ex)
{
if (ex is not OperationCanceledException || !ct.IsCancellationRequested)
activity.RecordFailure(ex);
_logger?.LogError(ex, "SQL execution failed: dataSource={DataSource}, outputType={OutputType}",
_options.DataSource, _options.OutputType);
if (tx != null)
{
// The rollback is not interruptible: a cancelled token would only turn it into a "rollback failed" log.
try { await tx.RollbackAsync(CancellationToken.None).ConfigureAwait(false); }
catch (Exception rbEx) { _logger?.LogError(rbEx, "SQL transaction rollback failed"); }
}
throw;
}
finally
{
if (!streamOwnsResources)
await ReleaseAsync(cmd, tx, lease).ConfigureAwait(false);
}
}
///
/// Releases the command, the transaction and the connection, each even when the one before it failed (the first failure
/// propagates): a transaction whose disposal throws must not leave the connection out of the pool. A lent connection is
/// given back, never closed.
///
private static async ValueTask ReleaseAsync(DbCommand? cmd, DbTransaction? tx, SqlConnectionLease lease)
{
try
{
if (cmd != null)
await cmd.DisposeAsync().ConfigureAwait(false);
}
finally
{
try
{
if (tx != null)
await tx.DisposeAsync().ConfigureAwait(false);
}
finally
{
await lease.DisposeAsync().ConfigureAwait(false);
}
}
}
///
/// outputType=Auto , as Apache Camel's execute() : the statement runs as a reader and the driver says what it
/// is — a result set (its rows, as ) or none (the rows affected, as
/// ). The text is never parsed: a comment before SELECT, a WITH that writes, an
/// INSERT … RETURNING all come out as what they return.
///
private async Task ExecuteAuto(DbCommand cmd, IExchange exchange, CancellationToken ct)
{
var poco = _endpoint.OutputMapping;
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
if (reader.FieldCount > 0)
{
await ReadRowsAsync(reader, poco, exchange, ct).ConfigureAwait(false);
return SqlOutputType.SelectList;
}
// No result set: the statement is read to its end, and the rows affected are taken once the reader is closed — the
// point at which every driver has them, as the batch reads them.
while (await reader.NextResultAsync(ct).ConfigureAwait(false))
{
}
await reader.CloseAsync().ConfigureAwait(false);
exchange.In.Headers[SqlHeaders.UpdateCount] = reader.RecordsAffected;
return SqlOutputType.None;
}
private async Task ExecuteSelectList(DbCommand cmd, IExchange exchange, CancellationToken ct)
{
var poco = _endpoint.OutputMapping;
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
await ReadRowsAsync(reader, poco, exchange, ct).ConfigureAwait(false);
}
/// Reads every row of into the result: a List<T> with outputClass , dictionaries otherwise.
private async Task ReadRowsAsync(DbDataReader reader, SqlRowMapperFactory.PocoMapping? poco, IExchange exchange, CancellationToken ct)
{
if (poco != null)
{
// outputClass is set → accumulate into a typed List, not List.
var typedRows = poco.CreateList();
while (await reader.ReadAsync(ct).ConfigureAwait(false))
typedRows.Add(poco.Map(reader));
exchange.In.Headers[SqlHeaders.RowCount] = typedRows.Count;
SetResult(exchange, typedRows);
return;
}
var mapper = new DictionaryRowMapper();
var rows = new List>();
while (await reader.ReadAsync(ct).ConfigureAwait(false))
rows.Add(mapper.Map(reader));
exchange.In.Headers[SqlHeaders.RowCount] = rows.Count;
SetResult(exchange, rows);
}
private async Task ExecuteSelectOne(DbCommand cmd, IExchange exchange, CancellationToken ct)
{
var poco = _endpoint.OutputMapping;
var mapper = new DictionaryRowMapper();
await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
if (await reader.ReadAsync(ct).ConfigureAwait(false))
{
var row = poco != null ? poco.Map(reader) : mapper.Map(reader);
exchange.In.Headers[SqlHeaders.RowCount] = 1;
SetResult(exchange, row);
}
else
{
exchange.In.Headers[SqlHeaders.RowCount] = 0;
SetResult(exchange, null);
}
}
private async Task ExecuteScalar(DbCommand cmd, IExchange exchange, CancellationToken ct)
{
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
if (result == DBNull.Value) result = null;
exchange.In.Headers[SqlHeaders.RowCount] = result != null ? 1 : 0;
SetResult(exchange, result);
}
private async Task ExecuteStreamList(DbCommand cmd, IExchange exchange, DbConnection connection, DbTransaction? tx, CancellationToken ct)
{
// StreamList differs from SelectList: rows are streamed lazily as IAsyncEnumerable, so the reader, command,
// transaction and connection outlive this method. The streamed result takes them over, and — as in Apache Camel,
// which closes the result set on exchange completion — it is registered with the exchange: whatever the route does
// with the body, the connection is returned when the exchange ends.
// The row type is resolved before the reader is open: a bad outputClass must not leave a reader behind.
var poco = _endpoint.OutputMapping;
var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
object body;
IAsyncDisposable release;
try
{
(body, release) = poco != null
? StreamedQueryResult.Create(poco.ElementType, reader, poco.Map, cmd, connection, tx)
: StreamedQueryResult.Create(typeof(Dictionary), reader, new DictionaryRowMapper().Map, cmd, connection, tx);
}
catch
{
// The stream never took the reader over: close it here, the caller releases the rest.
await reader.DisposeAsync().ConfigureAwait(false);
throw;
}
ExchangeResources.ReleaseWithExchange(exchange, release);
SetResult(exchange, body);
exchange.In.Headers[SqlHeaders.RowCount] = -1; // unknown until fully iterated
}
private static async Task ExecuteNonQuery(DbCommand cmd, IExchange exchange, CancellationToken ct)
{
var affected = await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
exchange.In.Headers[SqlHeaders.UpdateCount] = affected;
}
///
/// Delivers the query result. With outputHeader set, the result goes to that header
/// and the body is left untouched — which is what makes it possible to enrich a message
/// with a lookup without destroying the payload the route is already carrying.
/// Without it, the result replaces the body.
///
private void SetResult(IExchange exchange, object? value)
{
if (!string.IsNullOrEmpty(_options.OutputHeader))
exchange.In.Headers[SqlExchangeHeaders.ResolveOutputHeader(_options.OutputHeader, exchange)] = value;
else
exchange.In.Body = value;
}
private string ResolveQuery(IExchange exchange)
{
var rawSql = _endpoint.QueryOrProcedure;
if (_options.Query is { } dv)
{
var resolved = dv.Resolve(exchange);
if (resolved != null)
rawSql = resolved;
}
return ResolveNamedQuery(rawSql);
}
private string ResolveNamedQuery(string sql)
{
if (!sql.StartsWith(SqlNamedQueryRegistry.RefPrefix, StringComparison.OrdinalIgnoreCase))
return sql;
var registry = _endpoint.SqlComponent.Context?.GetService();
if (registry != null)
return registry.ResolveRef(sql);
throw new InvalidOperationException(
$"Named query reference '{sql}' cannot be resolved — no ISqlNamedQueryRegistry is registered.");
}
private ISqlConnectionFactory ResolveConnectionFactory() => _endpoint.ResolveConnectionFactory();
}
Path: redb-route/redb.Route.Sql/StreamedQueryResult.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Sql/StreamedQueryResult.cs
----
using System.Data.Common;
using System.Runtime.CompilerServices;
using redb.Route.Abstractions;
namespace redb.Route.Sql;
/// Creates the body of outputType=StreamList for a row type known only at run time.
internal static class StreamedQueryResult
{
///
/// A streamed result whose rows are , mapped by : the body to hand
/// the route, and the handle that releases it, to register with the exchange ( ).
///
internal static (object Body, IAsyncDisposable Release) Create(
Type elementType, DbDataReader reader, Func map,
DbCommand command, DbConnection connection, DbTransaction? transaction)
{
var body = (IStreamedQueryResult)Activator.CreateInstance(
typeof(StreamedQueryResult<>).MakeGenericType(elementType),
reader, map, command, connection, transaction)!;
return (body, new StreamedQueryResultRelease(body));
}
}
/// What the exchange releases when it ends: the reader, command, transaction and connection behind a streamed body.
internal interface IStreamedQueryResult
{
/// Releases everything the stream holds; the transaction is rolled back unless the rows were read to the end.
ValueTask ReleaseAsync();
}
///
/// The handle registered with the exchange. The body itself is not disposable on purpose: copies of the exchange (Enrich,
/// WireTap, RecipientList, Threads) share the body and are disposed when their own work is done, and a disposable body would
/// then be closed under the original. The release belongs to the exchange that registered it, or to the one Enrich hands it
/// over to.
///
internal sealed class StreamedQueryResultRelease(IStreamedQueryResult result) : IAsyncDisposable
{
///
public ValueTask DisposeAsync() => result.ReleaseAsync();
}
///
/// The body of outputType=StreamList : rows read lazily from an open reader. It owns the reader, its command, the
/// endpoint's local transaction (if any) and the connection, and releases them when the rows have been read to the end
/// (committing that transaction), when the reading stops early or fails, or — through the handle registered with the
/// exchange — when the exchange ends without anyone reading. The rows can be read once.
///
internal sealed class StreamedQueryResult : IAsyncEnumerable, IStreamedQueryResult, IExchangeBoundBody
{
private readonly DbDataReader _reader;
private readonly Func _map;
private readonly DbCommand _command;
private readonly DbConnection _connection;
private readonly DbTransaction? _transaction;
private int _enumerated;
private int _released;
public StreamedQueryResult(
DbDataReader reader, Func map, DbCommand command, DbConnection connection, DbTransaction? transaction)
{
_reader = reader;
_map = map;
_command = command;
_connection = connection;
_transaction = transaction;
}
///
/// The rows were already read, or the exchange has ended.
public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
// Read-once first: rows read to the end release the result too, and that is not "released with the exchange".
if (Interlocked.Exchange(ref _enumerated, 1) != 0)
throw new InvalidOperationException(
"A streamed SQL result (outputType=StreamList) can be read once: its rows come from one open reader.");
if (Volatile.Read(ref _released) != 0)
throw new InvalidOperationException(
"This streamed SQL result (outputType=StreamList) was released when its exchange ended; it can no longer be read.");
return ReadRows(cancellationToken).GetAsyncEnumerator(cancellationToken);
}
///
public ValueTask ReleaseAsync() => ReleaseAsync(commit: false);
private async IAsyncEnumerable ReadRows([EnumeratorCancellation] CancellationToken ct)
{
var readToEnd = false;
try
{
while (await _reader.ReadAsync(ct).ConfigureAwait(false))
yield return (T)_map(_reader);
readToEnd = true;
}
finally
{
await ReleaseAsync(commit: readToEnd).ConfigureAwait(false);
}
}
private async ValueTask ReleaseAsync(bool commit)
{
if (Interlocked.Exchange(ref _released, 1) != 0)
return;
// Each resource is released even when the one before it fails; the first failure propagates.
try
{
await _reader.DisposeAsync().ConfigureAwait(false);
}
finally
{
try
{
if (commit && _transaction is not null)
await _transaction.CommitAsync().ConfigureAwait(false);
}
finally
{
try
{
// Disposing an uncommitted transaction rolls it back.
if (_transaction is not null)
await _transaction.DisposeAsync().ConfigureAwait(false);
}
finally
{
try
{
await _command.DisposeAsync().ConfigureAwait(false);
}
finally
{
await _connection.DisposeAsync().ConfigureAwait(false);
}
}
}
}
}
}
Path: redb-route/redb.Route.Sql/redb.Route.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/redb.Route.Sql/redb.Route.Sql.csproj
----
redb.Route.Sql
SQL database transport for redb.Route ESB framework. Pure ADO.NET polling consumer, query/batch producer, stored procedure support. Provider-agnostic via System.Data.Common.
esb;messaging;sql;database;adonet;polling;redb
README.md