Skip to content

Commit 6d48ef6

Browse files
authored
Re-enable DateOnly/TimeOnly support, fixing the defects that got it disabled (#2228)
DateOnly/TimeOnly support (#2051) was compiled out in 907a4d9 pending #2071/#2072. This re-enables it with the root causes fixed, and teaches the read paths that the date/time family has no IConvertible bridge - which box a date or time column yields is a provider/version decision (Npgsql 10: DateOnly/TimeOnly; SqlClient and Npgsql 9: DateTime/TimeSpan), so both shapes must convert: - GetFieldValue<T> is no longer demanded of a column whose reported type needs a family conversion (a datetime column into a DateOnly member was the #2072 breakage; SqlDecimal-style entries, where GetFieldValue from a differently-reported column is the whole point, keep it); - the member, scalar and Parse<T> paths all convert DateOnly/TimeOnly <-> DateTime/TimeSpan in both directions (IL for members, object-level elsewhere), fixing reads against Npgsql 10 date/time columns (#2226); - Query<DateOnly>/<TimeOnly> in scalar form no longer silently return default(T) (#2227): the typeMap entries make them simple types again; - the same-TypeCode direct-unbox shortcut is restricted to distinct codes: TypeCode.Object matching TypeCode.Object says nothing (TimeSpan into TimeOnly? threw), while object on either side (sql_variant columns, dynamic members) keeps the direct unbox; - the scalar conversion fallback keeps Convert.ChangeType's strict null contract (TestConversionExceptionMessages pins it). The parked DateTimeOnlyTests are re-enabled, with new tests for the #2072 shape (datetime column into DateOnly member), the #2227 scalar shape, and date-as-DateTime regression guards; PostgresqlTests gains the Npgsql-10 interchange matrix ([FactPostgresql], so it runs where the documented container is available). Fixes #2072, #2226, #2227, #1728; expected to also resolve #2071.
1 parent 41d76c7 commit 6d48ef6

3 files changed

Lines changed: 153 additions & 6 deletions

File tree

‎Dapper/SqlMapper.cs‎

Lines changed: 94 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ public static implicit operator TypeMapEntry(DbType dbType)
202202
static SqlMapper()
203203
{
204204
typeMap = new Dictionary<Type, TypeMapEntry>(41
205-
#if NET6_0_OR_GREATER && DATEONLY
205+
#if NET6_0_OR_GREATER
206206
+ 4 // {Date|Time}Only[?]
207207
#endif
208208
)
@@ -248,7 +248,7 @@ static SqlMapper()
248248
[typeof(SqlDecimal?)] = TypeMapEntry.DecimalFieldValue,
249249
[typeof(SqlMoney)] = TypeMapEntry.DecimalFieldValue,
250250
[typeof(SqlMoney?)] = TypeMapEntry.DecimalFieldValue,
251-
#if NET6_0_OR_GREATER && DATEONLY
251+
#if NET6_0_OR_GREATER
252252
[typeof(DateOnly)] = TypeMapEntry.DoNotSetFieldValue,
253253
[typeof(TimeOnly)] = TypeMapEntry.DoNotSetFieldValue,
254254
[typeof(DateOnly?)] = TypeMapEntry.DoNotSetFieldValue,
@@ -1396,6 +1396,7 @@ private static T GetValue<T>(DbDataReader reader, Type effectiveType, object? va
13961396
try
13971397
{
13981398
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
1399+
if (TryConvertDateTimeFamily(val, convertToType, out var converted)) return (T)converted;
13991400
return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture)!;
14001401
}
14011402
catch (Exception ex)
@@ -3169,7 +3170,9 @@ static Func<DbDataReader, object> ReadViaGetFieldValueFactory(Type type, int ind
31693170
static readonly Hashtable s_ReadViaGetFieldValueCache = [];
31703171

31713172
static Func<DbDataReader, object> UnderlyingReadViaGetFieldValueFactory<T>(int index)
3172-
=> reader => reader.IsDBNull(index) ? null! : reader.GetFieldValue<T>(index)!;
3173+
=> reader => reader.IsDBNull(index) ? null!
3174+
: IsDateTimeFamilyConversion(reader.GetFieldType(index), typeof(T)) ? (object)Parse<T>(reader.GetValue(index))!
3175+
: reader.GetFieldValue<T>(index)!;
31733176

31743177
static bool UseGetFieldValue(Type type) => typeMap.TryGetValue(type, out var mapEntry)
31753178
&& (mapEntry.Flags & TypeMapEntryFlags.UseGetFieldValue) != 0;
@@ -3196,9 +3199,48 @@ private static T Parse<T>(object? value)
31963199
{
31973200
return (T)handler.Parse(type, value)!;
31983201
}
3202+
if (TryConvertDateTimeFamily(value, type, out var converted)) return (T)converted;
31993203
return (T)Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
32003204
}
32013205

3206+
// the date/time family has no IConvertible bridge; which box a "date" or "time"
3207+
// column yields is a provider/version decision (Npgsql 10: DateOnly/TimeOnly;
3208+
// SqlClient and Npgsql 9: DateTime/TimeSpan), so accept either shape
3209+
internal static bool IsDateTimeFamilyConversion(Type from, Type to)
3210+
#if NET6_0_OR_GREATER
3211+
=> (from == typeof(DateTime) && (to == typeof(DateOnly) || to == typeof(TimeOnly)))
3212+
|| (from == typeof(DateOnly) && to == typeof(DateTime))
3213+
|| (from == typeof(TimeSpan) && to == typeof(TimeOnly))
3214+
|| (from == typeof(TimeOnly) && to == typeof(TimeSpan));
3215+
#else
3216+
=> false;
3217+
#endif
3218+
3219+
internal static bool TryConvertDateTimeFamily(object? value, Type to, [NotNullWhen(true)] out object? converted)
3220+
{
3221+
#if NET6_0_OR_GREATER
3222+
if (to == typeof(DateOnly))
3223+
{
3224+
if (value is DateTime dateTime) { converted = DateOnly.FromDateTime(dateTime); return true; }
3225+
}
3226+
else if (to == typeof(TimeOnly))
3227+
{
3228+
if (value is TimeSpan timeSpan) { converted = TimeOnly.FromTimeSpan(timeSpan); return true; }
3229+
if (value is DateTime dateTime) { converted = TimeOnly.FromDateTime(dateTime); return true; }
3230+
}
3231+
else if (to == typeof(DateTime))
3232+
{
3233+
if (value is DateOnly dateOnly) { converted = dateOnly.ToDateTime(default); return true; }
3234+
}
3235+
else if (to == typeof(TimeSpan))
3236+
{
3237+
if (value is TimeOnly timeOnly) { converted = timeOnly.ToTimeSpan(); return true; }
3238+
}
3239+
#endif
3240+
converted = null;
3241+
return false;
3242+
}
3243+
32023244
private static readonly MethodInfo
32033245
enumParse = typeof(Enum).GetMethod(nameof(Enum.Parse), [typeof(Type), typeof(string), typeof(bool)])!,
32043246
getItem = typeof(DbDataReader).GetProperties(BindingFlags.Instance | BindingFlags.Public)
@@ -3728,7 +3770,7 @@ private static void LoadReaderValueViaGetFieldValue(ILGenerator il, int index, T
37283770
private static void LoadReaderValueOrBranchToDBNullLabel(ILGenerator il, int index, ref LocalBuilder? stringEnumLocal, LocalBuilder? valueCopyLocal, Type colType, Type memberType, out Label isDbNullLabel, out bool popWhenNull)
37293771
{
37303772
isDbNullLabel = il.DefineLabel();
3731-
if (UseGetFieldValue(memberType))
3773+
if (UseGetFieldValue(memberType) && !IsDateTimeFamilyConversion(colType, Nullable.GetUnderlyingType(memberType) ?? memberType))
37323774
{
37333775
LoadReaderValueViaGetFieldValue(il, index, memberType, valueCopyLocal, isDbNullLabel, out popWhenNull);
37343776
return;
@@ -3805,7 +3847,16 @@ private static void LoadReaderValueOrBranchToDBNullLabel(ILGenerator il, int ind
38053847
{
38063848
TypeCode dataTypeCode = Type.GetTypeCode(colType), unboxTypeCode = Type.GetTypeCode(unboxType);
38073849
bool hasTypeHandler;
3808-
if ((hasTypeHandler = typeHandlers.ContainsKey(unboxType)) || colType == unboxType || dataTypeCode == unboxTypeCode || dataTypeCode == Type.GetTypeCode(nullUnderlyingType))
3850+
// note the TypeCode tests are only meaningful for distinct codes: TypeCode.Object
3851+
// matching TypeCode.Object says nothing (TimeSpan vs TimeOnly?, say), and a direct
3852+
// unbox there throws; such pairs belong to the flexible-convert path below. A column
3853+
// reported as plain *object* (sql_variant etc) keeps the direct unbox: the runtime
3854+
// box is the only truth available there
3855+
if ((hasTypeHandler = typeHandlers.ContainsKey(unboxType)) || colType == unboxType
3856+
|| colType == typeof(object) || unboxType == typeof(object)
3857+
|| (dataTypeCode == unboxTypeCode && dataTypeCode != TypeCode.Object)
3858+
|| (dataTypeCode == Type.GetTypeCode(nullUnderlyingType) && dataTypeCode != TypeCode.Object)
3859+
|| colType == nullUnderlyingType)
38093860
{
38103861
if (hasTypeHandler)
38113862
{
@@ -3831,6 +3882,36 @@ private static void LoadReaderValueOrBranchToDBNullLabel(ILGenerator il, int ind
38313882
}
38323883
}
38333884

3885+
#if NET6_0_OR_GREATER
3886+
private static MethodInfo? GetDateTimeFamilyConversion(Type from, Type to)
3887+
{
3888+
string? name = null;
3889+
if (from == typeof(DateTime))
3890+
{
3891+
if (to == typeof(DateOnly)) name = nameof(DateTimeToDateOnly);
3892+
else if (to == typeof(TimeOnly)) name = nameof(DateTimeToTimeOnly);
3893+
}
3894+
else if (from == typeof(DateOnly))
3895+
{
3896+
if (to == typeof(DateTime)) name = nameof(DateOnlyToDateTime);
3897+
}
3898+
else if (from == typeof(TimeSpan))
3899+
{
3900+
if (to == typeof(TimeOnly)) name = nameof(TimeSpanToTimeOnly);
3901+
}
3902+
else if (from == typeof(TimeOnly))
3903+
{
3904+
if (to == typeof(TimeSpan)) name = nameof(TimeOnlyToTimeSpan);
3905+
}
3906+
return name is null ? null : typeof(SqlMapper).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic);
3907+
}
3908+
private static DateOnly DateTimeToDateOnly(DateTime value) => DateOnly.FromDateTime(value);
3909+
private static TimeOnly DateTimeToTimeOnly(DateTime value) => TimeOnly.FromDateTime(value);
3910+
private static DateTime DateOnlyToDateTime(DateOnly value) => value.ToDateTime(default);
3911+
private static TimeOnly TimeSpanToTimeOnly(TimeSpan value) => TimeOnly.FromTimeSpan(value);
3912+
private static TimeSpan TimeOnlyToTimeSpan(TimeOnly value) => value.ToTimeSpan();
3913+
#endif
3914+
38343915
private static void FlexibleConvertBoxedFromHeadOfStack(ILGenerator il, Type from, Type to, Type? via)
38353916
{
38363917
MethodInfo? op;
@@ -3844,6 +3925,14 @@ private static void FlexibleConvertBoxedFromHeadOfStack(ILGenerator il, Type fro
38443925
il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
38453926
il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
38463927
}
3928+
#if NET6_0_OR_GREATER
3929+
else if (GetDateTimeFamilyConversion(from, via ?? to) is { } conversion)
3930+
{
3931+
// no IConvertible bridge exists inside the date/time family (see Parse<T>)
3932+
il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
3933+
il.Emit(OpCodes.Call, conversion); // stack is now [target][target][typed-value]
3934+
}
3935+
#endif
38473936
else
38483937
{
38493938
bool handled = false;

‎tests/Dapper.Tests/DateTimeOnlyTests.cs‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Dapper.Tests;
99
[Collection("DateTimeOnlyTests")]
1010
public sealed class SystemSqlClientDateTimeOnlyTests : DateTimeOnlyTests<SystemSqlClientProvider> { }
1111
*/
12-
#if MSSQLCLIENT && DATEONLY
12+
#if MSSQLCLIENT
1313
[Collection("DateTimeOnlyTests")]
1414
public sealed class MicrosoftSqlClientDateTimeOnlyTests : DateTimeOnlyTests<MicrosoftSqlClientProvider> { }
1515
#endif
@@ -81,5 +81,37 @@ public void UntypedInOut()
8181
Assert.Equal(date, DateOnly.FromDateTime((DateTime)row.Date));
8282
Assert.Equal(time, TimeOnly.FromTimeSpan((TimeSpan)row.Time));
8383
}
84+
85+
[Fact] // #2072: a datetime column into a DateOnly member - the provider boxes DateTime,
86+
// so this must convert rather than demand GetFieldValue<DateOnly> of a datetime column
87+
public void MembersFromDateTimeAndTimeSpanColumns()
88+
{
89+
var row = connection.QuerySingle<HazDateTimeOnly>(
90+
"select 'x' as [Name], cast('2019-10-01' as datetime) as [Date], cast('03:03:03' as time) as [Time], cast('2019-10-02' as datetime) as [NDate], cast('04:04:04' as time) as [NTime]");
91+
Assert.Equal(new DateOnly(2019, 10, 1), row.Date);
92+
Assert.Equal(new TimeOnly(3, 3, 3), row.Time);
93+
Assert.Equal(new DateOnly(2019, 10, 2), row.NDate);
94+
Assert.Equal(new TimeOnly(4, 4, 4), row.NTime);
95+
}
96+
97+
[Fact] // #2227: the scalar form must not silently yield default(T)
98+
public void ScalarDateOnlyAndTimeOnly()
99+
{
100+
Assert.Equal(new DateOnly(2021, 1, 1), connection.QuerySingle<DateOnly>("select cast('2021-01-01' as date)"));
101+
Assert.Equal(new TimeOnly(3, 3, 3), connection.QuerySingle<TimeOnly>("select cast('03:03:03' as time)"));
102+
Assert.Equal(new DateOnly(2021, 1, 1), connection.QuerySingle<DateOnly?>("select cast('2021-01-01' as date)"));
103+
}
104+
105+
[Fact] // the pre-DateOnly reading of a date column must keep working
106+
public void DateColumnAsDateTime()
107+
{
108+
Assert.Equal(new DateTime(2021, 1, 1), connection.QuerySingle<DateTime>("select cast('2021-01-01' as date)"));
109+
Assert.Equal(new DateTime(2021, 1, 1), connection.QuerySingle<HazDateTime>("select cast('2021-01-01' as date) as [When]").When);
110+
}
111+
112+
public class HazDateTime
113+
{
114+
public DateTime When { get; set; }
115+
}
84116
}
85117
#endif

‎tests/Dapper.Tests/Providers/PostgresqlTests.cs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,32 @@ private class Cat
4444
new Cat() { Breed = "Persian", Name="MAGNA"}
4545
};
4646

47+
#if NET6_0_OR_GREATER
48+
[FactPostgresql] // #2226: Npgsql 10 boxes DateOnly/TimeOnly for date/time columns;
49+
// both spellings of a date read must work regardless of which box arrives
50+
public void DateOnlyDateTimeInterchange()
51+
{
52+
using var conn = GetOpenNpgsqlConnection();
53+
Assert.Equal(new DateTime(2021, 1, 1), conn.QuerySingle<DateTime>("select '2021-01-01'::date"));
54+
Assert.Equal(new DateTime(2021, 1, 1), conn.QuerySingle<DateTime?>("select '2021-01-01'::date"));
55+
Assert.Equal(new DateOnly(2021, 1, 1), conn.QuerySingle<DateOnly>("select '2021-01-01'::date"));
56+
Assert.Equal(new TimeOnly(3, 3, 3), conn.QuerySingle<TimeOnly>("select '03:03:03'::time"));
57+
58+
var row = conn.QuerySingle<DateReadings>(
59+
"select '2021-01-01'::date as \"AsDateTime\", '2021-01-01'::date as \"AsDateOnly\", '2021-01-01'::date as \"AsNullableDateTime\"");
60+
Assert.Equal(new DateTime(2021, 1, 1), row.AsDateTime);
61+
Assert.Equal(new DateOnly(2021, 1, 1), row.AsDateOnly);
62+
Assert.Equal(new DateTime(2021, 1, 1), row.AsNullableDateTime);
63+
}
64+
65+
private class DateReadings
66+
{
67+
public DateTime AsDateTime { get; set; }
68+
public DateOnly AsDateOnly { get; set; }
69+
public DateTime? AsNullableDateTime { get; set; }
70+
}
71+
#endif
72+
4773
[FactPostgresql]
4874
public void TestPostgresqlArrayParameters()
4975
{

0 commit comments

Comments
 (0)