Skip to content

Commit cb0accd

Browse files
Extend the supported range of Date32 to [0000-01-01, 9999-12-31]
`Date32` was limited to `[1900-01-01, 2299-12-31]` - the span covered by the `DateLUTImpl` lookup table - while `DateTime64` was already extended to `[0000-01-01, 9999-12-31]`. The mismatch was inconsistent on its own: parsing `toDate32('0079-08-24')` silently clamped to `1900-01-01` (so e.g. `age` returned a plausible-looking wrong answer), while the cast `toDate32(toDateTime64('0079-08-24 13:00:00', 0))` produced the correct out-of-range value, because the `Int32` day number has room for it and the extended formatting path is shared with `DateTime64`. `DateLUTImpl::makeDayNum` and `tryToMakeDayNum` now fall back to the cctz-based `makeDayNumOutOfRange` for valid calendar dates outside `[DATE_LUT_MIN_YEAR, DATE_LUT_MAX_YEAR]`, exactly like `makeDateTime` already does since the `DateTime64` extension. That single change covers text parsing everywhere: SQL casts from `String`, CSV/JSON/TSV/`Values` input formats, and `YYYYMMDDToDayNum`. Computations over the extended values were already handled by the `DateTime64` infrastructure, which gates every `ExtendedDayNum` argument with an out-of-range escape path. `Date` behavior is unchanged: its clamps happen downstream, on the day-number result. The LUT-derived `DATE_LUT_MAX_EXTEND_DAY_NUM` (120530, an exclusive bound) is replaced by inclusive `DATE_LUT_MIN_EXTEND_DAY_NUM` (-719528, `0000-01-01`) and `DATE_LUT_MAX_EXTEND_DAY_NUM` (2932896, `9999-12-31`), tied to the internal representable window by static asserts. In the numeric conversion `toDate32(N)`, the day-number/timestamp disambiguation threshold moves accordingly: values up to 2932896 are day numbers, larger values are Unix timestamps capped at the new `MAX_DATE32_TIMESTAMP` (`9999-12-31 23:59:59` instead of `2299-12-31 23:59:59`); values below the minimum saturate to `0000-01-01` instead of `1900-01-01`. The monotonicity analysis threshold is kept in sync, and the Parquet, Arrow, Arrow IPC and native ORC readers validate `Date32` input against the new bounds (also fixing an off-by-one that accepted day number 120530). `makeDate32`, `YYYYMMDDToDate32` and `changeDate` accept years `[0, 9999]`. The default value of `Date32` and the result of `toDate32OrZero` on unparseable input remain `1900-01-01`. Closes #111524 Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent e161dcb commit cb0accd

36 files changed

Lines changed: 436 additions & 192 deletions

‎docs/en/interfaces/formats/RowBinary/RowBinary.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ SELECT CAST('2024-01-15', 'Date') AS d
201201

202202
Stored as `Int32` (four bytes) representing the number of days ***before or after*** `1970-01-01`.
203203

204-
Supported range of values: `[1900-01-01, 2299-12-31]`.
204+
Supported range of values: `[0000-01-01, 9999-12-31]`.
205205

206206
Sample underlying values for `Date32`:
207207

‎docs/en/sql-reference/data-types/date32.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ title: 'Date32'
88
doc_type: 'reference'
99
---
1010

11-
A date. Supported range of values: `[1900-01-01, 2299-12-31]`. Stored as a signed 32-bit integer in native byte order with the value representing the days since `1900-01-01`. **Important!** 0 represents `1970-01-01`, and negative values represent the days before `1970-01-01`.
11+
A date. Supported range of values: `[0000-01-01, 9999-12-31]`. Stored as a signed 32-bit integer in native byte order with the value representing the days since the Unix epoch: 0 represents `1970-01-01`, and negative values represent the days before `1970-01-01`.
1212

1313
**Examples**
1414

‎src/Common/DateLUTImpl.h‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,10 @@ class time_zone;
3636

3737
#define DAYNUM_OFFSET_EPOCH 25567
3838

39-
/// Max int value of Date32, DATE LUT cache size minus daynum_offset_epoch
40-
#define DATE_LUT_MAX_EXTEND_DAY_NUM (DATE_LUT_SIZE - DAYNUM_OFFSET_EPOCH)
39+
/// Min and max value of Date32: day numbers (days relative to 1970-01-01) of
40+
/// DATE_LUT_MIN_REPRESENTABLE_YEAR-01-01 and DATE_LUT_MAX_REPRESENTABLE_YEAR-12-31.
41+
#define DATE_LUT_MIN_EXTEND_DAY_NUM (-719528)
42+
#define DATE_LUT_MAX_EXTEND_DAY_NUM 2932896
4143

4244
/// A constant to add to time_t so every supported time point becomes non-negative and still has the same remainder of division by 3600.
4345
/// If we treat "remainder of division" operation in the sense of modular arithmetic (not like in C++).
@@ -265,6 +267,10 @@ class DateLUTImpl
265267
static constexpr Time min_representable_time = -62167219200; /// 0000-01-01 00:00:00 UTC
266268
static constexpr Time max_representable_time = 253402300799; /// 9999-12-31 23:59:59 UTC
267269

270+
/// The Date32 range is the whole representable window.
271+
static_assert(DATE_LUT_MIN_EXTEND_DAY_NUM == min_representable_day_index - daynum_offset_epoch);
272+
static_assert(DATE_LUT_MAX_EXTEND_DAY_NUM == max_representable_day_index - daynum_offset_epoch);
273+
268274
/// std::chrono::system_clock::from_time_t can overflow for extreme Int64 inputs, so the cctz escape paths
269275
/// bound the UTC timestamp to this window before constructing a time point. It is wider than the
270276
/// representable calendar by more than a whole-day timezone offset, so that a local civil value at the
@@ -1721,6 +1727,9 @@ class DateLUTImpl
17211727
/// Create DayNum from year, month, day of month.
17221728
ExtendedDayNum makeDayNum(Int16 year, UInt8 month, UInt8 day_of_month, Int32 default_error_day_num = 0) const
17231729
{
1730+
if (unlikely(isMakeDateOutOfRange(year, month, day_of_month)))
1731+
return makeDayNumOutOfRange(year, month, day_of_month);
1732+
17241733
if (unlikely(year < DATE_LUT_MIN_YEAR || month < 1 || month > 12 || day_of_month < 1 || day_of_month > 31))
17251734
return ExtendedDayNum(default_error_day_num);
17261735

@@ -1729,6 +1738,9 @@ class DateLUTImpl
17291738

17301739
std::optional<ExtendedDayNum> tryToMakeDayNum(Int16 year, UInt8 month, UInt8 day_of_month) const
17311740
{
1741+
if (unlikely(isMakeDateOutOfRange(year, month, day_of_month)))
1742+
return makeDayNumOutOfRange(year, month, day_of_month);
1743+
17321744
if (unlikely(year < DATE_LUT_MIN_YEAR || month < 1 || month > 12 || day_of_month < 1 || day_of_month > 31))
17331745
return std::nullopt;
17341746

‎src/Common/QueryFuzzer.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ Field QueryFuzzer::getRandomField(int type)
389389
}
390390
case 3: {
391391
/// Date/Date32 boundary values as strings — stress date parsing and arithmetic.
392-
/// Date range is [1970-01-01, 2149-06-06], Date32 range is [1900-01-01, 2299-12-31].
392+
/// Date range is [1970-01-01, 2149-06-06], Date32 range is [0000-01-01, 9999-12-31].
393393
static constexpr const char * date_values[]
394394
= {"0000-01-01",
395395
"1899-12-31",
@@ -424,7 +424,7 @@ Field QueryFuzzer::getRandomField(int type)
424424
case 5: {
425425
/// DateTime/DateTime64 boundary values as strings — stress timestamp parsing, overflow and sub-second precision.
426426
/// DateTime range is [1970-01-01 00:00:00, 2106-02-07 06:28:15],
427-
/// DateTime64 range is [1900-01-01 00:00:00, 2299-12-31 23:59:59.99999999].
427+
/// DateTime64 range is [0000-01-01 00:00:00, 9999-12-31 23:59:59.99999999].
428428
static constexpr const char * datetime_values[]
429429
= {"1900-01-01 00:00:00",
430430
"1900-01-01 00:00:00.000000000",

‎src/Common/tests/gtest_DateLUTImpl.cpp‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,23 @@ TEST(DateLUTTest, dayShiftStaysWithinLUT)
143143
TEST(DateLUTTest, makeDayNumTest)
144144
{
145145
const DateLUTImpl & lut = DateLUT::instance("UTC");
146-
EXPECT_EQ(0, lut.makeDayNum(1899, 12, 31));
147-
EXPECT_EQ(-1, lut.makeDayNum(1899, 12, 31, -1));
146+
/// Valid dates outside the LUT years take the cctz escape path instead of clamping.
147+
EXPECT_EQ(-25568, lut.makeDayNum(1899, 12, 31));
148+
EXPECT_EQ(-25568, lut.makeDayNum(1899, 12, 31, -1));
148149
EXPECT_EQ(-25567, lut.makeDayNum(1900, 1, 1));
149150
EXPECT_EQ(-16436, lut.makeDayNum(1925, 1, 1));
150151
EXPECT_EQ(0, lut.makeDayNum(1970, 1, 1));
151-
EXPECT_EQ(120529, lut.makeDayNum(2300, 12, 31));
152-
EXPECT_EQ(120529, lut.makeDayNum(2500, 12, 25));
152+
EXPECT_EQ(120894, lut.makeDayNum(2300, 12, 31));
153+
EXPECT_EQ(193937, lut.makeDayNum(2500, 12, 25));
154+
155+
/// The whole representable window [0000-01-01, 9999-12-31]; years outside are clamped.
156+
EXPECT_EQ(DATE_LUT_MIN_EXTEND_DAY_NUM, lut.makeDayNum(0, 1, 1));
157+
EXPECT_EQ(DATE_LUT_MAX_EXTEND_DAY_NUM, lut.makeDayNum(9999, 12, 31));
158+
EXPECT_EQ(lut.makeDayNum(9999, 1, 1), lut.makeDayNum(10000, 1, 1));
159+
160+
/// A calendar-invalid date still yields the error default.
161+
EXPECT_EQ(0, lut.makeDayNum(2000, 13, 1));
162+
EXPECT_EQ(-1, lut.makeDayNum(2000, 13, 1, -1));
153163
}
154164

155165

‎src/DataTypes/DataTypeDate32.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ void registerDataTypeDate32(DataTypeFactory & factory)
2626
"Date32", [] { return DataTypePtr(std::make_shared<DataTypeDate32>()); }, DataTypeFactory::Case::Insensitive,
2727
Documentation{
2828
.description = R"DOCS_MD(
29-
A date. Supports the date range from `1900-01-01` to `2299-12-31`. Stored as a signed 32-bit integer in native byte order with the value representing the days since `1900-01-01`. **Important!** 0 represents `1970-01-01`, and negative values represent the days before `1970-01-01`.
29+
A date. Supports the date range from `0000-01-01` to `9999-12-31`. Stored as a signed 32-bit integer in native byte order with the value representing the days since the Unix epoch: 0 represents `1970-01-01`, and negative values represent the days before `1970-01-01`.
3030
3131
**Examples**
3232

‎src/Functions/DateTimeTransforms.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ namespace ErrorCodes
5656

5757
constexpr time_t MAX_DATETIME64_TIMESTAMP = 253402300799LL; // 9999-12-31 23:59:59 UTC
5858
constexpr time_t MIN_DATETIME64_TIMESTAMP = -62167219200LL; // 0000-01-01 00:00:00 UTC
59-
constexpr time_t MAX_DATE32_TIMESTAMP = 10413791999LL; // 2299-12-31 23:59:59 UTC (last day of Date32)
59+
constexpr time_t MAX_DATE32_TIMESTAMP = 253402300799LL; // 9999-12-31 23:59:59 UTC (last day of Date32)
6060
constexpr time_t MAX_DATETIME_TIMESTAMP = 0xFFFFFFFF;
6161
constexpr time_t MAX_DATE_TIMESTAMP = 5662310399; // 2149-06-06 23:59:59 UTC
6262
constexpr time_t MAX_TIME_TIMESTAMP = 3599999; // 999:59:59

‎src/Functions/FunctionBinaryArithmetic.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1618,7 +1618,7 @@ class FunctionBinaryArithmetic : public IFunction, WithContext
16181618
/// The valid range for the result, expressed in the result's own units:
16191619
/// DateTime: seconds in [0, 2^32-1], covering ~1970 to ~2106.
16201620
/// DateTime64: scaled values in [MIN_DATETIME64_TIMESTAMP * 10^scale, MAX_DATETIME64_TIMESTAMP * 10^scale],
1621-
/// covering ~1900 to ~2299 (but narrower at scale 9 due to Int64 capacity).
1621+
/// covering years 0000 to 9999 (but narrower at high scales due to Int64 capacity).
16221622
Int64 result_min = 0;
16231623
Int64 result_max = static_cast<Int64>(MAX_DATETIME_TIMESTAMP);
16241624
UInt32 result_scale = 0;

‎src/Functions/FunctionsConversion.h‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -337,28 +337,26 @@ struct ToDate32TransformFromSecondsOrDays
337337
static NO_SANITIZE_UNDEFINED Int32 execute(const FromType & from, const DateLUTImpl & time_zone)
338338
{
339339
constexpr bool overflow_throw = date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Throw;
340-
constexpr Int32 daynum_min_offset = -static_cast<Int32>(DateLUTImpl::getDayNumOffsetEpoch());
341340

342341
if constexpr (is_signed_v<FromType>)
343342
{
344343
bool is_nan = false;
345344
if constexpr (is_floating_point<FromType>)
346345
is_nan = isNaN(from);
347-
if (is_nan || from < daynum_min_offset)
346+
if (is_nan || from < DATE_LUT_MIN_EXTEND_DAY_NUM)
348347
{
349348
if constexpr (overflow_throw)
350349
throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "Timestamp value {} is out of bounds of type Date32", static_cast<Int64>(from));
351-
return daynum_min_offset;
350+
return DATE_LUT_MIN_EXTEND_DAY_NUM;
352351
}
353352
}
354353

355-
/// Date32 spans [1900, 2299] (unlike DateTime64, which now goes up to 9999), so it keeps its own upper bound.
356354
if constexpr (overflow_throw && std::numeric_limits<FromType>::max() > MAX_DATE32_TIMESTAMP)
357355
if (from > MAX_DATE32_TIMESTAMP) [[unlikely]]
358356
throw Exception(ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE, "Timestamp value {} is out of bounds of type Date32", static_cast<Int64>(from));
359357

360-
if constexpr (std::numeric_limits<FromType>::max() >= DATE_LUT_MAX_EXTEND_DAY_NUM)
361-
if (from >= DATE_LUT_MAX_EXTEND_DAY_NUM)
358+
if constexpr (std::numeric_limits<FromType>::max() > DATE_LUT_MAX_EXTEND_DAY_NUM)
359+
if (from > DATE_LUT_MAX_EXTEND_DAY_NUM)
362360
{
363361
/// Casting a huge floating-point value directly to Int64 is undefined behaviour and yields
364362
/// different results across architectures (e.g. INT64_MIN on x86 vs saturation on AArch64),
@@ -643,7 +641,7 @@ struct ToDateTime64Transform
643641
DateTime64::NativeType execute(Int32 d, const DateLUTImpl & time_zone) const
644642
{
645643
Int64 dt = static_cast<Int64>(time_zone.fromDayNum(ExtendedDayNum(d)));
646-
/// Date32 reaches 2299-12-31, whose whole-seconds value (10413705600) overflows the Int64 DateTime64 ticks
644+
/// Date32 reaches 9999-12-31, whose whole-seconds value (253402214400) overflows the Int64 DateTime64 ticks
647645
/// at high precision (e.g. * 10^9 at scale 9 exceeds Int64::max). Clamp to the scale-dependent bounds before
648646
/// multiplying, matching the numeric ToDateTime64Transform* transforms; otherwise decimalFromComponents throws
649647
/// DECIMAL_OVERFLOW. The Date (UInt16, up to 2149) and DateTime (UInt32, up to 2106) source overloads stay
@@ -1993,7 +1991,7 @@ struct ConvertImpl
19931991
* when user write toDate(UInt32), expecting conversion of unix timestamp to Date.
19941992
* (otherwise such usage would be frequent mistake).
19951993
*
1996-
* Same for converting to Date32, but the threshold is 120530 (DATE_LUT_MAX_EXTEND_DAY_NUM)
1994+
* Same for converting to Date32, but the threshold is 2932896 (DATE_LUT_MAX_EXTEND_DAY_NUM, i.e. 9999-12-31)
19971995
* instead of 65536.
19981996
*/
19991997
else if constexpr ((
@@ -4217,7 +4215,7 @@ struct ToDateMonotonicity
42174215

42184216
return {.is_monotonic = true, .is_always_monotonic = true};
42194217
}
4220-
constexpr UInt64 max_day_num = std::is_same_v<T, DataTypeDate32> ? DATE_LUT_MAX_EXTEND_DAY_NUM - 1 : DATE_LUT_MAX_DAY_NUM;
4218+
constexpr UInt64 max_day_num = std::is_same_v<T, DataTypeDate32> ? DATE_LUT_MAX_EXTEND_DAY_NUM : DATE_LUT_MAX_DAY_NUM;
42214219

42224220
if (((left.getType() == Field::Types::UInt64 || left.isNull()) && (right.getType() == Field::Types::UInt64 || right.isNull())
42234221
&& ((left.isNull() || left.safeGet<UInt64>() <= max_day_num) && (right.isNull() || right.safeGet<UInt64>() > max_day_num)))

‎src/Functions/FunctionsConversion_reg.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1114,7 +1114,7 @@ Converts the argument to the Date data type. This is a MySQL compatibility alias
11141114
/// toDate32 documentation
11151115
FunctionDocumentation::Description description_toDate32 = R"(
11161116
Converts the argument to the [Date32](../data-types/date32.md) data type.
1117-
If the value is outside the range, `toDate32` returns the border values supported by [Date32](../data-types/date32.md).
1117+
If the value is outside the `[0000-01-01, 9999-12-31]` range, `toDate32` returns the border values supported by [Date32](../data-types/date32.md).
11181118
If the argument is of type [`Date`](../data-types/date.md), it's bounds are taken into account.
11191119
)";
11201120
FunctionDocumentation::Syntax syntax_toDate32 = "toDate32(expr)";
@@ -1137,15 +1137,15 @@ toTypeName(value): Date32
11371137
)"
11381138
},
11391139
{
1140-
"Outside range",
1140+
"Before 1900",
11411141
R"(
11421142
SELECT toDate32('1899-01-01') AS value, toTypeName(value)
11431143
FORMAT Vertical
11441144
)",
11451145
R"(
11461146
Row 1:
11471147
──────
1148-
value: 1900-01-01
1148+
value: 1899-01-01
11491149
toTypeName(value): Date32
11501150
)"
11511151
}

0 commit comments

Comments
 (0)