From 5f38005ecc103856487e55a1a8372cf08e441941 Mon Sep 17 00:00:00 2001 From: Noah Date: Sat, 5 Dec 2026 20:03:59 -0500 Subject: [PATCH] feat: push down filters with decimal literals Comparisons and IN lists with a Decimal128 literal weren't converted to Iceberg predicates, so filters on decimal columns never skipped files. Convert the literal to an Iceberg decimal with the same value, precision and scale. A literal Iceberg can't hold (a negative scale, or more digits than its precision) isn't converted, and its filter stays with DataFusion. Literals DataFusion can't convert exactly to the column's type already leave a cast on the column, so they aren't pushed down either. Closes #73. --- crates/datafusion/src/read/predicate.rs | 133 +++++++++++- crates/datafusion/tests/filter_pushdown.rs | 76 ++++++- .../df_decimal_predicate_pushdown.toml | 23 ++ .../df_test/decimal_predicate_pushdown.slt | 204 ++++++++++++++++++ 4 files changed, 431 insertions(+), 5 deletions(-) create mode 100644 crates/sqllogictest/testdata/schedules/df_decimal_predicate_pushdown.toml create mode 100644 crates/sqllogictest/testdata/slts/df_test/decimal_predicate_pushdown.slt diff --git a/crates/datafusion/src/read/predicate.rs b/crates/datafusion/src/read/predicate.rs index 6c26b433..4f152c00 100644 --- a/crates/datafusion/src/read/predicate.rs +++ b/crates/datafusion/src/read/predicate.rs @@ -20,7 +20,7 @@ use datafusion::logical_expr::expr::{InList, ScalarFunction}; use datafusion::logical_expr::{BinaryExpr, Expr, Like, Operator}; use datafusion::scalar::ScalarValue; use iceberg::expr::{BinaryExpression, Predicate, PredicateOperator, Reference}; -use iceberg::spec::{Datum, PrimitiveLiteral}; +use iceberg::spec::{Datum, PrimitiveLiteral, PrimitiveType, Type}; /// A filter converted to an iceberg [`Predicate`]. enum Converted { @@ -362,12 +362,34 @@ fn scalar_value_to_datum(value: &ScalarValue) -> Option { ScalarValue::TimestampNanosecond(Some(v), Some(_)) => { Some(Datum::timestamptz_nanos(*v)) } - // TODO: Convert `Decimal128` literals with `Datum::decimal`, so filters - // on decimal columns are pushed down. + ScalarValue::Decimal128(Some(v), precision, scale) => { + decimal_to_datum(*v, *precision, *scale) + } _ => None, } } +/// Converts a `Decimal128` literal to an Iceberg decimal with the same value, +/// precision and scale. Returns `None` if Iceberg can't hold it: Arrow allows a +/// negative scale and a value with more digits than its precision, Iceberg +/// neither. +fn decimal_to_datum(value: i128, precision: u8, scale: i8) -> Option { + let precision = u32::from(precision); + let scale = u32::try_from(scale).ok()?; + // `try_from_bytes` reads Iceberg's serialization of a decimal, its unscaled + // value in big-endian two's complement, so the value is kept exactly. It + // doesn't validate the datum; `to` checks that the value fits the precision. + // + // TODO: Use `Datum::decimal_from_mantissa` instead if iceberg-rust makes it + // public. It builds the datum and checks the precision in one call. + let datum = Datum::try_from_bytes( + &value.to_be_bytes(), + PrimitiveType::Decimal { precision, scale }, + ) + .ok()?; + datum.to(&Type::decimal(precision, scale).ok()?).ok() +} + #[cfg(test)] mod tests { use std::collections::HashMap; @@ -377,7 +399,7 @@ mod tests { use datafusion::logical_expr::utils::split_conjunction; use datafusion::prelude::{Expr, SessionContext}; use iceberg::expr::{Predicate, Reference}; - use iceberg::spec::Datum; + use iceberg::spec::{Datum, Type}; use parquet::arrow::PARQUET_FIELD_ID_META_KEY; use super::convert_filters_to_predicate; @@ -709,6 +731,109 @@ mod tests { assert_eq!(datum, None); } + /// An Iceberg decimal parsed from `value`, so the expected datums don't come + /// from the conversion they test. + fn decimal(value: &str, precision: u32, scale: u32) -> Datum { + Datum::decimal_from_str(value) + .unwrap() + .to(&Type::decimal(precision, scale).unwrap()) + .unwrap() + } + + #[test] + fn test_scalar_value_to_datum_decimal() { + use datafusion::common::ScalarValue; + + let cases = [ + ( + ScalarValue::Decimal128(Some(1234), 10, 2), + Some(decimal("12.34", 10, 2)), + ), + ( + ScalarValue::Decimal128(Some(-1234), 10, 2), + Some(decimal("-12.34", 10, 2)), + ), + // Trailing zeros and scale are kept: 1.20 is not 1.2 at scale 1. + ( + ScalarValue::Decimal128(Some(120), 5, 2), + Some(decimal("1.20", 5, 2)), + ), + ( + ScalarValue::Decimal128(Some(0), 1, 0), + Some(decimal("0", 1, 0)), + ), + ( + ScalarValue::Decimal128(Some(5), 3, 3), + Some(decimal("0.005", 3, 3)), + ), + ( + ScalarValue::Decimal128(Some(10_i128.pow(38) - 1), 38, 0), + Some(decimal(&"9".repeat(38), 38, 0)), + ), + ( + ScalarValue::Decimal128(Some(1 - 10_i128.pow(38)), 38, 10), + Some(decimal( + &format!("-{}.{}", "9".repeat(28), "9".repeat(10)), + 38, + 10, + )), + ), + // More digits than the precision allows, which Arrow doesn't check. + (ScalarValue::Decimal128(Some(1000), 3, 0), None), + (ScalarValue::Decimal128(Some(10_i128.pow(38)), 38, 0), None), + // Iceberg has no negative scales. + (ScalarValue::Decimal128(Some(12), 10, -2), None), + (ScalarValue::Decimal128(None, 10, 2), None), + ]; + for (value, expected) in cases { + assert_eq!(super::scalar_value_to_datum(&value), expected, "{value:?}"); + } + } + + #[test] + fn test_predicate_conversion_with_decimal() { + use datafusion::common::ScalarValue; + use datafusion::prelude::{col, lit}; + + let price = || col("price"); + let value = |v| lit(ScalarValue::Decimal128(Some(v), 10, 2)); + let cases = [ + ( + price().gt(value(1234)), + Reference::new("price").greater_than(decimal("12.34", 10, 2)), + ), + ( + value(-1234).lt_eq(price()), + Reference::new("price") + .greater_than_or_equal_to(decimal("-12.34", 10, 2)), + ), + ( + price().in_list(vec![value(100), value(-5)], false), + Reference::new("price") + .is_in([decimal("1.00", 10, 2), decimal("-0.05", 10, 2)]), + ), + ( + price().in_list(vec![value(100)], true), + Reference::new("price").is_not_in([decimal("1.00", 10, 2)]), + ), + ]; + for (expr, expected) in cases { + assert_eq!( + convert_filters_to_predicate(std::slice::from_ref(&expr)), + Some(expected), + "{expr}" + ); + } + + // An IN list with a value Iceberg can't hold isn't pushed down at all: + // the other values alone would skip rows that match it. + let expr = price().in_list( + vec![value(100), lit(ScalarValue::Decimal128(Some(1000), 3, 0))], + false, + ); + assert_eq!(convert_filters_to_predicate(&[expr]), None); + } + #[test] fn test_scalar_value_to_datum_binary() { use datafusion::common::ScalarValue; diff --git a/crates/datafusion/tests/filter_pushdown.rs b/crates/datafusion/tests/filter_pushdown.rs index 783a1a26..5b9b8186 100644 --- a/crates/datafusion/tests/filter_pushdown.rs +++ b/crates/datafusion/tests/filter_pushdown.rs @@ -20,7 +20,9 @@ mod tests { use std::error::Error; use std::sync::Arc; - use datafusion::arrow::array::{Array, StringArray}; + use datafusion::arrow::array::{ + Array, ArrayRef, Decimal128Array, Int64Array, RecordBatch, StringArray, + }; use datafusion::error::Result; use datafusion::prelude::SessionContext; use iceberg::TableIdent; @@ -235,6 +237,78 @@ mod tests { Ok(()) } + #[tokio::test] + async fn decimal_filters_skip_files() -> Result<()> { + let schema = Schema::builder() + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Long)) + .into(), + NestedField::optional( + 2, + "price", + Type::Primitive(PrimitiveType::Decimal { + precision: 10, + scale: 2, + }), + ) + .into(), + ]) + .build() + .unwrap(); + let mut table = FixtureCatalog::try_new() + .await? + .table( + TableIdent::from_strs(["default", "prices"]).unwrap(), + schema, + ) + .create() + .await?; + let batch = |ids: Vec, prices: Vec>| -> Result { + let prices = Decimal128Array::from(prices).with_precision_and_scale(10, 2)?; + Ok(RecordBatch::try_from_iter([ + ("id", Arc::new(Int64Array::from(ids)) as ArrayRef), + ("price", Arc::new(prices) as ArrayRef), + ])?) + }; + let files = table + .append() + .file(batch(vec![1, 2], vec![Some(-1234), Some(-1)])?) + .file(batch(vec![3], vec![Some(120)])?) + .file(batch(vec![4, 5], vec![Some(1234), None])?) + .commit() + .await?; + let storage = ReadCountingStorageFactory::default(); + let (plan, rows) = IcebergTestHarness::builder() + .with_iceberg_table_factory( + IcebergTableProviderFactory::new_with_storage_factory(Arc::new( + storage.clone(), + )), + ) + .with_table(table) + .query("SELECT id FROM prices WHERE price > CAST('1.20' AS DECIMAL(10, 2))") + .await?; + + insta::assert_snapshot!(plan, @" + FilterExec: price@1 > 1.20, projection=[id@0] + CooperativeExec + DataSourceExec: format=iceberg, projection=[id, price], provider=lazy, predicate=price > 1.20 + "); + insta::assert_snapshot!(rows, @" + +----+ + | id | + +----+ + | 4 | + +----+ + "); + // Only the last file's bounds include a price above 1.20. + let opens = files + .iter() + .map(|file| storage.file_opens(file.file_path())) + .collect::>(); + assert_eq!(opens, [0, 0, 1]); + Ok(()) + } + #[tokio::test] async fn parquet_pruning_controls_row_group_reads() -> Result<()> { let storage = ReadCountingStorageFactory::default(); diff --git a/crates/sqllogictest/testdata/schedules/df_decimal_predicate_pushdown.toml b/crates/sqllogictest/testdata/schedules/df_decimal_predicate_pushdown.toml new file mode 100644 index 00000000..7fdf2a2a --- /dev/null +++ b/crates/sqllogictest/testdata/schedules/df_decimal_predicate_pushdown.toml @@ -0,0 +1,23 @@ +# 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. + +[engines] +df = { type = "datafusion" } + +[[steps]] +engine = "df" +slt = "df_test/decimal_predicate_pushdown.slt" diff --git a/crates/sqllogictest/testdata/slts/df_test/decimal_predicate_pushdown.slt b/crates/sqllogictest/testdata/slts/df_test/decimal_predicate_pushdown.slt new file mode 100644 index 00000000..c3c4899f --- /dev/null +++ b/crates/sqllogictest/testdata/slts/df_test/decimal_predicate_pushdown.slt @@ -0,0 +1,204 @@ +# 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. + +# Filters comparing a decimal column with a decimal literal are pushed down to +# Iceberg, which skips files whose bounds rule the value out. A literal that +# DataFusion can't convert exactly to the column's type leaves a cast on the +# column, and that filter isn't pushed down. + +statement ok +CREATE TABLE default.default.test_decimal_table (id INT NOT NULL, price DECIMAL(10, 2), big DECIMAL(38, 10)) + +# One data file per INSERT, so a file skipped by mistake loses its rows. The +# last two files hold the largest and smallest values each type allows. +query I +INSERT INTO default.default.test_decimal_table VALUES (1, -12.34, -1), (2, -0.01, 0) +---- +2 + +query I +INSERT INTO default.default.test_decimal_table VALUES (3, 0.00, 0.5), (4, 1.20, 1.2) +---- +2 + +query I +INSERT INTO default.default.test_decimal_table VALUES (5, 12.34, 12.34), (6, NULL, NULL) +---- +2 + +query I +INSERT INTO default.default.test_decimal_table VALUES (7, 99999999.99, CAST('9999999999999999999999999999.9999999999' AS DECIMAL(38, 10))) +---- +1 + +query I +INSERT INTO default.default.test_decimal_table VALUES (8, -99999999.99, CAST('-9999999999999999999999999999.9999999999' AS DECIMAL(38, 10))) +---- +1 + +# A decimal literal of the column's type +query TT +EXPLAIN SELECT id FROM default.default.test_decimal_table WHERE price > CAST('1.20' AS DECIMAL(10, 2)) +---- +logical_plan +01)Projection: default.default.test_decimal_table.id +02)--Filter: default.default.test_decimal_table.price > Decimal128(1.20,10,2) +03)----TableScan: default.default.test_decimal_table projection=[id, price], partial_filters=[default.default.test_decimal_table.price > Decimal128(1.20,10,2)] +physical_plan +01)FilterExec: price@1 > 1.20, projection=[id@0] +02)--CooperativeExec +03)----DataSourceExec: format=iceberg, projection=[id, price], provider=lazy, predicate=price > 1.20 + +# DataFusion converts a float literal to the column's type when that doesn't +# change the result. If apache/datafusion#14272 makes DataFusion compare floats +# with decimals as floats, the column is cast to Float64 instead, and this +# stops being pushed down. +query TT +EXPLAIN SELECT id FROM default.default.test_decimal_table WHERE price > 1.2 +---- +logical_plan +01)Projection: default.default.test_decimal_table.id +02)--Filter: default.default.test_decimal_table.price > Decimal128(1.20,10,2) +03)----TableScan: default.default.test_decimal_table projection=[id, price], partial_filters=[default.default.test_decimal_table.price > Decimal128(1.20,10,2)] +physical_plan +01)FilterExec: price@1 > 1.20, projection=[id@0] +02)--CooperativeExec +03)----DataSourceExec: format=iceberg, projection=[id, price], provider=lazy, predicate=price > 1.20 + +# DataFusion turns an IN list of up to three values into ORs, so this one +# has four. Its values are typed: DataFusion casts a float literal to +# Decimal128(30, 15) inexactly once it has seven or more digits before the +# point, so 99999999.99 wouldn't match (apache/datafusion#28053). +query TT +EXPLAIN SELECT id FROM default.default.test_decimal_table WHERE price NOT IN (CAST('1.20' AS DECIMAL(10, 2)), CAST('-0.01' AS DECIMAL(10, 2)), CAST('12.34' AS DECIMAL(10, 2)), CAST('99999999.99' AS DECIMAL(10, 2))) +---- +logical_plan +01)Projection: default.default.test_decimal_table.id +02)--Filter: default.default.test_decimal_table.price NOT IN ([Decimal128(1.20,10,2), Decimal128(-0.01,10,2), Decimal128(12.34,10,2), Decimal128(99999999.99,10,2)]) +03)----TableScan: default.default.test_decimal_table projection=[id, price], partial_filters=[default.default.test_decimal_table.price NOT IN ([Decimal128(1.20,10,2), Decimal128(-0.01,10,2), Decimal128(12.34,10,2), Decimal128(99999999.99,10,2)])] +physical_plan +01)FilterExec: price@1 NOT IN (SET) ([1.20, -0.01, 12.34, 99999999.99]), projection=[id@0] +02)--CooperativeExec +03)----DataSourceExec: format=iceberg, projection=[id, price], provider=lazy, predicate=price NOT IN (-0.01, 12.34, 99999999.99, 1.20) + +# A literal with more digits after the point than the column holds +query TT +EXPLAIN SELECT id FROM default.default.test_decimal_table WHERE price > CAST('1.205' AS DECIMAL(10, 3)) +---- +logical_plan +01)Projection: default.default.test_decimal_table.id +02)--Filter: CAST(default.default.test_decimal_table.price AS Decimal128(11, 3)) > Decimal128(1.205,11,3) +03)----TableScan: default.default.test_decimal_table projection=[id, price], partial_filters=[CAST(default.default.test_decimal_table.price AS Decimal128(11, 3)) > Decimal128(1.205,11,3)] +physical_plan +01)FilterExec: CAST(price@1 AS Decimal128(11, 3)) > 1.205, projection=[id@0] +02)--CooperativeExec +03)----DataSourceExec: format=iceberg, projection=[id, price], provider=lazy + +# A literal larger than the column's type allows +query TT +EXPLAIN SELECT id FROM default.default.test_decimal_table WHERE price < CAST('100000000.00' AS DECIMAL(11, 2)) +---- +logical_plan +01)Projection: default.default.test_decimal_table.id +02)--Filter: CAST(default.default.test_decimal_table.price AS Decimal128(11, 2)) < Decimal128(100000000.00,11,2) +03)----TableScan: default.default.test_decimal_table projection=[id, price], partial_filters=[CAST(default.default.test_decimal_table.price AS Decimal128(11, 2)) < Decimal128(100000000.00,11,2)] +physical_plan +01)FilterExec: CAST(price@1 AS Decimal128(11, 2)) < 100000000.00, projection=[id@0] +02)--CooperativeExec +03)----DataSourceExec: format=iceberg, projection=[id, price], provider=lazy + +# Comparisons + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price = 1.20 +---- +4 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price != 1.20 +---- +1, 2, 3, 5, 7, 8 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price < 1.20 +---- +1, 2, 3, 8 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price <= 1.20 +---- +1, 2, 3, 4, 8 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price > 1.20 +---- +5, 7 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price >= 1.20 +---- +4, 5, 7 + +# Zero and negative values + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price = 0 +---- +3 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price < 0 +---- +1, 2, 8 + +# IN lists + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price IN (CAST('1.20' AS DECIMAL(10, 2)), CAST('-0.01' AS DECIMAL(10, 2)), CAST('12.34' AS DECIMAL(10, 2)), CAST('99999999.99' AS DECIMAL(10, 2))) +---- +2, 4, 5, 7 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price NOT IN (CAST('1.20' AS DECIMAL(10, 2)), CAST('-0.01' AS DECIMAL(10, 2)), CAST('12.34' AS DECIMAL(10, 2)), CAST('99999999.99' AS DECIMAL(10, 2))) +---- +1, 3, 8 + +# The largest and smallest values of each type. The literals are typed, as in +# the IN lists above, so that they are pushed down. + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price >= CAST('99999999.99' AS DECIMAL(10, 2)) +---- +7 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE price <= CAST('-99999999.99' AS DECIMAL(10, 2)) +---- +8 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE big >= CAST('9999999999999999999999999999.9999999999' AS DECIMAL(38, 10)) +---- +7 + +query T +SELECT string_agg(CAST(id AS VARCHAR), ', ' ORDER BY id) FROM default.default.test_decimal_table WHERE big <= CAST('-9999999999999999999999999999.9999999999' AS DECIMAL(38, 10)) +---- +8 + +statement ok +DROP TABLE default.default.test_decimal_table