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
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:
1 parent
28e7a6e18a
commit
738c43ba0a
105 files changed
+8434
-73
No files matched your search
@@ -0,0 +1,39 @@
|
||||
namespace Khaemhat.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// SQLite has no exact decimal type: <c>Decimal(19,6)</c> values are stored as integers multiplied by 10⁶ (SPEC §5.2).
|
||||
/// Sums in SQL therefore stay exact integers and are scaled back when read. Values are rounded to 6 decimals half
|
||||
/// away from zero, like PostgreSQL <c>numeric(19,6)</c>. The usable range is ±9.2 x 10¹².
|
||||
/// </summary>
|
||||
public static class SqliteDecimalConverter
|
||||
{
|
||||
/// <summary>The scale factor, 10⁶.</summary>
|
||||
public const long Factor = 1_000_000;
|
||||
|
||||
/// <summary>The largest absolute value that can be stored.</summary>
|
||||
public static readonly decimal MaxValue = long.MaxValue / (decimal)Factor;
|
||||
|
||||
/// <summary>Converts a decimal to its scaled integer.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>The scaled integer.</returns>
|
||||
/// <exception cref="OverflowException">The value is beyond ±9.2 x 10¹².</exception>
|
||||
public static long ToScaled(decimal value)
|
||||
{
|
||||
var scaled = decimal.Round(value * Factor, 0, MidpointRounding.AwayFromZero);
|
||||
return scaled is > long.MaxValue or < long.MinValue
|
||||
? throw new OverflowException($"The amount exceeds the SQLite decimal range of ±{MaxValue:N0}.")
|
||||
: (long)scaled;
|
||||
}
|
||||
|
||||
/// <summary>Converts a scaled integer (or a scaled sum read as integer or real) back to a decimal.</summary>
|
||||
/// <param name="value">The stored value.</param>
|
||||
/// <returns>The decimal.</returns>
|
||||
public static decimal FromScaled(object value) => value switch
|
||||
{
|
||||
long l => (decimal)l / Factor,
|
||||
int i => (decimal)i / Factor,
|
||||
double d => (decimal)d / Factor,
|
||||
decimal m => m / Factor,
|
||||
_ => throw new InvalidCastException($"A {value.GetType().Name} is not a scaled SQLite decimal."),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// The SQLite dialect (SPEC §5.2): <c>STRICT</c> tables with <c>TEXT</c>, <c>INTEGER</c> and <c>BLOB</c>; decimals as
|
||||
/// integers x10⁶, dates <c>yyyy-MM-dd</c>, timestamps ISO 8601 UTC with microseconds, booleans 0/1, GUIDs as text.
|
||||
/// Case-insensitive search uses the <c>kh_lower</c> function registered on every connection, which lowers Unicode text
|
||||
/// (SQLite's own <c>LIKE</c> and <c>lower</c> only fold ASCII).
|
||||
/// </summary>
|
||||
public sealed class SqliteDialect : SqlDialectBase
|
||||
{
|
||||
/// <summary>The format of stored timestamps: fixed width, so text order is time order.</summary>
|
||||
public const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'";
|
||||
|
||||
/// <summary>The name of the Unicode lower-case function registered on connections.</summary>
|
||||
public const string LowerFunction = "kh_lower";
|
||||
|
||||
/// <summary>The shared instance.</summary>
|
||||
public static SqliteDialect Instance { get; } = new();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override DbEngine Engine => DbEngine.Sqlite;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string CurrentTimestampUtc => "strftime('%Y-%m-%dT%H:%M:%f000Z', 'now')";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern) =>
|
||||
SqlFragment.Literal(LowerFunction + "(") + column + SqlFragment.Literal(") LIKE " + LowerFunction + "(") + pattern
|
||||
+ SqlFragment.Literal(") ESCAPE '\\'");
|
||||
|
||||
/// <inheritdoc />
|
||||
public override SqlFragment AdvisoryLock(string key) => SqlFragment.Empty;
|
||||
|
||||
/// <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 or ColumnType.Int64 => value is Enum ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : ConvertTo<long>(value),
|
||||
ColumnType.Decimal => SqliteDecimalConverter.ToScaled(ConvertTo<decimal>(value)),
|
||||
ColumnType.Bool => ConvertTo<bool>(value) ? 1L : 0L,
|
||||
ColumnType.Date => ToDate(value).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
ColumnType.DateTimeUtc => ToUtc(value).ToString(TimestampFormat, CultureInfo.InvariantCulture),
|
||||
ColumnType.Guid => (value is Guid g ? g : Guid.Parse((string)value, CultureInfo.InvariantCulture)).ToString("D"),
|
||||
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 => SqliteDecimalConverter.FromScaled(value),
|
||||
ColumnType.Bool => ConvertTo<long>(value) != 0,
|
||||
ColumnType.Date => ToDate(value),
|
||||
ColumnType.DateTimeUtc => value is string s
|
||||
? DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal)
|
||||
: 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 string SqlType(ColumnType type, int? length, int? scale) => type switch
|
||||
{
|
||||
ColumnType.Int32 or ColumnType.Int64 or ColumnType.Decimal or ColumnType.Bool => "INTEGER",
|
||||
ColumnType.Bytes => "BLOB",
|
||||
_ => "TEXT",
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Literal(object? value, ColumnType type) => value switch
|
||||
{
|
||||
bool b => b ? "1" : "0",
|
||||
decimal d when type == ColumnType.Decimal => SqliteDecimalConverter.ToScaled(d).ToString(CultureInfo.InvariantCulture),
|
||||
_ => base.Literal(value, type),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using Khaemhat.Data.Schema;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Khaemhat.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// The SQLite engine (SPEC §1.3, §5.2): tests, demo, trial and read-only archives. Every connection gets
|
||||
/// <c>foreign_keys=ON</c> and <c>busy_timeout=5000</c>; file databases use <c>journal_mode=WAL</c>. Databases are files
|
||||
/// under <c>KHAEMHAT_DATA_DIR</c>, or in-memory databases shared by the connections of the process (tests).
|
||||
/// </summary>
|
||||
public sealed class SqliteProvider : IDbProvider
|
||||
{
|
||||
private const int BusyTimeoutMilliseconds = 5000;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbEngine Engine => DbEngine.Sqlite;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ISqlDialect Dialect => SqliteDialect.Instance;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DdlGenerator Ddl { get; } = new SqliteSchemaBuilder();
|
||||
|
||||
/// <inheritdoc />
|
||||
public string BuildConnectionString(DatabaseUrl url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
if (url.Engine != DbEngine.Sqlite)
|
||||
{
|
||||
throw new ArgumentException("Not a SQLite URL.", nameof(url));
|
||||
}
|
||||
|
||||
var builder = url.IsInMemory
|
||||
? new SqliteConnectionStringBuilder { DataSource = url.Database, Mode = SqliteOpenMode.Memory, Cache = SqliteCacheMode.Shared }
|
||||
: new SqliteConnectionStringBuilder { DataSource = Path.GetFullPath(url.Database), Mode = SqliteOpenMode.ReadWriteCreate };
|
||||
builder.Pooling = true;
|
||||
builder.DefaultTimeout = 30;
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbConnection CreateConnection(string connectionString)
|
||||
{
|
||||
var connection = new SqliteConnection(connectionString);
|
||||
connection.CreateFunction<string?, string?>(SqliteDialect.LowerFunction, static s => s?.ToLowerInvariant(), isDeterministic: true);
|
||||
var isFile = IsFile(connectionString);
|
||||
connection.StateChange += (sender, args) =>
|
||||
{
|
||||
if (args.CurrentState == ConnectionState.Open && sender is SqliteConnection open)
|
||||
{
|
||||
ApplyPragmas(open, isFile);
|
||||
}
|
||||
};
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IsFile(connectionString))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
await using var connection = CreateConnection(connectionString);
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IsFile(connectionString))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
using (var connection = new SqliteConnection(connectionString))
|
||||
{
|
||||
SqliteConnection.ClearPool(connection);
|
||||
}
|
||||
|
||||
var path = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
||||
foreach (var file in new[] { path, path + "-wal", path + "-shm", path + "-journal" })
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(!IsFile(connectionString) || File.Exists(new SqliteConnectionStringBuilder(connectionString).DataSource));
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var connection = CreateConnection(connectionString);
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var version = (string)(await ScalarAsync(connection, "SELECT sqlite_version()", cancellationToken).ConfigureAwait(false))!;
|
||||
var pages = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_count", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
||||
var pageSize = Convert.ToInt64(await ScalarAsync(connection, "PRAGMA page_size", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
||||
var journal = Convert.ToString(await ScalarAsync(connection, "PRAGMA journal_mode", cancellationToken).ConfigureAwait(false), CultureInfo.InvariantCulture);
|
||||
var parts = version.Split('.').Select(p => int.Parse(p, CultureInfo.InvariantCulture)).Concat([0, 0, 0]).ToArray();
|
||||
var source = new SqliteConnectionStringBuilder(connectionString).DataSource;
|
||||
return new DbServerInfo(
|
||||
DbEngine.Sqlite, version, (parts[0] * 1_000_000) + (parts[1] * 1_000) + parts[2],
|
||||
IsFile(connectionString) ? Path.GetFileNameWithoutExtension(source) : source, pages * pageSize)
|
||||
{
|
||||
Details = ["journal_mode=" + journal],
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsTransient(Exception exception) =>
|
||||
exception is SqliteException { SqliteErrorCode: 5 or 6 }; // SQLITE_BUSY, SQLITE_LOCKED
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
SqliteWriteLock.AcquireAsync(new SqliteConnectionStringBuilder(connectionString).DataSource, cancellationToken);
|
||||
|
||||
private static bool IsFile(string connectionString) =>
|
||||
new SqliteConnectionStringBuilder(connectionString).Mode != SqliteOpenMode.Memory;
|
||||
|
||||
private static void ApplyPragmas(SqliteConnection connection, bool isFile)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = isFile
|
||||
? $"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};"
|
||||
: $"PRAGMA foreign_keys=ON; PRAGMA busy_timeout={BusyTimeoutMilliseconds};";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
private static async Task<object?> ScalarAsync(DbConnection connection, string sql, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// DDL for SQLite (SPEC §21 <c>SqliteSchemaBuilder</c>): <c>STRICT</c> tables, <c>INTEGER PRIMARY KEY</c> for identity
|
||||
/// keys, and <c>CHECK</c> constraints that give text lengths and booleans the same limits as on PostgreSQL.
|
||||
/// </summary>
|
||||
public sealed class SqliteSchemaBuilder() : DdlGenerator(SqliteDialect.Instance)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override string TableOptions(TableDefinition table) => " STRICT";
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string IdentityPrimaryKey(ColumnDefinition column)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(column);
|
||||
return Dialect.Quote(column.Name) + " INTEGER PRIMARY KEY";
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string ColumnConstraints(ColumnDefinition column)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(column);
|
||||
var name = Dialect.Quote(column.Name);
|
||||
return column.Type switch
|
||||
{
|
||||
ColumnType.String => string.Create(CultureInfo.InvariantCulture, $" CHECK (length({name}) <= {column.Length})"),
|
||||
ColumnType.Bool => $" CHECK ({name} IN (0, 1))",
|
||||
_ => string.Empty,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Khaemhat.Data.Sqlite;
|
||||
|
||||
/// <summary>
|
||||
/// Serializes the writers of one SQLite database inside the process (SPEC §5.2). SQLite allows a single writer; waiting
|
||||
/// here is fairer and cheaper than retrying on <c>SQLITE_BUSY</c>. Other processes are kept out by
|
||||
/// <c>BEGIN IMMEDIATE</c> and <c>busy_timeout</c>. Do not open a second writing unit of work on the same database while
|
||||
/// holding one in the same flow: it would wait for itself.
|
||||
/// </summary>
|
||||
public static class SqliteWriteLock
|
||||
{
|
||||
private static readonly ConcurrentDictionary<string, SemaphoreSlim> Locks = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Waits for the write lock of a database.</summary>
|
||||
/// <param name="database">The database key: full file path, or the in-memory name.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The held lock; dispose it to release.</returns>
|
||||
public static async ValueTask<IAsyncDisposable> AcquireAsync(string database, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(database);
|
||||
var semaphore = Locks.GetOrAdd(database, static _ => new SemaphoreSlim(1, 1));
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new Releaser(semaphore);
|
||||
}
|
||||
|
||||
private sealed class Releaser(SemaphoreSlim semaphore) : IAsyncDisposable
|
||||
{
|
||||
private int _released;
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _released, 1) == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user