#nullable enable
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OpenWaf.Data;
///
/// A typed query whose SQL is rendered from an expression tree that is walked,
/// never compiled.
///
/// That last clause is the whole reason this type exists. EF answers the same
/// shape under NativeAOT with Query wasn't precompiled and dynamic code isn't
/// supported with NativeAOT — 32 of them in the 2026-10-07 probe window
/// before the first query moved off EF, 18 after —
/// because its query pipeline compiles expression trees into IL at run time.
/// Walking the tree with a switch over needs no
/// dynamic code, and the row materializer is a Func<DbDataReader,T>
/// the compiler emitted, so there is nothing left for the runtime to generate.
/// The mechanism is the neighbouring deployment's
/// (~/work/tskr/app/lib/MicroOrmRuntime/Query.cs , 1,219 lines); this is the
/// first slice of it, sized to the one query this tree has moved so far.
///
/// The supported grammar is a closed set, and it says so. Anything outside
/// it throws naming the node, rather
/// than rendering SQL that is quietly wrong. What is supported today: comparisons
/// (== != < <= > >= ) between a column and a value, null tests,
/// && , || , ! , captured locals and closure fields on the
/// value side, ordering, Take /Skip . What is not: joins, subqueries,
/// aggregates other than Count , updates and deletes, JSON columns, enum
/// comparisons. Each of those is a decision with a cost, not an oversight — and
/// RenderSelect is public so the rendered text can be asserted without a
/// database, which is how the neighbouring project tests its own renderers.
///
public sealed class Query
{
private readonly OrmContext _db;
private readonly Func _map;
private readonly TableMeta _meta;
private readonly List _where = [];
private readonly List<(string Column, bool Descending)> _order = [];
private readonly List _args = [];
private int? _limit;
private int? _offset;
public Query(OrmContext db, TableMeta meta, Func map)
{
_db = db;
_meta = meta;
_map = map;
}
public Query Where(Expression> predicate)
{
// No extra parentheses here: Translate parenthesizes every binary term it
// emits, so a WHERE over one term reads as WHERE (x = @p0) and a WHERE over
// several reads as WHERE ((…) AND (…)) rather than a stack of brackets.
_where.Add(Translate(predicate.Body, predicate.Parameters[0]));
return this;
}
public Query OrderBy(Expression> selector) => Order(selector, false);
public Query OrderByDescending(Expression> selector) => Order(selector, true);
private Query Order(Expression> selector, bool descending)
{
_order.Add((ColumnOf(selector.Body, selector.Parameters[0]), descending));
return this;
}
public Query Take(int n) { _limit = n; return this; }
public Query Skip(int n) { _offset = n; return this; }
/// The SELECT this query would run, with the parameters it binds in
/// the same order. Public on purpose: the renderer is the test seam, and a
/// wrong query should be red against a string, not only against a database.
public string RenderSelect()
{
var sb = new StringBuilder("SELECT ");
var quoted = new List(_meta.Columns.Length);
foreach (var column in _meta.Columns) quoted.Add(_db.Dialect.Quote(column));
sb.Append(string.Join(", ", quoted));
return AppendFrom(sb);
}
/// The COUNT this query would run for .
public string RenderCount() => AppendFrom(new StringBuilder("SELECT " + _db.Dialect.CountAllExpression));
private string AppendFrom(StringBuilder sb)
{
sb.Append(" FROM ").Append(_db.Dialect.Quote(_meta.Table));
if (_where.Count > 0) sb.Append(" WHERE ").Append(string.Join(" AND ", _where));
if (_order.Count > 0)
{
sb.Append(" ORDER BY ");
var terms = new List(_order.Count);
foreach (var o in _order)
terms.Add(_db.Dialect.Quote(o.Column) + (o.Descending ? " DESC" : " ASC"));
sb.Append(string.Join(", ", terms));
}
sb.Append(_db.Dialect.Page(_limit, _offset));
return sb.ToString();
}
public IReadOnlyList Arguments => _args;
public async Task> ToListAsync(CancellationToken ct = default)
{
var sql = RenderSelect();
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
await using var command = connection.CreateCommand();
command.CommandText = sql;
Bind(command);
await using var reader = await command.ExecuteReaderAsync(ct);
var rows = new List();
while (await reader.ReadAsync(ct)) rows.Add(_map(reader, _db.Dialect));
return rows;
}
public async Task CountAsync(CancellationToken ct = default)
{
var sql = RenderCount();
await using var connection = await _db.DataSource.OpenConnectionAsync(ct);
await using var command = connection.CreateCommand();
command.CommandText = sql;
Bind(command);
var value = await command.ExecuteScalarAsync(ct);
return Convert.ToInt64(value, CultureInfo.InvariantCulture);
}
public async Task FirstOrDefaultAsync(CancellationToken ct = default)
{
_limit = 1;
var rows = await ToListAsync(ct);
return rows.Count > 0 ? rows[0] : default;
}
private void Bind(DbCommand command)
{
for (var i = 0; i < _args.Count; i++)
{
var parameter = command.CreateParameter();
parameter.ParameterName = "@p" + i.ToString(CultureInfo.InvariantCulture);
parameter.Value = _args[i] ?? DBNull.Value;
command.Parameters.Add(parameter);
}
}
// ---- the translator ----------------------------------------------------
private string Translate(Expression expression, ParameterExpression entity)
{
switch (expression)
{
case UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert:
return Translate(convert.Operand, entity);
case UnaryExpression { NodeType: ExpressionType.Not } not:
return "NOT (" + Translate(not.Operand, entity) + ")";
case BinaryExpression binary:
return TranslateBinary(binary, entity);
case MemberExpression flag when IsColumn(flag, entity):
// A bare boolean column, rendered as a truth test: both providers
// this tree runs store a bool as 1/0.
return _db.Dialect.Quote(ColumnOf(flag, entity)) + " = 1";
case MethodCallExpression call:
throw new UnsupportedQueryNodeException(
$"method call '{call.Method.DeclaringType?.Name}.{call.Method.Name}'");
default:
throw new UnsupportedQueryNodeException(expression.NodeType.ToString());
}
}
private string TranslateBinary(BinaryExpression binary, ParameterExpression entity)
{
switch (binary.NodeType)
{
case ExpressionType.AndAlso:
return "(" + Translate(binary.Left, entity) + " AND " + Translate(binary.Right, entity) + ")";
case ExpressionType.OrElse:
return "(" + Translate(binary.Left, entity) + " OR " + Translate(binary.Right, entity) + ")";
}
var left = Operand(binary.Left, entity);
var right = Operand(binary.Right, entity);
// A null on either side is an IS [NOT] NULL test, never an equality with a
// parameter: "col = NULL" is unknown, not false, and a ban filter built that
// way silently stops matching the rows it was written for.
if (left.IsNull && right.IsNull)
throw new UnsupportedQueryNodeException("null compared with null");
if (left.IsNull) return NullTest(right.Column, binary.NodeType);
if (right.IsNull) return NullTest(left.Column, binary.NodeType);
var op = binary.NodeType switch
{
ExpressionType.Equal => "=",
ExpressionType.NotEqual => "<>",
ExpressionType.GreaterThan => ">",
ExpressionType.GreaterThanOrEqual => ">=",
ExpressionType.LessThan => "<",
ExpressionType.LessThanOrEqual => "<=",
_ => throw new UnsupportedQueryNodeException(binary.NodeType.ToString()),
};
// One side is the column, the other is a value already mapped for this
// provider. The parameter is appended before the placeholder is written, so
// the numbering and the bind order cannot disagree.
var column = left.Column ?? right.Column
?? throw new UnsupportedQueryNodeException("a comparison with no column on either side");
_args.Add(left.Column is null ? left.Value : right.Value);
// Parenthesized even though SQL's own precedence would usually allow it
// without: a rendered predicate is read by a human in a log, and a test
// that mixes AND and OR should not depend on who remembers the table.
return "(" + _db.Dialect.Quote(column) + " " + op + " " + _db.Dialect.Param(_args.Count - 1) + ")";
}
private string NullTest(string? column, ExpressionType nodeType)
{
if (column is null)
throw new UnsupportedQueryNodeException("a null test with no column to test");
return nodeType switch
{
ExpressionType.Equal => "(" + _db.Dialect.Quote(column) + " IS NULL)",
ExpressionType.NotEqual => "(" + _db.Dialect.Quote(column) + " IS NOT NULL)",
_ => throw new UnsupportedQueryNodeException(nodeType.ToString() + " against null"),
};
}
private readonly record struct OperandResult(string? Column, object? Value, bool IsNull);
private OperandResult Operand(Expression expression, ParameterExpression entity)
{
var unwrapped = Unwrap(expression);
if (unwrapped is ConstantExpression { Value: null }) return new OperandResult(null, null, true);
if (IsColumn(unwrapped, entity)) return new OperandResult(ColumnOf(unwrapped, entity), null, false);
var mapped = Value(unwrapped, entity);
// A captured null is a null test too. Rendering it as "col = @p0" bound to
// DBNull parses, runs, and matches nothing — the quietest wrong answer
// there is, and the one a nullable ban expiry produces.
return new OperandResult(null, mapped, mapped is null);
}
private static Expression Unwrap(Expression expression) =>
expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert
? Unwrap(convert.Operand)
: expression;
private static bool IsColumn(Expression expression, ParameterExpression entity) =>
Unwrap(expression) is MemberExpression member && RootOf(member) == entity;
private static Expression? RootOf(Expression expression) =>
expression switch
{
MemberExpression member => RootOf(member.Expression!),
UnaryExpression unary => RootOf(unary.Operand),
ParameterExpression parameter => parameter,
_ => null,
};
private string ColumnOf(Expression expression, ParameterExpression entity)
{
if (Unwrap(expression) is not MemberExpression member)
throw new UnsupportedQueryNodeException("an ordering or test that is not a column");
var name = member.Member.Name;
var column = _meta.ColumnOf(name);
if (column.Length == 0)
throw new UnsupportedQueryNodeException($"member '{name}' is not a column of {_meta.Table}");
return column;
}
/// The value side of a comparison: a literal, a captured local, or a
/// closure field. Reading a closure field is reflection over a field the
/// compiler generated for a lambda — the same move the neighbouring
/// deployment's renderer makes, and the one its AOT deployment proves works.
private object? Value(Expression expression, ParameterExpression entity)
{
expression = Unwrap(expression);
switch (expression)
{
case ConstantExpression constant:
return MapValue(constant.Value);
case MemberExpression member:
{
// The root of a captured variable is a ConstantExpression holding
// the closure object itself. It is the OWNER of the field read, not
// a value to bind — mapping it as a parameter is how a captured
// local turns into "a parameter of type <>c__DisplayClass10_0".
object? owner = null;
if (member.Expression is not null)
{
var ownerExpression = Unwrap(member.Expression);
owner = ownerExpression is ConstantExpression root ? root.Value : Value(ownerExpression, entity);
}
var raw = member.Member switch
{
FieldInfo field => field.GetValue(owner),
PropertyInfo property => property.GetValue(owner),
_ => throw new UnsupportedQueryNodeException($"member '{member.Member.Name}' on the value side"),
};
return MapValue(raw);
}
default:
throw new UnsupportedQueryNodeException(expression.NodeType.ToString() + " on the value side");
}
}
private object? MapValue(object? value) => value switch
{
null => null,
DateTimeOffset instant => _db.Dialect.WriteDateTimeOffset(instant),
bool flag => flag ? 1 : 0,
string or byte or sbyte or short or ushort or int or uint or long or ulong or float or double or decimal or Guid => value,
_ => throw new UnsupportedQueryNodeException(
$"a parameter of type {value.GetType().Name}; the generated query layer names the CLR types it binds"),
};
}
/// A query shape this layer refuses, said by name at the call site
/// rather than answered with SQL that looks right.
public sealed class UnsupportedQueryNodeException(string what)
: NotSupportedException($"OpenWaf.Data cannot render {what}. Either extend the renderer or leave the query to EF.")
{
public string What { get; } = what;
}