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>
110 lines
4.8 KiB
C#
110 lines
4.8 KiB
C#
using System.Collections.Immutable;
|
|
using System.Linq.Expressions;
|
|
|
|
namespace Khaemhat.Data.Querying;
|
|
|
|
/// <summary>Starts queries: <c>Query.For<Party>().Where(p => p.Name.Contains(text)).OrderBy(p => 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>&&</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")} > {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);
|