diff --git a/ClickHouse.Driver.Tests/Types/DateTimeBinaryRangeTests.cs b/ClickHouse.Driver.Tests/Types/DateTimeBinaryRangeTests.cs index 516a4e124..cca902ec8 100644 --- a/ClickHouse.Driver.Tests/Types/DateTimeBinaryRangeTests.cs +++ b/ClickHouse.Driver.Tests/Types/DateTimeBinaryRangeTests.cs @@ -1,14 +1,16 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using ClickHouse.Driver.ADO; using ClickHouse.Driver.Copy; using ClickHouse.Driver.Tests.Attributes; +using NodaTime; using NUnit.Framework.Interfaces; namespace ClickHouse.Driver.Tests.Types; /// -/// End-to-end coverage of binary-insert range validation for Date / Date32 / DateTime. +/// End-to-end coverage of binary-insert range validation for Date / Date32 / DateTime / DateTime64. /// Inserts via InsertBinaryAsync against a real ClickHouse server and asserts both round-trip /// at the canonical bounds and an just outside them /// (wrapped by the bulk-copy serializer as the inner exception). @@ -220,4 +222,75 @@ public void InsertBinaryAsync_Date32_AboveRange_ThrowsArgumentOutOfRangeExceptio AssertRangeException(ex, "Date32"); } + + // DateTime64: the wire value is an Int64 count of 10^-scale seconds since the epoch. Scales 8 and 9 are finer + // than a .NET tick, so they reach the Int64 limit inside the DateTime range. + + private static readonly DateTime DateTime64NanoMin = new DateTime(1677, 9, 21, 0, 12, 43, DateTimeKind.Utc).AddTicks(1_452_242); + private static readonly DateTime DateTime64NanoMax = new DateTime(2262, 4, 11, 23, 47, 16, DateTimeKind.Utc).AddTicks(8_547_758); + private static readonly DateTime DateTime64ScaleEightMax = new DateTime(4892, 10, 7, 21, 52, 48, DateTimeKind.Utc).AddTicks(5_477_580); + + // An Unspecified DateTime is read in the column timezone: Asia/Tokyo is UTC+9. + private static DateTime InTokyo(DateTime utc) => DateTime.SpecifyKind(utc.AddHours(9), DateTimeKind.Unspecified); + + private const string DateTime64NanoRange = "(1677-09-21 00:12:43.1452242 UTC to 2262-04-11 23:47:16.8547758 UTC)"; + + // DateTime64(8) has no lower limit within the DateTime range. + private const string DateTime64ScaleEightRange = "(up to 4892-10-07 21:52:48.5477580 UTC)"; + + private static IEnumerable DateTime64AtInt64LimitCases() + { + yield return new TestCaseData("DateTime64(9, 'UTC')", DateTime64NanoMin, -9_223_372_036_854_775_800L).SetArgDisplayNames("9", "min"); + yield return new TestCaseData("DateTime64(9, 'UTC')", DateTime64NanoMax, 9_223_372_036_854_775_800L).SetArgDisplayNames("9", "max"); + yield return new TestCaseData("DateTime64(8, 'UTC')", DateTime64ScaleEightMax, 9_223_372_036_854_775_800L).SetArgDisplayNames("8", "max"); + // The limit applies to the instant, not to the wall-clock time. + yield return new TestCaseData("DateTime64(9, 'UTC')", new DateTimeOffset(DateTime64NanoMax).ToOffset(TimeSpan.FromHours(1)), 9_223_372_036_854_775_800L) + .SetArgDisplayNames("9", "max at +01:00"); + yield return new TestCaseData("DateTime64(9, 'Asia/Tokyo')", InTokyo(DateTime64NanoMax), 9_223_372_036_854_775_800L) + .SetArgDisplayNames("9 Asia/Tokyo", "max as Unspecified"); + } + + private static IEnumerable DateTime64PastInt64LimitCases() + { + yield return new TestCaseData("DateTime64(9, 'UTC')", DateTime64NanoMin.AddTicks(-1), DateTime64NanoRange).SetArgDisplayNames("9", "min - 1 tick"); + yield return new TestCaseData("DateTime64(9, 'UTC')", DateTime64NanoMax.AddTicks(1), DateTime64NanoRange).SetArgDisplayNames("9", "max + 1 tick"); + yield return new TestCaseData("DateTime64(8, 'UTC')", DateTime64ScaleEightMax.AddTicks(1), DateTime64ScaleEightRange).SetArgDisplayNames("8", "max + 1 tick"); + yield return new TestCaseData("DateTime64(9, 'UTC')", new DateTimeOffset(DateTime64NanoMax.AddTicks(1)).ToOffset(TimeSpan.FromHours(-1)), DateTime64NanoRange) + .SetArgDisplayNames("9", "max + 1 tick at -01:00"); + yield return new TestCaseData("DateTime64(9, 'Asia/Tokyo')", InTokyo(DateTime64NanoMax.AddTicks(1)), DateTime64NanoRange) + .SetArgDisplayNames("9 Asia/Tokyo", "max + 1 tick as Unspecified"); + yield return new TestCaseData("DateTime64(9, 'UTC')", DateTime64NanoMax.AddTicks(1).ToLocalTime(), DateTime64NanoRange) + .SetArgDisplayNames("9", "max + 1 tick as Local"); + yield return new TestCaseData("DateTime64(9, 'UTC')", Instant.FromDateTimeUtc(DateTime64NanoMax.AddTicks(1)), DateTime64NanoRange) + .SetArgDisplayNames("9", "max + 1 tick as Instant"); + yield return new TestCaseData("DateTime64(9, 'UTC')", new DateOnly(1500, 6, 1), DateTime64NanoRange).SetArgDisplayNames("9", "DateOnly 1500-06-01"); + } + + [TestCaseSource(nameof(DateTime64AtInt64LimitCases))] + public async Task InsertBinaryAsync_DateTime64_AtInt64Limit_RoundTrips(string type, object value, long expectedCount) + { + var table = CreateTableName($"dt64_{type}"); + await client.ExecuteNonQueryAsync($"CREATE TABLE {table} (t {type}) ENGINE = Memory"); + + await client.InsertBinaryAsync(table, new[] { "t" }, new[] { new object[] { value } }); + + // The stored count, not toString(t): some supported servers (e.g. 26.3) render an instant before 1900 as 1900. + var actual = (long)await client.ExecuteScalarAsync($"SELECT reinterpretAsInt64(t) FROM {table}"); + Assert.That(actual, Is.EqualTo(expectedCount)); + } + + [TestCaseSource(nameof(DateTime64PastInt64LimitCases))] + public async Task InsertBinaryAsync_DateTime64_PastInt64Limit_ThrowsArgumentOutOfRangeException(string type, object value, string expectedRange) + { + var table = CreateTableName($"dt64_{type}"); + await client.ExecuteNonQueryAsync($"CREATE TABLE {table} (t {type}) ENGINE = Memory"); + + var ex = Assert.ThrowsAsync(async () => + await client.InsertBinaryAsync(table, new[] { "t" }, new[] { new object[] { value } })); + + AssertRangeException(ex, type); + var inner = (ArgumentOutOfRangeException)ex!.InnerException!; + Assert.That(inner.Message, Does.Contain(expectedRange)); + Assert.That(inner.ActualValue, Is.EqualTo(value)); + } } diff --git a/ClickHouse.Driver/Types/DateTime64Type.cs b/ClickHouse.Driver/Types/DateTime64Type.cs index 6d64704f0..c3c36626e 100644 --- a/ClickHouse.Driver/Types/DateTime64Type.cs +++ b/ClickHouse.Driver/Types/DateTime64Type.cs @@ -51,7 +51,38 @@ public override ParameterizedType Parse(SyntaxTreeNode node, Func Instant.FromUnixTimeTicks(MathUtils.ShiftDecimalPlaces(reader.ReadInt64(), 7 - Scale)); - // No range check: any coerced instant is representable, so 'original' is unused. - protected override void WriteChecked(ExtendedBinaryWriter writer, DateTimeOffset dto, T original) - => writer.Write(ToClickHouseTicks(Instant.FromDateTimeOffset(dto))); + // Scales finer than a .NET tick reach the Int64 limit inside the DateTime range (DateTime64(9): 1677 to 2262), + // so check before scaling up: an unchecked multiply would wrap and write a different instant. + protected override void WriteChecked(ExtendedBinaryWriter writer, DateTimeOffset dto, T value) + { + var instant = Instant.FromDateTimeOffset(dto); + if (Scale <= 7) + { + writer.Write(ToClickHouseTicks(instant)); + return; + } + + var factor = MathUtils.ToPower(10, Scale - 7); + var ticks = instant.ToUnixTimeTicks(); + if (ticks > long.MaxValue / factor || ticks < long.MinValue / factor) + { + throw new ArgumentOutOfRangeException( + nameof(value), + value, + $"Value is outside the range that ClickHouse {this} can store as an Int64 count of 10^-{Scale} s since the epoch ({DescribeInt64Range(factor)})."); + } + + writer.Write(ticks * factor); + } + + // The lower limit of DateTime64(8) is before DateTime.MinValue, so only its upper limit can be reached. + private static string DescribeInt64Range(long factor) + { + var minTicks = long.MinValue / factor; + var max = FormatUnixTicks(long.MaxValue / factor); + return minTicks < DateTime.MinValue.Ticks - DateTime.UnixEpoch.Ticks ? $"up to {max}" : $"{FormatUnixTicks(minTicks)} to {max}"; + } + + private static string FormatUnixTicks(long unixTicks) + => DateTime.UnixEpoch.AddTicks(unixTicks).ToString("yyyy-MM-dd HH:mm:ss.fffffff 'UTC'", CultureInfo.InvariantCulture); } diff --git a/changelog.d/711-datetime64-overflow.fixes.md b/changelog.d/711-datetime64-overflow.fixes.md new file mode 100644 index 000000000..7aae8a89b --- /dev/null +++ b/changelog.d/711-datetime64-overflow.fixes.md @@ -0,0 +1,3 @@ +* Fixed binary inserts silently storing a different timestamp for `DateTime64(9)` values before 1677-09-21 or + after 2262-04-11 UTC, and for `DateTime64(8)` values after 4892-10-07 UTC. These values now throw + `ArgumentOutOfRangeException` ([#711](https://github.com/ClickHouse/clickhouse-cs/issues/711)). diff --git a/docs/http.mdx b/docs/http.mdx index 1e1462472..0fd75bf30 100644 --- a/docs/http.mdx +++ b/docs/http.mdx @@ -1943,14 +1943,14 @@ When you write a `ClickHouseDecimal` to an `Int8`, `UInt8`, `Int16`, `UInt16`, ` | Date32 | `DateTime`, `DateTimeOffset`, `DateOnly`, NodaTime types | Converted to Unix days as Int32; supported range `[1900-01-01, 2299-12-31]` | | DateTime | `DateTime`, `DateTimeOffset`, `DateOnly`, NodaTime types | See below for details; supported range `[1970-01-01, 2106-02-07 06:28:15]` UTC | | DateTime32 | `DateTime`, `DateTimeOffset`, `DateOnly`, NodaTime types | Same as DateTime | -| DateTime64 | `DateTime`, `DateTimeOffset`, `DateOnly`, NodaTime types | Precision based on Scale parameter | +| DateTime64 | `DateTime`, `DateTimeOffset`, `DateOnly`, NodaTime types | Precision based on Scale parameter; `DateTime64(9)` accepts `[1677-09-21 00:12:43.1452242, 2262-04-11 23:47:16.8547758]` UTC, `DateTime64(8)` accepts values up to `4892-10-07 21:52:48.5477580` UTC | | Time | `TimeSpan`, `TimeOnly`, `int` | Clamped to ±999:59:59; int treated as seconds | | Time64 | `TimeSpan`, `TimeOnly`, `decimal`, `double`, `float`, `int`, `long`, `string` | String parsed as `[-]HHH:MM:SS[.fraction]`; clamped to ±999:59:59.999999999 | **Out-of-range values** -On the binary write path, `Date`, `Date32`, `DateTime`, and `DateTime32` values outside their supported range throw `ArgumentOutOfRangeException` at `Write` time, naming the column type and the supported range. Previously, out-of-range values could be silently truncated through a 32-bit integer and reinterpreted by the server, producing real-but-wrong timestamps. +On the binary write path, `Date`, `Date32`, `DateTime`, and `DateTime32` values outside their supported range throw `ArgumentOutOfRangeException` at `Write` time, naming the column type and the supported range. `DateTime64(8)` and `DateTime64(9)` values whose count of sub-second units since the epoch does not fit in an Int64 throw the same exception. Previously, out-of-range values could be silently truncated through a 32-bit integer and reinterpreted by the server, producing real-but-wrong timestamps. The driver respects `DateTime.Kind` when writing values: