DateIntervalRangeMapping.cs 2.2 KB
Newer Older
1 2 3
using NodaTime.Text;
using Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.Mapping;

4
// ReSharper disable once CheckNamespace
5 6
namespace Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal;

7
public class DateIntervalRangeMapping : NpgsqlTypeMapping
8
{
9 10 11 12 13 14
    private static readonly ConstructorInfo _constructorWithDates =
        typeof(DateInterval).GetConstructor(new[] { typeof(LocalDate), typeof(LocalDate) })!;

    private static readonly ConstructorInfo _localDateConstructor =
        typeof(LocalDate).GetConstructor(new[] { typeof(int), typeof(int), typeof(int) })!;

15
    public DateIntervalRangeMapping()
16 17 18 19
        : base("daterange", typeof(DateInterval), NpgsqlDbType.DateRange)
    {
    }

20
    protected DateIntervalRangeMapping(RelationalTypeMappingParameters parameters)
21 22 23 24 25
        : base(parameters, NpgsqlDbType.DateRange)
    {
    }

    protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters)
26
        => new DateIntervalRangeMapping(parameters);
27 28

    public override RelationalTypeMapping Clone(string storeType, int? size)
29
        => new DateIntervalRangeMapping(Parameters.WithStoreTypeAndSize(storeType, size));
30 31

    public override CoreTypeMapping Clone(ValueConverter? converter)
32
        => new DateIntervalRangeMapping(Parameters.WithComposedConverter(converter));
33 34

    protected override string GenerateNonNullSqlLiteral(object value)
35 36 37
        => $"'{GenerateEmbeddedNonNullSqlLiteral(value)}'::daterange";

    protected override string GenerateEmbeddedNonNullSqlLiteral(object value)
38
    {
39 40
        var dateInterval = (DateInterval)value;
        return $"[{LocalDatePattern.Iso.Format(dateInterval.Start)},{LocalDatePattern.Iso.Format(dateInterval.End)}]";
41 42 43
    }

    public override Expression GenerateCodeLiteral(object value)
44
    {
45 46 47 48 49 50
        var (start, end) = (DateInterval)value;
        return Expression.New(
            _constructorWithDates,
            Expression.New(_localDateConstructor, Expression.Constant(start.Year), Expression.Constant(start.Month), Expression.Constant(start.Day)),
            Expression.New(_localDateConstructor, Expression.Constant(end.Year), Expression.Constant(end.Month), Expression.Constant(end.Day))
        );
51
    }
52
}