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