#nullable enable
using System;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
namespace OpenWaf.Data;
/// Marks a class as a row of a table. The name is the table; the
/// generator reads it and emits the mapping, so nothing at run time has to ask a
/// type what it is.
[AttributeUsage(AttributeTargets.Class)]
public sealed class TableAttribute(string name) : Attribute
{
public string Name { get; } = name;
}
/// Names the column a property maps to when it is not the snake_case of
/// the property name.
[AttributeUsage(AttributeTargets.Property)]
public sealed class ColumnAttribute(string name) : Attribute
{
public string Name { get; } = name;
}
///
/// The table's metadata, registered by generated code at module start-up.
///
/// This is the piece that makes the whole thing AOT-safe: the mapping from a CLR
/// member name to a column name is a function the compiler emitted, not something
/// a run-time resolver discovers. A NativeAOT binary has no resolver to fall back
/// on, and asking for one is exactly the refusal this slice exists to remove.
/// Taken from MicroOrm.OrmMeta in the neighbouring deployment.
///
public static class OrmMeta
{
private static readonly ConcurrentDictionary Map = new();
public static void Register(string table, Func columnOf, ImmutableArray columns) =>
Map[typeof(T)] = new TableMeta(table, columnOf, columns);
public static bool TryGet(Type type, [MaybeNullWhen(false)] out TableMeta meta) => Map.TryGetValue(type, out meta);
public static TableMeta Get(Type type) =>
Map.TryGetValue(type, out var meta)
? meta
: throw new InvalidOperationException(
$"No generated ORM metadata is registered for {type.FullName}. The type needs [Table] and the "
+ "OpenWaf.Data.Generator analyzer attached to the project that declares it.");
}
public sealed record TableMeta(string Table, Func ColumnOf, ImmutableArray Columns);