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.");
}
}