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,26 @@
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Application locks on PostgreSQL (SPEC §5.2) for numerators, closings and the scheduler. The text key is hashed to
/// 64 bits by the server (<c>hashtextextended</c>); transaction locks are released by commit or rollback.
/// </summary>
public static class PostgresAdvisoryLocks
{
/// <summary>Waits for the lock and holds it until the end of the transaction.</summary>
/// <param name="key">The lock key.</param>
/// <returns>The statement.</returns>
public static SqlFragment TransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))");
}
/// <summary>Takes the lock if free, without waiting; the statement returns a boolean.</summary>
/// <param name="key">The lock key.</param>
/// <returns>The statement.</returns>
public static SqlFragment TryTransactionLock(string key)
{
ArgumentException.ThrowIfNullOrEmpty(key);
return SqlFragment.Of($"SELECT pg_try_advisory_xact_lock(hashtextextended({key}, 0))");
}
}
@@ -0,0 +1,92 @@
using System.Diagnostics.CodeAnalysis;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Creates and drops company databases on the server of <c>KHAEMHAT_DB_SERVER</c> (SPEC §5.4). It connects to the
/// maintenance database <c>postgres</c> with the same credentials. Database names are validated identifiers: they
/// cannot be parameters in DDL, so nothing else may reach the statement.
/// </summary>
public static class PostgresDatabaseCreator
{
private const string MaintenanceDatabase = "postgres";
/// <summary>Creates the database of <paramref name="connectionString"/> if it does not exist (UTF-8, from <c>template0</c>).</summary>
/// <param name="connectionString">The connection string of the database to create.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task EnsureExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
if (await ExistsAsync(connectionString, cancellationToken).ConfigureAwait(false))
{
return;
}
try
{
await ExecuteOnMaintenanceAsync(
connectionString, $"CREATE DATABASE \"{name}\" TEMPLATE template0 ENCODING 'UTF8'", cancellationToken).ConfigureAwait(false);
}
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.DuplicateDatabase)
{
// Created concurrently by another instance: the goal is reached.
}
}
/// <summary>Drops the database, closing its connections (<c>WITH (FORCE)</c>). Used only by the registry and restores.</summary>
/// <param name="connectionString">The connection string of the database to drop.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public static async Task DropAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
if (name == MaintenanceDatabase)
{
throw new InvalidOperationException("The maintenance database cannot be dropped.");
}
using (var connection = new NpgsqlConnection(connectionString))
{
NpgsqlConnection.ClearPool(connection);
}
await ExecuteOnMaintenanceAsync(connectionString, $"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", cancellationToken).ConfigureAwait(false);
}
/// <summary>Whether the database exists.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns><see langword="true"/> if it exists.</returns>
public static async Task<bool> ExistsAsync(string connectionString, CancellationToken cancellationToken = default)
{
var name = DatabaseName(connectionString);
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @name", connection);
command.Parameters.AddWithValue("name", name);
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is not null;
}
private static string DatabaseName(string connectionString)
{
var name = new NpgsqlConnectionStringBuilder(connectionString).Database ?? string.Empty;
return SqlNames.IsValidIdentifier(name)
? name
: throw new ArgumentException("The database name must be lower-case letters, digits and underscore.", nameof(connectionString));
}
private static string MaintenanceConnectionString(string connectionString) =>
new NpgsqlConnectionStringBuilder(connectionString) { Database = MaintenanceDatabase, Pooling = false }.ToString();
[SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
Justification = "The only variable part is a database name validated as a snake_case identifier.")]
private static async Task ExecuteOnMaintenanceAsync(string connectionString, string sql, CancellationToken cancellationToken)
{
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand(sql, connection);
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,126 @@
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Npgsql;
using NpgsqlTypes;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// The PostgreSQL dialect (SPEC §5.2): <c>varchar(n)/text/integer/bigint/numeric(19,6)/boolean/date/timestamptz/uuid/
/// bytea/jsonb</c>, <c>ILIKE</c> for case-insensitive search and <c>pg_advisory_xact_lock</c> for application locks.
/// Parameters get an explicit driver type, so <c>jsonb</c> and <c>timestamptz</c> columns accept them without casts.
/// </summary>
public sealed class PostgresDialect : SqlDialectBase
{
/// <summary>The shared instance.</summary>
public static PostgresDialect Instance { get; } = new();
/// <inheritdoc />
public override DbEngine Engine => DbEngine.PostgreSql;
/// <inheritdoc />
public override string CurrentTimestampUtc => "now()";
/// <inheritdoc />
public override SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern) =>
column + SqlFragment.Literal(" ILIKE ") + pattern + SqlFragment.Literal(" ESCAPE '\\'");
/// <inheritdoc />
public override SqlFragment AdvisoryLock(string key) => PostgresAdvisoryLocks.TransactionLock(key);
/// <inheritdoc />
public override object ToDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return DBNull.Value;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture)!,
ColumnType.Int32 => value is Enum ? Convert.ToInt32(value, CultureInfo.InvariantCulture) : ConvertTo<int>(value),
ColumnType.Int64 => value is Enum ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : ConvertTo<long>(value),
ColumnType.Decimal => ConvertTo<decimal>(value),
ColumnType.Bool => ConvertTo<bool>(value),
ColumnType.Date => ToDate(value),
ColumnType.DateTimeUtc => ToUtc(value),
ColumnType.Guid => value is Guid g ? g : Guid.Parse((string)value, CultureInfo.InvariantCulture),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override object? FromDbValue(object? value, ColumnType type)
{
if (value is null or DBNull)
{
return null;
}
return type switch
{
ColumnType.String or ColumnType.Text or ColumnType.Json => value as string ?? Convert.ToString(value, CultureInfo.InvariantCulture),
ColumnType.Int32 => ConvertTo<int>(value),
ColumnType.Int64 => ConvertTo<long>(value),
ColumnType.Decimal => ConvertTo<decimal>(value),
ColumnType.Bool => ConvertTo<bool>(value),
ColumnType.Date => ToDate(value),
ColumnType.DateTimeUtc => ToUtc(value),
ColumnType.Guid => value is Guid g ? g : Guid.Parse(Convert.ToString(value, CultureInfo.InvariantCulture)!, CultureInfo.InvariantCulture),
ColumnType.Bytes => (byte[])value,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
/// <inheritdoc />
public override string SqlType(ColumnType type, int? length, int? scale) => type switch
{
ColumnType.String => length is null ? "text" : string.Create(CultureInfo.InvariantCulture, $"varchar({length})"),
ColumnType.Text => "text",
ColumnType.Int32 => "integer",
ColumnType.Int64 => "bigint",
ColumnType.Decimal => string.Create(CultureInfo.InvariantCulture, $"numeric({ColumnTypes.DecimalPrecision},{scale ?? ColumnTypes.DecimalScale})"),
ColumnType.Bool => "boolean",
ColumnType.Date => "date",
ColumnType.DateTimeUtc => "timestamptz",
ColumnType.Guid => "uuid",
ColumnType.Bytes => "bytea",
ColumnType.Json => "jsonb",
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
/// <inheritdoc />
public override string Literal(object? value, ColumnType type) => value switch
{
bool b => b ? "TRUE" : "FALSE",
decimal d => d.ToString(CultureInfo.InvariantCulture),
_ => base.Literal(value, type),
};
/// <inheritdoc />
public override void ConfigureParameter(DbParameter parameter, object? value, ColumnType? type)
{
base.ConfigureParameter(parameter, value, type);
var logical = type ?? (value is null ? null : ColumnTypes.FromClrType(value.GetType()));
if (parameter is NpgsqlParameter npgsql && logical is not null)
{
npgsql.NpgsqlDbType = logical.Value switch
{
ColumnType.String or ColumnType.Text => NpgsqlDbType.Text,
ColumnType.Int32 => NpgsqlDbType.Integer,
ColumnType.Int64 => NpgsqlDbType.Bigint,
ColumnType.Decimal => NpgsqlDbType.Numeric,
ColumnType.Bool => NpgsqlDbType.Boolean,
ColumnType.Date => NpgsqlDbType.Date,
ColumnType.DateTimeUtc => NpgsqlDbType.TimestampTz,
ColumnType.Guid => NpgsqlDbType.Uuid,
ColumnType.Bytes => NpgsqlDbType.Bytea,
ColumnType.Json => NpgsqlDbType.Jsonb,
_ => npgsql.NpgsqlDbType,
};
}
}
}
@@ -0,0 +1,46 @@
using System.Globalization;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// Yearly range partitioning for the large tables (SPEC §5.2: <c>gl_entry_lines</c>, <c>inventory_entry_lines</c>,
/// <c>audit_log</c>, <c>sys_log</c>). Prepared, not active: tables record their partition column with
/// <c>TableBuilder.PartitionByYear</c>; when one exceeds 50 million rows a migration (through
/// <c>ISchemaBuilder.Sql</c>) recreates it partitioned using these statements and moves the rows.
/// </summary>
public static class PostgresPartitioning
{
/// <summary>The clause that makes a <c>CREATE TABLE</c> partitioned by range of <paramref name="column"/>.</summary>
/// <param name="column">The date or timestamp column.</param>
/// <returns>The clause, starting with a space.</returns>
public static string PartitionClause(string column) => " PARTITION BY RANGE (" + PostgresDialect.Instance.Quote(column) + ")";
/// <summary>The name of the partition of a year, for example <c>gl_entry_lines_2026</c>.</summary>
/// <param name="table">The partitioned table.</param>
/// <param name="year">The year.</param>
/// <returns>The partition name.</returns>
public static string PartitionName(string table, int year) => table + "_" + year.ToString(CultureInfo.InvariantCulture);
/// <summary>The statement creating the partition of one year if it does not exist.</summary>
/// <param name="table">The partitioned table.</param>
/// <param name="year">The year.</param>
/// <returns>The statement.</returns>
public static string CreateYearPartition(string table, int year)
{
ArgumentOutOfRangeException.ThrowIfLessThan(year, 1900);
ArgumentOutOfRangeException.ThrowIfGreaterThan(year, 9998);
var dialect = PostgresDialect.Instance;
return string.Create(
CultureInfo.InvariantCulture,
$"CREATE TABLE IF NOT EXISTS {dialect.Quote(PartitionName(table, year))} PARTITION OF {dialect.Quote(table)} FOR VALUES FROM ('{year:D4}-01-01') TO ('{year + 1:D4}-01-01')");
}
/// <summary>The statement creating the default partition, for rows outside the yearly ones.</summary>
/// <param name="table">The partitioned table.</param>
/// <returns>The statement.</returns>
public static string CreateDefaultPartition(string table)
{
var dialect = PostgresDialect.Instance;
return $"CREATE TABLE IF NOT EXISTS {dialect.Quote(table + "_default")} PARTITION OF {dialect.Quote(table)} DEFAULT";
}
}
@@ -0,0 +1,116 @@
using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>Settings of the PostgreSQL provider (SPEC §5.2), from the instance settings.</summary>
public sealed record PostgresProviderOptions
{
/// <summary>Maximum pooled connections per database (each database has its own pool).</summary>
public int MaxPoolSize { get; init; } = 20;
/// <summary>Server-side limit of a statement (<c>statement_timeout</c> of every session).</summary>
public TimeSpan StatementTimeout { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>The application name shown in <c>pg_stat_activity</c>.</summary>
public string ApplicationName { get; init; } = "khaemhat";
}
/// <summary>
/// The PostgreSQL engine (SPEC §1.3, §5.2), version 16 or later: one connection pool per database, a statement timeout
/// per session, databases created with <c>CREATE DATABASE</c> on the server (the role needs <c>CREATEDB</c>).
/// </summary>
/// <param name="options">The provider settings.</param>
public sealed class PostgresProvider(PostgresProviderOptions options) : IDbProvider
{
/// <summary>The oldest supported major version.</summary>
public const int MinimumMajorVersion = 16;
/// <summary>Creates the provider with default settings.</summary>
public PostgresProvider()
: this(new PostgresProviderOptions())
{
}
/// <inheritdoc />
public DbEngine Engine => DbEngine.PostgreSql;
/// <inheritdoc />
public ISqlDialect Dialect => PostgresDialect.Instance;
/// <inheritdoc />
public DdlGenerator Ddl { get; } = new PostgresSchemaBuilder();
/// <summary>The settings.</summary>
public PostgresProviderOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
/// <inheritdoc />
public string BuildConnectionString(DatabaseUrl url)
{
ArgumentNullException.ThrowIfNull(url);
if (url.Engine != DbEngine.PostgreSql)
{
throw new ArgumentException("Not a PostgreSQL URL.", nameof(url));
}
var builder = new NpgsqlConnectionStringBuilder
{
Host = url.Host,
Port = url.Port ?? 5432,
Username = url.UserName,
Password = url.Password,
Database = url.Database.Length == 0 ? "postgres" : url.Database,
MaxPoolSize = Options.MaxPoolSize,
ApplicationName = Options.ApplicationName,
Options = string.Create(CultureInfo.InvariantCulture, $"-c statement_timeout={(long)Options.StatementTimeout.TotalMilliseconds}"),
};
foreach (var (key, value) in url.Options)
{
try
{
builder[key] = value;
}
catch (ArgumentException)
{
throw new FormatException($"The PostgreSQL URL option '{key}' is not supported.");
}
}
return builder.ToString();
}
/// <inheritdoc />
public DbConnection CreateConnection(string connectionString) => new NpgsqlConnection(connectionString);
/// <inheritdoc />
public Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.EnsureExistsAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.DropAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresDatabaseCreator.ExistsAsync(connectionString, cancellationToken);
/// <inheritdoc />
public Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default) =>
PostgresServerInfo.ReadAsync(connectionString, cancellationToken);
/// <inheritdoc />
public bool IsTransient(Exception exception) => exception is NpgsqlException { IsTransient: true };
/// <inheritdoc />
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
ValueTask.FromResult<IAsyncDisposable>(NoScope.Instance);
private sealed class NoScope : IAsyncDisposable
{
public static NoScope Instance { get; } = new();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
@@ -0,0 +1,18 @@
using Khaemhat.Data.Schema;
namespace Khaemhat.Data.PostgreSql;
/// <summary>
/// DDL for PostgreSQL (SPEC §21 <c>PostgresSchemaBuilder</c>): identity keys are
/// <c>bigint GENERATED BY DEFAULT AS IDENTITY</c>, so restores and imports may still write explicit ids.
/// </summary>
public sealed class PostgresSchemaBuilder() : DdlGenerator(PostgresDialect.Instance)
{
/// <inheritdoc />
protected override string IdentityPrimaryKey(ColumnDefinition column)
{
ArgumentNullException.ThrowIfNull(column);
var type = column.Type == ColumnType.Int32 ? "integer" : "bigint";
return Dialect.Quote(column.Name) + " " + type + " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
}
}
@@ -0,0 +1,59 @@
using System.Globalization;
using Npgsql;
namespace Khaemhat.Data.PostgreSql;
/// <summary>Reads version, role, connections, size and extensions of a PostgreSQL database (SPEC §12.1).</summary>
public static class PostgresServerInfo
{
private const string Query = """
SELECT current_setting('server_version'),
current_setting('server_version_num')::int,
current_database(),
pg_database_size(current_database()),
current_user,
(SELECT rolcreatedb FROM pg_roles WHERE rolname = current_user),
(SELECT numbackends FROM pg_stat_database WHERE datname = current_database()),
current_setting('max_connections')::int,
(SELECT coalesce(string_agg(extname || ' ' || extversion, ',' ORDER BY extname), '') FROM pg_extension)
""";
/// <summary>Reads the information.</summary>
/// <param name="connectionString">The connection string of the database.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The information, with a warning below version 16 and when the role cannot create databases.</returns>
public static async Task<DbServerInfo> ReadAsync(string connectionString, CancellationToken cancellationToken = default)
{
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
await using var command = new NpgsqlCommand(Query, connection);
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
var versionNumber = reader.GetInt32(1);
var canCreate = !reader.IsDBNull(5) && reader.GetBoolean(5);
var warnings = new List<string>();
if (versionNumber / 10000 < PostgresProvider.MinimumMajorVersion)
{
warnings.Add(string.Create(
CultureInfo.InvariantCulture,
$"PostgreSQL {reader.GetString(0)} is older than {PostgresProvider.MinimumMajorVersion}, the oldest supported version; upgrade it (17 is recommended)."));
}
if (!canCreate)
{
warnings.Add($"The role {reader.GetString(4)} has no CREATEDB: new company databases must be created by an administrator.");
}
var extensions = reader.GetString(8);
return new DbServerInfo(DbEngine.PostgreSql, reader.GetString(0), versionNumber, reader.GetString(2), reader.GetInt64(3))
{
UserName = reader.GetString(4),
CanCreateDatabases = canCreate,
ActiveConnections = reader.IsDBNull(6) ? null : reader.GetInt32(6),
MaxConnections = reader.GetInt32(7),
Details = extensions.Length == 0 ? [] : extensions.Split(','),
Warnings = warnings,
};
}
}