Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 129 additions & 4 deletions crates/datafusion/src/read/predicate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -362,12 +362,34 @@ fn scalar_value_to_datum(value: &ScalarValue) -> Option<Datum> {
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<Datum> {
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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
76 changes: 75 additions & 1 deletion crates/datafusion/tests/filter_pushdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<i64>, prices: Vec<Option<i128>>| -> Result<RecordBatch> {
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::<Vec<_>>();
assert_eq!(opens, [0, 0, 1]);
Ok(())
}

#[tokio::test]
async fn parquet_pruning_controls_row_group_reads() -> Result<()> {
let storage = ReadCountingStorageFactory::default();
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
Loading