Files
Khaemhat/src/Khaemhat.Data.PostgreSql/PostgresDatabaseCreator.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

93 lines
4.6 KiB
C#

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);
}
}