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

137 lines
5.2 KiB
C#

namespace Khaemhat.Data.Schema;
/// <summary>A column of a table, in engine-neutral form.</summary>
public sealed class ColumnDefinition
{
/// <summary>Creates a column definition.</summary>
/// <param name="name">The column name (snake_case).</param>
/// <param name="type">The logical type.</param>
public ColumnDefinition(string name, ColumnType type)
{
SqlNames.EnsureIdentifier(name);
Name = name;
Type = type;
}
/// <summary>The column name.</summary>
public string Name { get; }
/// <summary>The logical type.</summary>
public ColumnType Type { get; }
/// <summary>The maximum length, for <see cref="ColumnType.String"/>.</summary>
public int? Length { get; init; }
/// <summary>The scale, for <see cref="ColumnType.Decimal"/> (default 6).</summary>
public int? Scale { get; init; }
/// <summary>Whether the column accepts <c>NULL</c>.</summary>
public bool IsNullable { get; init; } = true;
/// <summary>Whether the column is an identity primary key (<c>id</c>).</summary>
public bool IsIdentity { get; init; }
/// <summary>A constant default value written as an SQL literal, or <see langword="null"/>.</summary>
public object? DefaultValue { get; init; }
/// <summary>Whether the default is the current UTC timestamp.</summary>
public bool DefaultsToCurrentTimestamp { get; init; }
/// <summary>The logical type as documented, for example <c>String(20)</c>.</summary>
public string TypeDescription => ColumnTypes.Describe(Type, Length, Scale);
}
/// <summary>An index.</summary>
/// <param name="Name">The index name (for example <c>ix_parties_name</c> or <c>ux_parties_code</c>).</param>
/// <param name="Table">The table.</param>
/// <param name="Columns">The indexed columns, in order.</param>
/// <param name="IsUnique">Whether the index is unique.</param>
public sealed record IndexDefinition(string Name, string Table, IReadOnlyList<string> Columns, bool IsUnique);
/// <summary>What happens to referencing rows when the referenced row is deleted.</summary>
public enum ReferentialAction
{
/// <summary>The delete is refused while referencing rows exist (default).</summary>
Restrict = 0,
/// <summary>Referencing rows are deleted too.</summary>
Cascade = 1,
/// <summary>The referencing column is set to <c>NULL</c>.</summary>
SetNull = 2,
}
/// <summary>A foreign key.</summary>
/// <param name="Name">The constraint name (for example <c>fk_party_addresses_party</c>).</param>
/// <param name="Columns">The referencing columns.</param>
/// <param name="ReferencedTable">The referenced table.</param>
/// <param name="ReferencedColumns">The referenced columns (usually <c>id</c>).</param>
/// <param name="OnDelete">The action on delete.</param>
public sealed record ForeignKeyDefinition(
string Name, IReadOnlyList<string> Columns, string ReferencedTable, IReadOnlyList<string> ReferencedColumns,
ReferentialAction OnDelete = ReferentialAction.Restrict);
/// <summary>A table, in engine-neutral form.</summary>
public sealed class TableDefinition
{
private readonly List<ColumnDefinition> _columns = [];
private readonly List<IndexDefinition> _indexes = [];
private readonly List<ForeignKeyDefinition> _foreignKeys = [];
/// <summary>Creates a table definition.</summary>
/// <param name="name">The table name (snake_case).</param>
public TableDefinition(string name)
{
SqlNames.EnsureIdentifier(name);
Name = name;
}
/// <summary>The table name.</summary>
public string Name { get; }
/// <summary>The columns in order.</summary>
public IReadOnlyList<ColumnDefinition> Columns => _columns;
/// <summary>The primary key columns (usually <c>id</c>).</summary>
public IReadOnlyList<string> PrimaryKey { get; internal set; } = [];
/// <summary>The indexes.</summary>
public IReadOnlyList<IndexDefinition> Indexes => _indexes;
/// <summary>The foreign keys.</summary>
public IReadOnlyList<ForeignKeyDefinition> ForeignKeys => _foreignKeys;
/// <summary>
/// The date column by whose year PostgreSQL may partition the table (SPEC §5.2, large tables); recorded now,
/// applied by a later migration with <c>PostgresPartitioning</c>.
/// </summary>
public string? PartitionByYearColumn { get; internal set; }
/// <summary>Finds a column by name.</summary>
/// <param name="name">The column name.</param>
/// <returns>The column, or <see langword="null"/>.</returns>
public ColumnDefinition? Column(string name) => _columns.Find(c => c.Name == name);
internal void AddColumn(ColumnDefinition column)
{
if (Column(column.Name) is not null)
{
throw new InvalidOperationException($"Column {column.Name} is defined twice in table {Name}.");
}
_columns.Add(column);
}
internal void ReplaceColumn(ColumnDefinition column)
{
var index = _columns.FindIndex(c => c.Name == column.Name);
_columns[index] = column;
}
internal void AddIndex(IndexDefinition index) => _indexes.Add(index);
internal void RemoveIndex(string name) => _indexes.RemoveAll(i => i.Name == name);
internal void AddForeignKey(ForeignKeyDefinition foreignKey) => _foreignKeys.Add(foreignKey);
}