Files
Khaemhat/src/Khaemhat.Data/Querying/ExpressionTranslator.cs
T
Alby96andClaude Opus 5.5 738c43ba0a
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe
by construction:

- Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every
  interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and
  optimistic concurrency on row_version, retries on transient errors.
- SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE,
  serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database
  creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never
  appears in messages.
- C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration
  under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings.
- CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key,
  purpose as associated data), so a copied row cannot be read for another company.
- tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of
  docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale.
- C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion.
- Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts
  differ from SPEC 5.1. Docs, wiki, changelog and status updated.

Closes #7, #8, #9, #10, #11, #12, #13, #14

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:11:34 +01:00

308 lines
13 KiB
C#

using System.Collections;
using System.Linq.Expressions;
using System.Reflection;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Querying;
/// <summary>
/// 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 <see cref="NotSupportedException"/>: use a <see cref="SqlFragment"/> condition instead.
/// </summary>
/// <param name="map">The map of the queried entity.</param>
/// <param name="dialect">The dialect, for the case-insensitive <c>LIKE</c>.</param>
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");
/// <summary>Translates a predicate.</summary>
/// <param name="predicate">A lambda with one parameter of the entity type returning <see cref="bool"/>.</param>
/// <returns>The condition.</returns>
public SqlFragment Translate(LambdaExpression predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
return Condition(predicate.Body, predicate.Parameters[0]);
}
/// <summary>The column of a property selector such as <c>x =&gt; x.Name</c>.</summary>
/// <param name="selector">The selector.</param>
/// <returns>The column.</returns>
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<object?>().ToList() ?? [];
if (values.Count == 0)
{
return False;
}
var nonNull = values.Where(v => v is not null).Select(v => Value(inColumn, v!)).ToList();
var condition = nonNull.Count == 0
? SqlFragment.Empty
: Name(inColumn) + SqlFragment.Literal(" IN (") + SqlFragment.Join(", ", nonNull) + SqlFragment.Literal(")");
if (values.Count != nonNull.Count)
{
var isNull = Name(inColumn) + SqlFragment.Literal(" IS NULL");
condition = condition.IsEmpty ? isNull : (condition + SqlFragment.Literal(" OR ") + isNull).Parenthesize();
}
return condition;
}
if (call.Type == typeof(bool) && !References(call, entity))
{
return (bool)Evaluate(call)! ? True : False;
}
throw Unsupported(call);
}
/// <summary>
/// C# 14 binds <c>array.Contains(x)</c> to <c>MemoryExtensions.Contains(ReadOnlySpan&lt;T&gt;, T)</c> through an
/// implicit conversion; spans cannot be evaluated by the expression interpreter, so read the array behind it.
/// </summary>
private static Expression UnwrapSpan(Expression node)
{
while (IsSpan(node.Type))
{
switch (node)
{
case MethodCallExpression { Method.Name: "op_Implicit", Arguments.Count: 1 } conversion:
node = conversion.Arguments[0];
break;
case UnaryExpression { NodeType: ExpressionType.Convert } convert:
node = convert.Operand;
break;
default:
return node;
}
}
return node;
static bool IsSpan(Type type) =>
type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(ReadOnlySpan<>) || type.GetGenericTypeDefinition() == typeof(Span<>));
}
private SqlFragment Like(ColumnMap column, string pattern) =>
dialect.CaseInsensitiveLike(Name(column), SqlFragment.Parameter(pattern, ColumnType.Text));
private ColumnMap? TryColumn(Expression node, ParameterExpression entity)
{
while (node is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert)
{
node = convert.Operand;
}
return node is MemberExpression { Member: PropertyInfo property } member && member.Expression == entity
? map.FindByProperty(property.Name) ?? throw new NotSupportedException($"{map.EntityType.Name}.{property.Name} is not mapped.")
: null;
}
private static SqlFragment Name(ColumnMap column) => SqlFragment.Identifier(column.ColumnName);
private static SqlFragment Value(ColumnMap column, object value)
{
if (column.ValueType.IsEnum && value is not Enum)
{
value = Enum.ToObject(column.ValueType, value);
}
return SqlFragment.Parameter(column.ToProvider(value), column.Type);
}
private static string? Operator(ExpressionType type) => type switch
{
ExpressionType.Equal => "=",
ExpressionType.NotEqual => "<>",
ExpressionType.LessThan => "<",
ExpressionType.LessThanOrEqual => "<=",
ExpressionType.GreaterThan => ">",
ExpressionType.GreaterThanOrEqual => ">=",
_ => null,
};
private static string Mirror(string op) => op switch
{
"<" => ">",
"<=" => ">=",
">" => "<",
">=" => "<=",
_ => op,
};
private static string EscapeLike(string text) =>
text.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("%", "\\%", StringComparison.Ordinal).Replace("_", "\\_", StringComparison.Ordinal);
private static bool References(Expression node, ParameterExpression entity)
{
var finder = new ParameterFinder(entity);
finder.Visit(node);
return finder.Found;
}
private static object? Evaluate(Expression node)
{
switch (node)
{
case ConstantExpression constant:
return constant.Value;
case MemberExpression { Member: FieldInfo field } member when member.Expression is null or ConstantExpression:
return field.GetValue((member.Expression as ConstantExpression)?.Value);
case MemberExpression { Member: PropertyInfo property } member when member.Expression is null or ConstantExpression:
return property.GetValue((member.Expression as ConstantExpression)?.Value);
case MemberExpression { Member: FieldInfo field } member:
return field.GetValue(Evaluate(member.Expression!));
case MemberExpression { Member: PropertyInfo property } member:
return property.GetValue(Evaluate(member.Expression!));
case UnaryExpression { NodeType: ExpressionType.Convert } convert when convert.Type == typeof(object):
return Evaluate(convert.Operand);
default:
return Expression.Lambda<Func<object?>>(Expression.Convert(node, typeof(object))).Compile(preferInterpretation: true)();
}
}
private NotSupportedException Unsupported(Expression node) =>
new($"The expression '{node}' is outside the supported query subset for {map.EntityType.Name}; use a SqlFragment condition.");
private sealed class ParameterFinder(ParameterExpression parameter) : ExpressionVisitor
{
public bool Found { get; private set; }
protected override Expression VisitParameter(ParameterExpression node)
{
Found |= node == parameter;
return node;
}
}
}