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,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);
|
||||
}
|
||||
Reference in new issue
Block a user