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

127 lines
5.4 KiB
C#

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