feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 13:11:34 +01:00
1 parent 28e7a6e18a
commit 738c43ba0a
105 files changed
+8434 -73

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Schema;
using Khaemhat.Data.Sqlite;
using Khaemhat.Data.SystemDatabase.Migrations;
namespace Khaemhat.Data.Tests;
[TestClass]
public sealed class DdlTests
{
private static readonly MigrationInfo Companies = MigrationCatalog.ForSystem().Migrations.Single(m => m.Type == typeof(M20261111_001_CreateSysCompanies));
[TestMethod]
public void Sqlite_UsesStrictTables_IntegerKeys_AndChecks()
{
var sql = MigrationRunner.Statements(Companies, new SqliteProvider());
Assert.AreEqual(
"""
CREATE TABLE "sys_companies" (
"id" INTEGER PRIMARY KEY,
"code" TEXT NOT NULL CHECK (length("code") <= 20),
"name" TEXT NOT NULL CHECK (length("name") <= 200),
"engine" TEXT NOT NULL CHECK (length("engine") <= 20),
"connection_string" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'Active' CHECK (length("status") <= 40),
"is_default" INTEGER NOT NULL DEFAULT 0 CHECK ("is_default" IN (0, 1)),
"notes" TEXT,
"created_at" TEXT NOT NULL,
"created_by" TEXT CHECK (length("created_by") <= 100),
"updated_at" TEXT,
"updated_by" TEXT CHECK (length("updated_by") <= 100),
"row_version" INTEGER NOT NULL DEFAULT 1
) STRICT
""".ReplaceLineEndings("\n"),
sql[0]);
Assert.AreEqual("CREATE UNIQUE INDEX \"ux_sys_companies_code\" ON \"sys_companies\" (\"code\")", sql[1]);
}
[TestMethod]
public void Postgres_UsesIdentity_AndNativeTypes()
{
var sql = MigrationRunner.Statements(Companies, new PostgresProvider());
StringAssert.Contains(sql[0], "\"id\" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
StringAssert.Contains(sql[0], "\"code\" varchar(20) NOT NULL");
StringAssert.Contains(sql[0], "\"is_default\" boolean NOT NULL DEFAULT FALSE");
StringAssert.Contains(sql[0], "\"created_at\" timestamptz NOT NULL");
Assert.DoesNotContain("STRICT", sql[0]);
}
[TestMethod]
public void AllTypes_MapAsSpecSection5_2Says()
{
var expected = new Dictionary<ColumnType, (string Postgres, string Sqlite)>
{
[ColumnType.String] = ("varchar(30)", "TEXT"),
[ColumnType.Text] = ("text", "TEXT"),
[ColumnType.Int32] = ("integer", "INTEGER"),
[ColumnType.Int64] = ("bigint", "INTEGER"),
[ColumnType.Decimal] = ("numeric(19,6)", "INTEGER"),
[ColumnType.Bool] = ("boolean", "INTEGER"),
[ColumnType.Date] = ("date", "TEXT"),
[ColumnType.DateTimeUtc] = ("timestamptz", "TEXT"),
[ColumnType.Guid] = ("uuid", "TEXT"),
[ColumnType.Bytes] = ("bytea", "BLOB"),
[ColumnType.Json] = ("jsonb", "TEXT"),
};
foreach (var (type, (postgres, sqlite)) in expected)
{
var length = type == ColumnType.String ? 30 : (int?)null;
Assert.AreEqual(postgres, PostgresDialect.Instance.SqlType(type, length, null), type.ToString());
Assert.AreEqual(sqlite, SqliteDialect.Instance.SqlType(type, length, null), type.ToString());
}
}
[TestMethod]
public void ForeignKeys_CompositeKeys_AndAlterTable()
{
var schema = new SchemaBuilder();
schema.CreateTable("parent_rows", t => t.Id());
schema.CreateTable("child_rows", t =>
{
t.Id();
t.Int64("parent_row_id").NotNull();
t.ForeignKey("fk_child_rows_parent", "parent_row_id", "parent_rows", ReferentialAction.Cascade);
});
schema.AlterTable("child_rows", t =>
{
t.Decimal("price", 2).NotNull().Default(0m);
t.Index("ix_child_rows_price", "price");
});
var sql = new PostgresSchemaBuilder().Generate(schema.Operations);
StringAssert.Contains(sql[1], "CONSTRAINT \"fk_child_rows_parent\" FOREIGN KEY (\"parent_row_id\") REFERENCES \"parent_rows\" (\"id\") ON DELETE CASCADE");
Assert.AreEqual("ALTER TABLE \"child_rows\" ADD COLUMN \"price\" numeric(19,2) NOT NULL DEFAULT 0", sql[2]);
Assert.AreEqual("CREATE INDEX \"ix_child_rows_price\" ON \"child_rows\" (\"price\")", sql[3]);
Assert.ThrowsExactly<NotSupportedException>(() => schema.AlterTable("child_rows", t => t.ForeignKey("fk_x", "id", "parent_rows")));
}
[TestMethod]
public void SchemaVersion_HasCompositeKey_AndIsCreatedIfMissing()
{
var sql = new SqliteSchemaBuilder().Generate([SchemaVersionStore.CreateOperation]);
StringAssert.StartsWith(sql[0], "CREATE TABLE IF NOT EXISTS \"schema_version\"");
StringAssert.Contains(sql[0], "CONSTRAINT \"pk_schema_version\" PRIMARY KEY (\"module\", \"version\")");
}
[TestMethod]
public void Partitioning_IsPrepared()
{
Assert.AreEqual(
"CREATE TABLE IF NOT EXISTS \"gl_entry_lines_2026\" PARTITION OF \"gl_entry_lines\" FOR VALUES FROM ('2026-01-01') TO ('2027-01-01')",
PostgresPartitioning.CreateYearPartition("gl_entry_lines", 2026));
Assert.AreEqual(" PARTITION BY RANGE (\"entry_date\")", PostgresPartitioning.PartitionClause("entry_date"));
}
}