comphead commented on code in PR #5457:
URL: https://github.com/apache/datafusion-comet/pull/5457#discussion_r4670000520


##########
native/spark-expr/src/conversion_funcs/temporal.rs:
##########
@@ -15,17 +15,65 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use crate::conversion_funcs::string::parse_sign_offset;
+use crate::conversion_funcs::utils::{timestamp_micros_with_tz, 
MICROS_PER_SECOND};
 use crate::utils::resolve_local_datetime;
-use crate::{EvalMode, SparkCastOptions, SparkResult};
+use crate::{EvalMode, SparkCastOptions, SparkError, SparkResult};
 use arrow::array::timezone::Tz;
-use arrow::array::{ArrayRef, AsArray, TimestampMicrosecondBuilder};
-use arrow::compute::{cast_with_options, CastOptions};
-use arrow::datatypes::{DataType, Date32Type, TimeUnit};
-use chrono::NaiveDate;
-use datafusion::common::format::DEFAULT_CAST_OPTIONS;
-use std::str::FromStr;
+use arrow::array::{ArrayRef, AsArray, Date32Array, TimestampMicrosecondArray};
+use arrow::datatypes::{DataType, Date32Type};
+use chrono::{NaiveDate, NaiveTime};
 use std::sync::Arc;
 
+const DAYS_PER_400_YEARS: i64 = 146_097;
+
+/// JVM offsets for converting each local date to the instant returned by
+/// `LocalDate.atStartOfDay(zone)`. Subtracting the effective offset from 
midnight
+/// UTC yields that instant even when a gap spans midnight or skips a whole 
date.
+#[derive(Debug, Hash, PartialEq, Eq)]
+pub struct DateOffsets {
+    repeat_from_day: i32,
+    starts: Vec<i32>,
+    offsets: Vec<i32>,
+}
+
+impl DateOffsets {
+    /// `starts` holds strictly increasing epoch days beginning at `i32::MIN`.
+    /// Each offset in seconds applies from its inclusive start day until the 
next
+    /// start. Recurring rules repeat every 400 Gregorian years from 
`repeat_from_day`.
+    /// Zones without recurring rules use `i32::MAX` as `repeat_from_day`.
+    pub fn try_new(repeat_from_day: i32, starts: Vec<i32>, offsets: Vec<i32>) 
-> SparkResult<Self> {
+        let cycle_end = i64::from(repeat_from_day) + DAYS_PER_400_YEARS;
+        if starts.first() != Some(&i32::MIN)
+            || starts.len() != offsets.len()
+            || !starts.is_sorted_by(|a, b| a < b)
+            || starts
+                .last()
+                .is_some_and(|&day| i64::from(day) >= cycle_end)
+            || offsets.iter().any(|s| !(-64_800..=64_800).contains(s))
+        {
+            return Err(SparkError::Internal(
+                "Invalid start-of-day offsets for DATE to 
TIMESTAMP".to_string(),
+            ));
+        }
+        Ok(Self {
+            repeat_from_day,
+            starts,
+            offsets,
+        })
+    }
+
+    fn offset(&self, day: i32) -> i32 {
+        let elapsed = i64::from(day) - i64::from(self.repeat_from_day);
+        let day = if elapsed >= DAYS_PER_400_YEARS {
+            self.repeat_from_day + (elapsed % DAYS_PER_400_YEARS) as i32
+        } else {
+            day
+        };
+        self.offsets[self.starts.partition_point(|&start| start <= day) - 1]
+    }

Review Comment:
   Each row now does a modulo and a `partition_point` over the whole table. I 
rebuilt the driver table for `America/Los_Angeles` on JDK 11 tzdata and got 930 
entries, about 5.5 KB of protobuf per `Cast` node. A std-only model of this 
lookup (1,049 entries, 8,192 dates in a 2,200-day window, on a loaded shared 
Mac, so a rough local measurement only) took about 28 us for random dates and 
18 us for sorted dates. Reusing the last matched range took about 3 us for 
sorted dates and was no better for random ones. That is well below the old 
chrono loop, so it may be fine, but the PR says performance is unmeasured. 
Could you add a `cast_date_to_timestamp` criterion case for UTC, `+05:30` and a 
region zone so the region path has a number, and decide on a last-range cache 
from it?



##########
spark/src/test/resources/sql-tests/expressions/cast/cast_date_to_timestamp.sql:
##########
@@ -0,0 +1,93 @@
+-- Licensed to the Apache Software Foundation (ASF) under one
+-- or more contributor license agreements.  See the NOTICE file
+-- distributed with this work for additional information
+-- regarding copyright ownership.  The ASF licenses this file
+-- to you under the Apache License, Version 2.0 (the
+-- "License"); you may not use this file except in compliance
+-- with the License.  You may obtain a copy of the License at
+--
+--   http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing,
+-- software distributed under the License is distributed on an
+-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+-- KIND, either express or implied.  See the License for the
+-- specific language governing permissions and limitations
+-- under the License.
+
+-- Config: spark.comet.exec.scalaUDF.codegen.enabled=true
+-- Config: spark.sql.datetime.java8API.enabled=true
+-- Config: spark.sql.session.timeZone=GMT+05:30
+-- Config: spark.sql.ansi.enabled=true
+
+statement
+CREATE TABLE wide_dates(y INT, m INT, d INT) USING parquet
+
+-- Check both winter and summer beyond chrono's calendar, and summer just
+-- beyond chrono-tz's last DST transition for Los Angeles.
+statement
+INSERT INTO wide_dates VALUES
+  (262143, 1, 1), (262143, 7, 4), (-262144, 1, 1),
+  (2101, 7, 4), (1970, 1, 1), (1919, 3, 31), (NULL, 1, 1)
+
+query expect_native(cast, make_date)
+SELECT CAST(make_date(y, m, d) AS TIMESTAMP),
+       CAST(array(named_struct('d', make_date(y, m, d))) AS ARRAY<STRUCT<d: 
TIMESTAMP>>)
+FROM wide_dates
+
+statement
+SET spark.sql.session.timeZone=America/Los_Angeles
+
+query expect_native(cast, make_date)
+SELECT CAST(make_date(y, m, d) AS TIMESTAMP),
+       CAST(make_date(y, m, d) AS TIMESTAMP_NTZ) FROM wide_dates
+
+statement
+INSERT INTO wide_dates VALUES (300000, 6, 15), (-300000, 6, 15)
+
+query expect_native(try_cast)
+SELECT TRY_CAST(make_date(y, m, d) AS TIMESTAMP), TRY_CAST(make_date(y, m, d) 
AS TIMESTAMP_NTZ)
+FROM wide_dates
+
+-- Under ANSI, make_date with non-nullable inputs is non-nullable. Spark 
infers the
+-- same for the TRY_CAST, even though 300000-06-15 overflows.
+query expect_fallback(TRY_CAST from date can overflow)
+SELECT TRY_CAST(make_date(coalesce(y, 300000), 6, 15) AS TIMESTAMP) FROM 
wide_dates
+
+statement
+SET spark.sql.legacy.castComplexTypesToString.enabled=true
+
+-- The outer cast would otherwise send this subtree through the dispatcher.
+query expect_fallback(TRY_CAST from date can overflow)
+SELECT CAST(array(TRY_CAST(make_date(coalesce(y, 300000), 6, 15) AS 
TIMESTAMP_NTZ)) AS STRING)
+FROM wide_dates
+
+statement
+CREATE TABLE nested_dates USING parquet AS
+SELECT y = 1970 AS keep, named_struct('d', dt) AS s, map(1, dt) AS m, map(dt, 
1) AS k,
+       array(named_struct('d', dt)) AS a
+FROM (SELECT y, make_date(y, m, d) AS dt FROM wide_dates WHERE y IN (1970, 
300000))
+
+-- IF can null a container without clearing the overflowing date in its child 
buffer.
+-- Read each container twice to keep the optimizer from moving the cast inside 
the IF.
+query expect_native(cast)
+SELECT s, CAST(s AS STRUCT<d: TIMESTAMP>), m, CAST(m AS MAP<INT, 
TIMESTAMP_NTZ>),
+       k, CAST(k AS MAP<TIMESTAMP, INT>), a, CAST(a AS ARRAY<STRUCT<d: 
TIMESTAMP_NTZ>>)
+FROM (SELECT IF(keep, s, NULL) AS s, IF(keep, m, NULL) AS m, IF(keep, k, NULL) 
AS k,
+             IF(keep, a, NULL) AS a FROM nested_dates)
+
+query expect_native(try_cast)
+SELECT TRY_CAST(s AS STRUCT<d: TIMESTAMP>), TRY_CAST(m AS MAP<INT, 
TIMESTAMP_NTZ>),
+       TRY_CAST(a AS ARRAY<STRUCT<d: TIMESTAMP>>)
+FROM nested_dates
+
+query expect_fallback(null map key)
+SELECT TRY_CAST(k AS MAP<TIMESTAMP, INT>) FROM nested_dates
+
+-- The clocks jumped from 23:30 to 00:30 in Toronto. The date starts at
+-- the transition instant (04:30 UTC).
+statement
+SET spark.sql.session.timeZone=America/Toronto
+
+query expect_native(cast)
+SELECT CAST(make_date(y, m, d) AS TIMESTAMP) FROM wide_dates WHERE y = 1919

Review Comment:
   `buildDateOffsets` has cases that no fixture here or in 
`CometNativeCastSuite` reaches, since `generateDates()` covers 1970 to 2027 
plus a few far dates. They are a date before standard time, where the JVM 
offset has seconds (`Europe/Amsterdam` 1850-01-01 is `+00:17:30` on JDK 11 
tzdata), a date the zone skipped entirely (`Pacific/Apia` 2011-12-30, which 
resolves to `2011-12-31T00:00+14:00` and is why `record` covers `utcDay` to 
`utcDay + 2`), and a southern-hemisphere zone past 2099 (`Australia/Sydney` 
2101-01-15 and 2101-07-15), which exercises the 400-year remap with the 
opposite season. Could these go in here with a `-- ConfigMatrix: 
spark.sql.session.timeZone=...` like `min_max_struct_timezone.sql`? I have not 
run them, so I do not know that they pass.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to