namespace Bts.ColumnExpressions; public class ColumnExpression { public ColumnExpression(string name, Type? type = null, object? value = null) { Name = name; Type = type ?? value?.GetType() ?? throw new ArgumentException( "Type must be specified explicitly when value is null", nameof(type)); Value = value ?? DBNull.Value; } public string Name { get; } public Type Type { get; } public object Value { get; } public static ColumnExpression Create(string name, T value, Type? type = null) { // Try to convert value to 'type' to verify they are compatible // Note: Can't use `System.Type.IsAssignableFrom` because it doesn't // account for implicit conversions (e.g., int -> long), just inheritance. if (type is not null && !ConvertUtils.try_convert(type, value, out _)) { throw new ArgumentException( $"Type '{type}' is not assignable from value type '{value?.GetType()}'"); } return new(name, type ?? typeof(T), value); } internal static Type ParseType(string typeId) { return Candidates().ExceptNull().FirstOrDefault() ?? throw new ArgumentException($"Failed to parse Type from '{typeId}'", nameof(typeId)); IEnumerable Candidates() { if (typeId.Length == 0) { yield break; } yield return Type.GetType(typeId); yield return Type.GetType($"System.{typeId}"); if (typeId.Length > 1) { yield return Type.GetType($"System.{char.ToUpper(typeId[0]) + typeId[1..]}"); } yield return typeId.ToLower() switch { "float64" or "double" or "real64" or "number" => typeof(double), "float32" or "single" or "real32" or "real" or "float" => typeof(float), "int16" or "short" or "integer16" or "signed16" => typeof(short), "int32" or "int" or "integer" or "integer32" or "signed" => typeof(int), "int64" or "long" or "integer64" or "signed64" => typeof(long), "uint16" or "ushort" or "unsigned16" => typeof(ushort), "uint32" or "uint" or "unsigned" => typeof(uint), "uint64" or "ulong" or "unsigned64" => typeof(ulong), "char" => typeof(char), "byte" or "uint8" => typeof(byte), "bool" or "boolean" => typeof(bool), "string" or "text" => typeof(string), "date" or "datetime" => typeof(DateTime), _ => null }; } } }