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>
117 lines
4.5 KiB
C#
117 lines
4.5 KiB
C#
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;
|
|
}
|
|
}
|