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; } } }