gengliangwang commented on code in PR #60314:
URL: https://github.com/apache/spark/pull/60314#discussion_r4621545060


##########
sql/native/rust/src/domain.rs:
##########
@@ -0,0 +1,675 @@
+// 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.
+
+//! The domains of the columns that the filters of a query constrain, which a 
scan gets in
+//! [`ScanBuilder::push_domains`](crate::ScanBuilder::push_domains).
+
+use std::ops::Bound;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::{
+    Date32Type, Decimal128Type, Float32Type, Float64Type, Int16Type, 
Int32Type, Int64Type,
+    Int8Type, TimestampMicrosecondType,
+};
+use arrow_array::{Array, ArrayRef, BooleanArray, StructArray};
+use arrow_schema::{DataType, Fields, TimeUnit};
+use serde::{Deserialize, Serialize};
+
+use crate::{abi, Result};
+
+/// The domain of a column: the values that the column can have in the rows 
that match the
+/// filters of a query. A value is in the domain when it is:
+///
+/// - null, if [`null_allowed`](Self::null_allowed);
+/// - NaN, if [`nan_allowed`](Self::nan_allowed), for a `float` or `double` 
column;
+/// - another value, if [`ranges`](Self::ranges) is `None`, or if it is in one 
of the ranges.
+///
+/// A scan can skip the data that has no value in the domain of a column, such 
as a file or a
+/// row group whose statistics show that its values are all below the ranges, 
or a row whose
+/// value is outside them. It must never skip a row whose values are all in 
their domains, since
+/// Spark cannot detect it. Spark evaluates the filters again after reading, 
so the rows that a
+/// scan returns need not match them.
+///
+/// Values compare in the order of Spark SQL:
+///
+/// - numbers, dates and timestamps by their values. The bounds of the ranges 
of a `float` or
+///   `double` column are never NaN, and -0.0 is equal to 0.0: compare them 
with `<` and `==`,
+///   not with a total order, such as [`f64::total_cmp`], that puts -0.0 
before 0.0. Data that
+///   has NaN values, or may have, can only be skipped if `nan_allowed` is 
false;
+/// - strings by their UTF-8 bytes, as Rust compares `str`;
+/// - binary values as unsigned bytes, in lexicographic order, as Rust 
compares `[u8]`;
+/// - booleans with false before true.
+///
+/// A domain is serializable, so that the factory of a scan can carry it to 
the executors.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct Domain {
+    /// The column, by its name in 
[`ScanInfo::schema`](crate::ScanInfo::schema), and then by the
+    /// name of its field in each struct: `["point", "x"]` is the field `x` of 
the column
+    /// `point`.
+    pub path: Vec<String>,
+    /// Whether null is in the domain. A field of a struct is null in the rows 
where the struct,
+    /// or a struct that contains it, is null, whatever the child array of the 
field holds there:
+    /// Spark never allows null for a field of a struct, since statistics 
computed from that
+    /// child array may not count these rows as nulls.
+    pub null_allowed: bool,
+    /// Whether NaN is in the domain. Always false for the columns of other 
types than `float`
+    /// and `double`.
+    pub nan_allowed: bool,
+    /// The ranges of the other values in the domain, sorted, and without 
overlaps, or `None` if
+    /// they are all in it. With an empty list, no value other than null or 
NaN is in the domain.
+    pub ranges: Option<Vec<ValueRange>>,
+}
+
+impl Domain {
+    /// A domain without null or NaN, created outside Spark, for example in a 
test. Set
+    /// [`null_allowed`](Self::null_allowed) and 
[`nan_allowed`](Self::nan_allowed) for others.
+    pub fn new(path: Vec<String>, ranges: Option<Vec<ValueRange>>) -> Self {
+        Self {
+            path,
+            null_allowed: false,
+            nan_allowed: false,
+            ranges,
+        }
+    }
+
+    /// The domain that Spark passes for the column at the path of `pushed`, 
by the indices of the
+    /// column in `fields`, the schema that `create_reader` got, and then of 
its field in each
+    /// struct, or `None` if the SDK has no [`Value`] for the type of the 
column, which a later
+    /// version of Spark may pass.
+    pub(crate) fn from_abi(fields: &Fields, pushed: &abi::PushedDomain) -> 
Result<Option<Self>> {
+        let path = &pushed.path;
+        let invalid = || format!("the path {path:?} of a domain is not a 
column of the scan");
+        let (&last, parents) = path.split_last().ok_or_else(invalid)?;
+        let mut names = Vec::with_capacity(path.len());
+        let mut fields = fields;
+        for &index in parents {
+            let field = fields.get(index).ok_or_else(invalid)?;
+            let DataType::Struct(children) = field.data_type() else {
+                return Err(invalid().into());
+            };
+            names.push(field.name().clone());
+            fields = children;
+        }
+        let field = fields.get(last).ok_or_else(invalid)?;
+        if !has_value(field.data_type()) {
+            return Ok(None);
+        }
+        names.push(field.name().clone());
+        let ranges = pushed
+            .ranges
+            .as_ref()
+            .map(|ranges| value_ranges(ranges, field.data_type()))
+            .transpose()?;
+        Ok(Some(Self {
+            path: names,
+            null_allowed: pushed.null_allowed,
+            nan_allowed: pushed.nan_allowed,
+            ranges,
+        }))
+    }
+}
+
+/// A range of the values of a [`Domain`]. A single value is a range whose 
bounds are equal and
+/// included.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ValueRange {
+    /// The lower bound, or [`Bound::Unbounded`] if the range has none.
+    pub low: Bound<Value>,
+    /// The upper bound, or [`Bound::Unbounded`] if the range has none.
+    pub high: Bound<Value>,
+}
+
+impl ValueRange {
+    /// The range of a single value.
+    pub fn single(value: Value) -> Self {
+        Self {
+            low: Bound::Included(value.clone()),
+            high: Bound::Included(value),
+        }
+    }
+}
+
+/// A value of a column, in the bounds of the ranges of a [`Domain`]. It has 
the type of its
+/// column in [`ScanInfo::schema`](crate::ScanInfo::schema). New variants may 
be added for the
+/// types that a later version of Spark passes domains for: a connector 
ignores the domains of
+/// values that it does not handle.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum Value {
+    Boolean(bool),
+    /// A `tinyint`, `smallint`, `int`, or `bigint`.
+    Integer(i64),
+    /// A `float` or `double`, which is never NaN: a `float` is the exact 
value of the float.
+    Float(f64),
+    /// A `decimal(precision, scale)` of the precision and scale of its 
column, whose value is
+    /// `unscaled * 10^-scale`.
+    Decimal {
+        #[serde(with = "decimal_string")]
+        unscaled: i128,
+        precision: u8,
+        scale: i8,
+    },
+    String(String),
+    Binary(Vec<u8>),
+    /// A `date`, as days since 1970-01-01.
+    Date(i32),
+    /// A `timestamp`, as microseconds since the epoch.
+    Timestamp(i64),
+    /// A `timestamp_ntz`, as microseconds since 1970-01-01 00:00:00, without 
a time zone.
+    TimestampNtz(i64),
+}
+
+/// Encodes the unscaled value of a decimal as its decimal string. serde 
buffers the values of
+/// `flatten` fields and of `untagged` and internally tagged enums before 
decoding them, and its
+/// buffer has no 128-bit integers, so it could not decode an `i128` in a 
factory that uses them.
+mod decimal_string {
+    use serde::de::Error;
+    use serde::{Deserialize, Deserializer, Serializer};
+
+    pub fn serialize<S: Serializer>(unscaled: &i128, serializer: S) -> 
Result<S::Ok, S::Error> {
+        serializer.collect_str(unscaled)
+    }
+
+    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> 
Result<i128, D::Error> {
+        String::deserialize(deserializer)?
+            .parse()
+            .map_err(D::Error::custom)
+    }
+}
+
+/// Whether the SDK has a [`Value`] for the values of a column of `data_type`.
+fn has_value(data_type: &DataType) -> bool {
+    ranges_from_values(data_type, None).is_some()
+}
+
+/// The ranges of a domain of a column of `data_type`, a type that has a 
[`Value`], from the
+/// struct array that Spark passes, with the fields `low` and `high`, of the 
type of the column,
+/// and `low_inclusive` and `high_inclusive`.
+fn value_ranges(ranges: &StructArray, data_type: &DataType) -> 
Result<Vec<ValueRange>> {
+    let wrong_type = |name: &str, actual: &DataType| {
+        format!(
+            "the field {name} of the ranges of a domain has the type {actual}, 
not the type \
+             {data_type} of its column"
+        )
+    };
+    let supported = has_value(data_type);
+    let bounds = |name: &str| -> Result<&ArrayRef> {
+        let array = field(ranges, name)?;
+        if supported && array.data_type() == data_type {
+            Ok(array)
+        } else {
+            Err(wrong_type(name, array.data_type()).into())
+        }
+    };
+    let columns = RangeColumns {
+        low: bounds("low")?,
+        high: bounds("high")?,
+        low_inclusive: flags(ranges, "low_inclusive")?,
+        high_inclusive: flags(ranges, "high_inclusive")?,
+    };
+    ranges_from_values(data_type, Some(&columns))
+        .ok_or_else(|| wrong_type("low", columns.low.data_type()).into())
+}
+
+/// Validated columns of the ranges, whose typed bounds are collected directly 
into the result.
+struct RangeColumns<'a> {
+    low: &'a ArrayRef,
+    high: &'a ArrayRef,
+    low_inclusive: &'a BooleanArray,
+    high_inclusive: &'a BooleanArray,
+}
+
+impl RangeColumns<'_> {
+    fn collect<T>(
+        &self,
+        lows: impl IntoIterator<Item = Option<T>>,
+        highs: impl IntoIterator<Item = Option<T>>,
+        value: impl Fn(T) -> Value,
+    ) -> Vec<ValueRange> {
+        let bound = |endpoint: Option<T>, inclusive: bool| match 
endpoint.map(&value) {
+            None => Bound::Unbounded,
+            Some(value) if inclusive => Bound::Included(value),
+            Some(value) => Bound::Excluded(value),
+        };
+        lows.into_iter()
+            .zip(highs)
+            .enumerate()
+            .map(|(row, (low, high))| ValueRange {
+                low: bound(low, self.low_inclusive.value(row)),
+                high: bound(high, self.high_inclusive.value(row)),
+            })
+            .collect()
+    }
+}
+
+fn field<'a>(ranges: &'a StructArray, name: &str) -> Result<&'a ArrayRef> {
+    ranges
+        .column_by_name(name)
+        .ok_or_else(|| format!("the ranges of a domain have no field 
{name}").into())
+}
+
+fn flags<'a>(ranges: &'a StructArray, name: &str) -> Result<&'a BooleanArray> {
+    field(ranges, name)?
+        .as_boolean_opt()
+        .ok_or_else(|| format!("the field {name} of the ranges of a domain is 
not boolean").into())
+}
+
+/// Converts the ranges of a supported type, or probes support without 
allocating arrays when
+/// `columns` is `None`. The same dispatch determines support and downcasts 
both bound arrays,
+/// once per domain, before iterating their values.
+fn ranges_from_values(

Review Comment:
   Done in 4ba076fabc70: Restored the `values()` conversion, `value_ranges` and 
`has_value` exactly as in e9974ad03ae (macro, `RangeColumns` and the probe mode 
are gone); kept the added per-type tests, which don't depend on the shape.



##########
sql/native/rust/src/domain.rs:
##########
@@ -0,0 +1,675 @@
+// 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.
+
+//! The domains of the columns that the filters of a query constrain, which a 
scan gets in
+//! [`ScanBuilder::push_domains`](crate::ScanBuilder::push_domains).
+
+use std::ops::Bound;
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::{
+    Date32Type, Decimal128Type, Float32Type, Float64Type, Int16Type, 
Int32Type, Int64Type,
+    Int8Type, TimestampMicrosecondType,
+};
+use arrow_array::{Array, ArrayRef, BooleanArray, StructArray};
+use arrow_schema::{DataType, Fields, TimeUnit};
+use serde::{Deserialize, Serialize};
+
+use crate::{abi, Result};
+
+/// The domain of a column: the values that the column can have in the rows 
that match the
+/// filters of a query. A value is in the domain when it is:
+///
+/// - null, if [`null_allowed`](Self::null_allowed);
+/// - NaN, if [`nan_allowed`](Self::nan_allowed), for a `float` or `double` 
column;
+/// - another value, if [`ranges`](Self::ranges) is `None`, or if it is in one 
of the ranges.
+///
+/// A scan can skip the data that has no value in the domain of a column, such 
as a file or a
+/// row group whose statistics show that its values are all below the ranges, 
or a row whose
+/// value is outside them. It must never skip a row whose values are all in 
their domains, since
+/// Spark cannot detect it. Spark evaluates the filters again after reading, 
so the rows that a
+/// scan returns need not match them.
+///
+/// Values compare in the order of Spark SQL:
+///
+/// - numbers, dates and timestamps by their values. The bounds of the ranges 
of a `float` or
+///   `double` column are never NaN, and -0.0 is equal to 0.0: compare them 
with `<` and `==`,
+///   not with a total order, such as [`f64::total_cmp`], that puts -0.0 
before 0.0. Data that
+///   has NaN values, or may have, can only be skipped if `nan_allowed` is 
false;
+/// - strings by their UTF-8 bytes, as Rust compares `str`;
+/// - binary values as unsigned bytes, in lexicographic order, as Rust 
compares `[u8]`;
+/// - booleans with false before true.
+///
+/// A domain is serializable, so that the factory of a scan can carry it to 
the executors.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub struct Domain {
+    /// The column, by its name in 
[`ScanInfo::schema`](crate::ScanInfo::schema), and then by the
+    /// name of its field in each struct: `["point", "x"]` is the field `x` of 
the column
+    /// `point`.
+    pub path: Vec<String>,
+    /// Whether null is in the domain. A field of a struct is null in the rows 
where the struct,
+    /// or a struct that contains it, is null, whatever the child array of the 
field holds there:
+    /// Spark never allows null for a field of a struct, since statistics 
computed from that
+    /// child array may not count these rows as nulls.
+    pub null_allowed: bool,
+    /// Whether NaN is in the domain. Always false for the columns of other 
types than `float`
+    /// and `double`.
+    pub nan_allowed: bool,
+    /// The ranges of the other values in the domain, sorted, and without 
overlaps, or `None` if
+    /// they are all in it. With an empty list, no value other than null or 
NaN is in the domain.
+    pub ranges: Option<Vec<ValueRange>>,
+}
+
+impl Domain {
+    /// A domain without null or NaN, created outside Spark, for example in a 
test. Set
+    /// [`null_allowed`](Self::null_allowed) and 
[`nan_allowed`](Self::nan_allowed) for others.
+    pub fn new(path: Vec<String>, ranges: Option<Vec<ValueRange>>) -> Self {
+        Self {
+            path,
+            null_allowed: false,
+            nan_allowed: false,
+            ranges,
+        }
+    }
+
+    /// The domain that Spark passes for the column at the path of `pushed`, 
by the indices of the
+    /// column in `fields`, the schema that `create_reader` got, and then of 
its field in each
+    /// struct, or `None` if the SDK has no [`Value`] for the type of the 
column, which a later
+    /// version of Spark may pass.
+    pub(crate) fn from_abi(fields: &Fields, pushed: &abi::PushedDomain) -> 
Result<Option<Self>> {
+        let path = &pushed.path;
+        let invalid = || format!("the path {path:?} of a domain is not a 
column of the scan");
+        let (&last, parents) = path.split_last().ok_or_else(invalid)?;
+        let mut names = Vec::with_capacity(path.len());
+        let mut fields = fields;
+        for &index in parents {
+            let field = fields.get(index).ok_or_else(invalid)?;
+            let DataType::Struct(children) = field.data_type() else {
+                return Err(invalid().into());
+            };
+            names.push(field.name().clone());
+            fields = children;
+        }
+        let field = fields.get(last).ok_or_else(invalid)?;
+        if !has_value(field.data_type()) {
+            return Ok(None);
+        }
+        names.push(field.name().clone());
+        let ranges = pushed
+            .ranges
+            .as_ref()
+            .map(|ranges| value_ranges(ranges, field.data_type()))
+            .transpose()?;
+        Ok(Some(Self {
+            path: names,
+            null_allowed: pushed.null_allowed,
+            nan_allowed: pushed.nan_allowed,
+            ranges,
+        }))
+    }
+}
+
+/// A range of the values of a [`Domain`]. A single value is a range whose 
bounds are equal and
+/// included.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct ValueRange {
+    /// The lower bound, or [`Bound::Unbounded`] if the range has none.
+    pub low: Bound<Value>,
+    /// The upper bound, or [`Bound::Unbounded`] if the range has none.
+    pub high: Bound<Value>,
+}
+
+impl ValueRange {
+    /// The range of a single value.
+    pub fn single(value: Value) -> Self {
+        Self {
+            low: Bound::Included(value.clone()),
+            high: Bound::Included(value),
+        }
+    }
+}
+
+/// A value of a column, in the bounds of the ranges of a [`Domain`]. It has 
the type of its
+/// column in [`ScanInfo::schema`](crate::ScanInfo::schema). New variants may 
be added for the
+/// types that a later version of Spark passes domains for: a connector 
ignores the domains of
+/// values that it does not handle.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[non_exhaustive]
+pub enum Value {
+    Boolean(bool),
+    /// A `tinyint`, `smallint`, `int`, or `bigint`.
+    Integer(i64),
+    /// A `float` or `double`, which is never NaN: a `float` is the exact 
value of the float.
+    Float(f64),
+    /// A `decimal(precision, scale)` of the precision and scale of its 
column, whose value is
+    /// `unscaled * 10^-scale`.
+    Decimal {
+        #[serde(with = "decimal_string")]
+        unscaled: i128,
+        precision: u8,
+        scale: i8,
+    },
+    String(String),
+    Binary(Vec<u8>),
+    /// A `date`, as days since 1970-01-01.
+    Date(i32),
+    /// A `timestamp`, as microseconds since the epoch.
+    Timestamp(i64),
+    /// A `timestamp_ntz`, as microseconds since 1970-01-01 00:00:00, without 
a time zone.
+    TimestampNtz(i64),
+}
+
+/// Encodes the unscaled value of a decimal as its decimal string. serde 
buffers the values of
+/// `flatten` fields and of `untagged` and internally tagged enums before 
decoding them, and its
+/// buffer has no 128-bit integers, so it could not decode an `i128` in a 
factory that uses them.
+mod decimal_string {
+    use serde::de::Error;
+    use serde::{Deserialize, Deserializer, Serializer};
+
+    pub fn serialize<S: Serializer>(unscaled: &i128, serializer: S) -> 
Result<S::Ok, S::Error> {
+        serializer.collect_str(unscaled)
+    }
+
+    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> 
Result<i128, D::Error> {
+        String::deserialize(deserializer)?
+            .parse()
+            .map_err(D::Error::custom)
+    }
+}
+
+/// Whether the SDK has a [`Value`] for the values of a column of `data_type`.
+fn has_value(data_type: &DataType) -> bool {
+    ranges_from_values(data_type, None).is_some()
+}
+
+/// The ranges of a domain of a column of `data_type`, a type that has a 
[`Value`], from the
+/// struct array that Spark passes, with the fields `low` and `high`, of the 
type of the column,
+/// and `low_inclusive` and `high_inclusive`.
+fn value_ranges(ranges: &StructArray, data_type: &DataType) -> 
Result<Vec<ValueRange>> {
+    let wrong_type = |name: &str, actual: &DataType| {
+        format!(
+            "the field {name} of the ranges of a domain has the type {actual}, 
not the type \
+             {data_type} of its column"
+        )
+    };
+    let supported = has_value(data_type);

Review Comment:
   Done in 4ba076fabc70: Gone with the revert to the e9974ad03ae conversion: 
`value_ranges` no longer re-checks `has_value`, and the separate `ok_or_else` 
fallback is removed.



-- 
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