aleksandar-trajkovic-db commented on code in PR #60609:
URL: https://github.com/apache/spark/pull/60609#discussion_r4628064112
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -480,14 +506,16 @@ object JdbcUtils extends Logging with SQLConfHelper {
case _: StringType => JDBCValueGetter.StringGetter
case TimestampType if metadata.contains("logical_time_type") =>
JDBCValueGetter.LogicalTimeGetter
- case TimestampType => JDBCValueGetter.TimestampGetter(dialect)
+ case TimestampType =>
+ JDBCValueGetter.TimestampGetter(dialect, options.flatMap(calendarFor))
Review Comment:
**Non-blocking (P2):** The calendar reaches the scalar getter here, but
ArrayGetter is still built without it (JdbcUtils.scala:525). By my reading of
the code, take a Postgres row whose ts timestamp and tsa timestamp[] columns
both hold 2026-10-10 11:03:07, read from a JVM in Asia/Kolkata with the option
set to UTC. ts reads as 2026-10-10T11:03:07Z, but tsa[0] reads as
2026-10-10T05:33:07Z. The reason is that ArrayGetter converts the driver's
JVM-zone Timestamps without the calendar (JDBCValueGetter.scala:294-297).
Writes have the same gap, because the array setter passes elements to
createArrayOf with no calendar (JdbcUtils.scala:655-659).
**Recommended change:** Pass the option's calendar to ArrayGetter. When the
calendar is set, read TimestampType array elements through
java.sql.Array.getResultSet() with getTimestamp(2, calendar), recursing for
nested arrays. In the array setter, when the calendar is set, convert each
TimestampType element to the Timestamp whose JVM-zone wall clock equals the
element's wall clock in the option's zone before createArrayOf. Add a JDBC test
for a timestamp array column with the option set, on a database that supports
arrays, and keep unset-option reads and writes unchanged.
**Why this works:** Reading through the array's result set lets the driver
apply the calendar to each element exactly as getTimestamp(i, calendar) does
for scalars, so offset-carrying elements are not reinterpreted. Writing the
element as its wall clock in the option's zone makes the zone-less array text
the driver sends match what setTimestamp(i, ts, calendar) sends for a scalar.
**Risks:** Only with the option set, a driver whose java.sql.Array does not
support getResultSet() would now fail reads of timestamp array columns with an
error, where before it returned shifted values. Writes into an existing
timestamptz[] column send the elements as wall clocks in the option's zone,
which the database then interprets in its session zone. This matches the
option's meaning only when the database session uses that zone.
**Constraints:** TIMESTAMP_NTZ arrays and all arrays read or written without
the option keep their current conversion.
**Verification:**
- **Regression:** With the option set to UTC and a JVM default zone such as
Asia/Kolkata, a row holding the same wall clock in a scalar TIMESTAMP column
and in a TIMESTAMP array column reads both as the same instant.
- **Behavior:** With the option set, writing a TIMESTAMP array stores each
element's wall clock in the option's zone, and reading it back with the option
returns the original instants, for both settings of the Java 8 datetime API.
- **Compatibility:** Without the option, and for TIMESTAMP_NTZ arrays, array
reads and writes return the same values as before.
##########
docs/sql-data-sources-jdbc.md:
##########
@@ -398,6 +398,14 @@ logging into the data sources.
</td>
<td>read/write</td>
</tr>
+ <tr>
+ <td><code>timestampCalendarTimeZone</code></td>
+ <td>(none)</td>
+ <td>
+ When set, Spark reads and writes TIMESTAMP values in this time zone
instead of the JVM default time zone. Set it to the time zone the database
session uses for timestamps, for example <code>UTC</code> or
<code>Asia/Kolkata</code>, when the two differ and values come out shifted.
Only applies to TIMESTAMP columns, not TIMESTAMP_NTZ. When set, filters,
aggregates, joins and sorts that contain timestamp values are evaluated by
Spark instead of the database. An invalid time zone fails the query. If not
set, the JVM default time zone is used.
Review Comment:
**Nit (P3):** This sentence says that filters, aggregates, joins and sorts
containing timestamp values run in Spark, but the guard in
JdbcUtils.scala:457-465 declines only expressions with a timestamp literal.
ORDER BY ts LIMIT 10, MAX(ts), GROUP BY ts and a.ts = b.ts are still pushed to
the database, and correctly so. The sentence should name timestamp literals,
plus anything else the guard ends up declining.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60609#discussion_r4600276612).
**Verification:**
- **Inspection:** The timestampCalendarTimeZone row in the JDBC options
table describes the same set of expressions that the pushdown guard declines in
the final code, including any extension to date-part functions and casts.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/jdbc/JdbcUtils.scala:
##########
@@ -448,6 +449,31 @@ object JdbcUtils extends Logging with SQLConfHelper {
)
}
+ /**
+ * Whether `expr` has a TimestampType or TimestampLTZNanosType literal,
which would be rendered
+ * for the database without `timestampCalendarTimeZone`. Such expressions
are not pushed down
+ * when the option is set, so Spark evaluates them on the values read in the
option's time zone.
+ */
+ def containsCalendarTimeZoneTimestampLiteral(expr: Expression, options:
JDBCOptions): Boolean =
+ options.timestampCalendarTimeZone.isDefined && {
+ def walk(e: Expression): Boolean = e match {
+ case l: LiteralValue[_] =>
+ l.dataType == TimestampType ||
l.dataType.isInstanceOf[TimestampLTZNanosType]
Review Comment:
**Blocking (P1):** This guard only looks for timestamp literals, but a
pushed function of a timestamp column depends on the zone too. By my reading of
the code, take a catalog with the option set to UTC and
spark.sql.session.timeZone=Asia/Kolkata. The JDBCV2Suite row stored as
2022-05-19 00:00:00 reads back as 05:30 in the session zone, so Spark computes
hour(time1) = 5. WHERE hour(time1) = 0 has no timestamp literal, so it is
pushed as EXTRACT(HOUR FROM TIME1) = 0, the pushdown the existing h2 test at
JDBCV2Suite.scala:1618-1625 shows. H2 returns the row, and Spark does not
re-check it, while WHERE hour(time1) = 5 returns nothing. Group-bys and top-N
orders on such expressions, and comparisons between a timestamp column and a
DATE column that Spark casts to TIMESTAMP, take the database's answer the same
way. Without the option, this mismatch appears only when the JVM zone differs
from the session zone. With the option, it also appears in the usual setup
where they are equal.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60609#discussion_r4600276612).
**Recommended change:** When timestampCalendarTimeZone is set, the pushdown
guard also declines any expression that contains one of these: a cast from or
to TimestampType or TimestampLTZNanosType; a cast whose input type is not
recorded; or an EXTRACT whose source is a timestamp column of the scan or whose
source type cannot be determined. Such expressions then stay in Spark at every
V2 pushdown site. Add JDBC catalog tests for these functions with the option
set, and keep the existing literal behavior and the unset-option behavior
unchanged.
**Why this works:** The guard's tree walk gains two cases next to the
literal case. A V2 Cast is checked through its recorded input and target types,
and a V2 Extract is checked through its source, with column references resolved
against the scan schema. A cast to TIMESTAMP matters as much as a cast from it:
Spark places a DATE or STRING value at an instant in the session time zone,
while the database produces a wall clock. Because cannotPushDown already
applies the guard at the predicate, aggregate, join and top-N sites, those
expressions are returned to Spark there. Spark then evaluates them on the
values read in the option's zone, using the session time zone.
**Compatibility:** Without timestampCalendarTimeZone, every pushdown
decision and the SQL sent to the database are unchanged.
**Risks:** With the option set, queries that filter, group or sort by a
date-part function of a timestamp column, or by a cast to or from a timestamp
type, now read more rows from the database and lose aggregate and top-N
pushdown for those expressions. Unsetting the option restores the previous
pushdown.
**Constraints:** Expressions over DATE columns that do not cast them to a
timestamp, and column-only timestamp comparisons, sorts, MIN and MAX, keep
their current pushdown because they do not depend on the time zone.
**Exclusions:**
- Rendering pushed timestamp functions in the session time zone inside each
dialect is left out because it needs a dialect API change.
**Verification:**
- **Regression:** Through a JDBC catalog with timestampCalendarTimeZone set
to UTC and a session time zone of Asia/Kolkata, a filter such as hour(ts) = 0
on a column storing midnight returns no rows, and hour(ts) = 5 returns that
row, matching hour() computed on an unfiltered read.
- **Regression:** Through the same catalog, a filter comparing a timestamp
column with a DATE column of the same table, which Spark casts to TIMESTAMP,
returns the same rows as that comparison applied to an unfiltered read.
- **Behavior:** With the option set, the plan shows that the date-part
filter, the comparison with the cast DATE column, and a group-by over a
timestamp-to-date cast are not pushed, while a filter on a non-timestamp column
of the same scan is still pushed.
- **Compatibility:** Without the option, a date-part filter on a timestamp
column is still pushed as an EXTRACT predicate, and the existing pushdown tests
keep their pushed-filter plans.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/jdbc/JDBCScanBuilder.scala:
##########
@@ -112,8 +116,8 @@ case class JDBCScanBuilder(
override def pushAggregation(aggregation: Aggregation): Boolean = {
if (!jdbcOptions.pushDownAggregate) return false
- if (aggregation.aggregateExpressions.exists(containsUnsupportedCharPad) ||
- aggregation.groupByExpressions.exists(containsUnsupportedCharPad)) {
+ if (aggregation.aggregateExpressions.exists(cannotPushDown) ||
Review Comment:
**Non-blocking (P2):** The only new JDBCV2Suite test ('SPARK-61857:
timestamp predicates are not pushed down with timestampCalendarTimeZone')
issues WHERE predicates, so it exercises only pushPredicates. Suppose this
check, or the one in pushTopN at JDBCScanBuilder.scala:350, went back to
containsUnsupportedCharPad. Every SPARK-61857 test would still pass, while H2
would evaluate the aggregate or the ORDER BY against a timestamp literal
rendered in the session zone. JDBCV2Suite already has checkAggregateRemoved,
checkSortRemoved and checkLimitRemoved for asserting on these sites.
**Verification:**
- **Regression:** With the option set, an aggregate such as a SUM over CASE
WHEN on a timestamp column compared with a timestamp literal is not pushed and
returns the count Spark computes on the read values.
- **Regression:** With the option set, ORDER BY an expression comparing a
timestamp column with a timestamp literal, with LIMIT 1, is not pushed as a
top-N and returns the row Spark selects from the read values.
--
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]