diff --git a/vortex-duckdb/src/convert/expr.rs b/vortex-duckdb/src/convert/expr.rs index b487ab4fdc4..7b9c5dc3f6b 100644 --- a/vortex-duckdb/src/convert/expr.rs +++ b/vortex-duckdb/src/convert/expr.rs @@ -67,6 +67,7 @@ use vortex_spatial::scalar_fn::intersects::SpatialIntersects; use crate::SESSION; use crate::convert::dtype::FromLogicalType; use crate::convert::table_filter::dynamic_filter_expr; +use crate::convert::time_zone::align_time_zones; use crate::cpp::DUCKDB_TYPE; use crate::cpp::DUCKDB_VX_EXPR_TYPE; use crate::duckdb; @@ -393,6 +394,7 @@ fn try_from_bound_function( pub fn try_from_bound_expression( value: &ExpressionRef, fields: &[DuckdbField], + scope_dtype: &DType, ) -> VortexResult> { try_from_expression_inner( value, @@ -400,7 +402,9 @@ pub fn try_from_bound_expression( col_sub: None, fields: Some(fields), }, - ) + )? + .map(|expr| align_time_zones(expr, scope_dtype)) + .transpose() } pub(super) fn try_from_bound_expression_with_col_sub( diff --git a/vortex-duckdb/src/convert/mod.rs b/vortex-duckdb/src/convert/mod.rs index f1b5ba5bb10..6161c67bb46 100644 --- a/vortex-duckdb/src/convert/mod.rs +++ b/vortex-duckdb/src/convert/mod.rs @@ -5,6 +5,7 @@ mod dtype; mod expr; mod scalar; mod table_filter; +mod time_zone; mod vector; pub use dtype::FromLogicalType; diff --git a/vortex-duckdb/src/convert/table_filter.rs b/vortex-duckdb/src/convert/table_filter.rs index 2dce92d3d04..502e3c29dcf 100644 --- a/vortex-duckdb/src/convert/table_filter.rs +++ b/vortex-duckdb/src/convert/table_filter.rs @@ -27,6 +27,7 @@ use vortex::scan::selection::Selection; use vortex::scan::strict_sorted_buffer::StrictSortedBuffer; use super::expr::try_from_bound_expression_with_col_sub; +use super::time_zone::align_time_zones; use crate::cpp::DUCKDB_VX_EXPR_TYPE; use crate::duckdb::DynamicFilter; use crate::duckdb::ExpressionClass; @@ -40,6 +41,16 @@ pub fn try_from_table_filter( value: &TableFilterRef, col: &Expression, scope_dtype: &DType, +) -> VortexResult> { + try_from_table_filter_inner(value, col, scope_dtype)? + .map(|expr| align_time_zones(expr, scope_dtype)) + .transpose() +} + +fn try_from_table_filter_inner( + value: &TableFilterRef, + col: &Expression, + scope_dtype: &DType, ) -> VortexResult> { Ok(Some(match value.as_class() { TableFilterClass::ConstantComparison(const_) => { @@ -50,7 +61,7 @@ pub fn try_from_table_filter( TableFilterClass::ConjunctionAnd(conj_and) => { let Some(children) = conj_and .children() - .map(|child| try_from_table_filter(child, col, scope_dtype)) + .map(|child| try_from_table_filter_inner(child, col, scope_dtype)) .try_collect::<_, Option>, _>()? else { return Ok(None); @@ -62,7 +73,7 @@ pub fn try_from_table_filter( TableFilterClass::ConjunctionOr(disjuction_or) => { let Some(children) = disjuction_or .children() - .map(|child| try_from_table_filter(child, col, scope_dtype)) + .map(|child| try_from_table_filter_inner(child, col, scope_dtype)) .try_collect::<_, Option>, _>()? else { return Ok(None); @@ -73,11 +84,15 @@ pub fn try_from_table_filter( TableFilterClass::IsNull => is_null(col.clone()), TableFilterClass::IsNotNull => is_not_null(col.clone()), TableFilterClass::StructExtract(name, child_filter) => { - return try_from_table_filter(child_filter, &get_item(name, col.clone()), scope_dtype); + return try_from_table_filter_inner( + child_filter, + &get_item(name, col.clone()), + scope_dtype, + ); } TableFilterClass::Optional(child) => { // Optional expressions are optional not yet supported. - return try_from_table_filter(child, col, scope_dtype).or_else(|_err| { + return try_from_table_filter_inner(child, col, scope_dtype).or_else(|_err| { // Failed to convert the optional expression, but it's optional, so who cares? Ok(None) }); diff --git a/vortex-duckdb/src/convert/time_zone.rs b/vortex-duckdb/src/convert/time_zone.rs new file mode 100644 index 00000000000..861c24ffa7d --- /dev/null +++ b/vortex-duckdb/src/convert/time_zone.rs @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Time zones of the timestamp values that DuckDB compares with a zoned Vortex column. +//! +//! A DuckDB zoned timestamp is a UTC instant without a time zone, so its values convert to Vortex +//! timestamps in `UTC`. A Vortex column keeps the time zone it was written with, and Vortex only +//! compares timestamps of the same time zone. Both sides hold UTC instants, so a value takes the +//! time zone of the column it is compared with. + +use std::sync::Arc; + +use vortex::dtype::DType; +use vortex::error::VortexResult; +use vortex::expr::Expression; +use vortex::expr::dynamic; +use vortex::expr::lit; +use vortex::expr::traversal::NodeExt; +use vortex::expr::traversal::Transformed; +use vortex::extension::datetime::AnyTemporal; +use vortex::extension::datetime::TemporalMetadata; +use vortex::scalar::Scalar; +use vortex::scalar_fn::fns::dynamic::DynamicComparison; +use vortex::scalar_fn::fns::literal::Literal; + +/// Gives the timestamp literals and dynamic values in `expr` the time zone of the zoned timestamp +/// that they are compared with. `scope` is the dtype that `expr` is evaluated over. +pub(super) fn align_time_zones(expr: Expression, scope: &DType) -> VortexResult { + let aligned = expr.transform_down(|node| { + // An operand that is not over `scope`, such as a hive partition column, has no dtype + // here. DuckDB evaluates it, or binding reports it. + let Some(zoned) = node + .children() + .iter() + .filter(|child| !child.is::()) + .filter_map(|child| child.return_dtype(scope).ok()) + .find(|dtype| time_zone(dtype).is_some()) + else { + return Ok(Transformed::no(node)); + }; + + if let Some(options) = node.as_opt::() { + // The dtype of the dynamic value cannot be read here. DuckDB's values convert in + // `UTC`, so a column in `UTC` needs no new comparison. + if time_zone(&zoned) == Some("UTC") { + return Ok(Transformed::no(node)); + } + let (operator, default) = (options.operator(), options.default()); + let options = options.clone(); + let aligned = dynamic( + operator, + move || options.scalar().and_then(Scalar::into_value), + zoned.as_nullable(), + default, + node.child(0).clone(), + ); + return Ok(Transformed::yes(aligned)); + } + + let mut changed = false; + let children = node + .children() + .iter() + .map(|child| { + let Some(literal) = child.as_opt::() else { + return Ok(child.clone()); + }; + let Some(dtype) = aligned_dtype(literal.dtype(), &zoned) else { + return Ok(child.clone()); + }; + changed = true; + Scalar::try_new(dtype, literal.value().cloned()).map(lit) + }) + .collect::>>()?; + if !changed { + return Ok(Transformed::no(node)); + } + node.with_children(children).map(Transformed::yes) + })?; + Ok(aligned.value) +} + +/// The time zone of a zoned timestamp dtype. +fn time_zone(dtype: &DType) -> Option<&str> { + match dtype.as_extension_opt()?.metadata_opt::()? { + TemporalMetadata::Timestamp(_, tz) => tz.as_deref(), + _ => None, + } +} + +/// The dtype of a literal with its time zone replaced by that of `zoned`, or `None` if the literal +/// is not a timestamp, or a list of timestamps, that differs from `zoned` in its time zone alone. +fn aligned_dtype(literal: &DType, zoned: &DType) -> Option { + if let DType::List(element, nullability) = literal { + let element = aligned_dtype(element, zoned)?; + return Some(DType::List(Arc::new(element), *nullability)); + } + + let (literal_ext, zoned_ext) = (literal.as_extension_opt()?, zoned.as_extension_opt()?); + let TemporalMetadata::Timestamp(literal_unit, Some(literal_tz)) = + literal_ext.metadata_opt::()? + else { + return None; + }; + let TemporalMetadata::Timestamp(zoned_unit, Some(zoned_tz)) = + zoned_ext.metadata_opt::()? + else { + return None; + }; + (literal_unit == zoned_unit && literal_tz != zoned_tz) + .then(|| zoned.with_nullability(literal.nullability())) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + use vortex::dtype::DType; + use vortex::dtype::Nullability; + use vortex::dtype::PType; + use vortex::dtype::StructFields; + use vortex::error::VortexResult; + use vortex::expr::Expression; + use vortex::expr::between; + use vortex::expr::col; + use vortex::expr::gt_eq; + use vortex::expr::in_list_of; + use vortex::expr::lit; + use vortex::extension::datetime::TimeUnit; + use vortex::extension::datetime::Timestamp; + use vortex::extension::datetime::TimestampOptions; + use vortex::scalar::Scalar; + use vortex::scalar::ScalarValue; + use vortex::scalar_fn::fns::between::BetweenOptions; + use vortex::scalar_fn::fns::between::StrictComparison; + + use super::align_time_zones; + + fn timestamp(unit: TimeUnit, tz: Option<&str>, value: i64) -> VortexResult { + Ok(Scalar::extension::( + TimestampOptions { + unit, + tz: tz.map(Into::into), + }, + Scalar::try_new( + DType::Primitive(PType::I64, Nullability::Nullable), + Some(ScalarValue::from(value)), + )?, + )) + } + + /// A scope with the single column `t` of the dtype of `like`. + fn scope_of(like: &Scalar) -> DType { + DType::Struct( + StructFields::from_iter([("t", like.dtype().clone())]), + Nullability::NonNullable, + ) + } + + fn comparison(value: Scalar) -> VortexResult { + Ok(gt_eq(col("t"), lit(value))) + } + + fn range(value: Scalar) -> VortexResult { + let options = BetweenOptions { + lower_strict: StrictComparison::NonStrict, + upper_strict: StrictComparison::NonStrict, + }; + Ok(between(col("t"), lit(value.clone()), lit(value), options)) + } + + fn membership(value: Scalar) -> VortexResult { + in_list_of(col("t"), value.dtype().clone(), vec![value]) + } + + #[rstest] + #[case::comparison(comparison)] + #[case::between(range)] + #[case::in_list(membership)] + fn test_align_time_zones_literal_takes_column_zone( + #[case] filter: fn(Scalar) -> VortexResult, + ) -> VortexResult<()> { + let utc = timestamp(TimeUnit::Microseconds, Some("UTC"), 1)?; + let new_york = timestamp(TimeUnit::Microseconds, Some("America/New_York"), 1)?; + let scope = scope_of(&new_york); + + assert!(filter(utc.clone())?.bind(&scope).is_err()); + + let aligned = align_time_zones(filter(utc)?, &scope)?; + assert_eq!(aligned, filter(new_york)?); + aligned.bind(&scope)?; + + Ok(()) + } + + #[rstest] + #[case::same_zone(Some("UTC"), TimeUnit::Microseconds, Some("UTC"))] + #[case::other_unit(Some("America/New_York"), TimeUnit::Nanoseconds, Some("UTC"))] + #[case::literal_without_zone(Some("America/New_York"), TimeUnit::Microseconds, None)] + #[case::column_without_zone(None, TimeUnit::Microseconds, Some("UTC"))] + fn test_align_time_zones_leaves_other_literals( + #[case] column_tz: Option<&str>, + #[case] literal_unit: TimeUnit, + #[case] literal_tz: Option<&str>, + ) -> VortexResult<()> { + let scope = scope_of(×tamp(TimeUnit::Microseconds, column_tz, 1)?); + let filter = comparison(timestamp(literal_unit, literal_tz, 1)?)?; + + assert_eq!(align_time_zones(filter.clone(), &scope)?, filter); + + Ok(()) + } +} diff --git a/vortex-duckdb/src/e2e_test/vortex_scan_test.rs b/vortex-duckdb/src/e2e_test/vortex_scan_test.rs index 8c0812d4ec7..6a736433a62 100644 --- a/vortex-duckdb/src/e2e_test/vortex_scan_test.rs +++ b/vortex-duckdb/src/e2e_test/vortex_scan_test.rs @@ -29,6 +29,7 @@ use vortex::array::arrays::FixedSizeListArray; use vortex::array::arrays::ListArray; use vortex::array::arrays::PrimitiveArray; use vortex::array::arrays::StructArray; +use vortex::array::arrays::TemporalArray; use vortex::array::arrays::VarBinArray; use vortex::array::arrays::VarBinViewArray; use vortex::array::validity::Validity; @@ -36,6 +37,7 @@ use vortex::buffer::buffer; use vortex::dtype::Nullability; use vortex::dtype::PType; use vortex::encodings::fastlanes::RLEData; +use vortex::extension::datetime::TimeUnit; use vortex::file::WriteOptionsSessionExt; use vortex::io::runtime::BlockingRuntime; use vortex::layout::layouts::flat::writer::FlatLayoutStrategy; @@ -1435,3 +1437,55 @@ fn test_vortex_scan_v2_matches_v1(#[case] query: &str) -> Result<()> { assert_eq!(v2?, v1); Ok(()) } + +/// Rows `0..5000` with the timestamp of row `i` at `i` seconds after 2020-01-01 10:00:00 UTC, in +/// the given time zone. Every row with `i % 7 == 3` is null. +async fn write_zoned_timestamp_file(tz: &str) -> NamedTempFile { + let timestamps = PrimitiveArray::from_option_iter( + (0..5000i64).map(|i| (i % 7 != 3).then_some(1_577_872_800_000_000 + i * 1_000_000)), + ); + let timestamps = TemporalArray::new_timestamp( + timestamps.into_array(), + TimeUnit::Microseconds, + Some(tz.into()), + ); + let ids = PrimitiveArray::from_iter(0..5000i64); + write_vortex_file([("id", ids.into_array()), ("t", timestamps.into_array())].into_iter()).await +} + +/// DuckDB's `TIMESTAMPTZ` has no time zone, so its constants compare with a column in any zone. +#[rstest] +#[case::equal("count(*)", "WHERE t = TIMESTAMPTZ '2020-01-01 10:00:01+00'", 1)] +#[case::greater_or_equal("count(*)", "WHERE t >= TIMESTAMPTZ '2020-01-01 10:00:01+00'", 4285)] +#[case::between( + "count(*)", + "WHERE t BETWEEN TIMESTAMPTZ '2020-01-01 10:00:01+00' AND TIMESTAMPTZ '2020-01-01 10:00:09+00'", + 8 +)] +#[case::in_list( + "count(*)", + "WHERE t IN (TIMESTAMPTZ '2020-01-01 10:00:01+00', TIMESTAMPTZ '2020-01-01 10:00:05+00')", + 2 +)] +#[case::complex_filter( + "count(*)", + "WHERE t >= TIMESTAMPTZ '2020-01-01 10:00:01+00' OR id = 0", + 4286 +)] +#[case::top_n("id", "ORDER BY t DESC NULLS LAST LIMIT 1", 4999)] +fn test_vortex_scan_zoned_timestamp_filters( + #[case] projection: &str, + #[case] clause: &str, + #[case] expected: i64, + #[values("UTC", "America/New_York")] tz: &str, +) { + let file = RUNTIME.block_on(write_zoned_timestamp_file(tz)); + + let actual = scan_vortex_file_single_row::( + file, + &format!("SELECT {projection} FROM ? {clause}"), + 0, + ); + + assert_eq!(actual, expected); +} diff --git a/vortex-duckdb/src/table_function.rs b/vortex-duckdb/src/table_function.rs index e96dd83d12c..dab81fc02eb 100644 --- a/vortex-duckdb/src/table_function.rs +++ b/vortex-duckdb/src/table_function.rs @@ -482,7 +482,7 @@ pub fn pushdown_complex_filter( ) -> VortexResult { debug!(%expr, "pushing down expression"); - let Some(expr) = try_from_bound_expression(expr, &bind_data.columns)? else { + let Some(expr) = try_from_bound_expression(expr, &bind_data.columns, &bind_data.dtype)? else { debug!(%expr, "failed to push down expression"); return Ok(false); };