Files
Khaemhat/src/Khaemhat.Data/Execution/Repository.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

141 lines
5.9 KiB
C#

using System.Globalization;
using Khaemhat.Core.Common;
using Khaemhat.Core.Entities;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Querying;
namespace Khaemhat.Data.Execution;
/// <summary>
/// The repository of SPEC §5.1 for one entity type in one unit of work. Insert, update and delete statements are
/// cached per dialect (<see cref="CommandCache"/>); queries go through <see cref="QueryBuilder{T}"/>.
/// </summary>
/// <typeparam name="T">The entity type.</typeparam>
/// <typeparam name="TKey">The key type.</typeparam>
public sealed class Repository<T, TKey> : IRepository<T, TKey>
where T : class, IEntity<TKey>, new()
{
private readonly UnitOfWork _unitOfWork;
private readonly EntityMap<T> _map;
private readonly QueryBuilder<T> _builder;
internal Repository(UnitOfWork unitOfWork, EntityMap<T> map)
{
_unitOfWork = unitOfWork;
_map = map;
_builder = new QueryBuilder<T>(map, unitOfWork.Dialect);
}
/// <inheritdoc />
public Task<T?> GetAsync(TKey id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(id);
return _unitOfWork.QuerySingleAsync<T>(_builder.SelectByKey(id), cancellationToken);
}
/// <inheritdoc />
public Task<T?> FindAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
return _unitOfWork.QuerySingleAsync<T>(_builder.Select(query.Take(1)), cancellationToken);
}
/// <inheritdoc />
public async Task<PagedResult<T>> ListAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
var items = await _unitOfWork.QueryAsync<T>(_builder.Select(query), cancellationToken).ConfigureAwait(false);
long total = query.Limit is null && query.Offset == 0
? items.Count
: await CountAsync(query, cancellationToken).ConfigureAwait(false);
return new PagedResult<T>(items, total, query.Offset, query.Limit);
}
/// <inheritdoc />
public async Task<int> CountAsync(Query<T> query, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(query);
return (int)await _unitOfWork.QuerySingleAsync<long>(_builder.Count(query), cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<TKey> InsertAsync(T entity, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(entity);
if (entity is IAuditable audit)
{
audit.CreatedAt = _unitOfWork.Context.UtcNow;
audit.CreatedBy = _unitOfWork.Context.CurrentUser;
audit.UpdatedAt = null;
audit.UpdatedBy = null;
audit.RowVersion = 1;
}
var statement = CommandCache.Get(_map, CachedStatementKind.Insert, _unitOfWork.Dialect);
var parameters = Parameters(statement, entity, overrides: null);
if (!_map.Key.IsIdentity)
{
await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken).ConfigureAwait(false);
return entity.Id;
}
var generated = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteScalarAsync(ct), cancellationToken)
.ConfigureAwait(false);
var key = (TKey)ClrConverter.ConvertTo(_unitOfWork.Dialect.FromDbValue(generated, _map.Key.Type), typeof(TKey))!;
entity.Id = key;
return key;
}
/// <inheritdoc />
public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(entity);
var statement = CommandCache.Get(_map, CachedStatementKind.Update, _unitOfWork.Dialect);
var now = _unitOfWork.Context.UtcNow;
var user = _unitOfWork.Context.CurrentUser;
var overrides = new Dictionary<AuditRole, object?> { [AuditRole.UpdatedAt] = now, [AuditRole.UpdatedBy] = user };
var parameters = Parameters(statement, entity, overrides);
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
.ConfigureAwait(false);
if (affected == 0)
{
var version = entity is IAuditable a ? a.RowVersion : 0;
throw new ConcurrencyException(_map.Table, Convert.ToString(entity.Id, CultureInfo.InvariantCulture) ?? string.Empty, version);
}
if (entity is IAuditable audit)
{
audit.UpdatedAt = now;
audit.UpdatedBy = user;
audit.RowVersion++;
}
}
/// <inheritdoc />
public async Task<bool> DeleteAsync(TKey id, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(id);
var statement = CommandCache.Get(_map, CachedStatementKind.Delete, _unitOfWork.Dialect);
var parameters = new[] { new SqlParameterValue("p0", _map.Key.ToProvider(id), _map.Key.Type) };
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
.ConfigureAwait(false);
return affected > 0;
}
private static List<SqlParameterValue> Parameters(CachedStatement statement, T entity, Dictionary<AuditRole, object?>? overrides)
{
var parameters = new List<SqlParameterValue>(statement.Parameters.Count);
for (var i = 0; i < statement.Parameters.Count; i++)
{
var column = statement.Parameters[i];
var value = overrides is not null && column.Audit != AuditRole.None && overrides.TryGetValue(column.Audit, out var replaced)
? replaced
: column.GetValue(entity);
parameters.Add(new SqlParameterValue("p" + i.ToString(CultureInfo.InvariantCulture), column.ToProvider(value), column.Type));
}
return parameters;
}
}