#nullable enable using System; using System.Data.Common; namespace OpenWaf.Data; /// /// The one place a column crosses into a CLR value. /// /// Generated code calls these instead of inlining reader.GetString(i) for /// two reasons. A wrong read is then wrong in one place, and the provider /// differences have somewhere to live: sqlite stores a bool as an INTEGER and /// PostgreSQL as a boolean, and a timestamp as an integer and as timestamptz. The /// generated materializer cannot know which provider it is running against; this /// can ask. /// public static class RowReader { public static string String(DbDataReader reader, int ordinal) => reader.IsDBNull(ordinal) ? throw Null(ordinal, "string") : reader.GetString(ordinal); public static bool Boolean(DbDataReader reader, int ordinal) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, "bool"); // sqlite answers an INTEGER column, Npgsql a boolean one. return reader.GetValue(ordinal) switch { bool flag => flag, long number => number != 0, int number => number != 0, var other => throw Mismatch(ordinal, "bool", other), }; } public static int Int32(DbDataReader reader, int ordinal) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, "int"); return reader.GetValue(ordinal) switch { int number => number, long number => checked((int)number), var other => throw Mismatch(ordinal, "int", other), }; } public static long Int64(DbDataReader reader, int ordinal) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, "long"); return reader.GetValue(ordinal) switch { long number => number, int number => number, var other => throw Mismatch(ordinal, "long", other), }; } public static DateTimeOffset DateTimeOffset(DbDataReader reader, int ordinal, ISqlDialect dialect) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, "DateTimeOffset"); return dialect.ReadDateTimeOffset(reader, ordinal); } public static Guid Guid(DbDataReader reader, int ordinal) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, "Guid"); return reader.GetFieldValue(ordinal); } /// A CLR type this layer has no named read for. It still reads — the /// driver's own conversion is used — so an entity gains a plain column without /// the generator having to know about it, and a column the driver cannot /// convert fails with the ordinal and the type in the message. public static T Required(DbDataReader reader, int ordinal) { if (reader.IsDBNull(ordinal)) throw Null(ordinal, typeof(T).Name); return reader.GetFieldValue(ordinal); } private static InvalidOperationException Null(int ordinal, string type) => new($"Column {ordinal} is NULL but the generated mapping for {type} does not allow it."); private static InvalidCastException Mismatch(int ordinal, string expected, object actual) => new($"Column {ordinal} came back as {actual.GetType().Name} and the generated mapping expects {expected}."); }