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,51 @@
|
||||
namespace Khaemhat.Core.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Thrown when a row changed (or was deleted) after it was read: the update found no row with the expected
|
||||
/// <c>row_version</c> (SPEC §5.2). The interface reloads and asks the user; the API answers <c>409</c>.
|
||||
/// </summary>
|
||||
public sealed class ConcurrencyException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception for a row of <paramref name="table"/>.</summary>
|
||||
/// <param name="table">The table name.</param>
|
||||
/// <param name="key">The primary key of the row, as text.</param>
|
||||
/// <param name="expectedVersion">The <c>row_version</c> the caller read.</param>
|
||||
public ConcurrencyException(string table, string key, long expectedVersion)
|
||||
: base($"The row {key} of {table} was changed or deleted by someone else (expected version {expectedVersion}).")
|
||||
{
|
||||
Table = table;
|
||||
Key = key;
|
||||
ExpectedVersion = expectedVersion;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message only.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public ConcurrencyException(string message) : base(message)
|
||||
{
|
||||
Table = string.Empty;
|
||||
Key = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message and an inner exception.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public ConcurrencyException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
Table = string.Empty;
|
||||
Key = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception without details.</summary>
|
||||
public ConcurrencyException() : this("The row was changed or deleted by someone else.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>The table of the row.</summary>
|
||||
public string Table { get; }
|
||||
|
||||
/// <summary>The primary key of the row, as text.</summary>
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>The <c>row_version</c> the caller read.</summary>
|
||||
public long ExpectedVersion { get; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Khaemhat.Core.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// Convenience base class for entities with an identity key and the audit columns. Entities may also implement
|
||||
/// <see cref="IEntity{TKey}"/> and <see cref="IAuditable"/> directly.
|
||||
/// </summary>
|
||||
/// <typeparam name="TKey">The key type.</typeparam>
|
||||
public abstract class Entity<TKey> : IEntity<TKey>, IAuditable
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public TKey Id { get; set; } = default!;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? CreatedBy { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? UpdatedBy { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public long RowVersion { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Khaemhat.Core.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// An entity with the audit columns of SPEC §5.2 (<c>created_at</c>, <c>created_by</c>, <c>updated_at</c>,
|
||||
/// <c>updated_by</c>) and the <c>row_version</c> used for optimistic concurrency. The data layer fills them; code above
|
||||
/// it only reads them.
|
||||
/// </summary>
|
||||
public interface IAuditable
|
||||
{
|
||||
/// <summary>When the row was inserted, in UTC.</summary>
|
||||
DateTime CreatedAt { get; set; }
|
||||
|
||||
/// <summary>Who inserted the row (user name, or a system actor such as <c>system</c>), when known.</summary>
|
||||
string? CreatedBy { get; set; }
|
||||
|
||||
/// <summary>When the row was last updated, in UTC; <see langword="null"/> if it never was.</summary>
|
||||
DateTime? UpdatedAt { get; set; }
|
||||
|
||||
/// <summary>Who last updated the row, when known.</summary>
|
||||
string? UpdatedBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Incremented by every update. An update succeeds only if the stored value still equals this one; otherwise the
|
||||
/// data layer throws <see cref="Common.ConcurrencyException"/>.
|
||||
/// </summary>
|
||||
long RowVersion { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Khaemhat.Core.Entities;
|
||||
|
||||
/// <summary>An entity whose rows can be created by the demo seeder and removed with it (SPEC §14, column <c>is_demo</c>).</summary>
|
||||
public interface IDemoMarkable
|
||||
{
|
||||
/// <summary><see langword="true"/> for rows created by the demo data seeder.</summary>
|
||||
bool IsDemo { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace Khaemhat.Core.Entities;
|
||||
|
||||
/// <summary>An entity with an identity of type <typeparamref name="TKey"/>, stored in the <c>id</c> column (SPEC §5.2).</summary>
|
||||
/// <typeparam name="TKey">The key type: <see cref="long"/> for identity keys, which is the default for every table.</typeparam>
|
||||
public interface IEntity<TKey>
|
||||
{
|
||||
/// <summary>The primary key. For identity keys it is the default value until the row is inserted.</summary>
|
||||
TKey Id { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// A company in the instance registry (<c>sys_companies</c>, SPEC §5.4): its code, name and the location of its own
|
||||
/// database. The location is stored encrypted and is never shown or logged.
|
||||
/// </summary>
|
||||
public sealed class Company : Entity<long>
|
||||
{
|
||||
/// <summary>Company code: upper-case letters, digits and underscore, 1 to 20 characters (database <c>khaemhat_code</c>).</summary>
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>Company name (ragione sociale).</summary>
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The database engine name: <c>Sqlite</c> or <c>PostgreSql</c>.</summary>
|
||||
public string Engine { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The database URL, encrypted with the instance key.</summary>
|
||||
public string ConnectionString { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The company state.</summary>
|
||||
public CompanyStatus Status { get; set; }
|
||||
|
||||
/// <summary>Whether this is the company opened by default.</summary>
|
||||
public bool IsDefault { get; set; }
|
||||
|
||||
/// <summary>Free notes for administrators.</summary>
|
||||
public string? Notes { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Khaemhat.Core.Instance;
|
||||
|
||||
/// <summary>State of a company database in the registry (SPEC §5.4, §12.1).</summary>
|
||||
public enum CompanyStatus
|
||||
{
|
||||
/// <summary>In use.</summary>
|
||||
Active = 0,
|
||||
|
||||
/// <summary>Maintenance in progress (migration, restore): nobody but administrators can open it.</summary>
|
||||
Maintenance = 1,
|
||||
|
||||
/// <summary>Readable only, for example an archive.</summary>
|
||||
ReadOnly = 2,
|
||||
|
||||
/// <summary>Kept but not available.</summary>
|
||||
Disabled = 3,
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Core.Instance;
|
||||
|
||||
/// <summary>An instance setting (<c>sys_settings</c>). Secret values are stored encrypted (<see cref="IsSecret"/>).</summary>
|
||||
public sealed class SystemSetting : Entity<long>
|
||||
{
|
||||
/// <summary>The setting key, for example <c>smtp.host</c>.</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>The value; encrypted when <see cref="IsSecret"/> is set.</summary>
|
||||
public string? Value { get; set; }
|
||||
|
||||
/// <summary>Whether <see cref="Value"/> is a secret encrypted with the instance key.</summary>
|
||||
public bool IsSecret { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Khaemhat.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts secrets stored in the databases (company connection strings, SMTP/PEC/S3/WebDAV passwords, tokens) with
|
||||
/// the instance key <c>KHAEMHAT_SECRET_KEY</c> (SPEC §5.4). The <c>purpose</c> binds a ciphertext to its use: a value
|
||||
/// protected for one purpose cannot be read back for another.
|
||||
/// </summary>
|
||||
public interface ISecretProtector
|
||||
{
|
||||
/// <summary>Encrypts <paramref name="plaintext"/>; the result is printable text safe to store in a column.</summary>
|
||||
/// <param name="plaintext">The secret.</param>
|
||||
/// <param name="purpose">What the secret is for, for example <c>company:DEMO:database</c>.</param>
|
||||
/// <returns>The protected value.</returns>
|
||||
string Protect(string plaintext, string purpose);
|
||||
|
||||
/// <summary>Decrypts a value produced by <see cref="Protect"/> with the same key and purpose.</summary>
|
||||
/// <param name="protectedValue">The protected value.</param>
|
||||
/// <param name="purpose">The purpose given to <see cref="Protect"/>.</param>
|
||||
/// <returns>The secret.</returns>
|
||||
/// <exception cref="SecretProtectionException">The value was protected with another key or purpose, or is damaged.</exception>
|
||||
string Unprotect(string protectedValue, string purpose);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Khaemhat.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// A secret could not be decrypted: wrong instance key, wrong purpose or damaged value. The message never contains
|
||||
/// the secret or the ciphertext.
|
||||
/// </summary>
|
||||
public sealed class SecretProtectionException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public SecretProtectionException() : base("The secret cannot be decrypted.")
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message.</summary>
|
||||
/// <param name="message">The message (never the secret).</param>
|
||||
public SecretProtectionException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message and a cause.</summary>
|
||||
/// <param name="message">The message (never the secret).</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public SecretProtectionException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>
|
||||
/// Application locks on PostgreSQL (SPEC §5.2) for numerators, closings and the scheduler. The text key is hashed to
|
||||
/// 64 bits by the server (<c>hashtextextended</c>); transaction locks are released by commit or rollback.
|
||||
/// </summary>
|
||||
public static class PostgresAdvisoryLocks
|
||||
{
|
||||
/// <summary>Waits for the lock and holds it until the end of the transaction.</summary>
|
||||
/// <param name="key">The lock key.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public static SqlFragment TransactionLock(string key)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(key);
|
||||
return SqlFragment.Of($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))");
|
||||
}
|
||||
|
||||
/// <summary>Takes the lock if free, without waiting; the statement returns a boolean.</summary>
|
||||
/// <param name="key">The lock key.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public static SqlFragment TryTransactionLock(string key)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(key);
|
||||
return SqlFragment.Of($"SELECT pg_try_advisory_xact_lock(hashtextextended({key}, 0))");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Npgsql;
|
||||
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>
|
||||
/// Creates and drops company databases on the server of <c>KHAEMHAT_DB_SERVER</c> (SPEC §5.4). It connects to the
|
||||
/// maintenance database <c>postgres</c> with the same credentials. Database names are validated identifiers: they
|
||||
/// cannot be parameters in DDL, so nothing else may reach the statement.
|
||||
/// </summary>
|
||||
public static class PostgresDatabaseCreator
|
||||
{
|
||||
private const string MaintenanceDatabase = "postgres";
|
||||
|
||||
/// <summary>Creates the database of <paramref name="connectionString"/> if it does not exist (UTF-8, from <c>template0</c>).</summary>
|
||||
/// <param name="connectionString">The connection string of the database to create.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task EnsureExistsAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var name = DatabaseName(connectionString);
|
||||
if (await ExistsAsync(connectionString, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ExecuteOnMaintenanceAsync(
|
||||
connectionString, $"CREATE DATABASE \"{name}\" TEMPLATE template0 ENCODING 'UTF8'", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.DuplicateDatabase)
|
||||
{
|
||||
// Created concurrently by another instance: the goal is reached.
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Drops the database, closing its connections (<c>WITH (FORCE)</c>). Used only by the registry and restores.</summary>
|
||||
/// <param name="connectionString">The connection string of the database to drop.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task DropAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var name = DatabaseName(connectionString);
|
||||
if (name == MaintenanceDatabase)
|
||||
{
|
||||
throw new InvalidOperationException("The maintenance database cannot be dropped.");
|
||||
}
|
||||
|
||||
using (var connection = new NpgsqlConnection(connectionString))
|
||||
{
|
||||
NpgsqlConnection.ClearPool(connection);
|
||||
}
|
||||
|
||||
await ExecuteOnMaintenanceAsync(connectionString, $"DROP DATABASE IF EXISTS \"{name}\" WITH (FORCE)", cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>Whether the database exists.</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> if it exists.</returns>
|
||||
public static async Task<bool> ExistsAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var name = DatabaseName(connectionString);
|
||||
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var command = new NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname = @name", connection);
|
||||
command.Parameters.AddWithValue("name", name);
|
||||
return await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is not null;
|
||||
}
|
||||
|
||||
private static string DatabaseName(string connectionString)
|
||||
{
|
||||
var name = new NpgsqlConnectionStringBuilder(connectionString).Database ?? string.Empty;
|
||||
return SqlNames.IsValidIdentifier(name)
|
||||
? name
|
||||
: throw new ArgumentException("The database name must be lower-case letters, digits and underscore.", nameof(connectionString));
|
||||
}
|
||||
|
||||
private static string MaintenanceConnectionString(string connectionString) =>
|
||||
new NpgsqlConnectionStringBuilder(connectionString) { Database = MaintenanceDatabase, Pooling = false }.ToString();
|
||||
|
||||
[SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
|
||||
Justification = "The only variable part is a database name validated as a snake_case identifier.")]
|
||||
private static async Task ExecuteOnMaintenanceAsync(string connectionString, string sql, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(MaintenanceConnectionString(connectionString));
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var command = new NpgsqlCommand(sql, connection);
|
||||
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>
|
||||
/// Yearly range partitioning for the large tables (SPEC §5.2: <c>gl_entry_lines</c>, <c>inventory_entry_lines</c>,
|
||||
/// <c>audit_log</c>, <c>sys_log</c>). Prepared, not active: tables record their partition column with
|
||||
/// <c>TableBuilder.PartitionByYear</c>; when one exceeds 50 million rows a migration (through
|
||||
/// <c>ISchemaBuilder.Sql</c>) recreates it partitioned using these statements and moves the rows.
|
||||
/// </summary>
|
||||
public static class PostgresPartitioning
|
||||
{
|
||||
/// <summary>The clause that makes a <c>CREATE TABLE</c> partitioned by range of <paramref name="column"/>.</summary>
|
||||
/// <param name="column">The date or timestamp column.</param>
|
||||
/// <returns>The clause, starting with a space.</returns>
|
||||
public static string PartitionClause(string column) => " PARTITION BY RANGE (" + PostgresDialect.Instance.Quote(column) + ")";
|
||||
|
||||
/// <summary>The name of the partition of a year, for example <c>gl_entry_lines_2026</c>.</summary>
|
||||
/// <param name="table">The partitioned table.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The partition name.</returns>
|
||||
public static string PartitionName(string table, int year) => table + "_" + year.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>The statement creating the partition of one year if it does not exist.</summary>
|
||||
/// <param name="table">The partitioned table.</param>
|
||||
/// <param name="year">The year.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public static string CreateYearPartition(string table, int year)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(year, 1900);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(year, 9998);
|
||||
var dialect = PostgresDialect.Instance;
|
||||
return string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"CREATE TABLE IF NOT EXISTS {dialect.Quote(PartitionName(table, year))} PARTITION OF {dialect.Quote(table)} FOR VALUES FROM ('{year:D4}-01-01') TO ('{year + 1:D4}-01-01')");
|
||||
}
|
||||
|
||||
/// <summary>The statement creating the default partition, for rows outside the yearly ones.</summary>
|
||||
/// <param name="table">The partitioned table.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public static string CreateDefaultPartition(string table)
|
||||
{
|
||||
var dialect = PostgresDialect.Instance;
|
||||
return $"CREATE TABLE IF NOT EXISTS {dialect.Quote(table + "_default")} PARTITION OF {dialect.Quote(table)} DEFAULT";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Data.Common;
|
||||
using System.Globalization;
|
||||
using Khaemhat.Data.Schema;
|
||||
using Npgsql;
|
||||
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>Settings of the PostgreSQL provider (SPEC §5.2), from the instance settings.</summary>
|
||||
public sealed record PostgresProviderOptions
|
||||
{
|
||||
/// <summary>Maximum pooled connections per database (each database has its own pool).</summary>
|
||||
public int MaxPoolSize { get; init; } = 20;
|
||||
|
||||
/// <summary>Server-side limit of a statement (<c>statement_timeout</c> of every session).</summary>
|
||||
public TimeSpan StatementTimeout { get; init; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
/// <summary>The application name shown in <c>pg_stat_activity</c>.</summary>
|
||||
public string ApplicationName { get; init; } = "khaemhat";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The PostgreSQL engine (SPEC §1.3, §5.2), version 16 or later: one connection pool per database, a statement timeout
|
||||
/// per session, databases created with <c>CREATE DATABASE</c> on the server (the role needs <c>CREATEDB</c>).
|
||||
/// </summary>
|
||||
/// <param name="options">The provider settings.</param>
|
||||
public sealed class PostgresProvider(PostgresProviderOptions options) : IDbProvider
|
||||
{
|
||||
/// <summary>The oldest supported major version.</summary>
|
||||
public const int MinimumMajorVersion = 16;
|
||||
|
||||
/// <summary>Creates the provider with default settings.</summary>
|
||||
public PostgresProvider()
|
||||
: this(new PostgresProviderOptions())
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbEngine Engine => DbEngine.PostgreSql;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ISqlDialect Dialect => PostgresDialect.Instance;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DdlGenerator Ddl { get; } = new PostgresSchemaBuilder();
|
||||
|
||||
/// <summary>The settings.</summary>
|
||||
public PostgresProviderOptions Options { get; } = options ?? throw new ArgumentNullException(nameof(options));
|
||||
|
||||
/// <inheritdoc />
|
||||
public string BuildConnectionString(DatabaseUrl url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
if (url.Engine != DbEngine.PostgreSql)
|
||||
{
|
||||
throw new ArgumentException("Not a PostgreSQL URL.", nameof(url));
|
||||
}
|
||||
|
||||
var builder = new NpgsqlConnectionStringBuilder
|
||||
{
|
||||
Host = url.Host,
|
||||
Port = url.Port ?? 5432,
|
||||
Username = url.UserName,
|
||||
Password = url.Password,
|
||||
Database = url.Database.Length == 0 ? "postgres" : url.Database,
|
||||
MaxPoolSize = Options.MaxPoolSize,
|
||||
ApplicationName = Options.ApplicationName,
|
||||
Options = string.Create(CultureInfo.InvariantCulture, $"-c statement_timeout={(long)Options.StatementTimeout.TotalMilliseconds}"),
|
||||
};
|
||||
foreach (var (key, value) in url.Options)
|
||||
{
|
||||
try
|
||||
{
|
||||
builder[key] = value;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
throw new FormatException($"The PostgreSQL URL option '{key}' is not supported.");
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbConnection CreateConnection(string connectionString) => new NpgsqlConnection(connectionString);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
PostgresDatabaseCreator.EnsureExistsAsync(connectionString, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
PostgresDatabaseCreator.DropAsync(connectionString, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
PostgresDatabaseCreator.ExistsAsync(connectionString, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
PostgresServerInfo.ReadAsync(connectionString, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsTransient(Exception exception) => exception is NpgsqlException { IsTransient: true };
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default) =>
|
||||
ValueTask.FromResult<IAsyncDisposable>(NoScope.Instance);
|
||||
|
||||
private sealed class NoScope : IAsyncDisposable
|
||||
{
|
||||
public static NoScope Instance { get; } = new();
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>
|
||||
/// DDL for PostgreSQL (SPEC §21 <c>PostgresSchemaBuilder</c>): identity keys are
|
||||
/// <c>bigint GENERATED BY DEFAULT AS IDENTITY</c>, so restores and imports may still write explicit ids.
|
||||
/// </summary>
|
||||
public sealed class PostgresSchemaBuilder() : DdlGenerator(PostgresDialect.Instance)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override string IdentityPrimaryKey(ColumnDefinition column)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(column);
|
||||
var type = column.Type == ColumnType.Int32 ? "integer" : "bigint";
|
||||
return Dialect.Quote(column.Name) + " " + type + " GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Globalization;
|
||||
using Npgsql;
|
||||
|
||||
namespace Khaemhat.Data.PostgreSql;
|
||||
|
||||
/// <summary>Reads version, role, connections, size and extensions of a PostgreSQL database (SPEC §12.1).</summary>
|
||||
public static class PostgresServerInfo
|
||||
{
|
||||
private const string Query = """
|
||||
SELECT current_setting('server_version'),
|
||||
current_setting('server_version_num')::int,
|
||||
current_database(),
|
||||
pg_database_size(current_database()),
|
||||
current_user,
|
||||
(SELECT rolcreatedb FROM pg_roles WHERE rolname = current_user),
|
||||
(SELECT numbackends FROM pg_stat_database WHERE datname = current_database()),
|
||||
current_setting('max_connections')::int,
|
||||
(SELECT coalesce(string_agg(extname || ' ' || extversion, ',' ORDER BY extname), '') FROM pg_extension)
|
||||
""";
|
||||
|
||||
/// <summary>Reads the information.</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The information, with a warning below version 16 and when the role cannot create databases.</returns>
|
||||
public static async Task<DbServerInfo> ReadAsync(string connectionString, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var connection = new NpgsqlConnection(connectionString);
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var command = new NpgsqlCommand(Query, connection);
|
||||
await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
|
||||
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var versionNumber = reader.GetInt32(1);
|
||||
var canCreate = !reader.IsDBNull(5) && reader.GetBoolean(5);
|
||||
var warnings = new List<string>();
|
||||
if (versionNumber / 10000 < PostgresProvider.MinimumMajorVersion)
|
||||
{
|
||||
warnings.Add(string.Create(
|
||||
CultureInfo.InvariantCulture,
|
||||
$"PostgreSQL {reader.GetString(0)} is older than {PostgresProvider.MinimumMajorVersion}, the oldest supported version; upgrade it (17 is recommended)."));
|
||||
}
|
||||
|
||||
if (!canCreate)
|
||||
{
|
||||
warnings.Add($"The role {reader.GetString(4)} has no CREATEDB: new company databases must be created by an administrator.");
|
||||
}
|
||||
|
||||
var extensions = reader.GetString(8);
|
||||
return new DbServerInfo(DbEngine.PostgreSql, reader.GetString(0), versionNumber, reader.GetString(2), reader.GetInt64(3))
|
||||
{
|
||||
UserName = reader.GetString(4),
|
||||
CanCreateDatabases = canCreate,
|
||||
ActiveConnections = reader.IsDBNull(6) ? null : reader.GetInt32(6),
|
||||
MaxConnections = reader.GetInt32(7),
|
||||
Details = extensions.Length == 0 ? [] : extensions.Split(','),
|
||||
Warnings = warnings,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data.Execution;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Data.Companies;
|
||||
|
||||
/// <summary>A company to add to the registry.</summary>
|
||||
/// <param name="Code">The company code.</param>
|
||||
/// <param name="Name">The company name.</param>
|
||||
/// <param name="Database">Where its database is (printed redacted).</param>
|
||||
/// <param name="IsDefault">Whether it becomes the default company.</param>
|
||||
/// <param name="Notes">Notes for administrators.</param>
|
||||
public sealed record CompanyRegistration(string Code, string Name, DatabaseUrl Database, bool IsDefault = false, string? Notes = null);
|
||||
|
||||
/// <summary>
|
||||
/// The company registry in the system database (SPEC §5.4): it resolves <c>company code → (provider, connection
|
||||
/// string)</c>, decrypting the location stored in <c>sys_companies</c>.
|
||||
/// </summary>
|
||||
public interface ICompanyRegistry
|
||||
{
|
||||
/// <summary>All companies, by code.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The companies (their location stays encrypted).</returns>
|
||||
Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>A company by code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The company, or <see langword="null"/>.</returns>
|
||||
Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Adds a company whose database already exists or will be created by the caller.</summary>
|
||||
/// <param name="registration">The company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The stored company.</returns>
|
||||
Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The database of a company.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The target.</returns>
|
||||
/// <exception cref="KeyNotFoundException">No company has that code.</exception>
|
||||
Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Changes the state of a company.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <param name="status">The new state.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ICompanyRegistry"/> on <c>sys_companies</c>. The database URL is encrypted with
|
||||
/// <see cref="ISecretProtector"/> for the purpose <c>company:<code>:database</c>, so a row copied to another company
|
||||
/// cannot be decrypted. Resolved targets are cached until the row changes through this registry.
|
||||
/// </summary>
|
||||
public sealed class CompanyRegistry : ICompanyRegistry
|
||||
{
|
||||
private readonly DatabaseTarget _system;
|
||||
private readonly DbProviderCatalog _providers;
|
||||
private readonly ISecretProtector _protector;
|
||||
private readonly MapRegistry _maps;
|
||||
private readonly DataAccessContext _context;
|
||||
private readonly ConcurrentDictionary<string, DatabaseTarget> _resolved = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Creates the registry.</summary>
|
||||
/// <param name="system">The system database.</param>
|
||||
/// <param name="providers">The providers by engine.</param>
|
||||
/// <param name="protector">Encrypts the database locations.</param>
|
||||
/// <param name="maps">The entity maps, including <see cref="SystemDatabase.CompanyMap"/>.</param>
|
||||
/// <param name="context">Clock, user and retry policy.</param>
|
||||
public CompanyRegistry(DatabaseTarget system, DbProviderCatalog providers, ISecretProtector protector, MapRegistry maps, DataAccessContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(system);
|
||||
ArgumentNullException.ThrowIfNull(providers);
|
||||
ArgumentNullException.ThrowIfNull(protector);
|
||||
ArgumentNullException.ThrowIfNull(maps);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
_system = system;
|
||||
_providers = providers;
|
||||
_protector = protector;
|
||||
_maps = maps;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
/// <summary>The purpose used to encrypt the database location of a company.</summary>
|
||||
/// <param name="code">The normalized code.</param>
|
||||
/// <returns>The purpose.</returns>
|
||||
public static string Purpose(string code) => "company:" + code + ":database";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var page = await unitOfWork.Repository<Company, long>().ListAsync(Query.For<Company>().OrderBy(c => c.Code), cancellationToken).ConfigureAwait(false);
|
||||
return page.Items;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalized = CompanyCodes.Normalize(code);
|
||||
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
return await unitOfWork.Repository<Company, long>().FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(registration);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(registration.Name);
|
||||
var code = CompanyCodes.Normalize(registration.Code);
|
||||
_ = _providers.Get(registration.Database.Engine);
|
||||
|
||||
var company = new Company
|
||||
{
|
||||
Code = code,
|
||||
Name = registration.Name.Trim(),
|
||||
Engine = registration.Database.Engine.ToString(),
|
||||
ConnectionString = _protector.Protect(registration.Database.ToUnredactedString(), Purpose(code)),
|
||||
Status = CompanyStatus.Active,
|
||||
IsDefault = registration.IsDefault,
|
||||
Notes = registration.Notes,
|
||||
};
|
||||
|
||||
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var companies = unitOfWork.Repository<Company, long>();
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
if (await companies.CountAsync(Query.For<Company>().Where(c => c.Code == code), ct).ConfigureAwait(false) > 0)
|
||||
{
|
||||
throw new InvalidOperationException($"A company with code {code} already exists.");
|
||||
}
|
||||
|
||||
if (company.IsDefault)
|
||||
{
|
||||
await unitOfWork.ExecuteAsync(
|
||||
SqlFragment.Of($"UPDATE {SqlFragment.Identifier("sys_companies")} SET is_default = {false} WHERE is_default = {true}"), ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await companies.InsertAsync(company, ct).ConfigureAwait(false);
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_resolved.TryRemove(code, out _);
|
||||
return company;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalized = CompanyCodes.Normalize(code);
|
||||
if (_resolved.TryGetValue(normalized, out var cached))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
|
||||
var company = await FindAsync(normalized, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"No company has code {normalized}.");
|
||||
var url = DatabaseUrl.Parse(_protector.Unprotect(company.ConnectionString, Purpose(normalized)));
|
||||
var target = _providers.Resolve(url);
|
||||
_resolved[normalized] = target;
|
||||
return target;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var normalized = CompanyCodes.Normalize(code);
|
||||
await using var unitOfWork = await OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var companies = unitOfWork.Repository<Company, long>();
|
||||
var company = await companies.FindAsync(Query.For<Company>().Where(c => c.Code == normalized), cancellationToken).ConfigureAwait(false)
|
||||
?? throw new KeyNotFoundException($"No company has code {normalized}.");
|
||||
company.Status = status;
|
||||
await companies.UpdateAsync(company, cancellationToken).ConfigureAwait(false);
|
||||
_resolved.TryRemove(normalized, out _);
|
||||
}
|
||||
|
||||
private Task<UnitOfWork> OpenAsync(CancellationToken cancellationToken) => UnitOfWork.OpenAsync(_system, _maps, _context, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Finds the system database, or a company database through the registry.</summary>
|
||||
/// <param name="system">The system database.</param>
|
||||
/// <param name="companies">The company registry.</param>
|
||||
public sealed class DatabaseLocator(DatabaseTarget system, ICompanyRegistry companies) : IDatabaseLocator
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<DatabaseTarget> LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
return scope.IsSystem ? system : await companies.ResolveAsync(scope.CompanyCode!, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Rules for company codes and the names of their databases (SPEC §5.4): the code is 1 to 20 upper-case letters,
|
||||
/// digits or underscores starting with a letter; the database is <c>khaemhat_<code in lower case></c>.
|
||||
/// </summary>
|
||||
public static partial class CompanyCodes
|
||||
{
|
||||
/// <summary>The prefix of every company database name.</summary>
|
||||
public const string DatabasePrefix = "khaemhat_";
|
||||
|
||||
/// <summary>Whether <paramref name="code"/> (already normalized) is a valid company code.</summary>
|
||||
/// <param name="code">The code.</param>
|
||||
/// <returns><see langword="true"/> if valid.</returns>
|
||||
public static bool IsValid(string? code) => code is not null && CodePattern().IsMatch(code);
|
||||
|
||||
/// <summary>Trims and upper-cases a code, then validates it.</summary>
|
||||
/// <param name="code">The code as typed.</param>
|
||||
/// <returns>The normalized code.</returns>
|
||||
/// <exception cref="ArgumentException">The code is not valid.</exception>
|
||||
public static string Normalize(string code)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(code);
|
||||
var normalized = code.Trim().ToUpperInvariant();
|
||||
if (!IsValid(normalized))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"A company code has 1 to 20 characters: letters, digits or underscore, starting with a letter.", nameof(code));
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/// <summary>The database name of a company, for example <c>khaemhat_demo</c> for <c>DEMO</c>.</summary>
|
||||
/// <param name="code">The company code.</param>
|
||||
/// <returns>The database name.</returns>
|
||||
public static string DatabaseName(string code) => DatabasePrefix + Normalize(code).ToLowerInvariant();
|
||||
|
||||
[GeneratedRegex("^[A-Z][A-Z0-9_]{0,19}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex CodePattern();
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Which database a unit of work opens (SPEC §5.4): the instance system database or the database of one company.
|
||||
/// </summary>
|
||||
public sealed record DatabaseScope
|
||||
{
|
||||
private DatabaseScope(string? companyCode) => CompanyCode = companyCode;
|
||||
|
||||
/// <summary>The system database (<c>KHAEMHAT_SYSTEM_DB</c>).</summary>
|
||||
public static DatabaseScope System { get; } = new((string?)null);
|
||||
|
||||
/// <summary>The company code, or <see langword="null"/> for the system database.</summary>
|
||||
public string? CompanyCode { get; }
|
||||
|
||||
/// <summary>Whether this is the system database.</summary>
|
||||
public bool IsSystem => CompanyCode is null;
|
||||
|
||||
/// <summary>The database of the company with the given code.</summary>
|
||||
/// <param name="code">The company code (case-insensitive; stored upper-case).</param>
|
||||
/// <returns>The scope.</returns>
|
||||
public static DatabaseScope Company(string code) => new(CompanyCodes.Normalize(code));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => CompanyCode is null ? "system" : "company " + CompanyCode;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// A database ready to be opened: its provider and driver connection string. <see cref="ToString"/> shows only the
|
||||
/// engine and the database name, never the connection string.
|
||||
/// </summary>
|
||||
public sealed class DatabaseTarget
|
||||
{
|
||||
/// <summary>Creates a target.</summary>
|
||||
/// <param name="provider">The provider.</param>
|
||||
/// <param name="connectionString">The driver connection string.</param>
|
||||
/// <param name="databaseName">The database name, for messages.</param>
|
||||
public DatabaseTarget(IDbProvider provider, string connectionString, string databaseName)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(provider);
|
||||
ArgumentException.ThrowIfNullOrEmpty(connectionString);
|
||||
Provider = provider;
|
||||
ConnectionString = connectionString;
|
||||
DatabaseName = databaseName ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>The provider.</summary>
|
||||
public IDbProvider Provider { get; }
|
||||
|
||||
/// <summary>The driver connection string. It contains credentials: never log it.</summary>
|
||||
public string ConnectionString { get; }
|
||||
|
||||
/// <summary>The database name.</summary>
|
||||
public string DatabaseName { get; }
|
||||
|
||||
/// <summary>The engine.</summary>
|
||||
public DbEngine Engine => Provider.Engine;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => Engine + " " + DatabaseName;
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// A database location in URL form, as given by <c>KHAEMHAT_SYSTEM_DB</c>, <c>KHAEMHAT_DB_SERVER</c> and the company
|
||||
/// registry (SPEC §6):
|
||||
/// <list type="bullet">
|
||||
/// <item><c>postgres://user:password@host:5432/database?sslmode=require</c> (also <c>postgresql://</c>; the database
|
||||
/// may be empty for a server URL);</item>
|
||||
/// <item><c>sqlite:///absolute/path/file.db</c> (on Windows <c>sqlite:///C:/path/file.db</c>);</item>
|
||||
/// <item><c>sqlite://memory/name</c>, an in-memory database shared by the connections of the process (tests).</item>
|
||||
/// </list>
|
||||
/// <see cref="ToString"/> never shows the password; parsing errors never echo the input.
|
||||
/// </summary>
|
||||
public sealed class DatabaseUrl
|
||||
{
|
||||
private const string SqliteMemoryPrefix = "sqlite://memory/";
|
||||
|
||||
private DatabaseUrl(
|
||||
DbEngine engine, string database, string? host, int? port, string? userName, string? password,
|
||||
IReadOnlyDictionary<string, string> options, bool isInMemory)
|
||||
{
|
||||
Engine = engine;
|
||||
Database = database;
|
||||
Host = host;
|
||||
Port = port;
|
||||
UserName = userName;
|
||||
Password = password;
|
||||
Options = options;
|
||||
IsInMemory = isInMemory;
|
||||
}
|
||||
|
||||
/// <summary>The engine.</summary>
|
||||
public DbEngine Engine { get; }
|
||||
|
||||
/// <summary>
|
||||
/// PostgreSQL: the database name (empty for a server URL). SQLite: the file path, or the name of the in-memory database.
|
||||
/// </summary>
|
||||
public string Database { get; }
|
||||
|
||||
/// <summary>PostgreSQL host.</summary>
|
||||
public string? Host { get; }
|
||||
|
||||
/// <summary>PostgreSQL port, when given.</summary>
|
||||
public int? Port { get; }
|
||||
|
||||
/// <summary>PostgreSQL user.</summary>
|
||||
public string? UserName { get; }
|
||||
|
||||
/// <summary>PostgreSQL password. Never printed by <see cref="ToString"/>.</summary>
|
||||
public string? Password { get; }
|
||||
|
||||
/// <summary>Query-string options, for example <c>sslmode</c>.</summary>
|
||||
public IReadOnlyDictionary<string, string> Options { get; }
|
||||
|
||||
/// <summary>Whether this is an in-memory SQLite database.</summary>
|
||||
public bool IsInMemory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The short database name: the PostgreSQL database, or the SQLite file name without extension (or the in-memory name).
|
||||
/// </summary>
|
||||
public string DatabaseName => Engine == DbEngine.PostgreSql || IsInMemory
|
||||
? Database
|
||||
: Path.GetFileNameWithoutExtension(Database);
|
||||
|
||||
/// <summary>Parses a database URL.</summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <returns>The parsed URL.</returns>
|
||||
/// <exception cref="FormatException">The URL is not valid (the message does not repeat it).</exception>
|
||||
public static DatabaseUrl Parse(string url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
return TryParse(url, out var result, out var error) ? result : throw new FormatException(error);
|
||||
}
|
||||
|
||||
/// <summary>Tries to parse a database URL.</summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <param name="result">The parsed URL.</param>
|
||||
/// <returns><see langword="true"/> if the URL is valid.</returns>
|
||||
public static bool TryParse(string? url, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out DatabaseUrl? result) =>
|
||||
TryParse(url, out result, out _);
|
||||
|
||||
/// <summary>
|
||||
/// The same server with another database: on PostgreSQL the database name changes; on SQLite the file
|
||||
/// <c><name>.db</c> in the same directory (or another in-memory database).
|
||||
/// </summary>
|
||||
/// <param name="databaseName">The database name, for example <c>khaemhat_demo</c>.</param>
|
||||
/// <returns>The new URL.</returns>
|
||||
public DatabaseUrl WithDatabase(string databaseName)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(databaseName);
|
||||
if (Engine == DbEngine.PostgreSql || IsInMemory)
|
||||
{
|
||||
return new DatabaseUrl(Engine, databaseName, Host, Port, UserName, Password, Options, IsInMemory);
|
||||
}
|
||||
|
||||
var directory = Path.GetDirectoryName(Database) ?? string.Empty;
|
||||
var path = directory.Length == 0 ? databaseName + ".db" : directory.Replace('\\', '/') + "/" + databaseName + ".db";
|
||||
return new DatabaseUrl(Engine, path, Host, Port, UserName, Password, Options, IsInMemory);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The complete URL including the password, for storing it encrypted. Never log or display the result.
|
||||
/// </summary>
|
||||
/// <returns>The URL.</returns>
|
||||
public string ToUnredactedString() => Format(includePassword: true);
|
||||
|
||||
/// <summary>The URL with the password replaced by <c>***</c>.</summary>
|
||||
/// <returns>The redacted URL.</returns>
|
||||
public override string ToString() => Format(includePassword: false);
|
||||
|
||||
private string Format(bool includePassword)
|
||||
{
|
||||
if (Engine == DbEngine.Sqlite)
|
||||
{
|
||||
return IsInMemory ? SqliteMemoryPrefix + Database : "sqlite://" + (Database.StartsWith('/') ? Database : "/" + Database);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder("postgres://");
|
||||
if (UserName is not null)
|
||||
{
|
||||
builder.Append(Uri.EscapeDataString(UserName));
|
||||
if (Password is not null)
|
||||
{
|
||||
builder.Append(':').Append(includePassword ? Uri.EscapeDataString(Password) : "***");
|
||||
}
|
||||
|
||||
builder.Append('@');
|
||||
}
|
||||
|
||||
builder.Append(Host);
|
||||
if (Port is not null)
|
||||
{
|
||||
builder.Append(':').Append(Port.Value.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
builder.Append('/').Append(Uri.EscapeDataString(Database));
|
||||
var separator = '?';
|
||||
foreach (var (key, value) in Options)
|
||||
{
|
||||
builder.Append(separator).Append(Uri.EscapeDataString(key)).Append('=').Append(Uri.EscapeDataString(value));
|
||||
separator = '&';
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static bool TryParse(string? url, out DatabaseUrl result, out string error)
|
||||
{
|
||||
result = null!;
|
||||
url = url?.Trim();
|
||||
if (string.IsNullOrEmpty(url))
|
||||
{
|
||||
error = "The database URL is empty.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (url.StartsWith("sqlite:", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return TryParseSqlite(url, out result, out error);
|
||||
}
|
||||
|
||||
if (url.StartsWith("postgres://", StringComparison.OrdinalIgnoreCase)
|
||||
|| url.StartsWith("postgresql://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return TryParsePostgres(url, out result, out error);
|
||||
}
|
||||
|
||||
error = "The database URL must start with postgres:// or sqlite://.";
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryParseSqlite(string url, out DatabaseUrl result, out string error)
|
||||
{
|
||||
result = null!;
|
||||
var empty = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
if (url.StartsWith(SqliteMemoryPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var name = url[SqliteMemoryPrefix.Length..];
|
||||
if (name.Length == 0 || name.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '_' or '-')))
|
||||
{
|
||||
error = "An in-memory SQLite URL is sqlite://memory/<name> with letters, digits, '-' or '_'.";
|
||||
return false;
|
||||
}
|
||||
|
||||
result = new DatabaseUrl(DbEngine.Sqlite, name, null, null, null, null, empty, isInMemory: true);
|
||||
error = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!url.StartsWith("sqlite:///", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
error = "A SQLite URL is sqlite:///<absolute path> (three slashes).";
|
||||
return false;
|
||||
}
|
||||
|
||||
var path = url["sqlite://".Length..].Replace('\\', '/');
|
||||
// sqlite:///C:/data/x.db -> C:/data/x.db
|
||||
if (path.Length >= 3 && path[0] == '/' && char.IsAsciiLetter(path[1]) && path[2] == ':')
|
||||
{
|
||||
path = path[1..];
|
||||
}
|
||||
|
||||
if (path.Length < 2 || path.EndsWith('/'))
|
||||
{
|
||||
error = "The SQLite URL has no file name.";
|
||||
return false;
|
||||
}
|
||||
|
||||
result = new DatabaseUrl(DbEngine.Sqlite, path, null, null, null, null, empty, isInMemory: false);
|
||||
error = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParsePostgres(string url, out DatabaseUrl result, out string error)
|
||||
{
|
||||
result = null!;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || string.IsNullOrEmpty(uri.Host))
|
||||
{
|
||||
error = "The PostgreSQL URL is not valid: expected postgres://user:password@host:port/database.";
|
||||
return false;
|
||||
}
|
||||
|
||||
string? user = null;
|
||||
string? password = null;
|
||||
if (uri.UserInfo.Length > 0)
|
||||
{
|
||||
var parts = uri.UserInfo.Split(':', 2);
|
||||
user = Uri.UnescapeDataString(parts[0]);
|
||||
password = parts.Length == 2 ? Uri.UnescapeDataString(parts[1]) : null;
|
||||
}
|
||||
|
||||
var database = Uri.UnescapeDataString(uri.AbsolutePath.Trim('/'));
|
||||
if (database.Contains('/', StringComparison.Ordinal))
|
||||
{
|
||||
error = "The PostgreSQL URL path must be a single database name.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var options = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
var query = uri.Query.TrimStart('?');
|
||||
if (query.Length > 0)
|
||||
{
|
||||
foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var kv = pair.Split('=', 2);
|
||||
options[Uri.UnescapeDataString(kv[0])] = kv.Length == 2 ? Uri.UnescapeDataString(kv[1]) : string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
result = new DatabaseUrl(
|
||||
DbEngine.PostgreSql, database, uri.Host, uri.IsDefaultPort || uri.Port < 0 ? null : uri.Port, user, password,
|
||||
options, isInMemory: false);
|
||||
error = string.Empty;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>The database engines Khaemhat supports (SPEC §1.3).</summary>
|
||||
public enum DbEngine
|
||||
{
|
||||
/// <summary>SQLite: tests, demo, trial and read-only archives.</summary>
|
||||
Sqlite = 0,
|
||||
|
||||
/// <summary>PostgreSQL 16 or later (17 recommended): real installations.</summary>
|
||||
PostgreSql = 1,
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>The providers available to the instance, by engine. The web host registers SQLite and PostgreSQL.</summary>
|
||||
public sealed class DbProviderCatalog
|
||||
{
|
||||
private readonly Dictionary<DbEngine, IDbProvider> _providers = [];
|
||||
|
||||
/// <summary>Creates a catalog with the given providers.</summary>
|
||||
/// <param name="providers">The providers.</param>
|
||||
public DbProviderCatalog(params IEnumerable<IDbProvider> providers)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(providers);
|
||||
foreach (var provider in providers)
|
||||
{
|
||||
_providers[provider.Engine] = provider;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The provider of an engine.</summary>
|
||||
/// <param name="engine">The engine.</param>
|
||||
/// <returns>The provider.</returns>
|
||||
/// <exception cref="InvalidOperationException">No provider is registered for the engine.</exception>
|
||||
public IDbProvider Get(DbEngine engine) =>
|
||||
_providers.TryGetValue(engine, out var provider)
|
||||
? provider
|
||||
: throw new InvalidOperationException($"No database provider is registered for {engine}.");
|
||||
|
||||
/// <summary>The target for a database URL: its provider and connection string.</summary>
|
||||
/// <param name="url">The URL.</param>
|
||||
/// <returns>The target.</returns>
|
||||
public DatabaseTarget Resolve(DatabaseUrl url)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(url);
|
||||
var provider = Get(url.Engine);
|
||||
return new DatabaseTarget(provider, provider.BuildConnectionString(url), url.DatabaseName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>Information about a database and its server, for the system status page (SPEC §12.1).</summary>
|
||||
/// <param name="Engine">The engine.</param>
|
||||
/// <param name="Version">The server version as text, for example <c>17.2</c> or <c>3.46.1</c>.</param>
|
||||
/// <param name="VersionNumber">The version as a number: PostgreSQL <c>server_version_num</c> (170002), SQLite (3046001).</param>
|
||||
/// <param name="Database">The database name.</param>
|
||||
/// <param name="SizeBytes">The database size in bytes, when known.</param>
|
||||
public sealed record DbServerInfo(DbEngine Engine, string Version, int VersionNumber, string Database, long? SizeBytes)
|
||||
{
|
||||
/// <summary>The user the application connects as (PostgreSQL).</summary>
|
||||
public string? UserName { get; init; }
|
||||
|
||||
/// <summary>Whether that user may create databases (PostgreSQL <c>CREATEDB</c>).</summary>
|
||||
public bool? CanCreateDatabases { get; init; }
|
||||
|
||||
/// <summary>Open connections to this database (PostgreSQL).</summary>
|
||||
public int? ActiveConnections { get; init; }
|
||||
|
||||
/// <summary>The server connection limit (PostgreSQL <c>max_connections</c>).</summary>
|
||||
public int? MaxConnections { get; init; }
|
||||
|
||||
/// <summary>Installed extensions (PostgreSQL) or the journal mode (SQLite).</summary>
|
||||
public IReadOnlyList<string> Details { get; init; } = [];
|
||||
|
||||
/// <summary>Problems to show to administrators, for example a PostgreSQL version below 16.</summary>
|
||||
public IReadOnlyList<string> Warnings { get; init; } = [];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>The kinds of statements the repositories cache.</summary>
|
||||
public enum CachedStatementKind
|
||||
{
|
||||
/// <summary><c>INSERT</c>, with <c>RETURNING</c> for identity keys.</summary>
|
||||
Insert = 0,
|
||||
|
||||
/// <summary><c>UPDATE … WHERE key = … [AND row_version = …]</c>.</summary>
|
||||
Update = 1,
|
||||
|
||||
/// <summary><c>DELETE … WHERE key = …</c>.</summary>
|
||||
Delete = 2,
|
||||
}
|
||||
|
||||
/// <summary>A cached statement: SQL text whose parameter <c>p{i}</c> takes the value of <see cref="Parameters"/>[i].</summary>
|
||||
/// <param name="Text">The SQL text.</param>
|
||||
/// <param name="Parameters">The columns whose values fill the parameters, in order.</param>
|
||||
public sealed record CachedStatement(string Text, IReadOnlyList<ColumnMap> Parameters);
|
||||
|
||||
/// <summary>
|
||||
/// The SQL text of the repository statements, built once per entity, statement and dialect and reused (SPEC §21,
|
||||
/// <c>CommandCache</c>).
|
||||
/// </summary>
|
||||
public static class CommandCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<(Type Entity, CachedStatementKind Kind, DbEngine Engine), CachedStatement> Statements = new();
|
||||
|
||||
/// <summary>The statement of a kind for an entity map and dialect.</summary>
|
||||
/// <param name="map">The entity map.</param>
|
||||
/// <param name="kind">The statement kind.</param>
|
||||
/// <param name="dialect">The dialect.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public static CachedStatement Get(IEntityMap map, CachedStatementKind kind, ISqlDialect dialect)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
ArgumentNullException.ThrowIfNull(dialect);
|
||||
return Statements.GetOrAdd((map.EntityType, kind, dialect.Engine), _ => Build(map, kind, dialect));
|
||||
}
|
||||
|
||||
private static CachedStatement Build(IEntityMap map, CachedStatementKind kind, ISqlDialect dialect)
|
||||
{
|
||||
string P(int index) => dialect.Parameter("p" + index.ToString(CultureInfo.InvariantCulture));
|
||||
switch (kind)
|
||||
{
|
||||
case CachedStatementKind.Insert:
|
||||
{
|
||||
var columns = map.Columns.Where(c => !(c.IsKey && c.IsIdentity)).ToList();
|
||||
var names = columns.Select(c => c.ColumnName).ToList();
|
||||
var placeholders = columns.Select((_, i) => P(i)).ToList();
|
||||
var text = map.Key.IsIdentity
|
||||
? dialect.InsertReturningId(map.Table, names, placeholders, map.Key.ColumnName)
|
||||
: InsertOnly(dialect, map.Table, names, placeholders);
|
||||
return new CachedStatement(text, columns);
|
||||
}
|
||||
|
||||
case CachedStatementKind.Update:
|
||||
{
|
||||
var set = map.Columns
|
||||
.Where(c => !c.IsKey && c.Audit is not (Mapping.AuditRole.CreatedAt or Mapping.AuditRole.CreatedBy or Mapping.AuditRole.RowVersion))
|
||||
.ToList();
|
||||
var assignments = set.Select((c, i) => dialect.Quote(c.ColumnName) + " = " + P(i)).ToList();
|
||||
var parameters = new List<ColumnMap>(set) { map.Key };
|
||||
var where = dialect.Quote(map.Key.ColumnName) + " = " + P(set.Count);
|
||||
if (map.RowVersion is { } version)
|
||||
{
|
||||
assignments.Add(dialect.Quote(version.ColumnName) + " = " + dialect.Quote(version.ColumnName) + " + 1");
|
||||
where += " AND " + dialect.Quote(version.ColumnName) + " = " + P(parameters.Count);
|
||||
parameters.Add(version);
|
||||
}
|
||||
|
||||
var text = "UPDATE " + dialect.Quote(map.Table) + " SET " + string.Join(", ", assignments) + " WHERE " + where;
|
||||
return new CachedStatement(text, parameters);
|
||||
}
|
||||
|
||||
case CachedStatementKind.Delete:
|
||||
return new CachedStatement(
|
||||
"DELETE FROM " + dialect.Quote(map.Table) + " WHERE " + dialect.Quote(map.Key.ColumnName) + " = " + P(0), [map.Key]);
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(kind), kind, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static string InsertOnly(ISqlDialect dialect, string table, IReadOnlyList<string> columns, IReadOnlyList<string> placeholders) =>
|
||||
"INSERT INTO " + dialect.Quote(table) + " (" + string.Join(", ", columns.Select(dialect.Quote)) + ") VALUES (" + string.Join(", ", placeholders) + ")";
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// What the data layer needs from the running application: the clock for audit timestamps, the current user for
|
||||
/// <c>created_by</c>/<c>updated_by</c>, and the retry policy. The web host builds it from <c>ICurrentUser</c> (M2).
|
||||
/// </summary>
|
||||
public sealed class DataAccessContext
|
||||
{
|
||||
private readonly Func<string?> _currentUser;
|
||||
|
||||
/// <summary>Creates a context.</summary>
|
||||
/// <param name="clock">The clock.</param>
|
||||
/// <param name="currentUser">Returns the current user name, or <see langword="null"/>.</param>
|
||||
/// <param name="retryPolicy">The retry policy for transient errors outside transactions.</param>
|
||||
public DataAccessContext(TimeProvider clock, Func<string?> currentUser, TransientRetryPolicy? retryPolicy = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(currentUser);
|
||||
Clock = clock;
|
||||
_currentUser = currentUser;
|
||||
RetryPolicy = retryPolicy ?? TransientRetryPolicy.Default;
|
||||
}
|
||||
|
||||
/// <summary>System clock, no user, default retries.</summary>
|
||||
public static DataAccessContext Default { get; } = new(TimeProvider.System, static () => null);
|
||||
|
||||
/// <summary>The clock.</summary>
|
||||
public TimeProvider Clock { get; }
|
||||
|
||||
/// <summary>The retry policy.</summary>
|
||||
public TransientRetryPolicy RetryPolicy { get; }
|
||||
|
||||
/// <summary>The current user name, or <see langword="null"/>.</summary>
|
||||
public string? CurrentUser => _currentUser();
|
||||
|
||||
/// <summary>The current UTC time, truncated to microseconds (the precision of PostgreSQL and of SQLite storage).</summary>
|
||||
public DateTime UtcNow => Truncate(Clock.GetUtcNow().UtcDateTime);
|
||||
|
||||
/// <summary>Truncates a timestamp to microseconds.</summary>
|
||||
/// <param name="value">The timestamp.</param>
|
||||
/// <returns>The truncated timestamp.</returns>
|
||||
public static DateTime Truncate(DateTime value) => new(value.Ticks - (value.Ticks % 10), value.Kind);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Creates driver commands from rendered SQL. This is the only place where command text is assigned: the text comes
|
||||
/// from <see cref="SqlFragment.Render"/> or from the <see cref="CommandCache"/>, both built from code and mapped
|
||||
/// names, and every value travels as a parameter.
|
||||
/// </summary>
|
||||
/// <param name="dialect">The dialect that configures parameters.</param>
|
||||
public sealed class DbExecutor(ISqlDialect dialect)
|
||||
{
|
||||
/// <summary>Creates a command for a fragment.</summary>
|
||||
/// <param name="connection">The open connection.</param>
|
||||
/// <param name="transaction">The transaction, if any.</param>
|
||||
/// <param name="sql">The fragment.</param>
|
||||
/// <returns>The command; the caller disposes it.</returns>
|
||||
public DbCommand CreateCommand(DbConnection connection, DbTransaction? transaction, SqlFragment sql)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sql);
|
||||
var rendered = sql.Render(dialect);
|
||||
return CreateCommand(connection, transaction, rendered.Text, rendered.Parameters);
|
||||
}
|
||||
|
||||
/// <summary>Creates a command for rendered text and its parameters.</summary>
|
||||
/// <param name="connection">The open connection.</param>
|
||||
/// <param name="transaction">The transaction, if any.</param>
|
||||
/// <param name="text">SQL text produced by the data layer.</param>
|
||||
/// <param name="parameters">The parameters.</param>
|
||||
/// <returns>The command; the caller disposes it.</returns>
|
||||
[SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
|
||||
Justification = "Text comes only from SqlFragment rendering or the command cache; values are always parameters (SPEC §5.2).")]
|
||||
public DbCommand CreateCommand(DbConnection connection, DbTransaction? transaction, string text, IEnumerable<SqlParameterValue> parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connection);
|
||||
ArgumentNullException.ThrowIfNull(parameters);
|
||||
var command = connection.CreateCommand();
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = text;
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
var dbParameter = command.CreateParameter();
|
||||
dbParameter.ParameterName = parameter.Name;
|
||||
dialect.ConfigureParameter(dbParameter, parameter.Value, parameter.Type);
|
||||
command.Parameters.Add(dbParameter);
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Data.Common;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Maps reader rows to objects (SPEC §21, <c>ReaderMapper<T></c>). The plan for a type and a column layout is
|
||||
/// built once and cached; rows are then mapped with compiled delegates. Supported targets:
|
||||
/// <list type="bullet">
|
||||
/// <item>scalars (numbers, text, dates, GUIDs, enums, nullable or not): the first column;</item>
|
||||
/// <item>entities with a registered map: columns matched by column name;</item>
|
||||
/// <item>other classes and records: settable properties, or the parameters of the public constructor, matched by
|
||||
/// snake_case name.</item>
|
||||
/// </list>
|
||||
/// Values pass through <see cref="ISqlDialect.FromDbValue"/>, so for example scaled SQLite decimals (sums included)
|
||||
/// come back as <see cref="decimal"/>.
|
||||
/// </summary>
|
||||
public static class ReaderMapper
|
||||
{
|
||||
private static readonly ConcurrentDictionary<(Type Type, DbEngine Engine, string Layout), Delegate> Plans = new();
|
||||
|
||||
/// <summary>The row mapper for <typeparamref name="T"/> and the columns of <paramref name="reader"/>.</summary>
|
||||
/// <typeparam name="T">The target type.</typeparam>
|
||||
/// <param name="reader">The reader, positioned before or on a row.</param>
|
||||
/// <param name="dialect">The dialect.</param>
|
||||
/// <param name="maps">The entity maps.</param>
|
||||
/// <returns>A function mapping the current row.</returns>
|
||||
public static Func<DbDataReader, T> For<T>(DbDataReader reader, ISqlDialect dialect, MapRegistry maps)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(reader);
|
||||
ArgumentNullException.ThrowIfNull(dialect);
|
||||
ArgumentNullException.ThrowIfNull(maps);
|
||||
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
|
||||
var key = (typeof(T), dialect.Engine, string.Join('|', columns));
|
||||
return (Func<DbDataReader, T>)Plans.GetOrAdd(key, _ => Build<T>(columns, dialect, maps));
|
||||
}
|
||||
|
||||
private static Func<DbDataReader, T> Build<T>(string[] columns, ISqlDialect dialect, MapRegistry maps)
|
||||
{
|
||||
var target = typeof(T);
|
||||
if (IsScalar(target))
|
||||
{
|
||||
var type = LogicalType(target);
|
||||
return reader => (T)ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(0), type), target)!;
|
||||
}
|
||||
|
||||
if (maps.Find(target) is { } map)
|
||||
{
|
||||
return BuildEntity<T>(columns, dialect, map);
|
||||
}
|
||||
|
||||
var constructor = target.GetConstructor(Type.EmptyTypes);
|
||||
return constructor is not null ? BuildProperties<T>(columns, dialect) : BuildConstructor<T>(columns, dialect);
|
||||
}
|
||||
|
||||
private static Func<DbDataReader, T> BuildEntity<T>(string[] columns, ISqlDialect dialect, IEntityMap map)
|
||||
{
|
||||
var slots = columns
|
||||
.Select((name, ordinal) => (Ordinal: ordinal, Column: map.FindByColumn(name)))
|
||||
.Where(s => s.Column is not null)
|
||||
.Select(s => (s.Ordinal, Column: s.Column!))
|
||||
.ToArray();
|
||||
return reader =>
|
||||
{
|
||||
var entity = map.CreateEntity();
|
||||
foreach (var (ordinal, column) in slots)
|
||||
{
|
||||
column.SetValue(entity, column.FromProvider(dialect.FromDbValue(reader.GetValue(ordinal), column.Type)));
|
||||
}
|
||||
|
||||
return (T)entity;
|
||||
};
|
||||
}
|
||||
|
||||
private static Func<DbDataReader, T> BuildProperties<T>(string[] columns, ISqlDialect dialect)
|
||||
{
|
||||
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => p.CanWrite && p.GetSetMethod() is not null)
|
||||
.ToDictionary(p => SqlNames.ToSnakeCase(p.Name), StringComparer.OrdinalIgnoreCase);
|
||||
var create = Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
|
||||
var slots = new List<(int Ordinal, ColumnType Type, Type Target, Action<T, object?> Set)>();
|
||||
for (var ordinal = 0; ordinal < columns.Length; ordinal++)
|
||||
{
|
||||
if (!properties.TryGetValue(columns[ordinal], out var property))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var instance = Expression.Parameter(typeof(T));
|
||||
var value = Expression.Parameter(typeof(object));
|
||||
var set = Expression.Lambda<Action<T, object?>>(
|
||||
Expression.Assign(Expression.Property(instance, property), Expression.Convert(value, property.PropertyType)), instance, value).Compile();
|
||||
slots.Add((ordinal, LogicalType(property.PropertyType), property.PropertyType, set));
|
||||
}
|
||||
|
||||
return reader =>
|
||||
{
|
||||
var item = create();
|
||||
foreach (var (ordinal, type, target, set) in slots)
|
||||
{
|
||||
set(item, ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(ordinal), type), target));
|
||||
}
|
||||
|
||||
return item;
|
||||
};
|
||||
}
|
||||
|
||||
private static Func<DbDataReader, T> BuildConstructor<T>(string[] columns, ISqlDialect dialect)
|
||||
{
|
||||
var constructor = typeof(T).GetConstructors().OrderByDescending(c => c.GetParameters().Length).FirstOrDefault()
|
||||
?? throw new InvalidOperationException($"{typeof(T).Name} has no public constructor to map rows to.");
|
||||
var parameters = constructor.GetParameters();
|
||||
var ordinals = parameters.Select(p =>
|
||||
{
|
||||
var index = Array.FindIndex(columns, c => string.Equals(c, SqlNames.ToSnakeCase(p.Name!), StringComparison.OrdinalIgnoreCase));
|
||||
return index >= 0
|
||||
? index
|
||||
: throw new InvalidOperationException($"{typeof(T).Name}: no column {SqlNames.ToSnakeCase(p.Name!)} for constructor parameter {p.Name}.");
|
||||
}).ToArray();
|
||||
var types = parameters.Select(p => LogicalType(p.ParameterType)).ToArray();
|
||||
var arguments = Expression.Parameter(typeof(object?[]));
|
||||
var create = Expression.Lambda<Func<object?[], T>>(
|
||||
Expression.New(constructor, parameters.Select((p, i) =>
|
||||
(Expression)Expression.Convert(Expression.ArrayIndex(arguments, Expression.Constant(i)), p.ParameterType))),
|
||||
arguments).Compile();
|
||||
|
||||
return reader =>
|
||||
{
|
||||
var values = new object?[parameters.Length];
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
values[i] = ClrConverter.ConvertTo(dialect.FromDbValue(reader.GetValue(ordinals[i]), types[i]), parameters[i].ParameterType);
|
||||
}
|
||||
|
||||
return create(values);
|
||||
};
|
||||
}
|
||||
|
||||
private static bool IsScalar(Type type)
|
||||
{
|
||||
var underlying = Nullable.GetUnderlyingType(type) ?? type;
|
||||
return underlying.IsEnum || ColumnTypes.FromClrType(underlying) is not null;
|
||||
}
|
||||
|
||||
private static ColumnType LogicalType(Type type)
|
||||
{
|
||||
var underlying = Nullable.GetUnderlyingType(type) ?? type;
|
||||
return underlying.IsEnum ? ColumnType.Text : ColumnTypes.FromClrType(underlying) ?? ColumnType.Text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System.Globalization;
|
||||
using Khaemhat.Core.Common;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// The repository of SPEC §5.1 for one entity type in one unit of work. Insert, update and delete statements are
|
||||
/// cached per dialect (<see cref="CommandCache"/>); queries go through <see cref="QueryBuilder{T}"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <typeparam name="TKey">The key type.</typeparam>
|
||||
public sealed class Repository<T, TKey> : IRepository<T, TKey>
|
||||
where T : class, IEntity<TKey>, new()
|
||||
{
|
||||
private readonly UnitOfWork _unitOfWork;
|
||||
private readonly EntityMap<T> _map;
|
||||
private readonly QueryBuilder<T> _builder;
|
||||
|
||||
internal Repository(UnitOfWork unitOfWork, EntityMap<T> map)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_map = map;
|
||||
_builder = new QueryBuilder<T>(map, unitOfWork.Dialect);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<T?> GetAsync(TKey id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(id);
|
||||
return _unitOfWork.QuerySingleAsync<T>(_builder.SelectByKey(id), cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<T?> FindAsync(Query<T> query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
return _unitOfWork.QuerySingleAsync<T>(_builder.Select(query.Take(1)), cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<PagedResult<T>> ListAsync(Query<T> query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var items = await _unitOfWork.QueryAsync<T>(_builder.Select(query), cancellationToken).ConfigureAwait(false);
|
||||
long total = query.Limit is null && query.Offset == 0
|
||||
? items.Count
|
||||
: await CountAsync(query, cancellationToken).ConfigureAwait(false);
|
||||
return new PagedResult<T>(items, total, query.Offset, query.Limit);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<int> CountAsync(Query<T> query, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
return (int)await _unitOfWork.QuerySingleAsync<long>(_builder.Count(query), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<TKey> InsertAsync(T entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entity);
|
||||
if (entity is IAuditable audit)
|
||||
{
|
||||
audit.CreatedAt = _unitOfWork.Context.UtcNow;
|
||||
audit.CreatedBy = _unitOfWork.Context.CurrentUser;
|
||||
audit.UpdatedAt = null;
|
||||
audit.UpdatedBy = null;
|
||||
audit.RowVersion = 1;
|
||||
}
|
||||
|
||||
var statement = CommandCache.Get(_map, CachedStatementKind.Insert, _unitOfWork.Dialect);
|
||||
var parameters = Parameters(statement, entity, overrides: null);
|
||||
if (!_map.Key.IsIdentity)
|
||||
{
|
||||
await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken).ConfigureAwait(false);
|
||||
return entity.Id;
|
||||
}
|
||||
|
||||
var generated = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteScalarAsync(ct), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var key = (TKey)ClrConverter.ConvertTo(_unitOfWork.Dialect.FromDbValue(generated, _map.Key.Type), typeof(TKey))!;
|
||||
entity.Id = key;
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task UpdateAsync(T entity, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entity);
|
||||
var statement = CommandCache.Get(_map, CachedStatementKind.Update, _unitOfWork.Dialect);
|
||||
var now = _unitOfWork.Context.UtcNow;
|
||||
var user = _unitOfWork.Context.CurrentUser;
|
||||
var overrides = new Dictionary<AuditRole, object?> { [AuditRole.UpdatedAt] = now, [AuditRole.UpdatedBy] = user };
|
||||
var parameters = Parameters(statement, entity, overrides);
|
||||
|
||||
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (affected == 0)
|
||||
{
|
||||
var version = entity is IAuditable a ? a.RowVersion : 0;
|
||||
throw new ConcurrencyException(_map.Table, Convert.ToString(entity.Id, CultureInfo.InvariantCulture) ?? string.Empty, version);
|
||||
}
|
||||
|
||||
if (entity is IAuditable audit)
|
||||
{
|
||||
audit.UpdatedAt = now;
|
||||
audit.UpdatedBy = user;
|
||||
audit.RowVersion++;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<bool> DeleteAsync(TKey id, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(id);
|
||||
var statement = CommandCache.Get(_map, CachedStatementKind.Delete, _unitOfWork.Dialect);
|
||||
var parameters = new[] { new SqlParameterValue("p0", _map.Key.ToProvider(id), _map.Key.Type) };
|
||||
var affected = await _unitOfWork.WriteAsync(statement.Text, parameters, (c, ct) => c.ExecuteNonQueryAsync(ct), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return affected > 0;
|
||||
}
|
||||
|
||||
private static List<SqlParameterValue> Parameters(CachedStatement statement, T entity, Dictionary<AuditRole, object?>? overrides)
|
||||
{
|
||||
var parameters = new List<SqlParameterValue>(statement.Parameters.Count);
|
||||
for (var i = 0; i < statement.Parameters.Count; i++)
|
||||
{
|
||||
var column = statement.Parameters[i];
|
||||
var value = overrides is not null && column.Audit != AuditRole.None && overrides.TryGetValue(column.Audit, out var replaced)
|
||||
? replaced
|
||||
: column.GetValue(entity);
|
||||
parameters.Add(new SqlParameterValue("p" + i.ToString(CultureInfo.InvariantCulture), column.ToProvider(value), column.Type));
|
||||
}
|
||||
|
||||
return parameters;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// Retries an operation that failed with a transient error (database busy, connection lost). It is applied only
|
||||
/// outside transactions: inside one, a retry could repeat half of the work, so the error goes to the caller.
|
||||
/// </summary>
|
||||
/// <param name="maxAttempts">Total attempts, at least 1.</param>
|
||||
/// <param name="baseDelay">Delay before the second attempt; it doubles each time.</param>
|
||||
public sealed class TransientRetryPolicy(int maxAttempts, TimeSpan baseDelay)
|
||||
{
|
||||
/// <summary>Three attempts, 100 ms then 200 ms apart.</summary>
|
||||
public static TransientRetryPolicy Default { get; } = new(3, TimeSpan.FromMilliseconds(100));
|
||||
|
||||
/// <summary>No retries.</summary>
|
||||
public static TransientRetryPolicy None { get; } = new(1, TimeSpan.Zero);
|
||||
|
||||
/// <summary>Total attempts.</summary>
|
||||
public int MaxAttempts { get; } = maxAttempts >= 1 ? maxAttempts : throw new ArgumentOutOfRangeException(nameof(maxAttempts));
|
||||
|
||||
/// <summary>Runs <paramref name="operation"/>, retrying when <paramref name="isTransient"/> says the error is transient.</summary>
|
||||
/// <typeparam name="T">The result type.</typeparam>
|
||||
/// <param name="operation">The operation.</param>
|
||||
/// <param name="isTransient">Classifies exceptions.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The result.</returns>
|
||||
public async Task<T> ExecuteAsync<T>(
|
||||
Func<CancellationToken, Task<T>> operation, Func<Exception, bool> isTransient, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operation);
|
||||
ArgumentNullException.ThrowIfNull(isTransient);
|
||||
var delay = baseDelay;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await operation(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (attempt < MaxAttempts && !cancellationToken.IsCancellationRequested && isTransient(ex))
|
||||
{
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
delay += delay;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>
|
||||
/// The unit of work of SPEC §5.1 over one open connection. Statements outside a transaction are retried on transient
|
||||
/// errors; on SQLite every write enters the database write scope (the whole transaction, or the single statement).
|
||||
/// </summary>
|
||||
public sealed class UnitOfWork : IUnitOfWork
|
||||
{
|
||||
private readonly Dictionary<Type, object> _repositories = [];
|
||||
private IAsyncDisposable? _writeScope;
|
||||
private bool _disposed;
|
||||
|
||||
private UnitOfWork(DatabaseTarget target, DbConnection connection, MapRegistry maps, DataAccessContext context)
|
||||
{
|
||||
Target = target;
|
||||
Connection = connection;
|
||||
Maps = maps;
|
||||
Context = context;
|
||||
Executor = new DbExecutor(target.Provider.Dialect);
|
||||
}
|
||||
|
||||
/// <summary>The database.</summary>
|
||||
public DatabaseTarget Target { get; }
|
||||
|
||||
/// <summary>The provider.</summary>
|
||||
public IDbProvider Provider => Target.Provider;
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbConnection Connection { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public DbTransaction? Transaction { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public ISqlDialect Dialect => Provider.Dialect;
|
||||
|
||||
/// <summary>The entity maps.</summary>
|
||||
public MapRegistry Maps { get; }
|
||||
|
||||
/// <summary>Clock, user and retry policy.</summary>
|
||||
public DataAccessContext Context { get; }
|
||||
|
||||
/// <summary>Creates commands.</summary>
|
||||
public DbExecutor Executor { get; }
|
||||
|
||||
/// <summary>Opens a unit of work on a database.</summary>
|
||||
/// <param name="target">The database.</param>
|
||||
/// <param name="maps">The entity maps.</param>
|
||||
/// <param name="context">Clock, user and retry policy.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The open unit of work.</returns>
|
||||
public static async Task<UnitOfWork> OpenAsync(
|
||||
DatabaseTarget target, MapRegistry maps, DataAccessContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(maps);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var connection = target.Provider.CreateConnection(target.ConnectionString);
|
||||
try
|
||||
{
|
||||
await context.RetryPolicy.ExecuteAsync(
|
||||
async ct =>
|
||||
{
|
||||
await connection.OpenAsync(ct).ConfigureAwait(false);
|
||||
return true;
|
||||
},
|
||||
target.Provider.IsTransient,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await connection.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
|
||||
return new UnitOfWork(target, connection, maps, context);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task BeginAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (Transaction is not null)
|
||||
{
|
||||
throw new InvalidOperationException("A transaction is already open on this unit of work.");
|
||||
}
|
||||
|
||||
_writeScope = await Provider.EnterWriteScopeAsync(Target.ConnectionString, cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
Transaction = await Connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await ReleaseWriteScopeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task CommitAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var transaction = Transaction ?? throw new InvalidOperationException("No transaction is open.");
|
||||
try
|
||||
{
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await EndTransactionAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task RollbackAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var transaction = Transaction ?? throw new InvalidOperationException("No transaction is open.");
|
||||
try
|
||||
{
|
||||
await transaction.RollbackAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await EndTransactionAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IRepository<T, TKey> Repository<T, TKey>()
|
||||
where T : class, IEntity<TKey>, new()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (!_repositories.TryGetValue(typeof(T), out var repository))
|
||||
{
|
||||
repository = new Repository<T, TKey>(this, Maps.Get<T>());
|
||||
_repositories[typeof(T)] = repository;
|
||||
}
|
||||
|
||||
return (IRepository<T, TKey>)repository;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<int> ExecuteAsync(SqlFragment sql, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sql);
|
||||
var rendered = sql.Render(Dialect);
|
||||
return WriteAsync(rendered.Text, rendered.Parameters, (command, ct) => command.ExecuteNonQueryAsync(ct), cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<T?> QuerySingleAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = await ReadAsync<T>(sql, single: true, cancellationToken).ConfigureAwait(false);
|
||||
return rows.Count == 0 ? default : rows[0];
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<T>> QueryAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default) =>
|
||||
ReadAsync<T>(sql, single: false, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DbDataReader> StreamAsync(SqlFragment sql, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var command = Executor.CreateCommand(Connection, Transaction, sql);
|
||||
try
|
||||
{
|
||||
return await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
await command.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
if (Transaction is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Transaction.RollbackAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
// The connection may already be broken; disposing it releases the transaction anyway.
|
||||
}
|
||||
|
||||
await EndTransactionAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await Connection.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a writing command: inside the transaction if there is one; otherwise inside the write scope, with retries
|
||||
/// on transient errors.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The result type.</typeparam>
|
||||
/// <param name="text">The SQL text.</param>
|
||||
/// <param name="parameters">The parameters.</param>
|
||||
/// <param name="run">Runs the command.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The result.</returns>
|
||||
internal async Task<T> WriteAsync<T>(
|
||||
string text, IEnumerable<SqlParameterValue> parameters, Func<DbCommand, CancellationToken, Task<T>> run, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (Transaction is not null)
|
||||
{
|
||||
await using var command = Executor.CreateCommand(Connection, Transaction, text, parameters);
|
||||
return await run(command, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var materialized = parameters.ToList();
|
||||
return await Context.RetryPolicy.ExecuteAsync(
|
||||
async ct =>
|
||||
{
|
||||
await using var scope = await Provider.EnterWriteScopeAsync(Target.ConnectionString, ct).ConfigureAwait(false);
|
||||
await using var command = Executor.CreateCommand(Connection, null, text, materialized);
|
||||
return await run(command, ct).ConfigureAwait(false);
|
||||
},
|
||||
Provider.IsTransient,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<T>> ReadAsync<T>(SqlFragment sql, bool single, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
ArgumentNullException.ThrowIfNull(sql);
|
||||
|
||||
async Task<IReadOnlyList<T>> Run(CancellationToken ct)
|
||||
{
|
||||
await using var command = Executor.CreateCommand(Connection, Transaction, sql);
|
||||
await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
|
||||
var rows = new List<T>();
|
||||
Func<DbDataReader, T>? map = null;
|
||||
while (await reader.ReadAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
map ??= ReaderMapper.For<T>(reader, Dialect, Maps);
|
||||
rows.Add(map(reader));
|
||||
if (single)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
return Transaction is not null
|
||||
? await Run(cancellationToken).ConfigureAwait(false)
|
||||
: await Context.RetryPolicy.ExecuteAsync(Run, Provider.IsTransient, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task EndTransactionAsync()
|
||||
{
|
||||
if (Transaction is not null)
|
||||
{
|
||||
await Transaction.DisposeAsync().ConfigureAwait(false);
|
||||
Transaction = null;
|
||||
}
|
||||
|
||||
await ReleaseWriteScopeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task ReleaseWriteScopeAsync()
|
||||
{
|
||||
if (_writeScope is not null)
|
||||
{
|
||||
await _writeScope.DisposeAsync().ConfigureAwait(false);
|
||||
_writeScope = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.Execution;
|
||||
|
||||
/// <summary>Opens <see cref="UnitOfWork"/>s on the database of a scope (SPEC §5.1).</summary>
|
||||
/// <param name="locator">Finds the database of a scope.</param>
|
||||
/// <param name="maps">The entity maps.</param>
|
||||
/// <param name="context">Clock, user and retry policy.</param>
|
||||
public sealed class UnitOfWorkFactory(IDatabaseLocator locator, MapRegistry maps, DataAccessContext context) : IUnitOfWorkFactory
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<IUnitOfWork> CreateAsync(DatabaseScope scope, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
var target = await locator.LocateAsync(scope, cancellationToken).ConfigureAwait(false);
|
||||
return await UnitOfWork.OpenAsync(target, maps, context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
[assembly: SuppressMessage(
|
||||
"Naming", "CA1720:Identifier contains type name", Scope = "namespaceanddescendants", Target = "~N:Khaemhat.Data.Schema",
|
||||
Justification = "The logical column types are named as in SPEC §5.2 (String, Int32, Int64, Decimal, Guid): they are the vocabulary of migrations and docs.")]
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// A database engine (SPEC §5.1): connections, DDL, creation and removal of databases, server information. Implemented
|
||||
/// by <c>SqliteProvider</c> and <c>PostgresProvider</c>.
|
||||
/// </summary>
|
||||
public interface IDbProvider
|
||||
{
|
||||
/// <summary>The engine.</summary>
|
||||
DbEngine Engine { get; }
|
||||
|
||||
/// <summary>The SQL dialect.</summary>
|
||||
ISqlDialect Dialect { get; }
|
||||
|
||||
/// <summary>The DDL generator used by migrations.</summary>
|
||||
DdlGenerator Ddl { get; }
|
||||
|
||||
/// <summary>The driver connection string for a database URL.</summary>
|
||||
/// <param name="url">The database URL (its engine must be <see cref="Engine"/>).</param>
|
||||
/// <returns>The connection string. It contains credentials: never log it.</returns>
|
||||
string BuildConnectionString(DatabaseUrl url);
|
||||
|
||||
/// <summary>Creates a closed connection. Session settings (pragmas, timeouts) are applied when it opens.</summary>
|
||||
/// <param name="connectionString">The connection string.</param>
|
||||
/// <returns>The connection.</returns>
|
||||
DbConnection CreateConnection(string connectionString);
|
||||
|
||||
/// <summary>Creates the database if it does not exist (<c>CREATE DATABASE</c>, or the SQLite file).</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task EnsureDatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Drops the database. Only the company registry and the restore service call it.</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Whether the database exists.</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> if it exists.</returns>
|
||||
Task<bool> DatabaseExistsAsync(string connectionString, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Version, size, connections and warnings of the server and database (SPEC §12.1).</summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The information.</returns>
|
||||
Task<DbServerInfo> GetServerInfoAsync(string connectionString, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Whether an exception is transient (busy, connection lost) and the statement may be retried outside a transaction.</summary>
|
||||
/// <param name="exception">The exception.</param>
|
||||
/// <returns><see langword="true"/> if transient.</returns>
|
||||
bool IsTransient(Exception exception);
|
||||
|
||||
/// <summary>
|
||||
/// Enters the write scope of a database: on SQLite it serializes writers of the process (<c>SqliteWriteLock</c>);
|
||||
/// on PostgreSQL it does nothing. Dispose the result to leave.
|
||||
/// </summary>
|
||||
/// <param name="connectionString">The connection string of the database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The scope.</returns>
|
||||
ValueTask<IAsyncDisposable> EnterWriteScopeAsync(string connectionString, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Data.Querying;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Reads and writes the rows of one entity type in the database of a unit of work (SPEC §5.1). Updates check
|
||||
/// <c>row_version</c> and throw <see cref="Core.Common.ConcurrencyException"/> on conflict.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <typeparam name="TKey">The key type.</typeparam>
|
||||
public interface IRepository<T, TKey>
|
||||
where T : class, IEntity<TKey>
|
||||
{
|
||||
/// <summary>The row with the given key.</summary>
|
||||
/// <param name="id">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entity, or <see langword="null"/>.</returns>
|
||||
Task<T?> GetAsync(TKey id, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The first row of a query.</summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The entity, or <see langword="null"/>.</returns>
|
||||
Task<T?> FindAsync(Query<T> query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The rows of a query, with the total count when it is paged.</summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The page.</returns>
|
||||
Task<PagedResult<T>> ListAsync(Query<T> query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The number of rows matching a query.</summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The count.</returns>
|
||||
Task<int> CountAsync(Query<T> query, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Inserts a row. Audit columns are filled, <c>row_version</c> starts at 1, an identity key is generated and set
|
||||
/// on the entity.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The key.</returns>
|
||||
Task<TKey> InsertAsync(T entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Updates a row if its <c>row_version</c> is still the one on the entity, then increments it on the entity.
|
||||
/// </summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
/// <exception cref="Core.Common.ConcurrencyException">The row changed or no longer exists.</exception>
|
||||
Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Deletes the row with the given key; nothing happens if it does not exist.</summary>
|
||||
/// <param name="id">The key.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> if a row was deleted.</returns>
|
||||
Task<bool> DeleteAsync(TKey id, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// What differs between SQL engines (SPEC §5.1): quoting, parameters, paging, insert/upsert forms, case-insensitive
|
||||
/// search, advisory locks, value conversion and physical types. Everything above the providers uses only this
|
||||
/// interface, so no code outside <c>Khaemhat.Data.Sqlite</c> and <c>Khaemhat.Data.PostgreSql</c> knows the engine.
|
||||
/// </summary>
|
||||
public interface ISqlDialect
|
||||
{
|
||||
/// <summary>The engine.</summary>
|
||||
DbEngine Engine { get; }
|
||||
|
||||
/// <summary>The current UTC timestamp, in the same form the dialect stores <see cref="ColumnType.DateTimeUtc"/>.</summary>
|
||||
string CurrentTimestampUtc { get; }
|
||||
|
||||
/// <summary>Quotes a validated identifier.</summary>
|
||||
/// <param name="identifier">The identifier (snake_case).</param>
|
||||
/// <returns>The quoted identifier.</returns>
|
||||
string Quote(string identifier);
|
||||
|
||||
/// <summary>The placeholder of a named parameter, for example <c>@p0</c>.</summary>
|
||||
/// <param name="name">The parameter name without prefix.</param>
|
||||
/// <returns>The placeholder.</returns>
|
||||
string Parameter(string name);
|
||||
|
||||
/// <summary>The paging clause, appended after <c>ORDER BY</c>.</summary>
|
||||
/// <param name="offset">Rows to skip.</param>
|
||||
/// <param name="limit">Rows to return.</param>
|
||||
/// <returns>The clause, starting with a space.</returns>
|
||||
string Paging(int offset, int limit);
|
||||
|
||||
/// <summary>An insert that returns the generated key.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
/// <param name="columns">The inserted columns.</param>
|
||||
/// <param name="parameters">The parameter placeholders, one per column.</param>
|
||||
/// <param name="keyColumn">The generated key column.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
string InsertReturningId(string table, IReadOnlyList<string> columns, IReadOnlyList<string> parameters, string keyColumn);
|
||||
|
||||
/// <summary>An insert that updates the existing row on a conflict of <paramref name="conflictColumns"/>.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
/// <param name="columns">The inserted columns.</param>
|
||||
/// <param name="parameters">The parameter placeholders, one per column.</param>
|
||||
/// <param name="conflictColumns">The columns of the unique key.</param>
|
||||
/// <param name="updateColumns">The columns to update on conflict.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
string Upsert(
|
||||
string table, IReadOnlyList<string> columns, IReadOnlyList<string> parameters,
|
||||
IReadOnlyList<string> conflictColumns, IReadOnlyList<string> updateColumns);
|
||||
|
||||
/// <summary>A case-insensitive <c>LIKE</c> with <c>\</c> as escape character.</summary>
|
||||
/// <param name="column">The column (or expression).</param>
|
||||
/// <param name="pattern">The pattern, normally a parameter.</param>
|
||||
/// <returns>The condition.</returns>
|
||||
SqlFragment CaseInsensitiveLike(SqlFragment column, SqlFragment pattern);
|
||||
|
||||
/// <summary>
|
||||
/// A statement that takes a lock held until the end of the current transaction (numerators, closings, scheduler);
|
||||
/// empty where writes are already serialized.
|
||||
/// </summary>
|
||||
/// <param name="key">The lock key, for example <c>numerator:FV:2026</c>.</param>
|
||||
/// <returns>The statement, possibly empty.</returns>
|
||||
SqlFragment AdvisoryLock(string key);
|
||||
|
||||
/// <summary>Converts a CLR value to what the driver stores for <paramref name="type"/>; <c>null</c> becomes <see cref="DBNull"/>.</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <returns>The value for the driver.</returns>
|
||||
object ToDbValue(object? value, ColumnType type);
|
||||
|
||||
/// <summary>Converts a value read from the driver to the canonical CLR type of <paramref name="type"/> (see <see cref="ColumnTypes.ClrType"/>).</summary>
|
||||
/// <param name="value">The value read.</param>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <returns>The CLR value, or <see langword="null"/>.</returns>
|
||||
object? FromDbValue(object? value, ColumnType type);
|
||||
|
||||
/// <summary>The physical type of a column.</summary>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <param name="length">The length for <see cref="ColumnType.String"/>.</param>
|
||||
/// <param name="scale">The scale for <see cref="ColumnType.Decimal"/>.</param>
|
||||
/// <returns>The SQL type.</returns>
|
||||
string SqlType(ColumnType type, int? length, int? scale);
|
||||
|
||||
/// <summary>A constant as SQL literal, for DDL defaults only (values in statements are always parameters).</summary>
|
||||
/// <param name="value">The constant.</param>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <returns>The literal.</returns>
|
||||
string Literal(object? value, ColumnType type);
|
||||
|
||||
/// <summary>Sets the value (converted with <see cref="ToDbValue"/>) and the driver type of a parameter.</summary>
|
||||
/// <param name="parameter">The parameter.</param>
|
||||
/// <param name="value">The CLR value.</param>
|
||||
/// <param name="type">The logical type, or <see langword="null"/> to infer it from the value.</param>
|
||||
void ConfigureParameter(DbParameter parameter, object? value, ColumnType? type);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Data.Common;
|
||||
using Khaemhat.Core.Entities;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// An open connection to one database, with an optional explicit transaction (SPEC §5.1). Application services open
|
||||
/// one per operation, call <see cref="BeginAsync"/> for writes that must be atomic, and dispose it; a transaction not
|
||||
/// committed is rolled back on dispose.
|
||||
/// </summary>
|
||||
public interface IUnitOfWork : IAsyncDisposable
|
||||
{
|
||||
/// <summary>The open connection.</summary>
|
||||
DbConnection Connection { get; }
|
||||
|
||||
/// <summary>The current transaction, if any.</summary>
|
||||
DbTransaction? Transaction { get; }
|
||||
|
||||
/// <summary>The dialect of the database.</summary>
|
||||
ISqlDialect Dialect { get; }
|
||||
|
||||
/// <summary>Starts a transaction. On SQLite it also enters the write scope of the database.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task BeginAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Commits the transaction.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task CommitAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Rolls back the transaction.</summary>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
Task RollbackAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>The repository of an entity type.</summary>
|
||||
/// <typeparam name="T">The entity type, which needs a registered map.</typeparam>
|
||||
/// <typeparam name="TKey">The key type.</typeparam>
|
||||
/// <returns>The repository.</returns>
|
||||
IRepository<T, TKey> Repository<T, TKey>()
|
||||
where T : class, IEntity<TKey>, new();
|
||||
|
||||
/// <summary>Executes a statement that changes data or schema.</summary>
|
||||
/// <param name="sql">The statement.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The number of affected rows.</returns>
|
||||
Task<int> ExecuteAsync(SqlFragment sql, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Reads the first row (or <see langword="null"/>), mapped to <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">A scalar, a mapped entity, or a class/record whose members match the columns by snake_case name.</typeparam>
|
||||
/// <param name="sql">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The row, or <see langword="null"/>.</returns>
|
||||
Task<T?> QuerySingleAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>Reads all rows, mapped to <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">A scalar, a mapped entity, or a class/record whose members match the columns by snake_case name.</typeparam>
|
||||
/// <param name="sql">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows.</returns>
|
||||
Task<IReadOnlyList<T>> QueryAsync<T>(SqlFragment sql, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Opens a reader for large results (exports, reports) without loading them in memory. Dispose the reader before
|
||||
/// running anything else on this unit of work. Values are raw driver values: convert them with
|
||||
/// <see cref="ISqlDialect.FromDbValue"/>.
|
||||
/// </summary>
|
||||
/// <param name="sql">The query.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The reader.</returns>
|
||||
Task<DbDataReader> StreamAsync(SqlFragment sql, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Opens units of work on the system database or on a company database (SPEC §5.1).</summary>
|
||||
public interface IUnitOfWorkFactory
|
||||
{
|
||||
/// <summary>Opens a unit of work.</summary>
|
||||
/// <param name="scope">The system database, or a company.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The open unit of work.</returns>
|
||||
Task<IUnitOfWork> CreateAsync(DatabaseScope scope, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>Finds the database of a scope: the system database, or a company through the registry.</summary>
|
||||
public interface IDatabaseLocator
|
||||
{
|
||||
/// <summary>The database of a scope.</summary>
|
||||
/// <param name="scope">The scope.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The target.</returns>
|
||||
ValueTask<DatabaseTarget> LocateAsync(DatabaseScope scope, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Khaemhat.Data.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// Converts the canonical values returned by <see cref="ISqlDialect.FromDbValue"/> (or raw driver values) to the CLR
|
||||
/// type of a property, constructor parameter or scalar result.
|
||||
/// </summary>
|
||||
public static class ClrConverter
|
||||
{
|
||||
/// <summary>Converts <paramref name="value"/> to <paramref name="target"/>.</summary>
|
||||
/// <param name="value">The value, possibly <see langword="null"/> or <see cref="DBNull"/>.</param>
|
||||
/// <param name="target">The target type, nullable or not.</param>
|
||||
/// <returns>The converted value; <see langword="null"/> for a null input and a nullable target.</returns>
|
||||
/// <exception cref="InvalidCastException">A null value for a non-nullable value type, or an impossible conversion.</exception>
|
||||
public static object? ConvertTo(object? value, Type target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
var underlying = Nullable.GetUnderlyingType(target);
|
||||
if (value is null or DBNull)
|
||||
{
|
||||
return target.IsValueType && underlying is null
|
||||
? throw new InvalidCastException($"NULL cannot be assigned to {target.Name}.")
|
||||
: null;
|
||||
}
|
||||
|
||||
var type = underlying ?? target;
|
||||
if (type.IsInstanceOfType(value))
|
||||
{
|
||||
return type == typeof(DateTime) && value is DateTime { Kind: not DateTimeKind.Utc } d ? DateTime.SpecifyKind(d, DateTimeKind.Utc) : value;
|
||||
}
|
||||
|
||||
if (type.IsEnum)
|
||||
{
|
||||
return value is string name ? Enum.Parse(type, name, ignoreCase: false) : Enum.ToObject(type, value);
|
||||
}
|
||||
|
||||
return type switch
|
||||
{
|
||||
_ when type == typeof(DateOnly) => value switch
|
||||
{
|
||||
DateTime dt => DateOnly.FromDateTime(dt),
|
||||
string s => DateOnly.ParseExact(s, "yyyy-MM-dd", CultureInfo.InvariantCulture),
|
||||
_ => throw Impossible(value, type),
|
||||
},
|
||||
_ when type == typeof(DateTime) => value switch
|
||||
{
|
||||
DateTimeOffset o => o.UtcDateTime,
|
||||
DateOnly d => d.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc),
|
||||
string s => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal),
|
||||
_ => throw Impossible(value, type),
|
||||
},
|
||||
_ when type == typeof(Guid) => value is string g ? Guid.Parse(g, CultureInfo.InvariantCulture) : throw Impossible(value, type),
|
||||
_ when type == typeof(bool) && value is IConvertible => Convert.ToInt64(value, CultureInfo.InvariantCulture) != 0,
|
||||
_ when type == typeof(string) => Convert.ToString(value, CultureInfo.InvariantCulture),
|
||||
_ when value is IConvertible => Convert.ChangeType(value, type, CultureInfo.InvariantCulture),
|
||||
_ => throw Impossible(value, type),
|
||||
};
|
||||
}
|
||||
|
||||
private static InvalidCastException Impossible(object value, Type type) =>
|
||||
new($"A {value.GetType().Name} value cannot be converted to {type.Name}.");
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Mapping;
|
||||
|
||||
/// <summary>The role of a column among the audit columns of SPEC §5.2.</summary>
|
||||
public enum AuditRole
|
||||
{
|
||||
/// <summary>Not an audit column.</summary>
|
||||
None = 0,
|
||||
|
||||
/// <summary><c>created_at</c>.</summary>
|
||||
CreatedAt = 1,
|
||||
|
||||
/// <summary><c>created_by</c>.</summary>
|
||||
CreatedBy = 2,
|
||||
|
||||
/// <summary><c>updated_at</c>.</summary>
|
||||
UpdatedAt = 3,
|
||||
|
||||
/// <summary><c>updated_by</c>.</summary>
|
||||
UpdatedBy = 4,
|
||||
|
||||
/// <summary><c>row_version</c>.</summary>
|
||||
RowVersion = 5,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How a property is stored: column name, logical type, nullability, key and audit role, plus compiled accessors.
|
||||
/// Configured in the constructor of an <see cref="EntityMap{T}"/>, then frozen.
|
||||
/// </summary>
|
||||
public sealed class ColumnMap
|
||||
{
|
||||
private readonly Func<object, object?> _getter;
|
||||
private readonly Action<object, object?> _setter;
|
||||
private bool _frozen;
|
||||
private bool? _nullable;
|
||||
|
||||
internal ColumnMap(PropertyInfo property, Func<object, object?> getter, Action<object, object?> setter)
|
||||
{
|
||||
PropertyName = property.Name;
|
||||
PropertyType = property.PropertyType;
|
||||
ValueType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
|
||||
ColumnName = SqlNames.ToSnakeCase(property.Name);
|
||||
_getter = getter;
|
||||
_setter = setter;
|
||||
}
|
||||
|
||||
/// <summary>The C# property name.</summary>
|
||||
public string PropertyName { get; }
|
||||
|
||||
/// <summary>The declared property type.</summary>
|
||||
public Type PropertyType { get; }
|
||||
|
||||
/// <summary>The property type without <see cref="Nullable{T}"/>.</summary>
|
||||
public Type ValueType { get; }
|
||||
|
||||
/// <summary>The column name (snake_case of the property name unless set with <see cref="Named"/>).</summary>
|
||||
public string ColumnName { get; private set; }
|
||||
|
||||
/// <summary>The logical type.</summary>
|
||||
public ColumnType Type { get; private set; }
|
||||
|
||||
/// <summary>The maximum length, for <see cref="ColumnType.String"/>.</summary>
|
||||
public int? Length { get; private set; }
|
||||
|
||||
/// <summary>The scale, for <see cref="ColumnType.Decimal"/>.</summary>
|
||||
public int? Scale { get; private set; }
|
||||
|
||||
/// <summary>Whether the column accepts <c>NULL</c>.</summary>
|
||||
public bool IsNullable => _nullable ?? false;
|
||||
|
||||
/// <summary>Whether this is the primary key.</summary>
|
||||
public bool IsKey { get; internal set; }
|
||||
|
||||
/// <summary>Whether the key is generated by the database.</summary>
|
||||
public bool IsIdentity { get; internal set; }
|
||||
|
||||
/// <summary>The audit role.</summary>
|
||||
public AuditRole Audit { get; internal set; }
|
||||
|
||||
/// <summary>The logical type as documented, for example <c>String(20)</c>.</summary>
|
||||
public string TypeDescription => ColumnTypes.Describe(Type, Length, Scale);
|
||||
|
||||
internal bool HasExplicitType { get; private set; }
|
||||
|
||||
internal bool HasExplicitNullability => _nullable is not null;
|
||||
|
||||
/// <summary>Sets the column name.</summary>
|
||||
/// <param name="column">The column name (snake_case).</param>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Named(string column)
|
||||
{
|
||||
EnsureNotFrozen();
|
||||
SqlNames.EnsureIdentifier(column);
|
||||
ColumnName = column;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Stores a string as <see cref="ColumnType.String"/> with a maximum length (an enum by its name).</summary>
|
||||
/// <param name="length">The maximum length.</param>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap MaxLength(int length)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(length, 1);
|
||||
return SetType(ColumnType.String, length, null);
|
||||
}
|
||||
|
||||
/// <summary>Stores a string as <see cref="ColumnType.Text"/> (the default for strings).</summary>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Text() => SetType(ColumnType.Text, null, null);
|
||||
|
||||
/// <summary>Stores a string as <see cref="ColumnType.Json"/>.</summary>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Json() => SetType(ColumnType.Json, null, null);
|
||||
|
||||
/// <summary>Sets the scale of a decimal (default 6).</summary>
|
||||
/// <param name="scale">Digits after the point, 0 to 6.</param>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Scaled(int scale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, ColumnTypes.DecimalScale);
|
||||
return SetType(ColumnType.Decimal, null, scale);
|
||||
}
|
||||
|
||||
/// <summary>The column refuses <c>NULL</c>, whatever the property nullability says.</summary>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Required()
|
||||
{
|
||||
EnsureNotFrozen();
|
||||
_nullable = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>The column accepts <c>NULL</c>.</summary>
|
||||
/// <returns>This map.</returns>
|
||||
public ColumnMap Optional()
|
||||
{
|
||||
EnsureNotFrozen();
|
||||
_nullable = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Reads the property of an entity.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <returns>The property value.</returns>
|
||||
public object? GetValue(object entity) => _getter(entity);
|
||||
|
||||
/// <summary>Writes the property of an entity.</summary>
|
||||
/// <param name="entity">The entity.</param>
|
||||
/// <param name="value">The value, already of the property type.</param>
|
||||
public void SetValue(object entity, object? value)
|
||||
{
|
||||
if (value is null && PropertyType.IsValueType && Nullable.GetUnderlyingType(PropertyType) is null)
|
||||
{
|
||||
throw new InvalidCastException($"Column {ColumnName} is NULL but property {PropertyName} cannot hold null.");
|
||||
}
|
||||
|
||||
_setter(entity, value);
|
||||
}
|
||||
|
||||
/// <summary>Converts a property value to the value given to the dialect (enums become their name).</summary>
|
||||
/// <param name="value">The property value.</param>
|
||||
/// <returns>The value for <see cref="ISqlDialect.ToDbValue"/>.</returns>
|
||||
public object? ToProvider(object? value) => value is Enum e && ValueType.IsEnum ? e.ToString() : value;
|
||||
|
||||
/// <summary>Converts a canonical value from <see cref="ISqlDialect.FromDbValue"/> to the property type.</summary>
|
||||
/// <param name="value">The canonical value.</param>
|
||||
/// <returns>The property value.</returns>
|
||||
public object? FromProvider(object? value) => ClrConverter.ConvertTo(value, PropertyType);
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => ColumnName + " " + TypeDescription;
|
||||
|
||||
internal void SetDefaults(ColumnType type, int? length, bool nullable)
|
||||
{
|
||||
if (!HasExplicitType)
|
||||
{
|
||||
Type = type;
|
||||
Length = length;
|
||||
Scale = type == ColumnType.Decimal ? ColumnTypes.DecimalScale : null;
|
||||
}
|
||||
|
||||
_nullable ??= nullable;
|
||||
}
|
||||
|
||||
internal void Freeze() => _frozen = true;
|
||||
|
||||
private ColumnMap SetType(ColumnType type, int? length, int? scale)
|
||||
{
|
||||
EnsureNotFrozen();
|
||||
Type = type;
|
||||
Length = length;
|
||||
Scale = scale;
|
||||
HasExplicitType = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
private void EnsureNotFrozen()
|
||||
{
|
||||
if (_frozen)
|
||||
{
|
||||
throw new InvalidOperationException("A column map cannot change after its entity map is registered.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Core.Entities;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Mapping;
|
||||
|
||||
/// <summary>A map from an entity type to its table (non-generic view used by the data layer).</summary>
|
||||
public interface IEntityMap
|
||||
{
|
||||
/// <summary>The entity type.</summary>
|
||||
Type EntityType { get; }
|
||||
|
||||
/// <summary>The table name.</summary>
|
||||
string Table { get; }
|
||||
|
||||
/// <summary>The primary key column.</summary>
|
||||
ColumnMap Key { get; }
|
||||
|
||||
/// <summary>All columns, key first, audit columns last.</summary>
|
||||
IReadOnlyList<ColumnMap> Columns { get; }
|
||||
|
||||
/// <summary>The <c>row_version</c> column, if the entity is <see cref="IAuditable"/>.</summary>
|
||||
ColumnMap? RowVersion { get; }
|
||||
|
||||
/// <summary>Finds the column of a property.</summary>
|
||||
/// <param name="propertyName">The property name.</param>
|
||||
/// <returns>The column, or <see langword="null"/>.</returns>
|
||||
ColumnMap? FindByProperty(string propertyName);
|
||||
|
||||
/// <summary>Finds a column by name.</summary>
|
||||
/// <param name="columnName">The column name.</param>
|
||||
/// <returns>The column, or <see langword="null"/>.</returns>
|
||||
ColumnMap? FindByColumn(string columnName);
|
||||
|
||||
/// <summary>Creates an empty entity.</summary>
|
||||
/// <returns>The entity.</returns>
|
||||
object CreateEntity();
|
||||
|
||||
/// <summary>Completes the map by convention and makes it read-only. Called by <see cref="MapRegistry"/>.</summary>
|
||||
void Freeze();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The map of an entity to its table (SPEC §5.2: <c>XxxMap : EntityMap<Xxx></c>). The constructor names the table
|
||||
/// and states only what differs from the conventions; every other public read/write property is mapped by convention:
|
||||
/// <list type="bullet">
|
||||
/// <item>column name = snake_case of the property;</item>
|
||||
/// <item><c>Id</c> is the key, generated by the database when it is <see cref="long"/> or <see cref="int"/>;</item>
|
||||
/// <item>types from <see cref="ColumnTypes.FromClrType"/>, strings as <see cref="ColumnType.Text"/> unless
|
||||
/// <see cref="ColumnMap.MaxLength"/> is set, enums by name as <c>String(40)</c>;</item>
|
||||
/// <item>nullability from the C# declaration;</item>
|
||||
/// <item>the audit columns of <see cref="IAuditable"/> and <c>is_demo</c> of <see cref="IDemoMarkable"/>.</item>
|
||||
/// </list>
|
||||
/// Reflection is used only here, once; reading and writing use compiled accessors.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
public abstract class EntityMap<T> : IEntityMap
|
||||
where T : class, new()
|
||||
{
|
||||
private const int EnumLength = 40;
|
||||
private static readonly NullabilityInfoContext NullabilityContext = new();
|
||||
|
||||
private readonly Dictionary<string, ColumnMap> _configured = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _ignored = new(StringComparer.Ordinal);
|
||||
private readonly object _gate = new();
|
||||
private string? _table;
|
||||
private string _keyProperty = "Id";
|
||||
private bool? _keyIdentity;
|
||||
private List<ColumnMap>? _columns;
|
||||
private ColumnMap? _key;
|
||||
private ColumnMap? _rowVersion;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Type EntityType => typeof(T);
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Table => _table ?? throw new InvalidOperationException($"{GetType().Name} does not call ToTable.");
|
||||
|
||||
/// <inheritdoc />
|
||||
public ColumnMap Key
|
||||
{
|
||||
get
|
||||
{
|
||||
Freeze();
|
||||
return _key!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<ColumnMap> Columns
|
||||
{
|
||||
get
|
||||
{
|
||||
Freeze();
|
||||
return _columns!;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ColumnMap? RowVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
Freeze();
|
||||
return _rowVersion;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public ColumnMap? FindByProperty(string propertyName) => Columns.FirstOrDefault(c => c.PropertyName == propertyName);
|
||||
|
||||
/// <inheritdoc />
|
||||
public ColumnMap? FindByColumn(string columnName) => Columns.FirstOrDefault(c => c.ColumnName == columnName);
|
||||
|
||||
/// <summary>Creates an empty entity.</summary>
|
||||
/// <returns>The entity.</returns>
|
||||
public T Create() => new();
|
||||
|
||||
/// <inheritdoc />
|
||||
object IEntityMap.CreateEntity() => new T();
|
||||
|
||||
/// <summary>The column of a property.</summary>
|
||||
/// <typeparam name="TProperty">The property type.</typeparam>
|
||||
/// <param name="property">The property, for example <c>x => x.Code</c>.</param>
|
||||
/// <returns>The column.</returns>
|
||||
public ColumnMap Column<TProperty>(Expression<Func<T, TProperty>> property) =>
|
||||
FindByProperty(PropertyOf(property).Name) ?? throw new InvalidOperationException($"{typeof(T).Name}.{PropertyOf(property).Name} is not mapped.");
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Freeze()
|
||||
{
|
||||
if (_columns is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (_columns is null)
|
||||
{
|
||||
Build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sets the table name.</summary>
|
||||
/// <param name="table">The table (snake_case; <c>sys_</c> prefix in the system database).</param>
|
||||
protected void ToTable(string table)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(table);
|
||||
_table = table;
|
||||
}
|
||||
|
||||
/// <summary>Configures the column of a property.</summary>
|
||||
/// <typeparam name="TProperty">The property type.</typeparam>
|
||||
/// <param name="property">The property, for example <c>x => x.Code</c>.</param>
|
||||
/// <returns>The column map to configure.</returns>
|
||||
protected ColumnMap Map<TProperty>(Expression<Func<T, TProperty>> property)
|
||||
{
|
||||
if (_columns is not null)
|
||||
{
|
||||
throw new InvalidOperationException("The map is frozen.");
|
||||
}
|
||||
|
||||
var info = PropertyOf(property);
|
||||
if (!_configured.TryGetValue(info.Name, out var column))
|
||||
{
|
||||
column = CreateColumn(info);
|
||||
_configured[info.Name] = column;
|
||||
}
|
||||
|
||||
return column;
|
||||
}
|
||||
|
||||
/// <summary>Sets a key other than <c>Id</c>.</summary>
|
||||
/// <typeparam name="TProperty">The property type.</typeparam>
|
||||
/// <param name="property">The key property.</param>
|
||||
/// <param name="identity">Whether the database generates it.</param>
|
||||
protected void HasKey<TProperty>(Expression<Func<T, TProperty>> property, bool identity)
|
||||
{
|
||||
_keyProperty = PropertyOf(property).Name;
|
||||
_keyIdentity = identity;
|
||||
}
|
||||
|
||||
/// <summary>Excludes a property from the table.</summary>
|
||||
/// <typeparam name="TProperty">The property type.</typeparam>
|
||||
/// <param name="property">The property.</param>
|
||||
protected void Ignore<TProperty>(Expression<Func<T, TProperty>> property) => _ignored.Add(PropertyOf(property).Name);
|
||||
|
||||
private static PropertyInfo PropertyOf<TProperty>(Expression<Func<T, TProperty>> property)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(property);
|
||||
var body = property.Body is UnaryExpression { NodeType: ExpressionType.Convert } convert ? convert.Operand : property.Body;
|
||||
return body is MemberExpression { Member: PropertyInfo info } member && member.Expression == property.Parameters[0]
|
||||
? info
|
||||
: throw new ArgumentException("Use a property of the entity, for example x => x.Code.", nameof(property));
|
||||
}
|
||||
|
||||
private static ColumnMap CreateColumn(PropertyInfo property)
|
||||
{
|
||||
var entity = Expression.Parameter(typeof(object), "entity");
|
||||
var value = Expression.Parameter(typeof(object), "value");
|
||||
var typed = Expression.Convert(entity, typeof(T));
|
||||
var getter = Expression.Lambda<Func<object, object?>>(
|
||||
Expression.Convert(Expression.Property(typed, property), typeof(object)), entity).Compile();
|
||||
var setter = Expression.Lambda<Action<object, object?>>(
|
||||
Expression.Assign(Expression.Property(typed, property), Expression.Convert(value, property.PropertyType)), entity, value).Compile();
|
||||
return new ColumnMap(property, getter, setter);
|
||||
}
|
||||
|
||||
private void Build()
|
||||
{
|
||||
_ = Table;
|
||||
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(p => p.CanRead && p.CanWrite && p.GetSetMethod() is not null && p.GetIndexParameters().Length == 0)
|
||||
.ToList();
|
||||
var key = new List<ColumnMap>(1);
|
||||
var regular = new List<ColumnMap>();
|
||||
var audit = new List<ColumnMap>();
|
||||
|
||||
foreach (var property in properties)
|
||||
{
|
||||
if (_ignored.Contains(property.Name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var column = _configured.TryGetValue(property.Name, out var configured) ? configured : CreateColumn(property);
|
||||
var role = AuditRoleOf(property.Name);
|
||||
if (property.Name == _keyProperty)
|
||||
{
|
||||
column.IsKey = true;
|
||||
column.IsIdentity = _keyIdentity ?? (column.ValueType == typeof(long) || column.ValueType == typeof(int));
|
||||
Infer(column, property, forceNotNull: true);
|
||||
key.Add(column);
|
||||
}
|
||||
else if (role != AuditRole.None)
|
||||
{
|
||||
column.Audit = role;
|
||||
ApplyAuditDefaults(column, role);
|
||||
audit.Add(column);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (property.Name == nameof(IDemoMarkable.IsDemo) && typeof(IDemoMarkable).IsAssignableFrom(typeof(T)))
|
||||
{
|
||||
column.SetDefaults(ColumnType.Bool, null, nullable: false);
|
||||
}
|
||||
|
||||
Infer(column, property, forceNotNull: false);
|
||||
regular.Add(column);
|
||||
}
|
||||
}
|
||||
|
||||
if (key.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException($"{typeof(T).Name} has no key property {_keyProperty}.");
|
||||
}
|
||||
|
||||
var unknown = _configured.Keys.Except(properties.Select(p => p.Name)).ToList();
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
throw new InvalidOperationException($"{typeof(T).Name}: cannot map {string.Join(", ", unknown)} (needs a public getter and setter).");
|
||||
}
|
||||
|
||||
audit.Sort((a, b) => a.Audit.CompareTo(b.Audit));
|
||||
var columns = key.Concat(regular).Concat(audit).ToList();
|
||||
var duplicate = columns.GroupBy(c => c.ColumnName).FirstOrDefault(g => g.Count() > 1);
|
||||
if (duplicate is not null)
|
||||
{
|
||||
throw new InvalidOperationException($"{typeof(T).Name}: column {duplicate.Key} is mapped twice.");
|
||||
}
|
||||
|
||||
foreach (var column in columns)
|
||||
{
|
||||
column.Freeze();
|
||||
}
|
||||
|
||||
_key = key[0];
|
||||
_rowVersion = audit.Find(c => c.Audit == AuditRole.RowVersion);
|
||||
_columns = columns;
|
||||
}
|
||||
|
||||
private static void Infer(ColumnMap column, PropertyInfo property, bool forceNotNull)
|
||||
{
|
||||
var nullable = !forceNotNull && IsNullable(property);
|
||||
if (column.ValueType.IsEnum)
|
||||
{
|
||||
column.SetDefaults(ColumnType.String, EnumLength, nullable);
|
||||
return;
|
||||
}
|
||||
|
||||
var type = ColumnTypes.FromClrType(column.ValueType)
|
||||
?? throw new InvalidOperationException(
|
||||
$"{typeof(T).Name}.{property.Name}: type {column.ValueType.Name} has no column type; map or ignore it.");
|
||||
column.SetDefaults(type, null, nullable);
|
||||
if (column.Type == ColumnType.String && column.Length is null)
|
||||
{
|
||||
throw new InvalidOperationException($"{typeof(T).Name}.{property.Name}: a String column needs MaxLength.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsNullable(PropertyInfo property)
|
||||
{
|
||||
if (property.PropertyType.IsValueType)
|
||||
{
|
||||
return Nullable.GetUnderlyingType(property.PropertyType) is not null;
|
||||
}
|
||||
|
||||
lock (NullabilityContext)
|
||||
{
|
||||
return NullabilityContext.Create(property).WriteState != NullabilityState.NotNull;
|
||||
}
|
||||
}
|
||||
|
||||
private static AuditRole AuditRoleOf(string propertyName)
|
||||
{
|
||||
if (!typeof(IAuditable).IsAssignableFrom(typeof(T)))
|
||||
{
|
||||
return AuditRole.None;
|
||||
}
|
||||
|
||||
return propertyName switch
|
||||
{
|
||||
nameof(IAuditable.CreatedAt) => AuditRole.CreatedAt,
|
||||
nameof(IAuditable.CreatedBy) => AuditRole.CreatedBy,
|
||||
nameof(IAuditable.UpdatedAt) => AuditRole.UpdatedAt,
|
||||
nameof(IAuditable.UpdatedBy) => AuditRole.UpdatedBy,
|
||||
nameof(IAuditable.RowVersion) => AuditRole.RowVersion,
|
||||
_ => AuditRole.None,
|
||||
};
|
||||
}
|
||||
|
||||
private static void ApplyAuditDefaults(ColumnMap column, AuditRole role)
|
||||
{
|
||||
switch (role)
|
||||
{
|
||||
case AuditRole.CreatedAt:
|
||||
column.SetDefaults(ColumnType.DateTimeUtc, null, nullable: false);
|
||||
break;
|
||||
case AuditRole.UpdatedAt:
|
||||
column.SetDefaults(ColumnType.DateTimeUtc, null, nullable: true);
|
||||
break;
|
||||
case AuditRole.CreatedBy or AuditRole.UpdatedBy:
|
||||
column.SetDefaults(ColumnType.String, AuditColumnLengths.User, nullable: true);
|
||||
break;
|
||||
case AuditRole.RowVersion:
|
||||
column.SetDefaults(ColumnType.Int64, null, nullable: false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Reflection;
|
||||
|
||||
namespace Khaemhat.Data.Mapping;
|
||||
|
||||
/// <summary>
|
||||
/// The entity maps known to the instance (SPEC §5.2). Maps are completed and frozen when added; afterwards the data
|
||||
/// layer only reads them.
|
||||
/// </summary>
|
||||
public sealed class MapRegistry
|
||||
{
|
||||
private readonly ConcurrentDictionary<Type, IEntityMap> _maps = new();
|
||||
|
||||
/// <summary>All registered maps.</summary>
|
||||
public IReadOnlyCollection<IEntityMap> Maps => [.. _maps.Values.OrderBy(m => m.Table, StringComparer.Ordinal)];
|
||||
|
||||
/// <summary>Adds a map.</summary>
|
||||
/// <param name="map">The map.</param>
|
||||
/// <returns>This registry.</returns>
|
||||
/// <exception cref="InvalidOperationException">The entity already has a map, or the map is not valid.</exception>
|
||||
public MapRegistry Add(IEntityMap map)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(map);
|
||||
map.Freeze();
|
||||
if (!_maps.TryAdd(map.EntityType, map))
|
||||
{
|
||||
throw new InvalidOperationException($"{map.EntityType.Name} has two maps.");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds every non-abstract <see cref="IEntityMap"/> with a public parameterless constructor found in an assembly.</summary>
|
||||
/// <param name="assembly">The assembly.</param>
|
||||
/// <returns>This registry.</returns>
|
||||
public MapRegistry AddFromAssembly(Assembly assembly)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assembly);
|
||||
var types = assembly.GetTypes()
|
||||
.Where(t => t is { IsClass: true, IsAbstract: false } && typeof(IEntityMap).IsAssignableFrom(t) && t.GetConstructor(Type.EmptyTypes) is not null)
|
||||
.OrderBy(t => t.FullName, StringComparer.Ordinal);
|
||||
foreach (var type in types)
|
||||
{
|
||||
Add((IEntityMap)Activator.CreateInstance(type)!);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>The map of <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <returns>The map.</returns>
|
||||
/// <exception cref="InvalidOperationException">No map is registered.</exception>
|
||||
public EntityMap<T> Get<T>()
|
||||
where T : class, new() =>
|
||||
(EntityMap<T>)(Find(typeof(T)) ?? throw new InvalidOperationException($"{typeof(T).Name} has no entity map."));
|
||||
|
||||
/// <summary>The map of a type, if any.</summary>
|
||||
/// <param name="entityType">The entity type.</param>
|
||||
/// <returns>The map, or <see langword="null"/>.</returns>
|
||||
public IEntityMap? Find(Type entityType) => _maps.GetValueOrDefault(entityType);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// Renders the schema produced by the migrations as Markdown for <c>docs/DATA-MODEL.md</c> (SPEC §18), between two
|
||||
/// markers, so the document can never drift from the code. Used by <c>scripts/gen-datamodel.sh</c> and checked by a
|
||||
/// test. The text is Italian because it is documentation.
|
||||
/// </summary>
|
||||
public static class DataModelDocument
|
||||
{
|
||||
/// <summary>The line that opens the generated section.</summary>
|
||||
public const string BeginMarker = "<!-- BEGIN GENERATED: scripts/gen-datamodel.sh, do not edit by hand -->";
|
||||
|
||||
/// <summary>The line that closes the generated section.</summary>
|
||||
public const string EndMarker = "<!-- END GENERATED -->";
|
||||
|
||||
/// <summary>Renders both catalogues.</summary>
|
||||
/// <param name="system">The system database migrations.</param>
|
||||
/// <param name="company">The company database migrations.</param>
|
||||
/// <returns>The Markdown, without the markers, ending with a newline.</returns>
|
||||
public static string Render(MigrationCatalog system, MigrationCatalog company)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(system);
|
||||
ArgumentNullException.ThrowIfNull(company);
|
||||
var text = new StringBuilder();
|
||||
RenderCatalog(text, "Database di sistema", system);
|
||||
text.Append('\n');
|
||||
RenderCatalog(text, "Database aziendale", company);
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Replaces the generated section of a document.</summary>
|
||||
/// <param name="document">The current document.</param>
|
||||
/// <param name="generated">The output of <see cref="Render"/>.</param>
|
||||
/// <returns>The updated document.</returns>
|
||||
/// <exception cref="InvalidOperationException">The markers are missing or out of order.</exception>
|
||||
public static string Update(string document, string generated)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(document);
|
||||
ArgumentNullException.ThrowIfNull(generated);
|
||||
var begin = document.IndexOf(BeginMarker, StringComparison.Ordinal);
|
||||
var end = document.IndexOf(EndMarker, StringComparison.Ordinal);
|
||||
if (begin < 0 || end < begin)
|
||||
{
|
||||
throw new InvalidOperationException($"The document must contain '{BeginMarker}' followed by '{EndMarker}'.");
|
||||
}
|
||||
|
||||
var start = begin + BeginMarker.Length;
|
||||
return document[..start] + "\n\n" + generated + "\n" + document[end..];
|
||||
}
|
||||
|
||||
private static void RenderCatalog(StringBuilder text, string title, MigrationCatalog catalog)
|
||||
{
|
||||
var model = catalog.BuildModel();
|
||||
Line(text, $"### {title}");
|
||||
text.Append('\n');
|
||||
if (catalog.Migrations.Count == 0)
|
||||
{
|
||||
Line(text, "Nessuna migrazione: la tabella `schema_version` è l'unica presente.");
|
||||
}
|
||||
else
|
||||
{
|
||||
Line(text, "Migrazioni applicate in ordine:");
|
||||
text.Append('\n');
|
||||
foreach (var migration in catalog.Migrations)
|
||||
{
|
||||
Line(text, $"- `{migration.Module}` {migration.Version} `{migration.Name}` ({migration.Type.Name})");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var table in model.Tables.OrderBy(t => t.Name, StringComparer.Ordinal))
|
||||
{
|
||||
text.Append('\n');
|
||||
RenderTable(text, table);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RenderTable(StringBuilder text, TableDefinition table)
|
||||
{
|
||||
Line(text, $"#### `{table.Name}`");
|
||||
text.Append('\n');
|
||||
Line(text, "| Colonna | Tipo | Null | Default | Note |");
|
||||
Line(text, "|---|---|---|---|---|");
|
||||
foreach (var column in table.Columns)
|
||||
{
|
||||
var notes = new List<string>();
|
||||
if (table.PrimaryKey.Contains(column.Name))
|
||||
{
|
||||
notes.Add("chiave primaria");
|
||||
}
|
||||
|
||||
if (column.IsIdentity)
|
||||
{
|
||||
notes.Add("identity");
|
||||
}
|
||||
|
||||
notes.AddRange(table.ForeignKeys
|
||||
.Where(fk => fk.Columns.Contains(column.Name))
|
||||
.Select(fk => $"-> `{fk.ReferencedTable}` ({fk.OnDelete})"));
|
||||
Line(text, $"| `{column.Name}` | {column.TypeDescription} | {(column.IsNullable ? "sì" : "no")} | {Default(column)} | {string.Join(", ", notes)} |");
|
||||
}
|
||||
|
||||
if (table.PrimaryKey.Count > 1)
|
||||
{
|
||||
text.Append('\n');
|
||||
Line(text, $"Chiave primaria: {Columns(table.PrimaryKey)}.");
|
||||
}
|
||||
|
||||
if (table.Indexes.Count > 0)
|
||||
{
|
||||
text.Append('\n');
|
||||
foreach (var index in table.Indexes.OrderBy(i => i.Name, StringComparer.Ordinal))
|
||||
{
|
||||
Line(text, $"- indice {(index.IsUnique ? "unico " : string.Empty)}`{index.Name}` su {Columns(index.Columns)}");
|
||||
}
|
||||
}
|
||||
|
||||
if (table.PartitionByYearColumn is { } partition)
|
||||
{
|
||||
text.Append('\n');
|
||||
Line(text, $"Partizionata per anno su `{partition}` (solo PostgreSQL).");
|
||||
}
|
||||
}
|
||||
|
||||
private static string Default(ColumnDefinition column) => column switch
|
||||
{
|
||||
{ DefaultsToCurrentTimestamp: true } => "ora corrente (UTC)",
|
||||
{ DefaultValue: null } => string.Empty,
|
||||
{ DefaultValue: string s } => $"`'{s}'`",
|
||||
{ DefaultValue: bool b } => b ? "`true`" : "`false`",
|
||||
{ DefaultValue: IFormattable f } => $"`{f.ToString(null, CultureInfo.InvariantCulture)}`",
|
||||
_ => $"`{column.DefaultValue}`",
|
||||
};
|
||||
|
||||
private static string Columns(IEnumerable<string> names) => string.Join(", ", names.Select(n => $"`{n}`"));
|
||||
|
||||
private static void Line(StringBuilder text, string line) => text.Append(line).Append('\n');
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Migrations;
|
||||
|
||||
/// <summary>
|
||||
/// A schema migration (SPEC §5.3). Describe the change in neutral form in <see cref="Up"/>; add dialect-specific SQL in
|
||||
/// <see cref="UpSql"/> only for what the neutral form cannot express. Once released, a migration never changes: write a
|
||||
/// new one. Create the file with <c>scripts/new-migration.sh</c>.
|
||||
/// <code>
|
||||
/// [Migration(20261111_002, "create_sys_settings", Target = MigrationTarget.System)]
|
||||
/// public sealed class M20261111_002_CreateSysSettings : IMigration
|
||||
/// {
|
||||
/// public void Up(ISchemaBuilder schema) => schema.CreateTable("sys_settings", t => { … });
|
||||
/// }
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public interface IMigration
|
||||
{
|
||||
/// <summary>Describes the schema change.</summary>
|
||||
/// <param name="schema">The schema builder.</param>
|
||||
void Up(ISchemaBuilder schema);
|
||||
|
||||
/// <summary>Dialect-specific SQL run after <see cref="Up"/>, or <see langword="null"/>.</summary>
|
||||
/// <param name="dialect">The dialect of the database being migrated.</param>
|
||||
/// <returns>Trusted SQL (several statements separated by semicolons are allowed), or <see langword="null"/>.</returns>
|
||||
string? UpSql(ISqlDialect dialect) => null;
|
||||
}
|
||||
|
||||
/// <summary>Which catalog a migration belongs to.</summary>
|
||||
public enum MigrationTarget
|
||||
{
|
||||
/// <summary>Every company database (<c>khaemhat_<code></c>).</summary>
|
||||
Company = 0,
|
||||
|
||||
/// <summary>The system database (<c>khaemhat_system</c>).</summary>
|
||||
System = 1,
|
||||
}
|
||||
|
||||
/// <summary>Marks an <see cref="IMigration"/> with its version and name.</summary>
|
||||
/// <param name="version">The version <c>yyyymmdd_nnn</c> written as a number, for example <c>20261111_001</c>.</param>
|
||||
/// <param name="name">The name in snake_case, for example <c>create_sys_companies</c>.</param>
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class MigrationAttribute(long version, string name) : Attribute
|
||||
{
|
||||
/// <summary>The version <c>yyyymmddnnn</c>.</summary>
|
||||
public long Version { get; } = version;
|
||||
|
||||
/// <summary>The name.</summary>
|
||||
public string Name { get; } = name;
|
||||
|
||||
/// <summary>The catalog (default <see cref="MigrationTarget.Company"/>).</summary>
|
||||
public MigrationTarget Target { get; init; } = MigrationTarget.Company;
|
||||
|
||||
/// <summary>The module that owns the migration, as stored in <c>schema_version.module</c> (default <c>core</c>).</summary>
|
||||
public string Module { get; init; } = "core";
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Migrations;
|
||||
|
||||
/// <summary>A migration found in a catalog.</summary>
|
||||
/// <param name="Version">The version <c>yyyymmddnnn</c>.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="Module">The owning module.</param>
|
||||
/// <param name="Target">The catalog.</param>
|
||||
/// <param name="Type">The migration class.</param>
|
||||
public sealed record MigrationInfo(long Version, string Name, string Module, MigrationTarget Target, Type Type)
|
||||
{
|
||||
/// <summary>Creates the migration.</summary>
|
||||
/// <returns>The migration.</returns>
|
||||
public IMigration Create() => (IMigration)Activator.CreateInstance(Type)!;
|
||||
|
||||
/// <summary>Records the operations of the migration.</summary>
|
||||
/// <returns>The operations of <see cref="IMigration.Up"/>.</returns>
|
||||
public IReadOnlyList<SchemaOperation> Operations()
|
||||
{
|
||||
var builder = new SchemaBuilder();
|
||||
Create().Up(builder);
|
||||
return builder.Operations;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Module}/{Version} {Name}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The migrations of one database kind (SPEC §5.3): <see cref="MigrationTarget.System"/> for the system database,
|
||||
/// <see cref="MigrationTarget.Company"/> for every company. Built by scanning assemblies for <see cref="MigrationAttribute"/>.
|
||||
/// </summary>
|
||||
public sealed class MigrationCatalog
|
||||
{
|
||||
private MigrationCatalog(MigrationTarget target, IReadOnlyList<MigrationInfo> migrations)
|
||||
{
|
||||
Target = target;
|
||||
Migrations = migrations;
|
||||
}
|
||||
|
||||
/// <summary>The catalog kind.</summary>
|
||||
public MigrationTarget Target { get; }
|
||||
|
||||
/// <summary>The migrations, ordered by version then module.</summary>
|
||||
public IReadOnlyList<MigrationInfo> Migrations { get; }
|
||||
|
||||
/// <summary>The system catalog with the migrations of this assembly and of <paramref name="assemblies"/>.</summary>
|
||||
/// <param name="assemblies">Further assemblies with system migrations (security, licences, logs...).</param>
|
||||
/// <returns>The catalog.</returns>
|
||||
public static MigrationCatalog ForSystem(params Assembly[] assemblies) =>
|
||||
Discover(MigrationTarget.System, [typeof(MigrationCatalog).Assembly, .. assemblies]);
|
||||
|
||||
/// <summary>The company catalog with the migrations of <paramref name="assemblies"/>.</summary>
|
||||
/// <param name="assemblies">Assemblies with company migrations (the application modules).</param>
|
||||
/// <returns>The catalog.</returns>
|
||||
public static MigrationCatalog ForCompany(params Assembly[] assemblies) =>
|
||||
Discover(MigrationTarget.Company, [typeof(MigrationCatalog).Assembly, .. assemblies]);
|
||||
|
||||
/// <summary>Finds the migrations of <paramref name="target"/> in assemblies and validates them.</summary>
|
||||
/// <param name="target">The catalog kind.</param>
|
||||
/// <param name="assemblies">The assemblies.</param>
|
||||
/// <returns>The catalog.</returns>
|
||||
/// <exception cref="InvalidOperationException">A migration is not valid or a version is used twice in a module.</exception>
|
||||
public static MigrationCatalog Discover(MigrationTarget target, IEnumerable<Assembly> assemblies)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(assemblies);
|
||||
var migrations = new List<MigrationInfo>();
|
||||
foreach (var type in assemblies.Distinct().SelectMany(a => a.GetTypes()))
|
||||
{
|
||||
if (type.GetCustomAttribute<MigrationAttribute>() is not { } attribute || attribute.Target != target)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!typeof(IMigration).IsAssignableFrom(type) || type.IsAbstract || type.GetConstructor(Type.EmptyTypes) is null)
|
||||
{
|
||||
throw new InvalidOperationException($"{type.Name} has [Migration] but is not a concrete IMigration with a parameterless constructor.");
|
||||
}
|
||||
|
||||
Validate(type, attribute);
|
||||
migrations.Add(new MigrationInfo(attribute.Version, attribute.Name, attribute.Module, target, type));
|
||||
}
|
||||
|
||||
var duplicate = migrations.GroupBy(m => (m.Module, m.Version)).FirstOrDefault(g => g.Count() > 1);
|
||||
if (duplicate is not null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Version {duplicate.Key.Version} of module {duplicate.Key.Module} is used by {string.Join(", ", duplicate.Select(m => m.Type.Name))}.");
|
||||
}
|
||||
|
||||
return new MigrationCatalog(
|
||||
target, [.. migrations.OrderBy(m => m.Version).ThenBy(m => m.Module, StringComparer.Ordinal)]);
|
||||
}
|
||||
|
||||
/// <summary>The schema produced by all migrations from an empty database, plus <c>schema_version</c>.</summary>
|
||||
/// <returns>The schema model.</returns>
|
||||
public SchemaModel BuildModel()
|
||||
{
|
||||
var model = new SchemaModel();
|
||||
model.Apply([SchemaVersionStore.CreateOperation]);
|
||||
foreach (var migration in Migrations)
|
||||
{
|
||||
model.Apply(migration.Operations());
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
private static void Validate(Type type, MigrationAttribute attribute)
|
||||
{
|
||||
var text = attribute.Version.ToString(CultureInfo.InvariantCulture);
|
||||
if (text.Length != 11
|
||||
|| !DateOnly.TryParseExact(text[..8], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _)
|
||||
|| text[8..] == "000")
|
||||
{
|
||||
throw new InvalidOperationException($"{type.Name}: the version must be yyyymmdd_nnn (for example 20261111_001), not {text}.");
|
||||
}
|
||||
|
||||
if (!SqlNames.IsValidIdentifier(attribute.Name) || !SqlNames.IsValidIdentifier(attribute.Module) || attribute.Module.Length > 50)
|
||||
{
|
||||
throw new InvalidOperationException($"{type.Name}: name and module must be snake_case.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Khaemhat.Data.Execution;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Migrations;
|
||||
|
||||
/// <summary>The outcome of a migration run, for the log section <i>Migrazioni</i> (written by the caller).</summary>
|
||||
/// <param name="Database">The database name.</param>
|
||||
/// <param name="Applied">The migrations applied now, with their duration.</param>
|
||||
/// <param name="AlreadyApplied">How many catalog migrations were already applied.</param>
|
||||
/// <param name="Warnings">
|
||||
/// Applied migrations whose statements differ from what the code generates now (a changed migration or DDL generator).
|
||||
/// </param>
|
||||
public sealed record MigrationReport(
|
||||
string Database, IReadOnlyList<(MigrationInfo Migration, TimeSpan Duration)> Applied, int AlreadyApplied, IReadOnlyList<string> Warnings);
|
||||
|
||||
/// <summary>A database cannot be migrated, for example because it is newer than the application.</summary>
|
||||
public sealed class MigrationException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception.</summary>
|
||||
public MigrationException()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
public MigrationException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates the exception with a message and a cause.</summary>
|
||||
/// <param name="message">The message.</param>
|
||||
/// <param name="innerException">The cause.</param>
|
||||
public MigrationException(string message, Exception innerException) : base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the pending migrations of a catalog to a database (SPEC §5.3): each in its own transaction together with its
|
||||
/// <c>schema_version</c> row, under an application lock so that two instances never migrate at the same time.
|
||||
/// Re-running does nothing. A database with applied versions unknown to the catalog (a downgrade) is refused.
|
||||
/// </summary>
|
||||
/// <param name="context">Clock and retry policy.</param>
|
||||
public sealed class MigrationRunner(DataAccessContext context)
|
||||
{
|
||||
private const string LockKey = "khaemhat:migrations";
|
||||
private static readonly MapRegistry NoMaps = new();
|
||||
|
||||
/// <summary>Migrates a database.</summary>
|
||||
/// <param name="target">The database.</param>
|
||||
/// <param name="catalog">The catalog for this kind of database.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>What was done.</returns>
|
||||
/// <exception cref="MigrationException">The database has versions unknown to this application.</exception>
|
||||
public async Task<MigrationReport> RunAsync(DatabaseTarget target, MigrationCatalog catalog, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(target);
|
||||
ArgumentNullException.ThrowIfNull(catalog);
|
||||
await using var unitOfWork = await UnitOfWork.OpenAsync(target, NoMaps, context, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
await unitOfWork.InTransactionAsync(ct => SchemaVersionStore.EnsureCreatedAsync(unitOfWork, ct), cancellationToken).ConfigureAwait(false);
|
||||
var applied = await SchemaVersionStore.ReadAsync(unitOfWork, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var known = catalog.Migrations.Select(m => (m.Module, m.Version)).ToHashSet();
|
||||
var unknown = applied.Where(a => !known.Contains((a.Module, a.Version))).ToList();
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
throw new MigrationException(
|
||||
$"Database {target.DatabaseName} has migrations this version of Khaemhat does not know ("
|
||||
+ string.Join(", ", unknown.Select(u => $"{u.Module}/{u.Version} {u.Name}"))
|
||||
+ "): it was used by a newer version. Downgrades are not supported; restore a backup or install the newer version.");
|
||||
}
|
||||
|
||||
var appliedByKey = applied.ToDictionary(a => (a.Module, a.Version));
|
||||
var done = new List<(MigrationInfo, TimeSpan)>();
|
||||
var warnings = new List<string>();
|
||||
var alreadyApplied = 0;
|
||||
foreach (var migration in catalog.Migrations)
|
||||
{
|
||||
var statements = Statements(migration, unitOfWork.Provider);
|
||||
var checksum = Checksum(statements);
|
||||
if (appliedByKey.TryGetValue((migration.Module, migration.Version), out var row))
|
||||
{
|
||||
alreadyApplied++;
|
||||
if (!string.Equals(row.Checksum, checksum, StringComparison.Ordinal))
|
||||
{
|
||||
warnings.Add($"{migration}: the statements differ from those applied on {row.AppliedAt:yyyy-MM-dd}.");
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var watch = Stopwatch.StartNew();
|
||||
var appliedNow = false;
|
||||
await unitOfWork.InTransactionAsync(
|
||||
async ct =>
|
||||
{
|
||||
await unitOfWork.AcquireLockAsync(LockKey, ct).ConfigureAwait(false);
|
||||
if (await SchemaVersionStore.IsAppliedAsync(unitOfWork, migration.Module, migration.Version, ct).ConfigureAwait(false))
|
||||
{
|
||||
return; // another instance applied it meanwhile
|
||||
}
|
||||
|
||||
foreach (var statement in statements)
|
||||
{
|
||||
await unitOfWork.ExecuteAsync(SqlFragment.Literal(statement), ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await SchemaVersionStore.RecordAsync(
|
||||
unitOfWork, new AppliedMigration(migration.Module, migration.Version, migration.Name, context.UtcNow, checksum), ct)
|
||||
.ConfigureAwait(false);
|
||||
appliedNow = true;
|
||||
},
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (appliedNow)
|
||||
{
|
||||
done.Add((migration, watch.Elapsed));
|
||||
}
|
||||
else
|
||||
{
|
||||
alreadyApplied++;
|
||||
}
|
||||
}
|
||||
|
||||
return new MigrationReport(target.DatabaseName, done, alreadyApplied, warnings);
|
||||
}
|
||||
|
||||
/// <summary>The statements a migration runs on a provider.</summary>
|
||||
/// <param name="migration">The migration.</param>
|
||||
/// <param name="provider">The provider.</param>
|
||||
/// <returns>The statements.</returns>
|
||||
public static IReadOnlyList<string> Statements(MigrationInfo migration, IDbProvider provider)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(migration);
|
||||
ArgumentNullException.ThrowIfNull(provider);
|
||||
var instance = migration.Create();
|
||||
var builder = new SchemaBuilder();
|
||||
instance.Up(builder);
|
||||
var statements = provider.Ddl.Generate(builder.Operations).ToList();
|
||||
if (instance.UpSql(provider.Dialect) is { Length: > 0 } sql)
|
||||
{
|
||||
statements.Add(sql);
|
||||
}
|
||||
|
||||
return statements;
|
||||
}
|
||||
|
||||
private static string Checksum(IEnumerable<string> statements) =>
|
||||
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join(";\n", statements))));
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using Khaemhat.Data.Execution;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Migrations;
|
||||
|
||||
/// <summary>A row of <c>schema_version</c>.</summary>
|
||||
/// <param name="Module">The owning module.</param>
|
||||
/// <param name="Version">The version.</param>
|
||||
/// <param name="Name">The name.</param>
|
||||
/// <param name="AppliedAt">When it was applied (UTC).</param>
|
||||
/// <param name="Checksum">SHA-256 of the statements that were run, in hexadecimal.</param>
|
||||
public sealed record AppliedMigration(string Module, long Version, string Name, DateTime AppliedAt, string Checksum);
|
||||
|
||||
/// <summary>
|
||||
/// The <c>schema_version(module, version, name, applied_at, checksum)</c> table present in every database (SPEC §5.3).
|
||||
/// </summary>
|
||||
public static class SchemaVersionStore
|
||||
{
|
||||
/// <summary>The table name.</summary>
|
||||
public const string Table = "schema_version";
|
||||
|
||||
/// <summary>The operation creating the table if it is missing.</summary>
|
||||
public static CreateTableOperation CreateOperation { get; } = BuildCreateOperation();
|
||||
|
||||
/// <summary>Creates the table if it is missing.</summary>
|
||||
/// <param name="unitOfWork">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task EnsureCreatedAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
foreach (var statement in unitOfWork.Provider.Ddl.Generate([CreateOperation]))
|
||||
{
|
||||
await unitOfWork.ExecuteAsync(SqlFragment.Literal(statement), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>All applied migrations.</summary>
|
||||
/// <param name="unitOfWork">The unit of work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The rows, ordered by version.</returns>
|
||||
public static Task<IReadOnlyList<AppliedMigration>> ReadAsync(UnitOfWork unitOfWork, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
return unitOfWork.QueryAsync<AppliedMigration>(
|
||||
SqlFragment.Literal("SELECT module, version, name, applied_at, checksum FROM ") + SqlFragment.Identifier(Table)
|
||||
+ SqlFragment.Literal(" ORDER BY version, module"),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Whether a version is applied (read inside the migration transaction).</summary>
|
||||
/// <param name="unitOfWork">The unit of work.</param>
|
||||
/// <param name="module">The module.</param>
|
||||
/// <param name="version">The version.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns><see langword="true"/> if applied.</returns>
|
||||
public static async Task<bool> IsAppliedAsync(UnitOfWork unitOfWork, string module, long version, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
var count = await unitOfWork.QuerySingleAsync<long>(
|
||||
SqlFragment.Of($"SELECT COUNT(*) FROM {SqlFragment.Identifier(Table)} WHERE module = {module} AND version = {version}"),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
/// <summary>Records an applied migration.</summary>
|
||||
/// <param name="unitOfWork">The unit of work, inside the migration transaction.</param>
|
||||
/// <param name="applied">The row.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static Task RecordAsync(UnitOfWork unitOfWork, AppliedMigration applied, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentNullException.ThrowIfNull(applied);
|
||||
return unitOfWork.ExecuteAsync(
|
||||
SqlFragment.Of(
|
||||
$"INSERT INTO {SqlFragment.Identifier(Table)} (module, version, name, applied_at, checksum) VALUES ({applied.Module}, {applied.Version}, {applied.Name}, {applied.AppliedAt}, {applied.Checksum})"),
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
private static CreateTableOperation BuildCreateOperation()
|
||||
{
|
||||
var builder = new SchemaBuilder();
|
||||
builder.CreateTable(Table, t =>
|
||||
{
|
||||
t.String("module", 50).NotNull();
|
||||
t.Int64("version").NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.DateTimeUtc("applied_at").NotNull();
|
||||
t.String("checksum", 64).NotNull();
|
||||
t.PrimaryKey("module", "version");
|
||||
});
|
||||
return ((CreateTableOperation)builder.Operations[0]) with { IfNotExists = true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>A page of results with the total number of matching rows.</summary>
|
||||
/// <typeparam name="T">The item type.</typeparam>
|
||||
/// <param name="Items">The rows of the page.</param>
|
||||
/// <param name="TotalCount">All rows matching the filters.</param>
|
||||
/// <param name="Offset">Rows skipped.</param>
|
||||
/// <param name="Limit">Page size, or <see langword="null"/> when not paged.</param>
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, long TotalCount, int Offset, int? Limit)
|
||||
{
|
||||
/// <summary>Whether more rows follow this page.</summary>
|
||||
public bool HasMore => Offset + Items.Count < TotalCount;
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
using System.Collections;
|
||||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using Khaemhat.Data.Mapping;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.Querying;
|
||||
|
||||
/// <summary>
|
||||
/// Translates predicates of the safe subset of SPEC §5.2 into parameterized SQL. Every value — constants, captured
|
||||
/// variables, list items — becomes a parameter; only mapped column names reach the SQL text. Anything outside the
|
||||
/// subset throws <see cref="NotSupportedException"/>: use a <see cref="SqlFragment"/> condition instead.
|
||||
/// </summary>
|
||||
/// <param name="map">The map of the queried entity.</param>
|
||||
/// <param name="dialect">The dialect, for the case-insensitive <c>LIKE</c>.</param>
|
||||
public sealed class ExpressionTranslator(IEntityMap map, ISqlDialect dialect)
|
||||
{
|
||||
private static readonly SqlFragment True = SqlFragment.Literal("1 = 1");
|
||||
private static readonly SqlFragment False = SqlFragment.Literal("1 = 0");
|
||||
|
||||
/// <summary>Translates a predicate.</summary>
|
||||
/// <param name="predicate">A lambda with one parameter of the entity type returning <see cref="bool"/>.</param>
|
||||
/// <returns>The condition.</returns>
|
||||
public SqlFragment Translate(LambdaExpression predicate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(predicate);
|
||||
return Condition(predicate.Body, predicate.Parameters[0]);
|
||||
}
|
||||
|
||||
/// <summary>The column of a property selector such as <c>x => x.Name</c>.</summary>
|
||||
/// <param name="selector">The selector.</param>
|
||||
/// <returns>The column.</returns>
|
||||
public ColumnMap Column(LambdaExpression selector)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selector);
|
||||
return TryColumn(selector.Body, selector.Parameters[0])
|
||||
?? throw new NotSupportedException($"Only mapped properties of {map.EntityType.Name} can be used here: {selector}.");
|
||||
}
|
||||
|
||||
private SqlFragment Condition(Expression node, ParameterExpression entity)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case BinaryExpression { NodeType: ExpressionType.AndAlso } and:
|
||||
return (Condition(and.Left, entity) + SqlFragment.Literal(" AND ") + Condition(and.Right, entity)).Parenthesize();
|
||||
case BinaryExpression { NodeType: ExpressionType.OrElse } or:
|
||||
return (Condition(or.Left, entity) + SqlFragment.Literal(" OR ") + Condition(or.Right, entity)).Parenthesize();
|
||||
case UnaryExpression { NodeType: ExpressionType.Not } not:
|
||||
return SqlFragment.Literal("NOT ") + Condition(not.Operand, entity).Parenthesize();
|
||||
case BinaryExpression binary when Operator(binary.NodeType) is not null:
|
||||
return Comparison(binary, entity);
|
||||
case MethodCallExpression call:
|
||||
return Method(call, entity);
|
||||
case ConstantExpression { Value: bool constant }:
|
||||
return constant ? True : False;
|
||||
default:
|
||||
if (node.Type == typeof(bool) && TryColumn(node, entity) is { } flag)
|
||||
{
|
||||
return Name(flag) + SqlFragment.Literal(" = ") + Value(flag, true);
|
||||
}
|
||||
|
||||
if (node.Type == typeof(bool) && !References(node, entity))
|
||||
{
|
||||
return (bool)Evaluate(node)! ? True : False;
|
||||
}
|
||||
|
||||
throw Unsupported(node);
|
||||
}
|
||||
}
|
||||
|
||||
private SqlFragment Comparison(BinaryExpression binary, ParameterExpression entity)
|
||||
{
|
||||
var op = Operator(binary.NodeType)!;
|
||||
var leftColumn = TryColumn(binary.Left, entity);
|
||||
var rightColumn = TryColumn(binary.Right, entity);
|
||||
|
||||
if (leftColumn is not null && rightColumn is not null)
|
||||
{
|
||||
return Name(leftColumn) + SqlFragment.Literal(" " + op + " ") + Name(rightColumn);
|
||||
}
|
||||
|
||||
if (leftColumn is null && rightColumn is not null)
|
||||
{
|
||||
// value op column -> column (mirrored op) value
|
||||
(leftColumn, op) = (rightColumn, Mirror(op));
|
||||
return CompareWithValue(leftColumn, op, binary.Left, entity);
|
||||
}
|
||||
|
||||
return leftColumn is not null ? CompareWithValue(leftColumn, op, binary.Right, entity) : throw Unsupported(binary);
|
||||
}
|
||||
|
||||
private SqlFragment CompareWithValue(ColumnMap column, string op, Expression valueNode, ParameterExpression entity)
|
||||
{
|
||||
if (References(valueNode, entity))
|
||||
{
|
||||
throw Unsupported(valueNode);
|
||||
}
|
||||
|
||||
var value = Evaluate(valueNode);
|
||||
if (value is null)
|
||||
{
|
||||
return op switch
|
||||
{
|
||||
"=" => Name(column) + SqlFragment.Literal(" IS NULL"),
|
||||
"<>" => Name(column) + SqlFragment.Literal(" IS NOT NULL"),
|
||||
_ => throw new NotSupportedException($"Cannot compare {column.PropertyName} with null using {op}."),
|
||||
};
|
||||
}
|
||||
|
||||
return Name(column) + SqlFragment.Literal(" " + op + " ") + Value(column, value);
|
||||
}
|
||||
|
||||
private SqlFragment Method(MethodCallExpression call, ParameterExpression entity)
|
||||
{
|
||||
// column.Contains / StartsWith / EndsWith (value): case-insensitive LIKE
|
||||
if (call.Method.DeclaringType == typeof(string) && call.Object is not null && call.Arguments.Count >= 1
|
||||
&& call.Method.Name is nameof(string.Contains) or nameof(string.StartsWith) or nameof(string.EndsWith)
|
||||
&& TryColumn(call.Object, entity) is { } textColumn)
|
||||
{
|
||||
if (References(call.Arguments[0], entity))
|
||||
{
|
||||
throw Unsupported(call);
|
||||
}
|
||||
|
||||
var text = Evaluate(call.Arguments[0]) as string ?? string.Empty;
|
||||
var escaped = EscapeLike(text);
|
||||
var pattern = call.Method.Name switch
|
||||
{
|
||||
nameof(string.StartsWith) => escaped + "%",
|
||||
nameof(string.EndsWith) => "%" + escaped,
|
||||
_ => "%" + escaped + "%",
|
||||
};
|
||||
return Like(textColumn, pattern);
|
||||
}
|
||||
|
||||
// string.IsNullOrEmpty(column)
|
||||
if (call.Method.DeclaringType == typeof(string) && call.Method.Name == nameof(string.IsNullOrEmpty)
|
||||
&& TryColumn(call.Arguments[0], entity) is { } emptyColumn)
|
||||
{
|
||||
return (Name(emptyColumn) + SqlFragment.Literal(" IS NULL OR ") + Name(emptyColumn) + SqlFragment.Literal(" = ")
|
||||
+ SqlFragment.Parameter(string.Empty, emptyColumn.Type)).Parenthesize();
|
||||
}
|
||||
|
||||
// values.Contains(column) -> column IN (...)
|
||||
Expression? collection = null;
|
||||
Expression? item = null;
|
||||
if (call.Method.Name == nameof(Enumerable.Contains))
|
||||
{
|
||||
if (call.Object is null && call.Arguments.Count == 2)
|
||||
{
|
||||
(collection, item) = (call.Arguments[0], call.Arguments[1]);
|
||||
}
|
||||
else if (call.Object is not null && call.Arguments.Count == 1)
|
||||
{
|
||||
(collection, item) = (call.Object, call.Arguments[0]);
|
||||
}
|
||||
}
|
||||
|
||||
if (collection is not null && item is not null && TryColumn(item, entity) is { } inColumn && !References(collection, entity))
|
||||
{
|
||||
collection = UnwrapSpan(collection);
|
||||
var values = (Evaluate(collection) as IEnumerable)?.Cast<object?>().ToList() ?? [];
|
||||
if (values.Count == 0)
|
||||
{
|
||||
return False;
|
||||
}
|
||||
|
||||
var nonNull = values.Where(v => v is not null).Select(v => Value(inColumn, v!)).ToList();
|
||||
var condition = nonNull.Count == 0
|
||||
? SqlFragment.Empty
|
||||
: Name(inColumn) + SqlFragment.Literal(" IN (") + SqlFragment.Join(", ", nonNull) + SqlFragment.Literal(")");
|
||||
if (values.Count != nonNull.Count)
|
||||
{
|
||||
var isNull = Name(inColumn) + SqlFragment.Literal(" IS NULL");
|
||||
condition = condition.IsEmpty ? isNull : (condition + SqlFragment.Literal(" OR ") + isNull).Parenthesize();
|
||||
}
|
||||
|
||||
return condition;
|
||||
}
|
||||
|
||||
if (call.Type == typeof(bool) && !References(call, entity))
|
||||
{
|
||||
return (bool)Evaluate(call)! ? True : False;
|
||||
}
|
||||
|
||||
throw Unsupported(call);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// C# 14 binds <c>array.Contains(x)</c> to <c>MemoryExtensions.Contains(ReadOnlySpan<T>, T)</c> through an
|
||||
/// implicit conversion; spans cannot be evaluated by the expression interpreter, so read the array behind it.
|
||||
/// </summary>
|
||||
private static Expression UnwrapSpan(Expression node)
|
||||
{
|
||||
while (IsSpan(node.Type))
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case MethodCallExpression { Method.Name: "op_Implicit", Arguments.Count: 1 } conversion:
|
||||
node = conversion.Arguments[0];
|
||||
break;
|
||||
case UnaryExpression { NodeType: ExpressionType.Convert } convert:
|
||||
node = convert.Operand;
|
||||
break;
|
||||
default:
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
|
||||
static bool IsSpan(Type type) =>
|
||||
type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(ReadOnlySpan<>) || type.GetGenericTypeDefinition() == typeof(Span<>));
|
||||
}
|
||||
|
||||
private SqlFragment Like(ColumnMap column, string pattern) =>
|
||||
dialect.CaseInsensitiveLike(Name(column), SqlFragment.Parameter(pattern, ColumnType.Text));
|
||||
|
||||
private ColumnMap? TryColumn(Expression node, ParameterExpression entity)
|
||||
{
|
||||
while (node is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } convert)
|
||||
{
|
||||
node = convert.Operand;
|
||||
}
|
||||
|
||||
return node is MemberExpression { Member: PropertyInfo property } member && member.Expression == entity
|
||||
? map.FindByProperty(property.Name) ?? throw new NotSupportedException($"{map.EntityType.Name}.{property.Name} is not mapped.")
|
||||
: null;
|
||||
}
|
||||
|
||||
private static SqlFragment Name(ColumnMap column) => SqlFragment.Identifier(column.ColumnName);
|
||||
|
||||
private static SqlFragment Value(ColumnMap column, object value)
|
||||
{
|
||||
if (column.ValueType.IsEnum && value is not Enum)
|
||||
{
|
||||
value = Enum.ToObject(column.ValueType, value);
|
||||
}
|
||||
|
||||
return SqlFragment.Parameter(column.ToProvider(value), column.Type);
|
||||
}
|
||||
|
||||
private static string? Operator(ExpressionType type) => type switch
|
||||
{
|
||||
ExpressionType.Equal => "=",
|
||||
ExpressionType.NotEqual => "<>",
|
||||
ExpressionType.LessThan => "<",
|
||||
ExpressionType.LessThanOrEqual => "<=",
|
||||
ExpressionType.GreaterThan => ">",
|
||||
ExpressionType.GreaterThanOrEqual => ">=",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string Mirror(string op) => op switch
|
||||
{
|
||||
"<" => ">",
|
||||
"<=" => ">=",
|
||||
">" => "<",
|
||||
">=" => "<=",
|
||||
_ => op,
|
||||
};
|
||||
|
||||
private static string EscapeLike(string text) =>
|
||||
text.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("%", "\\%", StringComparison.Ordinal).Replace("_", "\\_", StringComparison.Ordinal);
|
||||
|
||||
private static bool References(Expression node, ParameterExpression entity)
|
||||
{
|
||||
var finder = new ParameterFinder(entity);
|
||||
finder.Visit(node);
|
||||
return finder.Found;
|
||||
}
|
||||
|
||||
private static object? Evaluate(Expression node)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case ConstantExpression constant:
|
||||
return constant.Value;
|
||||
case MemberExpression { Member: FieldInfo field } member when member.Expression is null or ConstantExpression:
|
||||
return field.GetValue((member.Expression as ConstantExpression)?.Value);
|
||||
case MemberExpression { Member: PropertyInfo property } member when member.Expression is null or ConstantExpression:
|
||||
return property.GetValue((member.Expression as ConstantExpression)?.Value);
|
||||
case MemberExpression { Member: FieldInfo field } member:
|
||||
return field.GetValue(Evaluate(member.Expression!));
|
||||
case MemberExpression { Member: PropertyInfo property } member:
|
||||
return property.GetValue(Evaluate(member.Expression!));
|
||||
case UnaryExpression { NodeType: ExpressionType.Convert } convert when convert.Type == typeof(object):
|
||||
return Evaluate(convert.Operand);
|
||||
default:
|
||||
return Expression.Lambda<Func<object?>>(Expression.Convert(node, typeof(object))).Compile(preferInterpretation: true)();
|
||||
}
|
||||
}
|
||||
|
||||
private NotSupportedException Unsupported(Expression node) =>
|
||||
new($"The expression '{node}' is outside the supported query subset for {map.EntityType.Name}; use a SqlFragment condition.");
|
||||
|
||||
private sealed class ParameterFinder(ParameterExpression parameter) : ExpressionVisitor
|
||||
{
|
||||
public bool Found { get; private set; }
|
||||
|
||||
protected override Expression VisitParameter(ParameterExpression node)
|
||||
{
|
||||
Found |= node == parameter;
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace Khaemhat.Data.Querying;
|
||||
|
||||
/// <summary>Starts queries: <c>Query.For<Party>().Where(p => p.Name.Contains(text)).OrderBy(p => p.Name).Page(0, 50)</c>.</summary>
|
||||
public static class Query
|
||||
{
|
||||
/// <summary>A query over all rows of <typeparamref name="T"/>.</summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <returns>The query.</returns>
|
||||
public static Query<T> For<T>()
|
||||
where T : class => Query<T>.All;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An immutable query over the table of <typeparamref name="T"/> (SPEC §5.2): filters in the safe expression subset
|
||||
/// (equality, comparisons, <c>Contains</c>/<c>StartsWith</c>/<c>EndsWith</c>, <c>In</c> as <c>list.Contains(x.Prop)</c>,
|
||||
/// <c>&&</c>, <c>||</c>, <c>!</c>, <c>== null</c>), parameterized <see cref="SqlFragment"/> conditions, ordering and
|
||||
/// paging. Each method returns a new query.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
public sealed class Query<T>
|
||||
where T : class
|
||||
{
|
||||
private Query(
|
||||
ImmutableList<LambdaExpression> filters, ImmutableList<SqlFragment> conditions, ImmutableList<QueryOrder> order, int offset, int? limit)
|
||||
{
|
||||
Filters = filters;
|
||||
Conditions = conditions;
|
||||
Order = order;
|
||||
Offset = offset;
|
||||
Limit = limit;
|
||||
}
|
||||
|
||||
internal static Query<T> All { get; } = new([], [], [], 0, null);
|
||||
|
||||
/// <summary>The expression filters, combined with <c>AND</c>.</summary>
|
||||
public ImmutableList<LambdaExpression> Filters { get; }
|
||||
|
||||
/// <summary>The SQL conditions, combined with <c>AND</c>.</summary>
|
||||
public ImmutableList<SqlFragment> Conditions { get; }
|
||||
|
||||
/// <summary>The ordering, in priority order.</summary>
|
||||
public ImmutableList<QueryOrder> Order { get; }
|
||||
|
||||
/// <summary>Rows to skip.</summary>
|
||||
public int Offset { get; }
|
||||
|
||||
/// <summary>Rows to return at most, or <see langword="null"/> for all.</summary>
|
||||
public int? Limit { get; }
|
||||
|
||||
/// <summary>Adds a filter.</summary>
|
||||
/// <param name="predicate">The predicate, in the supported subset.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> Where(Expression<Func<T, bool>> predicate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(predicate);
|
||||
return new(Filters.Add(predicate), Conditions, Order, Offset, Limit);
|
||||
}
|
||||
|
||||
/// <summary>Adds a parameterized SQL condition, for what expressions cannot say.</summary>
|
||||
/// <param name="condition">The condition, for example <c>SqlFragment.Of($"{SqlFragment.Identifier("total")} > {min}")</c>.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> Where(SqlFragment condition)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(condition);
|
||||
return condition.IsEmpty ? this : new(Filters, Conditions.Add(condition), Order, Offset, Limit);
|
||||
}
|
||||
|
||||
/// <summary>Orders by a property, ascending; further calls add secondary orderings.</summary>
|
||||
/// <typeparam name="TKey">The property type.</typeparam>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> OrderBy<TKey>(Expression<Func<T, TKey>> property) => AddOrder(property, descending: false);
|
||||
|
||||
/// <summary>Orders by a property, descending; further calls add secondary orderings.</summary>
|
||||
/// <typeparam name="TKey">The property type.</typeparam>
|
||||
/// <param name="property">The property.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> OrderByDescending<TKey>(Expression<Func<T, TKey>> property) => AddOrder(property, descending: true);
|
||||
|
||||
/// <summary>Returns at most <paramref name="limit"/> rows after skipping <paramref name="offset"/>.</summary>
|
||||
/// <param name="offset">Rows to skip.</param>
|
||||
/// <param name="limit">Rows to return.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> Page(int offset, int limit)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(offset);
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(limit);
|
||||
return new(Filters, Conditions, Order, offset, limit);
|
||||
}
|
||||
|
||||
/// <summary>Returns at most <paramref name="limit"/> rows.</summary>
|
||||
/// <param name="limit">Rows to return.</param>
|
||||
/// <returns>The new query.</returns>
|
||||
public Query<T> Take(int limit) => Page(Offset, limit);
|
||||
|
||||
private Query<T> AddOrder(LambdaExpression property, bool descending)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(property);
|
||||
return new(Filters, Conditions, Order.Add(new QueryOrder(property, descending)), Offset, Limit);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An ordering of a query.</summary>
|
||||
/// <param name="Property">The property selector.</param>
|
||||
/// <param name="Descending">Whether the order is descending.</param>
|
||||
public sealed record QueryOrder(LambdaExpression Property, bool Descending);
|
||||
@@ -0,0 +1,75 @@
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.Querying;
|
||||
|
||||
/// <summary>Turns a <see cref="Query{T}"/> into parameterized <c>SELECT</c> and <c>COUNT</c> statements for one dialect.</summary>
|
||||
/// <typeparam name="T">The entity type.</typeparam>
|
||||
/// <param name="map">The map of the entity.</param>
|
||||
/// <param name="dialect">The dialect.</param>
|
||||
public sealed class QueryBuilder<T>(EntityMap<T> map, ISqlDialect dialect)
|
||||
where T : class, new()
|
||||
{
|
||||
private readonly ExpressionTranslator _translator = new(map, dialect);
|
||||
|
||||
/// <summary>The map.</summary>
|
||||
public EntityMap<T> Map { get; } = map;
|
||||
|
||||
/// <summary>The list of mapped columns, in map order.</summary>
|
||||
public SqlFragment ColumnList => SqlFragment.Join(", ", Map.Columns.Select(c => SqlFragment.Identifier(c.ColumnName)));
|
||||
|
||||
/// <summary>The <c>WHERE</c> clause (with leading space), or empty when the query has no filters.</summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <returns>The clause.</returns>
|
||||
public SqlFragment Where(Query<T> query)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var conditions = query.Filters.Select(_translator.Translate).Concat(query.Conditions.Select(c => c.Parenthesize())).ToList();
|
||||
return conditions.Count == 0 ? SqlFragment.Empty : SqlFragment.Literal(" WHERE ") + SqlFragment.Join(" AND ", conditions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The <c>SELECT</c> statement with ordering and paging. A paged query without ordering is ordered by the key,
|
||||
/// so pages are stable.
|
||||
/// </summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public SqlFragment Select(Query<T> query)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(query);
|
||||
var sql = SqlFragment.Literal("SELECT ") + ColumnList + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(Map.Table) + Where(query);
|
||||
var order = query.Order
|
||||
.Select(o => SqlFragment.Identifier(_translator.Column(o.Property).ColumnName) + SqlFragment.Literal(o.Descending ? " DESC" : " ASC"))
|
||||
.ToList();
|
||||
var paged = query.Limit is not null || query.Offset > 0;
|
||||
if (order.Count == 0 && paged)
|
||||
{
|
||||
order.Add(SqlFragment.Identifier(Map.Key.ColumnName) + SqlFragment.Literal(" ASC"));
|
||||
}
|
||||
|
||||
if (order.Count > 0)
|
||||
{
|
||||
sql += SqlFragment.Literal(" ORDER BY ") + SqlFragment.Join(", ", order);
|
||||
}
|
||||
|
||||
if (paged)
|
||||
{
|
||||
sql += SqlFragment.Literal(dialect.Paging(query.Offset, query.Limit ?? int.MaxValue));
|
||||
}
|
||||
|
||||
return sql;
|
||||
}
|
||||
|
||||
/// <summary>The <c>COUNT(*)</c> statement for the filters of the query (ordering and paging ignored).</summary>
|
||||
/// <param name="query">The query.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public SqlFragment Count(Query<T> query) =>
|
||||
SqlFragment.Literal("SELECT COUNT(*) FROM ") + SqlFragment.Identifier(Map.Table) + Where(query);
|
||||
|
||||
/// <summary>The <c>SELECT</c> of one row by key.</summary>
|
||||
/// <param name="key">The key value.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
public SqlFragment SelectByKey(object key) =>
|
||||
SqlFragment.Literal("SELECT ") + ColumnList + SqlFragment.Literal(" FROM ") + SqlFragment.Identifier(Map.Table)
|
||||
+ SqlFragment.Literal(" WHERE ") + SqlFragment.Identifier(Map.Key.ColumnName) + SqlFragment.Literal(" = ")
|
||||
+ SqlFragment.Parameter(Map.Key.ToProvider(key), Map.Key.Type);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>
|
||||
/// Logical column types (SPEC §5.2), mapped by each dialect to a physical type:
|
||||
/// PostgreSQL <c>varchar(n)/text/int/bigint/numeric(19,6)/boolean/date/timestamptz/uuid/bytea/jsonb</c>;
|
||||
/// SQLite <c>TEXT/TEXT/INTEGER/INTEGER/INTEGER x10⁶/INTEGER 0-1/TEXT yyyy-MM-dd/TEXT ISO 8601 UTC/TEXT/BLOB/TEXT</c>.
|
||||
/// </summary>
|
||||
public enum ColumnType
|
||||
{
|
||||
/// <summary>Text with a maximum length <c>n</c> (<see cref="string"/>).</summary>
|
||||
String = 0,
|
||||
|
||||
/// <summary>Text without a length limit (<see cref="string"/>).</summary>
|
||||
Text = 1,
|
||||
|
||||
/// <summary>32-bit integer (<see cref="int"/>).</summary>
|
||||
Int32 = 2,
|
||||
|
||||
/// <summary>64-bit integer (<see cref="long"/>): primary and foreign keys.</summary>
|
||||
Int64 = 3,
|
||||
|
||||
/// <summary>Exact decimal with 19 digits, 6 after the point (<see cref="decimal"/>): amounts and quantities.</summary>
|
||||
Decimal = 4,
|
||||
|
||||
/// <summary>Boolean (<see cref="bool"/>).</summary>
|
||||
Bool = 5,
|
||||
|
||||
/// <summary>Calendar date without time (<see cref="DateOnly"/>).</summary>
|
||||
Date = 6,
|
||||
|
||||
/// <summary>Instant in UTC (<see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/>).</summary>
|
||||
DateTimeUtc = 7,
|
||||
|
||||
/// <summary>GUID (<see cref="System.Guid"/>).</summary>
|
||||
Guid = 8,
|
||||
|
||||
/// <summary>Binary data (<c>byte[]</c>).</summary>
|
||||
Bytes = 9,
|
||||
|
||||
/// <summary>JSON document stored as text (<see cref="string"/>).</summary>
|
||||
Json = 10,
|
||||
}
|
||||
|
||||
/// <summary>Helpers on <see cref="ColumnType"/>.</summary>
|
||||
public static class ColumnTypes
|
||||
{
|
||||
/// <summary>The fixed precision of <see cref="ColumnType.Decimal"/>.</summary>
|
||||
public const int DecimalPrecision = 19;
|
||||
|
||||
/// <summary>The default scale of <see cref="ColumnType.Decimal"/>.</summary>
|
||||
public const int DecimalScale = 6;
|
||||
|
||||
/// <summary>
|
||||
/// The logical type for a CLR type, or <see langword="null"/> when there is none (the value is then passed to the
|
||||
/// driver as it is). <see cref="string"/> maps to <see cref="ColumnType.Text"/>; enums are not mapped here
|
||||
/// (entity maps store them by name).
|
||||
/// </summary>
|
||||
/// <param name="type">The CLR type, nullable or not.</param>
|
||||
/// <returns>The logical type, if any.</returns>
|
||||
public static ColumnType? FromClrType(Type type)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(type);
|
||||
type = Nullable.GetUnderlyingType(type) ?? type;
|
||||
return type switch
|
||||
{
|
||||
_ when type == typeof(string) => ColumnType.Text,
|
||||
_ when type == typeof(int) || type == typeof(short) || type == typeof(byte) => ColumnType.Int32,
|
||||
_ when type == typeof(long) => ColumnType.Int64,
|
||||
_ when type == typeof(decimal) => ColumnType.Decimal,
|
||||
_ when type == typeof(bool) => ColumnType.Bool,
|
||||
_ when type == typeof(DateOnly) => ColumnType.Date,
|
||||
_ when type == typeof(DateTime) || type == typeof(DateTimeOffset) => ColumnType.DateTimeUtc,
|
||||
_ when type == typeof(Guid) => ColumnType.Guid,
|
||||
_ when type == typeof(byte[]) => ColumnType.Bytes,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The canonical CLR type the dialects return for a logical type.</summary>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <returns>The CLR type.</returns>
|
||||
public static Type ClrType(ColumnType type) => type switch
|
||||
{
|
||||
ColumnType.String or ColumnType.Text or ColumnType.Json => typeof(string),
|
||||
ColumnType.Int32 => typeof(int),
|
||||
ColumnType.Int64 => typeof(long),
|
||||
ColumnType.Decimal => typeof(decimal),
|
||||
ColumnType.Bool => typeof(bool),
|
||||
ColumnType.Date => typeof(DateOnly),
|
||||
ColumnType.DateTimeUtc => typeof(DateTime),
|
||||
ColumnType.Guid => typeof(Guid),
|
||||
ColumnType.Bytes => typeof(byte[]),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
|
||||
};
|
||||
|
||||
/// <summary>The logical type as written in the documentation, for example <c>String(20)</c> or <c>Decimal(19,6)</c>.</summary>
|
||||
/// <param name="type">The logical type.</param>
|
||||
/// <param name="length">The length for <see cref="ColumnType.String"/>.</param>
|
||||
/// <param name="scale">The scale for <see cref="ColumnType.Decimal"/>.</param>
|
||||
/// <returns>The description.</returns>
|
||||
public static string Describe(ColumnType type, int? length, int? scale) => type switch
|
||||
{
|
||||
ColumnType.String => FormattableString.Invariant($"String({length})"),
|
||||
ColumnType.Decimal => FormattableString.Invariant($"Decimal({DecimalPrecision},{scale ?? DecimalScale})"),
|
||||
_ => type.ToString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>
|
||||
/// Turns recorded <see cref="SchemaOperation"/>s into DDL statements for one engine (SPEC §5.3, <c>DdlGenerator</c>).
|
||||
/// The common SQL lives here; providers override what differs (identity columns, table options, constraints).
|
||||
/// </summary>
|
||||
/// <param name="dialect">The dialect of the engine.</param>
|
||||
public abstract class DdlGenerator(ISqlDialect dialect)
|
||||
{
|
||||
/// <summary>The dialect.</summary>
|
||||
public ISqlDialect Dialect { get; } = dialect ?? throw new ArgumentNullException(nameof(dialect));
|
||||
|
||||
/// <summary>Generates the statements for <paramref name="operations"/>, in order.</summary>
|
||||
/// <param name="operations">The operations.</param>
|
||||
/// <returns>The statements, without trailing semicolons.</returns>
|
||||
public IReadOnlyList<string> Generate(IEnumerable<SchemaOperation> operations)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operations);
|
||||
var statements = new List<string>();
|
||||
foreach (var operation in operations)
|
||||
{
|
||||
switch (operation)
|
||||
{
|
||||
case CreateTableOperation create:
|
||||
statements.Add(CreateTable(create.Table, create.IfNotExists));
|
||||
statements.AddRange(create.Table.Indexes.Select(i => CreateIndex(i, create.IfNotExists)));
|
||||
break;
|
||||
case DropTableOperation drop:
|
||||
statements.Add("DROP TABLE " + Dialect.Quote(drop.Table));
|
||||
break;
|
||||
case AddColumnOperation add:
|
||||
statements.Add("ALTER TABLE " + Dialect.Quote(add.Table) + " ADD COLUMN " + Column(add.Column, inlinePrimaryKey: false));
|
||||
break;
|
||||
case CreateIndexOperation index:
|
||||
statements.Add(CreateIndex(index.Index, ifNotExists: false));
|
||||
break;
|
||||
case DropIndexOperation dropIndex:
|
||||
statements.Add("DROP INDEX " + Dialect.Quote(dropIndex.Name));
|
||||
break;
|
||||
case RawSqlOperation raw when raw.Sql(Dialect) is { Length: > 0 } sql:
|
||||
statements.Add(sql);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return statements;
|
||||
}
|
||||
|
||||
/// <summary>The <c>CREATE TABLE</c> statement.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
/// <param name="ifNotExists">Whether to add <c>IF NOT EXISTS</c>.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
protected virtual string CreateTable(TableDefinition table, bool ifNotExists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(table);
|
||||
var identityKey = table.PrimaryKey.Count == 1 && table.Column(table.PrimaryKey[0])?.IsIdentity == true;
|
||||
var lines = table.Columns.Select(c => Column(c, inlinePrimaryKey: identityKey && c.Name == table.PrimaryKey[0])).ToList();
|
||||
if (!identityKey && table.PrimaryKey.Count > 0)
|
||||
{
|
||||
lines.Add("CONSTRAINT " + Dialect.Quote("pk_" + table.Name) + " PRIMARY KEY (" + string.Join(", ", table.PrimaryKey.Select(Dialect.Quote)) + ")");
|
||||
}
|
||||
|
||||
foreach (var foreignKey in table.ForeignKeys)
|
||||
{
|
||||
lines.Add(
|
||||
"CONSTRAINT " + Dialect.Quote(foreignKey.Name) + " FOREIGN KEY (" + string.Join(", ", foreignKey.Columns.Select(Dialect.Quote))
|
||||
+ ") REFERENCES " + Dialect.Quote(foreignKey.ReferencedTable) + " (" + string.Join(", ", foreignKey.ReferencedColumns.Select(Dialect.Quote))
|
||||
+ ") ON DELETE " + foreignKey.OnDelete switch
|
||||
{
|
||||
ReferentialAction.Cascade => "CASCADE",
|
||||
ReferentialAction.SetNull => "SET NULL",
|
||||
_ => "RESTRICT",
|
||||
});
|
||||
}
|
||||
|
||||
var builder = new StringBuilder("CREATE TABLE ");
|
||||
if (ifNotExists)
|
||||
{
|
||||
builder.Append("IF NOT EXISTS ");
|
||||
}
|
||||
|
||||
builder.Append(Dialect.Quote(table.Name)).Append(" (\n ").AppendJoin(",\n ", lines).Append("\n)").Append(TableOptions(table));
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Text appended after the closing parenthesis of <c>CREATE TABLE</c> (SQLite: <c> STRICT</c>).</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
/// <returns>The options, possibly empty.</returns>
|
||||
protected virtual string TableOptions(TableDefinition table) => string.Empty;
|
||||
|
||||
/// <summary>A column definition.</summary>
|
||||
/// <param name="column">The column.</param>
|
||||
/// <param name="inlinePrimaryKey">Whether the column is the identity primary key.</param>
|
||||
/// <returns>The SQL.</returns>
|
||||
protected virtual string Column(ColumnDefinition column, bool inlinePrimaryKey)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(column);
|
||||
if (inlinePrimaryKey)
|
||||
{
|
||||
return IdentityPrimaryKey(column);
|
||||
}
|
||||
|
||||
var builder = new StringBuilder(Dialect.Quote(column.Name)).Append(' ').Append(Dialect.SqlType(column.Type, column.Length, column.Scale));
|
||||
if (!column.IsNullable)
|
||||
{
|
||||
builder.Append(" NOT NULL");
|
||||
}
|
||||
|
||||
if (column.DefaultsToCurrentTimestamp)
|
||||
{
|
||||
builder.Append(" DEFAULT (").Append(Dialect.CurrentTimestampUtc).Append(')');
|
||||
}
|
||||
else if (column.DefaultValue is not null)
|
||||
{
|
||||
builder.Append(" DEFAULT ").Append(Dialect.Literal(column.DefaultValue, column.Type));
|
||||
}
|
||||
|
||||
builder.Append(ColumnConstraints(column));
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
/// <summary>Extra constraints after a column, for example SQLite checks for lengths and booleans.</summary>
|
||||
/// <param name="column">The column.</param>
|
||||
/// <returns>The constraints, possibly empty.</returns>
|
||||
protected virtual string ColumnConstraints(ColumnDefinition column) => string.Empty;
|
||||
|
||||
/// <summary>The definition of an identity primary key column.</summary>
|
||||
/// <param name="column">The column.</param>
|
||||
/// <returns>The SQL.</returns>
|
||||
protected abstract string IdentityPrimaryKey(ColumnDefinition column);
|
||||
|
||||
/// <summary>The <c>CREATE INDEX</c> statement.</summary>
|
||||
/// <param name="index">The index.</param>
|
||||
/// <param name="ifNotExists">Whether to add <c>IF NOT EXISTS</c>.</param>
|
||||
/// <returns>The statement.</returns>
|
||||
protected virtual string CreateIndex(IndexDefinition index, bool ifNotExists)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(index);
|
||||
return "CREATE " + (index.IsUnique ? "UNIQUE " : string.Empty) + "INDEX " + (ifNotExists ? "IF NOT EXISTS " : string.Empty)
|
||||
+ Dialect.Quote(index.Name) + " ON " + Dialect.Quote(index.Table) + " (" + string.Join(", ", index.Columns.Select(Dialect.Quote)) + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>
|
||||
/// What a migration uses to describe schema changes in engine-neutral form (SPEC §5.3). The calls are recorded as
|
||||
/// <see cref="SchemaOperation"/>s; each provider's <see cref="DdlGenerator"/> turns them into DDL for its engine.
|
||||
/// <code>
|
||||
/// schema.CreateTable("sys_settings", t =>
|
||||
/// {
|
||||
/// t.Id();
|
||||
/// t.String("key", 200).NotNull();
|
||||
/// t.Text("value");
|
||||
/// t.AuditColumns();
|
||||
/// t.Unique("ux_sys_settings_key", "key");
|
||||
/// });
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public interface ISchemaBuilder
|
||||
{
|
||||
/// <summary>Creates a table.</summary>
|
||||
/// <param name="name">The table name.</param>
|
||||
/// <param name="define">Defines columns, keys, indexes and foreign keys.</param>
|
||||
void CreateTable(string name, Action<TableBuilder> define);
|
||||
|
||||
/// <summary>
|
||||
/// Changes an existing table: adds columns and indexes. Foreign keys can only be declared when the table is
|
||||
/// created (SQLite cannot add them later).
|
||||
/// </summary>
|
||||
/// <param name="name">The table name.</param>
|
||||
/// <param name="define">Adds columns and indexes.</param>
|
||||
void AlterTable(string name, Action<TableBuilder> define);
|
||||
|
||||
/// <summary>Drops a table.</summary>
|
||||
/// <param name="name">The table name.</param>
|
||||
void DropTable(string name);
|
||||
|
||||
/// <summary>Creates an index.</summary>
|
||||
/// <param name="table">The table.</param>
|
||||
/// <param name="name">The index name.</param>
|
||||
/// <param name="unique">Whether it is unique.</param>
|
||||
/// <param name="columns">The columns.</param>
|
||||
void CreateIndex(string table, string name, bool unique, params string[] columns);
|
||||
|
||||
/// <summary>Drops an index.</summary>
|
||||
/// <param name="name">The index name.</param>
|
||||
void DropIndex(string name);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a dialect-specific statement at this point, for what the neutral operations cannot express. The function
|
||||
/// returns <see langword="null"/> for dialects where nothing is needed.
|
||||
/// </summary>
|
||||
/// <param name="sql">Produces the trusted SQL for a dialect.</param>
|
||||
void Sql(Func<ISqlDialect, string?> sql);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>Records the calls of a migration as <see cref="SchemaOperation"/>s.</summary>
|
||||
public sealed class SchemaBuilder : ISchemaBuilder
|
||||
{
|
||||
private readonly List<SchemaOperation> _operations = [];
|
||||
|
||||
/// <summary>The recorded operations, in order.</summary>
|
||||
public IReadOnlyList<SchemaOperation> Operations => _operations;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CreateTable(string name, Action<TableBuilder> define)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(define);
|
||||
var builder = new TableBuilder(name, alter: false);
|
||||
define(builder);
|
||||
_operations.AddRange(builder.Build());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void AlterTable(string name, Action<TableBuilder> define)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(define);
|
||||
var builder = new TableBuilder(name, alter: true);
|
||||
define(builder);
|
||||
_operations.AddRange(builder.Build());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void DropTable(string name)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(name);
|
||||
_operations.Add(new DropTableOperation(name));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CreateIndex(string table, string name, bool unique, params string[] columns) =>
|
||||
AlterTable(table, t => _ = unique ? t.Unique(name, columns) : t.Index(name, columns));
|
||||
|
||||
/// <inheritdoc />
|
||||
public void DropIndex(string name)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(name);
|
||||
_operations.Add(new DropIndexOperation(name));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Sql(Func<ISqlDialect, string?> sql)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sql);
|
||||
_operations.Add(new RawSqlOperation(sql));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>
|
||||
/// The schema that results from applying operations, kept in memory: used to document the data model
|
||||
/// (<c>scripts/gen-datamodel.sh</c>) and to check that entity maps agree with the migrations. Dialect-specific
|
||||
/// statements (<see cref="RawSqlOperation"/>) are not modelled.
|
||||
/// </summary>
|
||||
public sealed class SchemaModel
|
||||
{
|
||||
private readonly SortedDictionary<string, TableDefinition> _tables = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The tables, by name.</summary>
|
||||
public IReadOnlyCollection<TableDefinition> Tables => _tables.Values;
|
||||
|
||||
/// <summary>Finds a table.</summary>
|
||||
/// <param name="name">The table name.</param>
|
||||
/// <returns>The table, or <see langword="null"/>.</returns>
|
||||
public TableDefinition? Table(string name) => _tables.GetValueOrDefault(name);
|
||||
|
||||
/// <summary>Applies operations in order.</summary>
|
||||
/// <param name="operations">The operations.</param>
|
||||
public void Apply(IEnumerable<SchemaOperation> operations)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(operations);
|
||||
foreach (var operation in operations)
|
||||
{
|
||||
Apply(operation);
|
||||
}
|
||||
}
|
||||
|
||||
private void Apply(SchemaOperation operation)
|
||||
{
|
||||
switch (operation)
|
||||
{
|
||||
case CreateTableOperation create when create.IfNotExists && _tables.ContainsKey(create.Table.Name):
|
||||
break;
|
||||
case CreateTableOperation create:
|
||||
if (!_tables.TryAdd(create.Table.Name, Copy(create.Table)))
|
||||
{
|
||||
throw new InvalidOperationException($"Table {create.Table.Name} is created twice.");
|
||||
}
|
||||
|
||||
break;
|
||||
case DropTableOperation drop:
|
||||
_tables.Remove(drop.Table);
|
||||
break;
|
||||
case AddColumnOperation add:
|
||||
Require(add.Table).AddColumn(add.Column);
|
||||
break;
|
||||
case CreateIndexOperation index:
|
||||
Require(index.Index.Table).AddIndex(index.Index);
|
||||
break;
|
||||
case DropIndexOperation dropIndex:
|
||||
foreach (var table in _tables.Values)
|
||||
{
|
||||
table.RemoveIndex(dropIndex.Name);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private TableDefinition Require(string name) =>
|
||||
_tables.GetValueOrDefault(name) ?? throw new InvalidOperationException($"Table {name} does not exist.");
|
||||
|
||||
private static TableDefinition Copy(TableDefinition source)
|
||||
{
|
||||
var copy = new TableDefinition(source.Name) { PrimaryKey = source.PrimaryKey, PartitionByYearColumn = source.PartitionByYearColumn };
|
||||
foreach (var column in source.Columns)
|
||||
{
|
||||
copy.AddColumn(column);
|
||||
}
|
||||
|
||||
foreach (var index in source.Indexes)
|
||||
{
|
||||
copy.AddIndex(index);
|
||||
}
|
||||
|
||||
foreach (var foreignKey in source.ForeignKeys)
|
||||
{
|
||||
copy.AddForeignKey(foreignKey);
|
||||
}
|
||||
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>A schema change recorded by <see cref="ISchemaBuilder"/>.</summary>
|
||||
public abstract record SchemaOperation;
|
||||
|
||||
/// <summary>Creates a table.</summary>
|
||||
/// <param name="Table">The table.</param>
|
||||
/// <param name="IfNotExists">Whether to skip the creation when the table exists (only for <c>schema_version</c>).</param>
|
||||
public sealed record CreateTableOperation(TableDefinition Table, bool IfNotExists = false) : SchemaOperation;
|
||||
|
||||
/// <summary>Drops a table.</summary>
|
||||
/// <param name="Table">The table name.</param>
|
||||
public sealed record DropTableOperation(string Table) : SchemaOperation;
|
||||
|
||||
/// <summary>Adds a column to an existing table.</summary>
|
||||
/// <param name="Table">The table name.</param>
|
||||
/// <param name="Column">The column.</param>
|
||||
public sealed record AddColumnOperation(string Table, ColumnDefinition Column) : SchemaOperation;
|
||||
|
||||
/// <summary>Creates an index.</summary>
|
||||
/// <param name="Index">The index.</param>
|
||||
public sealed record CreateIndexOperation(IndexDefinition Index) : SchemaOperation;
|
||||
|
||||
/// <summary>Drops an index.</summary>
|
||||
/// <param name="Name">The index name.</param>
|
||||
public sealed record DropIndexOperation(string Name) : SchemaOperation;
|
||||
|
||||
/// <summary>A dialect-specific statement.</summary>
|
||||
/// <param name="Sql">Produces the SQL for a dialect, or <see langword="null"/>.</param>
|
||||
public sealed record RawSqlOperation(Func<ISqlDialect, string?> Sql) : SchemaOperation;
|
||||
@@ -0,0 +1,347 @@
|
||||
namespace Khaemhat.Data.Schema;
|
||||
|
||||
/// <summary>Defines the columns, keys, indexes and foreign keys of a table inside <see cref="ISchemaBuilder"/>.</summary>
|
||||
public sealed class TableBuilder
|
||||
{
|
||||
private readonly List<ColumnBuilder> _columns = [];
|
||||
private readonly List<IndexDefinition> _indexes = [];
|
||||
private readonly List<ForeignKeyDefinition> _foreignKeys = [];
|
||||
private readonly bool _alter;
|
||||
private string[] _primaryKey = [];
|
||||
private string? _partitionColumn;
|
||||
|
||||
internal TableBuilder(string name, bool alter)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(name);
|
||||
Name = name;
|
||||
_alter = alter;
|
||||
}
|
||||
|
||||
/// <summary>The table name.</summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>The standard primary key: <c>id</c>, 64-bit identity.</summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder Id()
|
||||
{
|
||||
var column = Add("id", ColumnType.Int64).NotNull();
|
||||
column.Identity = true;
|
||||
_primaryKey = ["id"];
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.String"/> column of at most <paramref name="length"/> characters.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <param name="length">The maximum length (1 to 10485760).</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder String(string name, int length)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(length, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(length, 10_485_760);
|
||||
var column = Add(name, ColumnType.String);
|
||||
column.Length = length;
|
||||
return column;
|
||||
}
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Text"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Text(string name) => Add(name, ColumnType.Text);
|
||||
|
||||
/// <summary>Adds an <see cref="ColumnType.Int32"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Int32(string name) => Add(name, ColumnType.Int32);
|
||||
|
||||
/// <summary>Adds an <see cref="ColumnType.Int64"/> column (for example a foreign key <c>party_id</c>).</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Int64(string name) => Add(name, ColumnType.Int64);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Decimal"/> column, precision 19.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <param name="scale">Digits after the point, 0 to 6.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Decimal(string name, int scale = ColumnTypes.DecimalScale)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(scale);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, ColumnTypes.DecimalScale);
|
||||
var column = Add(name, ColumnType.Decimal);
|
||||
column.Scale = scale;
|
||||
return column;
|
||||
}
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Bool"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Bool(string name) => Add(name, ColumnType.Bool);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Date"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Date(string name) => Add(name, ColumnType.Date);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.DateTimeUtc"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder DateTimeUtc(string name) => Add(name, ColumnType.DateTimeUtc);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Guid"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Guid(string name) => Add(name, ColumnType.Guid);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Bytes"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Bytes(string name) => Add(name, ColumnType.Bytes);
|
||||
|
||||
/// <summary>Adds a <see cref="ColumnType.Json"/> column.</summary>
|
||||
/// <param name="name">The column name.</param>
|
||||
/// <returns>The column builder.</returns>
|
||||
public ColumnBuilder Json(string name) => Add(name, ColumnType.Json);
|
||||
|
||||
/// <summary>
|
||||
/// Adds the audit columns of SPEC §5.2: <c>created_at</c>, <c>created_by</c>, <c>updated_at</c>, <c>updated_by</c>,
|
||||
/// <c>row_version</c> (default 1).
|
||||
/// </summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder AuditColumns()
|
||||
{
|
||||
DateTimeUtc("created_at").NotNull();
|
||||
String("created_by", AuditColumnLengths.User);
|
||||
DateTimeUtc("updated_at");
|
||||
String("updated_by", AuditColumnLengths.User);
|
||||
Int64("row_version").NotNull().Default(1L);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds <c>is_demo</c> (boolean, default false) for rows created by the demo seeder (SPEC §14).</summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder DemoColumn()
|
||||
{
|
||||
Bool("is_demo").NotNull().Default(false);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Sets a primary key other than <see cref="Id"/>, for example a composite key.</summary>
|
||||
/// <param name="columns">The key columns.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder PrimaryKey(params string[] columns)
|
||||
{
|
||||
EnsureCreate("A primary key");
|
||||
ArgumentNullException.ThrowIfNull(columns);
|
||||
ArgumentOutOfRangeException.ThrowIfZero(columns.Length);
|
||||
_primaryKey = columns;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>Adds a non-unique index.</summary>
|
||||
/// <param name="name">The index name, for example <c>ix_parties_name</c>.</param>
|
||||
/// <param name="columns">The columns.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder Index(string name, params string[] columns) => AddIndex(name, false, columns);
|
||||
|
||||
/// <summary>Adds a unique index.</summary>
|
||||
/// <param name="name">The index name, for example <c>ux_parties_code</c>.</param>
|
||||
/// <param name="columns">The columns.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder Unique(string name, params string[] columns) => AddIndex(name, true, columns);
|
||||
|
||||
/// <summary>Adds a foreign key from <paramref name="column"/> to the <c>id</c> of <paramref name="referencedTable"/>.</summary>
|
||||
/// <param name="name">The constraint name, for example <c>fk_party_addresses_party</c>.</param>
|
||||
/// <param name="column">The referencing column.</param>
|
||||
/// <param name="referencedTable">The referenced table.</param>
|
||||
/// <param name="onDelete">The action on delete.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder ForeignKey(string name, string column, string referencedTable, ReferentialAction onDelete = ReferentialAction.Restrict)
|
||||
{
|
||||
EnsureCreate("A foreign key");
|
||||
SqlNames.EnsureIdentifier(name);
|
||||
SqlNames.EnsureIdentifier(column);
|
||||
SqlNames.EnsureIdentifier(referencedTable);
|
||||
_foreignKeys.Add(new ForeignKeyDefinition(name, [column], referencedTable, ["id"], onDelete));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records that PostgreSQL may partition this table by the year of <paramref name="column"/> (SPEC §5.2). Nothing
|
||||
/// changes now; a later migration activates it beyond 50 million rows.
|
||||
/// </summary>
|
||||
/// <param name="column">A <see cref="ColumnType.Date"/> or <see cref="ColumnType.DateTimeUtc"/> column.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public TableBuilder PartitionByYear(string column)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(column);
|
||||
_partitionColumn = column;
|
||||
return this;
|
||||
}
|
||||
|
||||
internal IEnumerable<SchemaOperation> Build()
|
||||
{
|
||||
if (!_alter)
|
||||
{
|
||||
var table = new TableDefinition(Name) { PrimaryKey = _primaryKey, PartitionByYearColumn = _partitionColumn };
|
||||
foreach (var column in _columns)
|
||||
{
|
||||
table.AddColumn(column.ToDefinition());
|
||||
}
|
||||
|
||||
foreach (var index in _indexes)
|
||||
{
|
||||
EnsureColumnsExist(table, index.Columns);
|
||||
table.AddIndex(index);
|
||||
}
|
||||
|
||||
foreach (var foreignKey in _foreignKeys)
|
||||
{
|
||||
EnsureColumnsExist(table, foreignKey.Columns);
|
||||
table.AddForeignKey(foreignKey);
|
||||
}
|
||||
|
||||
EnsureColumnsExist(table, table.PrimaryKey);
|
||||
yield return new CreateTableOperation(table);
|
||||
yield break;
|
||||
}
|
||||
|
||||
foreach (var column in _columns)
|
||||
{
|
||||
yield return new AddColumnOperation(Name, column.ToDefinition());
|
||||
}
|
||||
|
||||
foreach (var index in _indexes)
|
||||
{
|
||||
yield return new CreateIndexOperation(index);
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureColumnsExist(TableDefinition table, IEnumerable<string> columns)
|
||||
{
|
||||
foreach (var column in columns)
|
||||
{
|
||||
if (table.Column(column) is null)
|
||||
{
|
||||
throw new InvalidOperationException($"Table {table.Name} has no column {column}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ColumnBuilder Add(string name, ColumnType type)
|
||||
{
|
||||
if (_columns.Exists(c => c.Name == name))
|
||||
{
|
||||
throw new InvalidOperationException($"Column {name} is defined twice in table {Name}.");
|
||||
}
|
||||
|
||||
var column = new ColumnBuilder(name, type);
|
||||
_columns.Add(column);
|
||||
return column;
|
||||
}
|
||||
|
||||
private TableBuilder AddIndex(string name, bool unique, string[] columns)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(name);
|
||||
ArgumentNullException.ThrowIfNull(columns);
|
||||
ArgumentOutOfRangeException.ThrowIfZero(columns.Length);
|
||||
foreach (var column in columns)
|
||||
{
|
||||
SqlNames.EnsureIdentifier(column);
|
||||
}
|
||||
|
||||
_indexes.Add(new IndexDefinition(name, Name, columns, unique));
|
||||
return this;
|
||||
}
|
||||
|
||||
private void EnsureCreate(string what)
|
||||
{
|
||||
if (_alter)
|
||||
{
|
||||
throw new NotSupportedException(what + " can only be declared when the table is created.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Configures a column inside <see cref="TableBuilder"/>.</summary>
|
||||
public sealed class ColumnBuilder
|
||||
{
|
||||
internal ColumnBuilder(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; }
|
||||
|
||||
internal int? Length { get; set; }
|
||||
|
||||
internal int? Scale { get; set; }
|
||||
|
||||
internal bool Identity { get; set; }
|
||||
|
||||
private bool Nullable { get; set; } = true;
|
||||
|
||||
private object? DefaultValue { get; set; }
|
||||
|
||||
private bool DefaultTimestamp { get; set; }
|
||||
|
||||
/// <summary>The column refuses <c>NULL</c>.</summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public ColumnBuilder NotNull()
|
||||
{
|
||||
Nullable = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>The column accepts <c>NULL</c> (the default).</summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public ColumnBuilder Null()
|
||||
{
|
||||
Nullable = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>A constant default value (string, number, boolean or decimal).</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <returns>This builder.</returns>
|
||||
public ColumnBuilder Default(object value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
DefaultValue = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>The current UTC timestamp as default, for <see cref="ColumnType.DateTimeUtc"/>.</summary>
|
||||
/// <returns>This builder.</returns>
|
||||
public ColumnBuilder DefaultCurrentTimestamp()
|
||||
{
|
||||
if (Type != ColumnType.DateTimeUtc)
|
||||
{
|
||||
throw new InvalidOperationException("Only DateTimeUtc columns can default to the current timestamp.");
|
||||
}
|
||||
|
||||
DefaultTimestamp = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
internal ColumnDefinition ToDefinition() => new(Name, Type)
|
||||
{
|
||||
Length = Length,
|
||||
Scale = Scale,
|
||||
IsNullable = Nullable,
|
||||
IsIdentity = Identity,
|
||||
DefaultValue = DefaultValue,
|
||||
DefaultsToCurrentTimestamp = DefaultTimestamp,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Lengths of the audit columns.</summary>
|
||||
public static class AuditColumnLengths
|
||||
{
|
||||
/// <summary>Length of <c>created_by</c> and <c>updated_by</c>.</summary>
|
||||
public const int User = 100;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
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) + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// A piece of SQL whose values are always parameters (SPEC §5.2: never concatenate user input into SQL).
|
||||
/// Build it with an interpolated string: the literal text is code written by us, every hole becomes a parameter.
|
||||
/// <code>
|
||||
/// var sql = SqlFragment.Of($"SELECT name FROM parties WHERE code = {code} AND is_active = {true}");
|
||||
/// </code>
|
||||
/// A hole can also hold another <see cref="SqlFragment"/> (inserted as SQL, its parameters renumbered) or an
|
||||
/// identifier made with <see cref="Identifier"/> (quoted by the dialect). The text is produced only by
|
||||
/// <see cref="Render"/>, for one dialect.
|
||||
/// </summary>
|
||||
public sealed class SqlFragment
|
||||
{
|
||||
private readonly ImmutableArray<SqlPart> _parts;
|
||||
|
||||
private SqlFragment(ImmutableArray<SqlPart> parts) => _parts = parts;
|
||||
|
||||
/// <summary>The empty fragment.</summary>
|
||||
public static SqlFragment Empty { get; } = new([]);
|
||||
|
||||
/// <summary>Whether the fragment contains nothing.</summary>
|
||||
public bool IsEmpty => _parts.IsEmpty;
|
||||
|
||||
/// <summary>The number of parameters.</summary>
|
||||
public int ParameterCount => _parts.Count(p => p is ParameterPart);
|
||||
|
||||
internal ImmutableArray<SqlPart> Parts => _parts;
|
||||
|
||||
internal static SqlFragment FromParts(ImmutableArray<SqlPart> parts) => parts.IsEmpty ? Empty : new(parts);
|
||||
|
||||
/// <summary>Builds a fragment from an interpolated string: holes become parameters.</summary>
|
||||
/// <param name="handler">The interpolated string.</param>
|
||||
/// <returns>The fragment.</returns>
|
||||
public static SqlFragment Of(ref SqlInterpolatedStringHandler handler) => handler.ToFragment();
|
||||
|
||||
/// <summary>
|
||||
/// A fragment of trusted SQL text written in the code (keywords, operators, DDL generated from definitions).
|
||||
/// Never pass text that comes from users, files or the network: use parameters for values.
|
||||
/// </summary>
|
||||
/// <param name="trustedSql">The SQL text.</param>
|
||||
/// <returns>The fragment.</returns>
|
||||
public static SqlFragment Literal(string trustedSql)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(trustedSql);
|
||||
return trustedSql.Length == 0 ? Empty : new([new TextPart(trustedSql)]);
|
||||
}
|
||||
|
||||
/// <summary>A table or column name, quoted by the dialect when rendered.</summary>
|
||||
/// <param name="name">The identifier: lower-case letters, digits and underscore, optionally <c>table.column</c>.</param>
|
||||
/// <returns>The fragment.</returns>
|
||||
public static SqlFragment Identifier(string name)
|
||||
{
|
||||
SqlNames.EnsureQualifiedIdentifier(name);
|
||||
return new([new IdentifierPart(name)]);
|
||||
}
|
||||
|
||||
/// <summary>A single parameter, optionally with its logical type (needed for example for <see cref="ColumnType.Json"/>).</summary>
|
||||
/// <param name="value">The value.</param>
|
||||
/// <param name="type">The logical type, or <see langword="null"/> to infer it from the CLR type.</param>
|
||||
/// <returns>The fragment.</returns>
|
||||
public static SqlFragment Parameter(object? value, ColumnType? type = null) => new([new ParameterPart(value, type)]);
|
||||
|
||||
/// <summary>Joins fragments with a trusted separator such as <c>", "</c> or <c>" AND "</c>.</summary>
|
||||
/// <param name="separator">The separator text.</param>
|
||||
/// <param name="fragments">The fragments; empty ones are skipped.</param>
|
||||
/// <returns>The joined fragment.</returns>
|
||||
public static SqlFragment Join(string separator, IEnumerable<SqlFragment> fragments)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fragments);
|
||||
var builder = ImmutableArray.CreateBuilder<SqlPart>();
|
||||
var first = true;
|
||||
foreach (var fragment in fragments)
|
||||
{
|
||||
if (fragment.IsEmpty)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!first && separator.Length > 0)
|
||||
{
|
||||
builder.Add(new TextPart(separator));
|
||||
}
|
||||
|
||||
builder.AddRange(fragment._parts);
|
||||
first = false;
|
||||
}
|
||||
|
||||
return new(builder.ToImmutable());
|
||||
}
|
||||
|
||||
/// <summary>Concatenates two fragments.</summary>
|
||||
/// <param name="left">The first fragment.</param>
|
||||
/// <param name="right">The second fragment.</param>
|
||||
/// <returns>The concatenation.</returns>
|
||||
public static SqlFragment operator +(SqlFragment left, SqlFragment right)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(left);
|
||||
ArgumentNullException.ThrowIfNull(right);
|
||||
return left.Append(right);
|
||||
}
|
||||
|
||||
/// <summary>Appends another fragment.</summary>
|
||||
/// <param name="other">The fragment to append.</param>
|
||||
/// <returns>The concatenation.</returns>
|
||||
public SqlFragment Append(SqlFragment other)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(other);
|
||||
if (other.IsEmpty)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
return IsEmpty ? other : new(_parts.AddRange(other._parts));
|
||||
}
|
||||
|
||||
/// <summary>Wraps the fragment in parentheses.</summary>
|
||||
/// <returns>The wrapped fragment.</returns>
|
||||
public SqlFragment Parenthesize() => IsEmpty ? this : Literal("(") + this + Literal(")");
|
||||
|
||||
/// <summary>Produces the SQL text and the parameters for a dialect. Parameters are named <c>p0</c>, <c>p1</c>, …</summary>
|
||||
/// <param name="dialect">The dialect.</param>
|
||||
/// <returns>The text and the parameters.</returns>
|
||||
public RenderedSql Render(ISqlDialect dialect)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dialect);
|
||||
var text = new StringBuilder();
|
||||
var parameters = new List<SqlParameterValue>();
|
||||
foreach (var part in _parts)
|
||||
{
|
||||
switch (part)
|
||||
{
|
||||
case TextPart t:
|
||||
text.Append(t.Text);
|
||||
break;
|
||||
case IdentifierPart i:
|
||||
text.Append(QuoteQualified(dialect, i.Name));
|
||||
break;
|
||||
case ParameterPart p:
|
||||
var name = "p" + parameters.Count.ToString(CultureInfo.InvariantCulture);
|
||||
text.Append(dialect.Parameter(name));
|
||||
parameters.Add(new SqlParameterValue(name, p.Value, p.Type));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new RenderedSql(text.ToString(), parameters);
|
||||
}
|
||||
|
||||
/// <summary>A readable form for diagnostics: parameters appear as <c>@p0</c>, never with their values.</summary>
|
||||
/// <returns>The text.</returns>
|
||||
public override string ToString()
|
||||
{
|
||||
var text = new StringBuilder();
|
||||
var index = 0;
|
||||
foreach (var part in _parts)
|
||||
{
|
||||
text.Append(part switch
|
||||
{
|
||||
TextPart t => t.Text,
|
||||
IdentifierPart i => "\"" + i.Name + "\"",
|
||||
_ => "@p" + (index++).ToString(CultureInfo.InvariantCulture),
|
||||
});
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
}
|
||||
|
||||
private static string QuoteQualified(ISqlDialect dialect, string name)
|
||||
{
|
||||
var dot = name.IndexOf('.', StringComparison.Ordinal);
|
||||
return dot < 0 ? dialect.Quote(name) : dialect.Quote(name[..dot]) + "." + dialect.Quote(name[(dot + 1)..]);
|
||||
}
|
||||
|
||||
internal abstract record SqlPart;
|
||||
|
||||
internal sealed record TextPart(string Text) : SqlPart;
|
||||
|
||||
internal sealed record IdentifierPart(string Name) : SqlPart;
|
||||
|
||||
internal sealed record ParameterPart(object? Value, ColumnType? Type) : SqlPart;
|
||||
}
|
||||
|
||||
/// <summary>SQL text and parameters produced by <see cref="SqlFragment.Render"/>.</summary>
|
||||
/// <param name="Text">The SQL text.</param>
|
||||
/// <param name="Parameters">The parameters in order.</param>
|
||||
public sealed record RenderedSql(string Text, IReadOnlyList<SqlParameterValue> Parameters);
|
||||
|
||||
/// <summary>A parameter of a rendered statement.</summary>
|
||||
/// <param name="Name">The name without prefix, for example <c>p0</c>.</param>
|
||||
/// <param name="Value">The CLR value.</param>
|
||||
/// <param name="Type">The logical type, when known.</param>
|
||||
public sealed record SqlParameterValue(string Name, object? Value, ColumnType? Type)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => "@" + Name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Interpolated string handler for <see cref="SqlFragment.Of"/>: literal parts are kept as SQL text, holes become
|
||||
/// parameters (or nested fragments).
|
||||
/// </summary>
|
||||
[InterpolatedStringHandler]
|
||||
public ref struct SqlInterpolatedStringHandler
|
||||
{
|
||||
private readonly ImmutableArray<SqlFragment.SqlPart>.Builder _parts;
|
||||
|
||||
/// <summary>Called by the compiler.</summary>
|
||||
/// <param name="literalLength">Total length of the literal parts.</param>
|
||||
/// <param name="formattedCount">Number of holes.</param>
|
||||
public SqlInterpolatedStringHandler(int literalLength, int formattedCount)
|
||||
{
|
||||
_ = literalLength;
|
||||
_parts = ImmutableArray.CreateBuilder<SqlFragment.SqlPart>((formattedCount * 2) + 1);
|
||||
}
|
||||
|
||||
/// <summary>Called by the compiler for literal text.</summary>
|
||||
/// <param name="value">The literal.</param>
|
||||
public readonly void AppendLiteral(string value)
|
||||
{
|
||||
if (value.Length > 0)
|
||||
{
|
||||
_parts.Add(new SqlFragment.TextPart(value));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Called by the compiler for a hole: a parameter, or a nested fragment.</summary>
|
||||
/// <typeparam name="T">The value type.</typeparam>
|
||||
/// <param name="value">The value.</param>
|
||||
public readonly void AppendFormatted<T>(T value)
|
||||
{
|
||||
if (value is SqlFragment fragment)
|
||||
{
|
||||
_parts.AddRange(fragment.Parts);
|
||||
}
|
||||
else
|
||||
{
|
||||
_parts.Add(new SqlFragment.ParameterPart(value, null));
|
||||
}
|
||||
}
|
||||
|
||||
internal readonly SqlFragment ToFragment() => SqlFragment.FromParts(_parts.ToImmutable());
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Naming rules for tables, columns, indexes and constraints (SPEC §5.2): <c>snake_case</c>, lower-case ASCII letters,
|
||||
/// digits and underscore, at most 63 characters (the PostgreSQL limit). Identifiers are validated before being quoted,
|
||||
/// so they can never carry SQL.
|
||||
/// </summary>
|
||||
public static partial class SqlNames
|
||||
{
|
||||
/// <summary>Whether <paramref name="name"/> is a valid identifier.</summary>
|
||||
/// <param name="name">The name.</param>
|
||||
/// <returns><see langword="true"/> if valid.</returns>
|
||||
public static bool IsValidIdentifier(string? name) => name is not null && IdentifierPattern().IsMatch(name);
|
||||
|
||||
/// <summary>Throws if <paramref name="name"/> is not a valid identifier.</summary>
|
||||
/// <param name="name">The name.</param>
|
||||
/// <exception cref="ArgumentException">Not a valid identifier.</exception>
|
||||
public static void EnsureIdentifier(string name)
|
||||
{
|
||||
if (!IsValidIdentifier(name))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"'{name}' is not a valid SQL identifier: use lower-case letters, digits and underscore (snake_case).", nameof(name));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Throws if <paramref name="name"/> is neither an identifier nor <c>table.column</c>.</summary>
|
||||
/// <param name="name">The name.</param>
|
||||
public static void EnsureQualifiedIdentifier(string name)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
var dot = name.IndexOf('.', StringComparison.Ordinal);
|
||||
if (dot < 0)
|
||||
{
|
||||
EnsureIdentifier(name);
|
||||
return;
|
||||
}
|
||||
|
||||
EnsureIdentifier(name[..dot]);
|
||||
EnsureIdentifier(name[(dot + 1)..]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a C# name to <c>snake_case</c>: <c>RowVersion</c> → <c>row_version</c>, <c>VatID</c> → <c>vat_id</c>,
|
||||
/// <c>HTTPCode</c> → <c>http_code</c>, <c>Address2</c> → <c>address2</c>.
|
||||
/// </summary>
|
||||
/// <param name="name">The C# name.</param>
|
||||
/// <returns>The snake_case name.</returns>
|
||||
public static string ToSnakeCase(string name)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(name);
|
||||
var builder = new StringBuilder(name.Length + 8);
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
var c = name[i];
|
||||
if (char.IsUpper(c))
|
||||
{
|
||||
var previous = i > 0 ? name[i - 1] : '\0';
|
||||
var next = i + 1 < name.Length ? name[i + 1] : '\0';
|
||||
var startsWord = i > 0 && (char.IsLower(previous) || char.IsDigit(previous) || (char.IsUpper(previous) && char.IsLower(next)));
|
||||
if (startsWord && previous != '_')
|
||||
{
|
||||
builder.Append('_');
|
||||
}
|
||||
|
||||
builder.Append(char.ToLowerInvariant(c));
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
[GeneratedRegex("^[a-z_][a-z0-9_]{0,62}$", RegexOptions.CultureInvariant)]
|
||||
private static partial Regex IdentifierPattern();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase.Migrations;
|
||||
|
||||
/// <summary>The company registry (SPEC §5.4): one row per company database, its location stored encrypted.</summary>
|
||||
[Migration(20261111_001, "create_sys_companies", Target = MigrationTarget.System)]
|
||||
public sealed class M20261111_001_CreateSysCompanies : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("sys_companies", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("code", 20).NotNull();
|
||||
t.String("name", 200).NotNull();
|
||||
t.String("engine", 20).NotNull();
|
||||
t.Text("connection_string").NotNull();
|
||||
t.String("status", 40).NotNull().Default("Active");
|
||||
t.Bool("is_default").NotNull().Default(false);
|
||||
t.Text("notes");
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sys_companies_code", "code");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Khaemhat.Data.Migrations;
|
||||
using Khaemhat.Data.Schema;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase.Migrations;
|
||||
|
||||
/// <summary>Instance settings (SPEC §5.4): key/value pairs, secrets encrypted with the instance key.</summary>
|
||||
[Migration(20261111_002, "create_sys_settings", Target = MigrationTarget.System)]
|
||||
public sealed class M20261111_002_CreateSysSettings : IMigration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void Up(ISchemaBuilder schema)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schema);
|
||||
schema.CreateTable("sys_settings", t =>
|
||||
{
|
||||
t.Id();
|
||||
t.String("key", 200).NotNull();
|
||||
t.Text("value");
|
||||
t.Bool("is_secret").NotNull().Default(false);
|
||||
t.AuditColumns();
|
||||
t.Unique("ux_sys_settings_key", "key");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Data.Mapping;
|
||||
|
||||
namespace Khaemhat.Data.SystemDatabase;
|
||||
|
||||
/// <summary>Map of <see cref="Company"/> to <c>sys_companies</c>.</summary>
|
||||
public sealed class CompanyMap : EntityMap<Company>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public CompanyMap()
|
||||
{
|
||||
ToTable("sys_companies");
|
||||
Map(x => x.Code).MaxLength(20);
|
||||
Map(x => x.Name).MaxLength(200);
|
||||
Map(x => x.Engine).MaxLength(20);
|
||||
Map(x => x.Status).MaxLength(40);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Map of <see cref="SystemSetting"/> to <c>sys_settings</c>.</summary>
|
||||
public sealed class SystemSettingMap : EntityMap<SystemSetting>
|
||||
{
|
||||
/// <summary>Creates the map.</summary>
|
||||
public SystemSettingMap()
|
||||
{
|
||||
ToTable("sys_settings");
|
||||
Map(x => x.Key).MaxLength(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
namespace Khaemhat.Data;
|
||||
|
||||
/// <summary>Helpers on <see cref="IUnitOfWork"/>.</summary>
|
||||
public static class UnitOfWorkExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Takes the application lock <paramref name="key"/> until the end of the current transaction (numerators, closings,
|
||||
/// scheduler): <c>pg_advisory_xact_lock</c> on PostgreSQL; on SQLite the transaction already holds the write lock.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">The unit of work, with an open transaction.</param>
|
||||
/// <param name="key">The lock key, for example <c>numerator:FV:2026</c>.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task completed when the lock is held.</returns>
|
||||
public static async Task AcquireLockAsync(this IUnitOfWork unitOfWork, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentException.ThrowIfNullOrEmpty(key);
|
||||
if (unitOfWork.Transaction is null)
|
||||
{
|
||||
throw new InvalidOperationException("An application lock is held until the end of a transaction: call BeginAsync first.");
|
||||
}
|
||||
|
||||
var statement = unitOfWork.Dialect.AdvisoryLock(key);
|
||||
if (!statement.IsEmpty)
|
||||
{
|
||||
await unitOfWork.ExecuteAsync(statement, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in a transaction: commits if it completes, rolls back if it throws.</summary>
|
||||
/// <param name="unitOfWork">The unit of work.</param>
|
||||
/// <param name="work">The work.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>A task.</returns>
|
||||
public static async Task InTransactionAsync(this IUnitOfWork unitOfWork, Func<CancellationToken, Task> work, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(unitOfWork);
|
||||
ArgumentNullException.ThrowIfNull(work);
|
||||
await unitOfWork.BeginAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await work(cancellationToken).ConfigureAwait(false);
|
||||
await unitOfWork.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (unitOfWork.Transaction is not null)
|
||||
{
|
||||
await unitOfWork.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The instance key from <c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 random bytes (SPEC §6). The encryption key
|
||||
/// is derived with HKDF-SHA256, so the configured bytes are never used directly. The key is never printed.
|
||||
/// </summary>
|
||||
public sealed class SecretKey
|
||||
{
|
||||
/// <summary>The minimum length of the configured key, in bytes.</summary>
|
||||
public const int MinimumLength = 32;
|
||||
|
||||
private static readonly byte[] EncryptionInfo = "khaemhat/secrets/aes-256-gcm/v1"u8.ToArray();
|
||||
private static readonly byte[] IdentifierInfo = "khaemhat/secrets/key-id/v1"u8.ToArray();
|
||||
|
||||
private SecretKey(byte[] encryptionKey, string id)
|
||||
{
|
||||
EncryptionKey = encryptionKey;
|
||||
Id = id;
|
||||
}
|
||||
|
||||
/// <summary>A short public identifier of the key (8 hexadecimal digits), stored with each ciphertext.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
internal byte[] EncryptionKey { get; }
|
||||
|
||||
/// <summary>Reads a key in base64.</summary>
|
||||
/// <param name="base64">The configured value.</param>
|
||||
/// <returns>The key.</returns>
|
||||
/// <exception cref="FormatException">Not base64, or shorter than 32 bytes (the message never repeats the value).</exception>
|
||||
public static SecretKey FromBase64(string base64)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(base64))
|
||||
{
|
||||
throw new FormatException("KHAEMHAT_SECRET_KEY is empty: set it to the base64 of at least 32 random bytes.");
|
||||
}
|
||||
|
||||
byte[] material;
|
||||
try
|
||||
{
|
||||
material = Convert.FromBase64String(base64.Trim());
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new FormatException("KHAEMHAT_SECRET_KEY is not valid base64.");
|
||||
}
|
||||
|
||||
if (material.Length < MinimumLength)
|
||||
{
|
||||
throw new FormatException($"KHAEMHAT_SECRET_KEY must be the base64 of at least {MinimumLength} bytes (for example: openssl rand -base64 32).");
|
||||
}
|
||||
|
||||
var encryption = HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 32, salt: null, info: EncryptionInfo);
|
||||
var id = Convert.ToHexStringLower(HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 4, salt: null, info: IdentifierInfo));
|
||||
CryptographicOperations.ZeroMemory(material);
|
||||
return new SecretKey(encryption, id);
|
||||
}
|
||||
|
||||
/// <summary>Creates a new random key in base64, for setup instructions and tests.</summary>
|
||||
/// <returns>The base64 text of 32 random bytes.</returns>
|
||||
public static string GenerateBase64() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(MinimumLength));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => "SecretKey " + Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ISecretProtector"/> with AES-256-GCM (SPEC §5.4). A protected value is
|
||||
/// <c>khs1.<key id>.<base64url(nonce | tag | ciphertext)></c>; the purpose is authenticated as associated
|
||||
/// data, so a value cannot be moved to another purpose, and a value of another key is recognized by its key id.
|
||||
/// </summary>
|
||||
/// <param name="key">The instance key.</param>
|
||||
public sealed class SecretProtector(SecretKey key) : ISecretProtector
|
||||
{
|
||||
private const string Prefix = "khs1";
|
||||
private const int NonceSize = 12;
|
||||
private const int TagSize = 16;
|
||||
|
||||
/// <summary>The key.</summary>
|
||||
public SecretKey Key { get; } = key ?? throw new ArgumentNullException(nameof(key));
|
||||
|
||||
/// <summary>The key id stored in a protected value, or <see langword="null"/> if it is not one.</summary>
|
||||
/// <param name="protectedValue">The value.</param>
|
||||
/// <returns>The key id.</returns>
|
||||
public static string? KeyIdOf(string? protectedValue)
|
||||
{
|
||||
var parts = protectedValue?.Split('.');
|
||||
return parts is [Prefix, var id, _] ? id : null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Protect(string plaintext, string purpose)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plaintext);
|
||||
ArgumentException.ThrowIfNullOrEmpty(purpose);
|
||||
var plain = Encoding.UTF8.GetBytes(plaintext);
|
||||
var buffer = new byte[NonceSize + TagSize + plain.Length];
|
||||
var nonce = buffer.AsSpan(0, NonceSize);
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
using (var aes = new AesGcm(Key.EncryptionKey, TagSize))
|
||||
{
|
||||
aes.Encrypt(nonce, plain, buffer.AsSpan(NonceSize + TagSize), buffer.AsSpan(NonceSize, TagSize), Encoding.UTF8.GetBytes(purpose));
|
||||
}
|
||||
|
||||
CryptographicOperations.ZeroMemory(plain);
|
||||
return Prefix + "." + Key.Id + "." + Base64Url(buffer);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Unprotect(string protectedValue, string purpose)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(purpose);
|
||||
var parts = protectedValue?.Split('.');
|
||||
if (parts is not [Prefix, var id, var payload])
|
||||
{
|
||||
throw new SecretProtectionException("The value is not a protected secret.");
|
||||
}
|
||||
|
||||
if (!string.Equals(id, Key.Id, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SecretProtectionException(
|
||||
$"The secret was protected with another instance key ({id}, current {Key.Id}): check KHAEMHAT_SECRET_KEY or run the key rotation.");
|
||||
}
|
||||
|
||||
byte[] buffer;
|
||||
try
|
||||
{
|
||||
buffer = FromBase64Url(payload);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new SecretProtectionException("The protected secret is damaged.", ex);
|
||||
}
|
||||
|
||||
if (buffer.Length < NonceSize + TagSize)
|
||||
{
|
||||
throw new SecretProtectionException("The protected secret is damaged.");
|
||||
}
|
||||
|
||||
var plain = new byte[buffer.Length - NonceSize - TagSize];
|
||||
try
|
||||
{
|
||||
using var aes = new AesGcm(Key.EncryptionKey, TagSize);
|
||||
aes.Decrypt(
|
||||
buffer.AsSpan(0, NonceSize), buffer.AsSpan(NonceSize + TagSize), buffer.AsSpan(NonceSize, TagSize), plain, Encoding.UTF8.GetBytes(purpose));
|
||||
return Encoding.UTF8.GetString(plain);
|
||||
}
|
||||
catch (AuthenticationTagMismatchException ex)
|
||||
{
|
||||
throw new SecretProtectionException("The secret cannot be decrypted: damaged value or different purpose.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(plain);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
|
||||
private static byte[] FromBase64Url(string text)
|
||||
{
|
||||
var base64 = text.Replace('-', '+').Replace('_', '/');
|
||||
return Convert.FromBase64String(base64.PadRight(base64.Length + ((4 - (base64.Length % 4)) % 4), '='));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-encryption of secrets from the current key to <c>KHAEMHAT_SECRET_KEY_NEW</c> (SPEC §12.9). This is the building
|
||||
/// block; the procedure that walks every encrypted column of every database arrives in milestone M12.
|
||||
/// </summary>
|
||||
/// <param name="current">The protector with the current key.</param>
|
||||
/// <param name="next">The protector with the new key.</param>
|
||||
public sealed class SecretRotation(SecretProtector current, SecretProtector next)
|
||||
{
|
||||
/// <summary>Whether a value still needs to be re-encrypted with the new key.</summary>
|
||||
/// <param name="protectedValue">The protected value.</param>
|
||||
/// <returns><see langword="true"/> if it is not protected with the new key yet.</returns>
|
||||
public bool NeedsRotation(string protectedValue) => SecretProtector.KeyIdOf(protectedValue) != next.Key.Id;
|
||||
|
||||
/// <summary>Re-encrypts a value with the new key; values already rotated are returned unchanged.</summary>
|
||||
/// <param name="protectedValue">The protected value.</param>
|
||||
/// <param name="purpose">Its purpose.</param>
|
||||
/// <returns>The value protected with the new key.</returns>
|
||||
public string Rotate(string protectedValue, string purpose) =>
|
||||
NeedsRotation(protectedValue) ? next.Protect(current.Unprotect(protectedValue, purpose), purpose) : protectedValue;
|
||||
}
|
||||
Reference in new issue
Block a user