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

+145
View File
@@ -0,0 +1,145 @@
using System.Data;
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Microsoft.Data.Sqlite;
namespace Khaemhat.Data.Sqlite;
/// <summary>
/// The SQLite engine (SPEC §1.3, §5.2): tests, demo, trial and read-only archives. Every connection gets
/// <c>foreign_keys=ON</c> and <c>busy_timeout=5000</c>; file databases use <c>journal_mode=WAL</c>. Databases are files
/// under <c>KHAEMHAT_DATA_DIR</c>, or in-memory databases shared by the connections of the process (tests).
/// </summary>
public sealed class SqliteProvider : IDbProvider
{
private const int BusyTimeoutMilliseconds = 5000;
/// <inheritdoc />
public DbEngine Engine => DbEngine.Sqlite;
/// <inheritdoc />
public ISqlDialect Dialect => SqliteDialect.Instance;
/// <inheritdoc />
public DdlGenerator Ddl { get; } = new SqliteSchemaBuilder();
/// <inheritdoc />
public string BuildConnectionString(DatabaseUrl url)
{
ArgumentNullException.ThrowIfNull(url);
if (url.Engine != DbEngine.Sqlite)
{
throw new ArgumentException("Not a SQLite URL.", nameof(url));
}
var builder = url.IsInMemory
? new SqliteConnectionStringBuilder { DataSource = url.Database, Mode = SqliteOpenMode.Memory, Cache = SqliteCacheMode.Shared }
: new SqliteConnectionStringBuilder { DataSource = Path.GetFullPath(url.Database), Mode = SqliteOpenMode.ReadWriteCreate };
builder.Pooling = true;
builder.DefaultTimeout = 30;
return builder.ToString();
}
/// <inheritdoc />
public DbConnection CreateConnection(string connectionString)
{
var connection = new SqliteConnection(connectionString);
connection.CreateFunction<string?, string?>(SqliteDialect.LowerFunction, static s => s?.ToLowerInvariant(), isDeterministic: true);
var isFile = IsFile(connectionString);
connection.StateChange += (sender, args) =>
{
if (args.CurrentState == ConnectionState.Open && sender is SqliteConnection open)
{
ApplyPragmas(open, isFile);
}
};
return connection;
}
/// <inheritdoc />
public async Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
if (!IsFile(connectionString))
{
return;
}
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
await using var connection = CreateConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
{
if (!IsFile(connectionString))
{
return Task.CompletedTask;
}
using (var connection = new SqliteConnection(connectionString))
{
SqliteConnection.ClearPool(connection);
}
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
foreach (var file in new[] { path, path + "-wal", path + "-shm", path + "-journal" })
{
File.Delete(file);
}
return Task.CompletedTask;
}
/// <inheritdoc />
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
Task.FromResult(!IsFile(connectionString) || File.Exists(new SqliteConnectionStringBuilder(connectionString).DataSource));
/// <inheritdoc />
public async Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default)
{
await using var connection = CreateConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
var version = (string)(await ScalarAsync(connection, "SELECT sqlite_version()", cancellationToken).ConfigureAwait(false))!;
var pages = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_count", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var pageSize = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_size", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var journal = Convert.ToString(await ScalarAsync(connection, "PRAGMA journal_mode", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
var parts = version.Split('.').Select(p => int.Parse(p, CultureInfo.InvariantCulture)).Concat([0, 0, 0]).ToArray();
var source = new SqliteConnectionStringBuilder(connectionString).DataSource;
return new DbServerInfo(
DbEngine.Sqlite, version, (parts[0] * 1_000_000) + (parts[1] * 1_000) + parts[2],
IsFile(connectionString) ? Path.GetFileNameWithoutExtension(source) : source, pages * pageSize)
{
Details = ["journal_mode=" + journal],
};
}
/// <inheritdoc />
public bool IsTransient(Exception exception) =>
exception is SqliteException { SqliteErrorCode: 5 or 6 }; // SQLITE_BUSY, SQLITE_LOCKED
/// <inheritdoc />
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
SqliteWriteLock.AcquireAsync(new SqliteConnectionStringBuilder(connectionString).DataSource, cancellationToken);
private static bool IsFile(string connectionString) =>
new SqliteConnectionStringBuilder(connectionString).Mode != SqliteOpenMode.Memory;
private static void ApplyPragmas(SqliteConnection connection, bool isFile)
{
using var command = connection.CreateCommand();
command.CommandText = isFile
? $"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};"
: $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};";
command.ExecuteNonQuery();
}
private static async Task<object?> ScalarAsync(DbConnection connection, string sql, CancellationToken cancellationToken)
{
await using var command = connection.CreateCommand();
command.CommandText = sql;
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
}
}