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

131 lines
5.6 KiB
C#

using System.Data.Common;
using System.Globalization;
using Khaemhat.Data.Schema;
namespace Khaemhat.Data;
/// <summary>
/// The parts of <see cref="ISqlDialect"/> that SQLite (3.35 or later) and PostgreSQL write the same way: double-quoted
/// identifiers, <c>@name</c> parameters, <c>LIMIT/OFFSET</c>, <c>RETURNING</c> and <c>ON CONFLICT … DO UPDATE</c>.
/// </summary>
public abstract class SqlDialectBase : ISqlDialect
{
/// <inheritdoc />
public abstract DbEngine Engine { get; }
/// <inheritdoc />
public abstract string CurrentTimestampUtc { get; }
/// <inheritdoc />
public string Quote(string identifier)
{
SqlNames.EnsureIdentifier(identifier);
return "\"" + identifier + "\"";
}
/// <inheritdoc />
public string Parameter(string name) => "@" + name;
/// <inheritdoc />
public string Paging(int offset, int limit)
{
ArgumentOutOfRangeException.ThrowIfNegative(offset);
ArgumentOutOfRangeException.ThrowIfNegative(limit);
return string.Create(CultureInfo.InvariantCulture, $" LIMIT {limit} OFFSET {offset}");
}
/// <inheritdoc />
public string InsertReturningId(string table, IReadOnlyList<string> columns, IReadOnlyList<string> parameters, string keyColumn) =>
Insert(table, columns, parameters) + " RETURNING " + Quote(keyColumn);
/// <inheritdoc />
public string Upsert(
string table, IReadOnlyList<string> columns, IReadOnlyList<string> parameters,
IReadOnlyList<string> conflictColumns, IReadOnlyList<string> updateColumns)
{
ArgumentNullException.ThrowIfNull(conflictColumns);
ArgumentNullException.ThrowIfNull(updateColumns);
var conflict = string.Join(", ", conflictColumns.Select(Quote));
var action = updateColumns.Count == 0
? "DO NOTHING"
: "DO UPDATE SET " + string.Join(", ", updateColumns.Select(c => Quote(c) + " = excluded." + Quote(c)));
return Insert(table, columns, parameters) + " ON CONFLICT (" + conflict + ") " + action;
}
/// <inheritdoc />
public abstract SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern);
/// <inheritdoc />
public abstract SqlFragment AdvisoryLock(string key);
/// <inheritdoc />
public abstract object ToDbValue(object? value, ColumnType type);
/// <inheritdoc />
public abstract object? FromDbValue(object? value, ColumnType type);
/// <inheritdoc />
public abstract string SqlType(ColumnType type, int? length, int? scale);
/// <inheritdoc />
public virtual string Literal(object? value, ColumnType type) => value switch
{
null => "NULL",
string s => "'" + s.Replace("'", "''", StringComparison.Ordinal) + "'",
Enum e => "'" + e.ToString() + "'",
IFormattable f when type is ColumnType.Int32 or ColumnType.Int64 => f.ToString(null, CultureInfo.InvariantCulture),
_ => throw new NotSupportedException($"No SQL literal for a {value.GetType().Name} default of a {type} column."),
};
/// <inheritdoc />
public virtual void ConfigureParameter(DbParameter parameter, object? value, ColumnType? type)
{
ArgumentNullException.ThrowIfNull(parameter);
var logical = type ?? (value is null ? null : ColumnTypes.FromClrType(value.GetType()));
parameter.Value = logical is null ? value ?? DBNull.Value : ToDbValue(value, logical.Value);
}
/// <summary>Converts a value to <typeparamref name="T"/> with invariant culture, as drivers may widen numbers.</summary>
/// <typeparam name="T">The target type.</typeparam>
/// <param name="value">The value.</param>
/// <returns>The converted value.</returns>
protected static T ConvertTo<T>(object value) => (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
/// <summary>Converts a <see cref="DateTime"/> or <see cref="DateTimeOffset"/> to UTC. An unspecified kind is taken as UTC.</summary>
/// <param name="value">The value.</param>
/// <returns>The UTC instant.</returns>
protected static DateTime ToUtc(object value) => value switch
{
DateTime { Kind: DateTimeKind.Utc } d => d,
DateTime { Kind: DateTimeKind.Local } d => d.ToUniversalTime(),
DateTime d => DateTime.SpecifyKind(d, DateTimeKind.Utc),
DateTimeOffset o => o.UtcDateTime,
_ => throw new InvalidCastException($"A {value.GetType().Name} is not a timestamp."),
};
/// <summary>Converts a value to <see cref="DateOnly"/>.</summary>
/// <param name="value">A <see cref="DateOnly"/>, <see cref="DateTime"/> or <c>yyyy-MM-dd</c> text.</param>
/// <returns>The date.</returns>
protected static DateOnly ToDate(object value) => value switch
{
DateOnly d => d,
DateTime d => DateOnly.FromDateTime(d),
string s => DateOnly.ParseExact(s, "yyyy-MM-dd", CultureInfo.InvariantCulture),
_ => throw new InvalidCastException($"A {value.GetType().Name} is not a date."),
};
private string Insert(string table, IReadOnlyList<string> columns, IReadOnlyList<string> parameters)
{
ArgumentNullException.ThrowIfNull(columns);
ArgumentNullException.ThrowIfNull(parameters);
if (columns.Count != parameters.Count)
{
throw new ArgumentException("One parameter per column is required.", nameof(parameters));
}
return columns.Count == 0
? "INSERT INTO " + Quote(table) + " DEFAULT VALUES"
: "INSERT INTO " + Quote(table) + " (" + string.Join(", ", columns.Select(Quote)) + ") VALUES (" + string.Join(", ", parameters) + ")";
}
}