RelationalFieldRule.cs 1.6 KB

12345678910111213141516171819202122232425262728293031
  1. using System.Globalization;
  2. using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Connectors;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Relational;
  4. public sealed record RelationalFieldRule(string Field, string Kind, string? TimeZone = null, string? Encoding = null,
  5. int? Precision = null, int? Scale = null)
  6. {
  7. public object Apply(object source) => Kind switch
  8. {
  9. "text" when source is byte[] bytes && Encoding is not null => RelationalFieldValues.Decode(bytes, Encoding),
  10. "utc" when source is DateTimeOffset instant => instant.ToUniversalTime(),
  11. "utc" when source is DateTime time && time.Kind == DateTimeKind.Utc => new DateTimeOffset(time),
  12. "utc" when source is DateTime local && TimeZone is not null
  13. && TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out var zone) => RelationalFieldValues.ToUtc(local, zone),
  14. "date" when source is DateOnly date => date,
  15. "date" when source is DateTime dateTime => DateOnly.FromDateTime(dateTime),
  16. "decimal" when Precision.HasValue && Scale.HasValue => RelationalFieldValues.DecimalValue(
  17. Convert.ToString(source, CultureInfo.InvariantCulture) ?? "", Precision.Value, Scale.Value),
  18. _ => throw new ConnectorContractException(ConnectorError.InvalidBatch),
  19. };
  20. public bool Valid => Kind switch
  21. {
  22. "text" => Encoding is "utf-8" or "utf8" or "utf8mb4" or "al32utf8" or "gbk" or "gb18030" or "big5",
  23. "utc" => TimeZone is null || TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _),
  24. "date" => true,
  25. "decimal" => Precision is >= 1 and <= 28 && Scale is >= 0 && Scale <= Precision,
  26. _ => false,
  27. };
  28. }