feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
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

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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 13:11:34 +01:00
1 parent 28e7a6e18a
commit 738c43ba0a
105 files changed
+8434 -73

No files matched your search

@@ -0,0 +1,307 @@
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;
}
}
}
+109
View File
@@ -0,0 +1,109 @@
using System.Collections.Immutable;
using System.Linq.Expressions;
namespace Khaemhat.Data.Querying;
/// <summary>Starts queries: <c>Query.For&lt;Party&gt;().Where(p =&gt; p.Name.Contains(text)).OrderBy(p =&gt; p.Name).Page(0, 50)</c>.</summary>
public static class Query
{
/// <summary>A query over all rows of <typeparamref name="T"/>.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <returns>The query.</returns>
public static Query<T> For<T>()
where T : class => Query<T>.All;
}
/// <summary>
/// An immutable query over the table of <typeparamref name="T"/> (SPEC §5.2): filters in the safe expression subset
/// (equality, comparisons, <c>Contains</c>/<c>StartsWith</c>/<c>EndsWith</c>, <c>In</c> as <c>list.Contains(x.Prop)</c>,
/// <c>&amp;&amp;</c>, <c>||</c>, <c>!</c>, <c>== null</c>), parameterized <see cref="SqlFragment"/> conditions, ordering and
/// paging. Each method returns a new query.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
public sealed class Query<T>
where T : class
{
private Query(
ImmutableList<LambdaExpression> filters, ImmutableList<SqlFragment> conditions, ImmutableList<QueryOrder> order, int offset, int? limit)
{
Filters = filters;
Conditions = conditions;
Order = order;
Offset = offset;
Limit = limit;
}
internal static Query<T> All { get; } = new([], [], [], 0, null);
/// <summary>The expression filters, combined with <c>AND</c>.</summary>
public ImmutableList<LambdaExpression> Filters { get; }
/// <summary>The SQL conditions, combined with <c>AND</c>.</summary>
public ImmutableList<SqlFragment> Conditions { get; }
/// <summary>The ordering, in priority order.</summary>
public ImmutableList<QueryOrder> Order { get; }
/// <summary>Rows to skip.</summary>
public int Offset { get; }
/// <summary>Rows to return at most, or <see langword="null"/> for all.</summary>
public int? Limit { get; }
/// <summary>Adds a filter.</summary>
/// <param name="predicate">The predicate, in the supported subset.</param>
/// <returns>The new query.</returns>
public Query<T> Where(Expression<Func<T, bool>> predicate)
{
ArgumentNullException.ThrowIfNull(predicate);
return new(Filters.Add(predicate), Conditions, Order, Offset, Limit);
}
/// <summary>Adds a parameterized SQL condition, for what expressions cannot say.</summary>
/// <param name="condition">The condition, for example <c>SqlFragment.Of($"{SqlFragment.Identifier("total")} &gt; {min}")</c>.</param>
/// <returns>The new query.</returns>
public Query<T> Where(SqlFragment condition)
{
ArgumentNullException.ThrowIfNull(condition);
return condition.IsEmpty ? this : new(Filters, Conditions.Add(condition), Order, Offset, Limit);
}
/// <summary>Orders by a property, ascending; further calls add secondary orderings.</summary>
/// <typeparam name="TKey">The property type.</typeparam>
/// <param name="property">The property.</param>
/// <returns>The new query.</returns>
public Query<T> OrderBy<TKey>(Expression<Func<T, TKey>> property) => AddOrder(property, descending: false);
/// <summary>Orders by a property, descending; further calls add secondary orderings.</summary>
/// <typeparam name="TKey">The property type.</typeparam>
/// <param name="property">The property.</param>
/// <returns>The new query.</returns>
public Query<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> property) => AddOrder(property, descending: true);
/// <summary>Returns at most <paramref name="limit"/> rows after skipping <paramref name="offset"/>.</summary>
/// <param name="offset">Rows to skip.</param>
/// <param name="limit">Rows to return.</param>
/// <returns>The new query.</returns>
public Query<T> Page(int offset, int limit)
{
ArgumentOutOfRangeException.ThrowIfNegative(offset);
ArgumentOutOfRangeException.ThrowIfNegative(limit);
return new(Filters, Conditions, Order, offset, limit);
}
/// <summary>Returns at most <paramref name="limit"/> rows.</summary>
/// <param name="limit">Rows to return.</param>
/// <returns>The new query.</returns>
public Query<T> Take(int limit) => Page(Offset, limit);
private Query<T> AddOrder(LambdaExpression property, bool descending)
{
ArgumentNullException.ThrowIfNull(property);
return new(Filters, Conditions, Order.Add(new QueryOrder(property, descending)), Offset, Limit);
}
}
/// <summary>An ordering of a query.</summary>
/// <param name="Property">The property selector.</param>
/// <param name="Descending">Whether the order is descending.</param>
public sealed record QueryOrder(LambdaExpression Property, bool Descending);
@@ -0,0 +1,75 @@
using Khaemhat.Data.Mapping;
namespace Khaemhat.Data.Querying;
/// <summary>Turns a <see cref="Query{T}"/> into parameterized <c>SELECT</c> and <c>COUNT</c> statements for one dialect.</summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <param name="map">The map of the entity.</param>
/// <param name="dialect">The dialect.</param>
public sealed class QueryBuilder<T>(EntityMap<T> map, ISqlDialect dialect)
where T : class, new()
{
private readonly ExpressionTranslator _translator = new(map, dialect);
/// <summary>The map.</summary>
public EntityMap<T> Map { get; } = map;
/// <summary>The list of mapped columns, in map order.</summary>
public SqlFragment ColumnList => SqlFragment.Join(", ", Map.Columns.Select(c => SqlFragment.Identifier(c.ColumnName)));
/// <summary>The <c>WHERE</c> clause (with leading space), or empty when the query has no filters.</summary>
/// <param name="query">The query.</param>
/// <returns>The clause.</returns>
public SqlFragment Where(Query<T> query)
{
ArgumentNullException.ThrowIfNull(query);
var conditions = query.Filters.Select(_translator.Translate).Concat(query.Conditions.Select(c => c.Parenthesize())).ToList();
return conditions.Count == 0 ? SqlFragment.Empty : SqlFragment.Literal(" WHERE ") + SqlFragment.Join(" AND ", conditions);
}
/// <summary>
/// The <c>SELECT</c> statement with ordering and paging. A paged query without ordering is ordered by the key,
/// so pages are stable.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The statement.</returns>
public SqlFragment Select(Query<T> query)
{
ArgumentNullException.ThrowIfNull(query);
var sql = SqlFragment.Literal("SELECT ") + ColumnList + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(Map.Table) + Where(query);
var order = query.Order
.Select(o => SqlFragment.Identifier(_translator.Column(o.Property).ColumnName) + SqlFragment.Literal(o.Descending ? " DESC" : " ASC"))
.ToList();
var paged = query.Limit is not null || query.Offset > 0;
if (order.Count == 0 && paged)
{
order.Add(SqlFragment.Identifier(Map.Key.ColumnName) + SqlFragment.Literal(" ASC"));
}
if (order.Count > 0)
{
sql += SqlFragment.Literal(" ORDER BY ") + SqlFragment.Join(", ", order);
}
if (paged)
{
sql += SqlFragment.Literal(dialect.Paging(query.Offset, query.Limit ?? int.MaxValue));
}
return sql;
}
/// <summary>The <c>COUNT(*)</c> statement for the filters of the query (ordering and paging ignored).</summary>
/// <param name="query">The query.</param>
/// <returns>The statement.</returns>
public SqlFragment Count(Query<T> query) =>
SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(Map.Table) + Where(query);
/// <summary>The <c>SELECT</c> of one row by key.</summary>
/// <param name="key">The key value.</param>
/// <returns>The statement.</returns>
public SqlFragment SelectByKey(object key) =>
SqlFragment.Literal("SELECT ") + ColumnList + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(Map.Table)
+ SqlFragment.Literal(" WHERE ") + SqlFragment.Identifier(Map.Key.ColumnName) + SqlFragment.Literal(" = ")
+ SqlFragment.Parameter(Map.Key.ToProvider(key), Map.Key.Type);
}