Path: redb-route/redb.Route.Core/Query/RedbQueryTranslator.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.Core/Query/RedbQueryTranslator.cs
----
using System.Globalization;
using System.Reflection;
using redb.Core.Models.Contracts;
using redb.Core.Query.Mapping;
using redb.Core.Utils;
using redb.Route.Abstractions;
using redb.Route.Expressions.Ast;
using SysExpression = System.Linq.Expressions.Expression;
namespace redb.Route.RedbCore.Query;
///
/// What a condition string is translated against: the props type (where=, redb
/// Where) or the base fields of the stored object (whereRedb=, redb
/// WhereRedb over ). One translator serves both; the root
/// decides which identifiers are storage members and how the refusals name them.
///
internal sealed class QueryRoot
{
private readonly Func _find;
private QueryRoot(Type type, string noun, string attribute, bool nested, Func find, IEnumerable candidates)
{
Type = type;
Noun = noun;
Attribute = attribute;
Nested = nested;
_find = find;
Candidates = string.Join(", ", candidates);
}
/// The lambda parameter type.
public Type Type { get; }
/// How a member is called in a refusal: "props property" or "base field".
public string Noun { get; }
/// The attribute the condition came from, for the refusal prefix.
public string Attribute { get; }
/// Whether a member path may walk further (Customer.Name); base fields are flat.
public bool Nested { get; }
/// The member names, for a refusal that helps fix a typo.
public string Candidates { get; }
/// The root member by name (case-insensitive), or null when the name is not one.
public PropertyInfo? Find(string name) => _find(name);
/// The props of : every public instance property, paths nest.
public static QueryRoot Props(Type propsType) => new(propsType, "props property", "where", nested: true,
name => FindProperty(propsType, name),
propsType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name));
private static readonly PropertyInfo[] BaseFields = typeof(IRedbObject)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => BaseFieldMapper.IsBaseField(p.Name) && p.Name != nameof(IRedbObject.ValueBytes))
.ToArray();
///
/// The base fields of a stored object — exactly the members the core maps to columns
/// (). The core maps an unknown name to _id without a
/// word, so nothing outside that list may reach it. ValueBytes is left out: a byte
/// array has no comparison a condition string could express.
///
public static QueryRoot Base { get; } = new(typeof(IRedbObject), "base field", "whereRedb", nested: false,
name => BaseFields.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)),
BaseFields.Select(p => p.Name));
private static PropertyInfo? FindProperty(Type type, string name)
=> type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
}
///
/// Translates a route-language condition string into a server-side redb LINQ predicate — the
/// visitor over the engine's ONE expression AST (no parser of its own, §9 of the language
/// catalog). The split rule: a subtree that references a storage member of the root (a props
/// property, or a base field for whereRedb) is TRANSLATED into the LINQ expression; a
/// subtree that does not (headers, body, functions, arithmetic — anything the engine can
/// evaluate) is FOLDED per message through the AST's own and
/// enters the query as a constant. What is neither — an unknown identifier, arithmetic over a
/// storage member, an untranslatable function — refuses LOUDLY at route build, never by
/// silently filtering on the client.
///
internal static class RedbQueryTranslator
{
/// The engine's value roots — never storage members (the tokenizer's reserved words).
private static readonly HashSet EngineRoots = new(StringComparer.OrdinalIgnoreCase)
{ "body", "header", "property", "jpath", "xpath", "logical" };
/// The string functions translated onto storage members (everything else stays value-side).
private static readonly Dictionary StringFunctions = new(StringComparer.OrdinalIgnoreCase)
{ ["contains"] = nameof(string.Contains), ["startsWith"] = nameof(string.StartsWith), ["endsWith"] = nameof(string.EndsWith) };
///
/// Builds the per-message predicate factory: parse and translate ONCE at definition time,
/// produce an Expression<Func<TRoot, bool>> per message (value-side
/// subtrees are evaluated against the exchange right then).
///
public static Func TranslateWhere(QueryRoot root, string where)
{
var ast = Parse(where);
var parameter = SysExpression.Parameter(root.Type, "p");
var build = BuildBool(ast, root, parameter, where);
return exchange => SysExpression.Lambda(build(exchange), parameter);
}
///
/// An ordering key selector over a member path — static, nothing per-message in it. Typed
/// exactly Func<TRoot, TKey> with the member's own key type: the provider's
/// ordering parser reads a property access, not a boxing Convert (an end-to-end finding).
///
public static System.Linq.Expressions.LambdaExpression TranslateOrderBy(QueryRoot root, string path)
{
var parameter = SysExpression.Parameter(root.Type, "p");
if (!TryMember(Parse(path), root, parameter, out var member))
throw new InvalidOperationException(
$"orderBy '{path}' is not a {root.Noun} path of {root.Type.Name} — ordering happens server-side " +
$"(available: {root.Candidates}).");
return SysExpression.Lambda(
typeof(Func<,>).MakeGenericType(root.Type, member!.Type), member, parameter);
}
// ── the visitor ──────────────────────────────────────────────────
private static AstNode Parse(string expression)
{
var tokens = new Tokenizer(expression).GetAllTokens();
return new Parser(tokens).Parse();
}
/// A subtree that must come out boolean.
private static Func BuildBool(
AstNode node, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source)
{
switch (node)
{
case BinaryOperationNode { Operator: "AND" or "OR" } logical:
{
var left = BuildBool(logical.Left, root, parameter, source);
var right = BuildBool(logical.Right, root, parameter, source);
return logical.Operator == "AND"
? x => SysExpression.AndAlso(left(x), right(x))
: x => SysExpression.OrElse(left(x), right(x));
}
case UnaryOperationNode { Operator: "NOT" or "!" } not:
{
var operand = BuildBool(not.Operand, root, parameter, source);
return x => SysExpression.Not(operand(x));
}
case BinaryOperationNode { Operator: "==" or "!=" or ">" or "<" or ">=" or "<=" } comparison:
return BuildComparison(comparison, root, parameter, source);
case InOperationNode membership:
return BuildMembership(membership, root, parameter, source);
case FunctionCallNode function when StringFunctions.ContainsKey(function.Name):
return BuildStringFunction(function, root, parameter, source);
default:
{
// A bool member standing alone — or a value-only subtree, folded to a
// per-message boolean constant (a header gate inside AND is legitimate).
if (TryMember(node, root, parameter, out var member))
{
if (member!.Type != typeof(bool))
throw Refuse(root, source, $"'{node}' is a {member.Type.Name} {root.Noun} where a condition is expected" +
(member.Type == typeof(bool?) ? $" (compare it: {node} == true)" : ""));
return _ => member;
}
if (ContainsMemberRef(node, root))
throw Refuse(root, source, $"'{node}' mixes {root.Noun} members into an operation the storage cannot run " +
"server-side (arithmetic and unknown functions stay on the value side, or use filter=\"#spec\")");
ValidateValueSide(node, root, source);
return x => SysExpression.Constant(
System.Convert.ToBoolean(node.Evaluate(x) ?? false, CultureInfo.InvariantCulture));
}
}
}
private static Func BuildComparison(
BinaryOperationNode comparison, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source)
{
var leftIsMember = TryMember(comparison.Left, root, parameter, out var leftMember);
var rightIsMember = TryMember(comparison.Right, root, parameter, out var rightMember);
if (leftIsMember && rightIsMember)
return _ => MakeBinary(comparison.Operator, leftMember!, rightMember!);
if (!leftIsMember && !rightIsMember)
{
// No member reference at all — a per-message gate; still refuse when a member
// is buried inside arithmetic (that is the silent-mistranslation trap).
if (ContainsMemberRef(comparison, root))
throw Refuse(root, source, $"'{comparison}' uses a {root.Noun} inside an expression the storage " +
"cannot run server-side (move it to a plain comparison, or use filter=\"#spec\")");
ValidateValueSide(comparison, root, source);
return x => SysExpression.Constant(
System.Convert.ToBoolean(comparison.Evaluate(x) ?? false, CultureInfo.InvariantCulture));
}
var (member, valueNode, op) = leftIsMember
? (leftMember!, comparison.Right, comparison.Operator)
: (rightMember!, comparison.Left, Mirror(comparison.Operator));
if (member.Type == typeof(string) && op is ">" or "<" or ">=" or "<=")
throw Refuse(root, source, $"ordering comparison '{op}' on a string {root.Noun} is not supported " +
"(compare equality, or use filter=\"#spec\")");
if (ContainsMemberRef(valueNode, root))
throw Refuse(root, source, $"'{valueNode}' mixes a {root.Noun} into the value side of a comparison " +
$"(compare a {root.Noun} against a value, or use filter=\"#spec\")");
ValidateValueSide(valueNode, root, source);
return x => MakeBinary(op, member, ConstantOfType(valueNode.Evaluate(x), member.Type, root, source));
}
///
/// member in list → Enumerable.Contains(T[], member), the shape the storage turns
/// into an SQL IN for props and base fields alike. The list is evaluated per message and
/// each element converted to the member's type the way a single comparison converts its value.
/// An empty (or missing) list is decided here as a constant — nothing found for in,
/// everything for not in — so it never reaches the storage as {"$in": []}, whose
/// meaning is decided in SQL we do not see from here.
///
private static Func BuildMembership(
InOperationNode membership, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source)
{
if (ContainsMemberRef(membership.List, root))
throw Refuse(root, source, $"'{membership}' has a {root.Noun} on the right of in; the right side is a list " +
"of values — a collection the message carries (header.codes) or a literal ('a','b')");
if (!TryMember(membership.Value, root, parameter, out var member))
{
// No member on either side: a per-message gate, like any other header condition.
if (ContainsMemberRef(membership.Value, root))
throw Refuse(root, source, $"'{membership.Value}' uses a {root.Noun} inside an expression the storage " +
"cannot run server-side (put the member alone on the left of in, or use filter=\"#spec\")");
ValidateValueSide(membership, root, source);
return x => SysExpression.Constant(
System.Convert.ToBoolean(membership.Evaluate(x) ?? false, CultureInfo.InvariantCulture));
}
ValidateValueSide(membership.List, root, source);
var contains = typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)
.First(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2)
.MakeGenericMethod(member!.Type);
return x =>
{
var raw = membership.List.Evaluate(x);
var items = raw switch
{
null => [],
string => throw Refuse(root, source, $"'{membership}': the right side of in is a string, and a string " +
"is not split into a list — reference a collection or write ('a','b')"),
System.Collections.IEnumerable e => e.Cast