using System.Collections;
using System.Linq.Expressions;
using System.Reflection;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Querying;
///
/// Translates predicates of the safe subset of SPEC §5.2 into parameterized SQL. Every value — constants, captured
/// variables, list items — becomes a parameter; only mapped column names reach the SQL text. Anything outside the
/// subset throws : use a condition instead.
///
/// The map of the queried entity.
/// The dialect, for the case-insensitive LIKE.
public sealed class ExpressionTranslator(IEntityMap map, ISqlDialect dialect)
{
private static readonly SqlFragment True = SqlFragment.Literal("1 = 1");
private static readonly SqlFragment False = SqlFragment.Literal("1 = 0");
/// Translates a predicate.
/// A lambda with one parameter of the entity type returning .
/// The condition.
public SqlFragment Translate(LambdaExpression predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
return Condition(predicate.Body, predicate.Parameters[0]);
}
/// The column of a property selector such as x => x.Name.
/// The selector.
/// The column.
public ColumnMap Column(LambdaExpression selector)
{
ArgumentNullException.ThrowIfNull(selector);
return TryColumn(selector.Body, selector.Parameters[0])
?? throw new NotSupportedException($"Only mapped properties of {map.EntityType.Name} can be used here: {selector}.");
}
private SqlFragment Condition(Expression node, ParameterExpression entity)
{
switch (node)
{
case BinaryExpression { NodeType: ExpressionType.AndAlso } and:
return (Condition(and.Left, entity) + SqlFragment.Literal(" AND ") + Condition(and.Right, entity)).Parenthesize();
case BinaryExpression { NodeType: ExpressionType.OrElse } or:
return (Condition(or.Left, entity) + SqlFragment.Literal(" OR ") + Condition(or.Right, entity)).Parenthesize();
case UnaryExpression { NodeType: ExpressionType.Not } not:
return SqlFragment.Literal("NOT ") + Condition(not.Operand, entity).Parenthesize();
case BinaryExpression binary when Operator(binary.NodeType) is not null:
return Comparison(binary, entity);
case MethodCallExpression call:
return Method(call, entity);
case ConstantExpression { Value: bool constant }:
return constant ? True : False;
default:
if (node.Type == typeof(bool) && TryColumn(node, entity) is { } flag)
{
return Name(flag) + SqlFragment.Literal(" = ") + Value(flag, true);
}
if (node.Type == typeof(bool) && !References(node, entity))
{
return (bool)Evaluate(node)! ? True : False;
}
throw Unsupported(node);
}
}
private SqlFragment Comparison(BinaryExpression binary, ParameterExpression entity)
{
var op = Operator(binary.NodeType)!;
var leftColumn = TryColumn(binary.Left, entity);
var rightColumn = TryColumn(binary.Right, entity);
if (leftColumn is not null && rightColumn is not null)
{
return Name(leftColumn) + SqlFragment.Literal(" " + op + " ") + Name(rightColumn);
}
if (leftColumn is null && rightColumn is not null)
{
// value op column -> column (mirrored op) value
(leftColumn, op) = (rightColumn, Mirror(op));
return CompareWithValue(leftColumn, op, binary.Left, entity);
}
return leftColumn is not null ? CompareWithValue(leftColumn, op, binary.Right, entity) : throw Unsupported(binary);
}
private SqlFragment CompareWithValue(ColumnMap column, string op, Expression valueNode, ParameterExpression entity)
{
if (References(valueNode, entity))
{
throw Unsupported(valueNode);
}
var value = Evaluate(valueNode);
if (value is null)
{
return op switch
{
"=" => Name(column) + SqlFragment.Literal(" IS NULL"),
"<>" => Name(column) + SqlFragment.Literal(" IS NOT NULL"),
_ => throw new NotSupportedException($"Cannot compare {column.PropertyName} with null using {op}."),
};
}
return Name(column) + SqlFragment.Literal(" " + op + " ") + Value(column, value);
}
private SqlFragment Method(MethodCallExpression call, ParameterExpression entity)
{
// column.Contains / StartsWith / EndsWith (value): case-insensitive LIKE
if (call.Method.DeclaringType == typeof(string) && call.Object is not null && call.Arguments.Count >= 1
&& call.Method.Name is nameof(string.Contains) or nameof(string.StartsWith) or nameof(string.EndsWith)
&& TryColumn(call.Object, entity) is { } textColumn)
{
if (References(call.Arguments[0], entity))
{
throw Unsupported(call);
}
var text = Evaluate(call.Arguments[0]) as string ?? string.Empty;
var escaped = EscapeLike(text);
var pattern = call.Method.Name switch
{
nameof(string.StartsWith) => escaped + "%",
nameof(string.EndsWith) => "%" + escaped,
_ => "%" + escaped + "%",
};
return Like(textColumn, pattern);
}
// string.IsNullOrEmpty(column)
if (call.Method.DeclaringType == typeof(string) && call.Method.Name == nameof(string.IsNullOrEmpty)
&& TryColumn(call.Arguments[0], entity) is { } emptyColumn)
{
return (Name(emptyColumn) + SqlFragment.Literal(" IS NULL OR ") + Name(emptyColumn) + SqlFragment.Literal(" = ")
+ SqlFragment.Parameter(string.Empty, emptyColumn.Type)).Parenthesize();
}
// values.Contains(column) -> column IN (...)
Expression? collection = null;
Expression? item = null;
if (call.Method.Name == nameof(Enumerable.Contains))
{
if (call.Object is null && call.Arguments.Count == 2)
{
(collection, item) = (call.Arguments[0], call.Arguments[1]);
}
else if (call.Object is not null && call.Arguments.Count == 1)
{
(collection, item) = (call.Object, call.Arguments[0]);
}
}
if (collection is not null && item is not null && TryColumn(item, entity) is { } inColumn && !References(collection, entity))
{
collection = UnwrapSpan(collection);
var values = (Evaluate(collection) as IEnumerable)?.Cast