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,95 @@
using Khaemhat.Data.Execution;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.Migrations;
/// <summary>A row of <c>schema_version</c>.</summary>
/// <param name="Module">The owning module.</param>
/// <param name="Version">The version.</param>
/// <param name="Name">The name.</param>
/// <param name="AppliedAt">When it was applied (UTC).</param>
/// <param name="Checksum">SHA-256 of the statements that were run, in hexadecimal.</param>
public sealed record AppliedMigration(string Module, long Version, string Name, DateTime AppliedAt, string Checksum);
/// <summary>
/// The <c>schema_version(module, version, name, applied_at, checksum)</c> table present in every database (SPEC §5.3).
/// </summary>
public static class SchemaVersionStore
{
/// <summary>The table name.</summary>
public const string Table = "schema_version";
/// <summary>The operation creating the table if it is missing.</summary>
public static CreateTableOperation CreateOperation { get; } = BuildCreateOperation();
/// <summary>Creates the table if it is missing.</summary>
/// <param name="unitOfWork">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task EnsureCreatedAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
foreach (var statement in unitOfWork.Provider.Ddl.Generate([CreateOperation]))
{
await unitOfWork.ExecuteAsync(SqlFragment.Literal(statement), cancellationToken).ConfigureAwait(false);
}
}
/// <summary>All applied migrations.</summary>
/// <param name="unitOfWork">The unit of work.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The rows, ordered by version.</returns>
public static Task<IReadOnlyList<AppliedMigration>> ReadAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
return unitOfWork.QueryAsync<AppliedMigration>(
SqlFragment.Literal("SELECT module, version, name, applied_at, checksum FROM ") + SqlFragment.Identifier(Table)
+ SqlFragment.Literal(" ORDER BY version, module"),
cancellationToken);
}
/// <summary>Whether a version is applied (read inside the migration transaction).</summary>
/// <param name="unitOfWork">The unit of work.</param>
/// <param name="module">The module.</param>
/// <param name="version">The version.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if applied.</returns>
public static async Task<bool> IsAppliedAsync(UnitOfWork unitOfWork, string module, long version, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
var count = await unitOfWork.QuerySingleAsync<long>(
SqlFragment.Of($"SELECT COUNT(*) FROM {SqlFragment.Identifier(Table)} WHERE module = {module} AND version = {version}"),
cancellationToken).ConfigureAwait(false);
return count > 0;
}
/// <summary>Records an applied migration.</summary>
/// <param name="unitOfWork">The unit of work, inside the migration transaction.</param>
/// <param name="applied">The row.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static Task RecordAsync(UnitOfWork unitOfWork, AppliedMigration applied, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(unitOfWork);
ArgumentNullException.ThrowIfNull(applied);
return unitOfWork.ExecuteAsync(
SqlFragment.Of(
$"INSERT INTO {SqlFragment.Identifier(Table)} (module, version, name, applied_at, checksum) VALUES ({applied.Module}, {applied.Version}, {applied.Name}, {applied.AppliedAt}, {applied.Checksum})"),
cancellationToken);
}
private static CreateTableOperation BuildCreateOperation()
{
var builder = new SchemaBuilder();
builder.CreateTable(Table, t =>
{
t.String("module", 50).NotNull();
t.Int64("version").NotNull();
t.String("name", 200).NotNull();
t.DateTimeUtc("applied_at").NotNull();
t.String("checksum", 64).NotNull();
t.PrimaryKey("module", "version");
});
return ((CreateTableOperation)builder.Operations[0]) with { IfNotExists = true };
}
}