Skip to main content

common_function/scalars/
iceberg_hash.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! SQL forms of the hash used by `iceberg_hash` partition rules.
16//!
17//! `iceberg_hash(col)` is the same function partition rules evaluate, exposed so
18//! that users can measure a distribution or verify which bucket a value falls
19//! into. It must never diverge from the rule form: both are built from
20//! [`partition::function::iceberg_hash_udf`].
21//!
22//! `iceberg_hash_bounds(n)` prints the breakpoints of an equal-width n-bucket
23//! split, ready to paste into `PARTITION ON COLUMNS`. It only formats the
24//! numbers; it does not create or change partitions.
25//!
26//! `iceberg_hash_breakpoints(v1, v2, ...)` hashes the given constant values
27//! (any order, all from one hash encoding: strings, or integers) and prints them
28//! sorted, for building buckets around known key values instead of around equal
29//! widths.
30//!
31//! `iceberg_hash_ranges_sql(column, n)` renders the whole rule list for
32//! `PARTITION ON COLUMNS` from an equal-width split, so it can be pasted
33//! without expanding the breakpoints by hand. The column name is quoted, so
34//! names that are not plain lowercase identifiers round-trip.
35
36use std::fmt;
37
38use datafusion::arrow::array::ArrayRef;
39use datafusion::arrow::datatypes::DataType;
40use datafusion_common::{DataFusionError, ScalarValue};
41use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature, Volatility};
42use partition::function::{IcebergHash, iceberg_hash_udf};
43
44use crate::function::Function;
45use crate::function_registry::FunctionRegistry;
46
47/// `iceberg_hash_bounds` hard limit. Each region carries its own WAL, memtable,
48/// manifest and compaction stream, so four-digit bucket counts are already far
49/// beyond any practical table.
50const MAX_BUCKETS: i64 = 1024;
51
52/// `iceberg_hash(col)`: registers the UDF partition rules already plan.
53///
54/// The raw [`iceberg_hash_udf`] is registered instead of a `Function` wrapper:
55/// a wrapper is a different `ScalarUDFImpl` type, and DataFusion compares
56/// expressions by concrete type, so `iceberg_hash(host)` from SQL would not
57/// compare equal to the expression `Operand::IcebergHash::to_logical_expr`
58/// builds. One impl type also keeps a batch from constructing a fresh
59/// `ScalarUDF`.
60pub(crate) struct IcebergHashFunction;
61
62impl IcebergHashFunction {
63    pub fn register(registry: &FunctionRegistry) {
64        registry.register(iceberg_hash_udf());
65    }
66}
67
68/// `iceberg_hash_bounds(n)`: the `n - 1` equal-width breakpoints of the hash
69/// space, as comma separated `INT32` literals.
70#[derive(Debug)]
71pub(crate) struct IcebergHashBoundsFunction {
72    signature: Signature,
73}
74
75impl Default for IcebergHashBoundsFunction {
76    fn default() -> Self {
77        Self {
78            signature: Signature::any(1, Volatility::Immutable),
79        }
80    }
81}
82
83impl IcebergHashBoundsFunction {
84    pub fn register(registry: &FunctionRegistry) {
85        registry.register_scalar(Self::default());
86    }
87
88    /// Returns the bucket count a constant scalar names, or an error naming
89    /// the rejected input and the calling function.
90    fn bucket_count(name: &str, scalar: &ScalarValue) -> datafusion_common::Result<i64> {
91        let count = match scalar {
92            ScalarValue::Int64(Some(v)) => *v,
93            ScalarValue::Int32(Some(v)) => i64::from(*v),
94            ScalarValue::Int16(Some(v)) => i64::from(*v),
95            ScalarValue::Int8(Some(v)) => i64::from(*v),
96            ScalarValue::UInt64(Some(v)) => i64::try_from(*v).map_err(|_| {
97                DataFusionError::Execution(format!("{name} bucket count is too large: {v}"))
98            })?,
99            ScalarValue::UInt32(Some(v)) => i64::from(*v),
100            ScalarValue::UInt16(Some(v)) => i64::from(*v),
101            ScalarValue::UInt8(Some(v)) => i64::from(*v),
102            other => {
103                return Err(DataFusionError::Execution(format!(
104                    "{name} expects an integer bucket count, got {other:?}"
105                )));
106            }
107        };
108        Ok(count)
109    }
110
111    /// Returns the `n - 1` equal-width breakpoints a constant bucket count
112    /// names, or an error when the count is not a constant integer in
113    /// `[2, MAX_BUCKETS]`. Shared with [`IcebergHashRangesSqlFunction`], which
114    /// passes its own name so errors name the function the user called.
115    fn breakpoints_of(name: &str, scalar: &ScalarValue) -> datafusion_common::Result<Vec<i32>> {
116        equal_split_breakpoints(name, Self::bucket_count(name, scalar)?)
117    }
118}
119
120impl Function for IcebergHashBoundsFunction {
121    fn name(&self) -> &str {
122        "iceberg_hash_bounds"
123    }
124
125    fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result<DataType> {
126        Ok(DataType::Utf8)
127    }
128
129    fn signature(&self) -> &Signature {
130        &self.signature
131    }
132
133    fn invoke_with_args(
134        &self,
135        args: ScalarFunctionArgs,
136    ) -> datafusion_common::Result<ColumnarValue> {
137        let [arg] = args.args.as_slice() else {
138            return Err(DataFusionError::Execution(format!(
139                "{} expects one argument, got {}",
140                self.name(),
141                args.args.len()
142            )));
143        };
144        let value = match arg {
145            ColumnarValue::Scalar(scalar) => scalar,
146            ColumnarValue::Array(_) => {
147                return Err(DataFusionError::Execution(format!(
148                    "{} expects a constant bucket count, not a column",
149                    self.name()
150                )));
151            }
152        };
153        if value.is_null() {
154            return Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)));
155        }
156        Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
157            Self::breakpoints_of(self.name(), value)?
158                .iter()
159                .map(i32::to_string)
160                .collect::<Vec<_>>()
161                .join(", "),
162        ))))
163    }
164}
165
166impl fmt::Display for IcebergHashBoundsFunction {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.write_str("ICEBERG_HASH_BOUNDS")
169    }
170}
171
172/// `iceberg_hash_breakpoints(v1, v2, ...)`: the sorted, comma separated hash
173/// values of the given constant values, as `INT32` literals.
174///
175/// The values do not need to be sorted; the output is. Every value must be a
176/// constant from one hash encoding, exactly like the values a partition rule
177/// compares the hashed column against: all strings, or all integers. Mixing a
178/// string with an integer is rejected because the two hash differently, so the
179/// result would not describe the target column.
180///
181/// NULL values hash to NULL and can never match a comparison bound, so they are
182/// rejected rather than silently dropped; an empty argument list is rejected
183/// too.
184#[derive(Debug)]
185pub(crate) struct IcebergHashBreakpointsFunction {
186    signature: Signature,
187}
188
189impl Default for IcebergHashBreakpointsFunction {
190    fn default() -> Self {
191        Self {
192            signature: Signature::variadic_any(Volatility::Immutable),
193        }
194    }
195}
196
197impl IcebergHashBreakpointsFunction {
198    pub fn register(registry: &FunctionRegistry) {
199        registry.register_scalar(Self::default());
200    }
201
202    /// Hashes the scalar arguments into sorted breakpoints, or an error when
203    /// the arguments cannot form a usable breakpoint list.
204    fn breakpoints(&self, args: &ScalarFunctionArgs) -> datafusion_common::Result<String> {
205        if args.args.is_empty() {
206            return Err(DataFusionError::Execution(format!(
207                "{} expects at least one value, got none",
208                self.name()
209            )));
210        }
211        let mut domain: Option<HashDomain> = None;
212        let mut scalars: Vec<i32> = Vec::with_capacity(args.args.len());
213        for (position, arg) in args.args.iter().enumerate() {
214            let scalar = match arg {
215                ColumnarValue::Scalar(scalar) => scalar,
216                ColumnarValue::Array(_) => {
217                    return Err(DataFusionError::Execution(format!(
218                        "{} expects constant values, not a column (argument {})",
219                        self.name(),
220                        position + 1
221                    )));
222                }
223            };
224            let hashed = if scalar.is_null() {
225                // A NULL hash can never match a comparison bound, so a NULL
226                // value cannot be a breakpoint. Reject it instead of silently
227                // dropping it: the user asked for that value's breakpoint.
228                return Err(DataFusionError::Execution(format!(
229                    "{} cannot use NULL as a breakpoint (argument {}): NULL rows fall in the lowest bucket",
230                    self.name(),
231                    position + 1
232                )));
233            } else {
234                let value_domain = HashDomain::of(scalar).ok_or_else(|| {
235                    DataFusionError::Execution(format!(
236                        "{} expects string or integer values, argument {} is {scalar:?}",
237                        self.name(),
238                        position + 1
239                    ))
240                })?;
241                match domain {
242                    Some(expected) if expected != value_domain => {
243                        return Err(DataFusionError::Execution(format!(
244                            "{} expects values with one hash encoding, argument {} is {} but earlier values are {}",
245                            self.name(),
246                            position + 1,
247                            value_domain,
248                            expected
249                        )));
250                    }
251                    Some(_) => {}
252                    None => domain = Some(value_domain),
253                }
254                into_hashed_scalar(self.name(), position + 1, scalar)?
255            };
256            scalars.push(hashed);
257        }
258        scalars.sort_unstable();
259        scalars.dedup();
260        Ok(scalars
261            .iter()
262            .map(i32::to_string)
263            .collect::<Vec<_>>()
264            .join(", "))
265    }
266}
267
268impl Function for IcebergHashBreakpointsFunction {
269    fn name(&self) -> &str {
270        "iceberg_hash_breakpoints"
271    }
272
273    fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result<DataType> {
274        Ok(DataType::Utf8)
275    }
276
277    fn signature(&self) -> &Signature {
278        &self.signature
279    }
280
281    fn invoke_with_args(
282        &self,
283        args: ScalarFunctionArgs,
284    ) -> datafusion_common::Result<ColumnarValue> {
285        Ok(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
286            self.breakpoints(&args)?,
287        ))))
288    }
289}
290
291impl fmt::Display for IcebergHashBreakpointsFunction {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        f.write_str("ICEBERG_HASH_BREAKPOINTS")
294    }
295}
296
297/// `iceberg_hash_ranges_sql(column, n)`: the ready-to-paste rule list for
298/// `PARTITION ON COLUMNS`, built from an equal-width `n`-bucket split.
299///
300/// The first argument is the column name as a constant string, the second the
301/// constant bucket count accepted by [`IcebergHashBoundsFunction`]. The output
302/// is the complete expression list: `iceberg_hash(c) < b1`,
303/// `iceberg_hash(c) >= b1 AND iceberg_hash(c) < b2`, ..., one rule per bucket,
304/// with the same breakpoints `iceberg_hash_bounds(n)` prints.
305///
306/// It only renders text; it does not create or change any partition.
307#[derive(Debug)]
308pub(crate) struct IcebergHashRangesSqlFunction {
309    signature: Signature,
310}
311
312impl Default for IcebergHashRangesSqlFunction {
313    fn default() -> Self {
314        Self {
315            signature: Signature::any(2, Volatility::Immutable),
316        }
317    }
318}
319
320impl IcebergHashRangesSqlFunction {
321    pub fn register(registry: &FunctionRegistry) {
322        registry.register_scalar(Self::default());
323    }
324
325    /// Renders the rule list from the hashed column name and the bucket count.
326    fn ranges_sql(&self, args: &ScalarFunctionArgs) -> datafusion_common::Result<Option<String>> {
327        let [column_name, buckets] = args.args.as_slice() else {
328            return Err(DataFusionError::Execution(format!(
329                "{} expects (column, buckets), got {} arguments",
330                self.name(),
331                args.args.len()
332            )));
333        };
334        let (name, buckets) = match (column_name, buckets) {
335            (ColumnarValue::Scalar(name), ColumnarValue::Scalar(buckets)) => (name, buckets),
336            (ColumnarValue::Array(_), _) | (_, ColumnarValue::Array(_)) => {
337                return Err(DataFusionError::Execution(format!(
338                    "{} expects constant arguments (column name, bucket count)",
339                    self.name()
340                )));
341            }
342        };
343        if name.is_null() || buckets.is_null() {
344            return Ok(None);
345        }
346        // Every string representation is a valid column name: a literal is
347        // `Utf8`, but a user can hand over `Utf8View` explicitly (for example
348        // `arrow_cast('host', 'Utf8View')`), and `Signature::any` does not
349        // convert it back.
350        let column = match name.try_as_str() {
351            Some(Some(column)) => column,
352            _ => {
353                return Err(DataFusionError::Execution(format!(
354                    "{} expects a column name string, got {name:?}",
355                    self.name()
356                )));
357            }
358        };
359        if column.is_empty() {
360            return Err(DataFusionError::Execution(format!(
361                "{} expects a non-empty column name",
362                self.name()
363            )));
364        }
365        let bounds = IcebergHashBoundsFunction::breakpoints_of(self.name(), buckets)?;
366        // `column` is a raw name, not SQL text: quote it so names with dashes,
367        // spaces, dots, quotes or upper case stay a single identifier when the
368        // rendered rules are pasted into `PARTITION ON COLUMNS`.
369        let column = quoted_identifier(column);
370        let mut rules = Vec::with_capacity(bounds.len() + 1);
371        for (index, bound) in bounds.iter().copied().enumerate() {
372            if index == 0 {
373                // First rule: only the upper bound; NULL rows land here.
374                rules.push(format!("iceberg_hash({column}) < {bound}"));
375            } else {
376                let lower = bounds[index - 1];
377                rules.push(format!(
378                    "iceberg_hash({column}) >= {lower} AND iceberg_hash({column}) < {bound}"
379                ));
380            }
381        }
382        // Last rule: only the lower bound.
383        rules.push(format!(
384            "iceberg_hash({column}) >= {}",
385            bounds[bounds.len() - 1]
386        ));
387        Ok(Some(rules.join(",\n")))
388    }
389}
390
391impl Function for IcebergHashRangesSqlFunction {
392    fn name(&self) -> &str {
393        "iceberg_hash_ranges_sql"
394    }
395
396    fn return_type(&self, _input_types: &[DataType]) -> datafusion_common::Result<DataType> {
397        Ok(DataType::Utf8)
398    }
399
400    fn signature(&self) -> &Signature {
401        &self.signature
402    }
403
404    fn invoke_with_args(
405        &self,
406        args: ScalarFunctionArgs,
407    ) -> datafusion_common::Result<ColumnarValue> {
408        Ok(ColumnarValue::Scalar(ScalarValue::Utf8(
409            self.ranges_sql(&args)?,
410        )))
411    }
412}
413
414impl fmt::Display for IcebergHashRangesSqlFunction {
415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
416        f.write_str("ICEBERG_HASH_RANGES_SQL")
417    }
418}
419
420/// The hash encoding a constant goes through. Integer widths share one
421/// encoding (`INT32`, `UINT8`, ... all hash as Iceberg longs), while strings use
422/// their UTF-8 bytes, so mixing the two produces breakpoints that do not
423/// describe a single column.
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425enum HashDomain {
426    String,
427    Integer,
428}
429
430impl HashDomain {
431    fn of(scalar: &ScalarValue) -> Option<Self> {
432        match scalar {
433            ScalarValue::Utf8(_) | ScalarValue::LargeUtf8(_) | ScalarValue::Utf8View(_) => {
434                Some(Self::String)
435            }
436            ScalarValue::Int8(_)
437            | ScalarValue::Int16(_)
438            | ScalarValue::Int32(_)
439            | ScalarValue::Int64(_)
440            | ScalarValue::UInt8(_)
441            | ScalarValue::UInt16(_)
442            | ScalarValue::UInt32(_)
443            | ScalarValue::UInt64(_) => Some(Self::Integer),
444            _ => None,
445        }
446    }
447}
448
449impl fmt::Display for HashDomain {
450    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451        match self {
452            Self::String => f.write_str("string"),
453            Self::Integer => f.write_str("integer"),
454        }
455    }
456}
457
458/// Quotes a column name as a SQL identifier: wrap it in double quotes and
459/// double every embedded quote.
460fn quoted_identifier(column: &str) -> String {
461    format!("\"{}\"", column.replace('"', "\"\""))
462}
463
464/// Hashes one constant by evaluating it through the shared array form, so the
465/// value goes through exactly the code a partition rule evaluates.
466fn into_hashed_scalar(
467    name: &str,
468    position: usize,
469    scalar: &ScalarValue,
470) -> datafusion_common::Result<i32> {
471    let array: ArrayRef = scalar.to_array()?;
472    // Hash through the array form a partition rule evaluates, one value per row.
473    let hashed = IcebergHash::evaluate_array(array.as_ref()).map_err(|error| {
474        DataFusionError::Execution(format!("{name} argument {position}: {error}"))
475    })?;
476    let value = ScalarValue::try_from_array(&hashed, 0)?;
477    match value {
478        ScalarValue::Int32(Some(hashed)) => Ok(hashed),
479        ScalarValue::Int32(None) => Err(DataFusionError::Execution(format!(
480            "{name} argument {position}: NULL hash"
481        ))),
482        other => Err(DataFusionError::Execution(format!(
483            "{name} argument {position}: unexpected hash {other:?}"
484        ))),
485    }
486}
487
488/// Returns the `n - 1` equal-width breakpoints of `buckets` over `INT32`,
489/// following `bi = i32::MIN + floor(i * 2^32 / n)`.
490fn equal_split_breakpoints(name: &str, buckets: i64) -> datafusion_common::Result<Vec<i32>> {
491    if !(2..=MAX_BUCKETS).contains(&buckets) {
492        return Err(DataFusionError::Execution(format!(
493            "{name} expects a bucket count in [2, {MAX_BUCKETS}], got {buckets}"
494        )));
495    }
496
497    Ok((1..buckets)
498        .map(|i| {
499            let offset = ((i as i128) << 32) / buckets as i128;
500            i32::MIN as i64 + offset as i64
501        })
502        .map(|bound| bound as i32)
503        .collect())
504}
505
506#[cfg(test)]
507mod tests {
508    use std::sync::Arc;
509
510    use datafusion::arrow::array::{Array, AsArray, Int64Array};
511    use datafusion::arrow::datatypes::{DataType, Field, Int32Type};
512    use datatypes::value::Value;
513
514    use super::*;
515    use crate::function_registry::FUNCTION_REGISTRY;
516
517    fn invoke(
518        function: &impl Function,
519        args: Vec<ColumnarValue>,
520        rows: usize,
521        return_type: DataType,
522    ) -> ColumnarValue {
523        function
524            .invoke_with_args(ScalarFunctionArgs {
525                args,
526                arg_fields: vec![],
527                number_rows: rows,
528                return_field: Arc::new(Field::new("result", return_type, true)),
529                config_options: Arc::new(Default::default()),
530            })
531            .unwrap()
532    }
533
534    fn invoke_udf(
535        udf: &datafusion::logical_expr::ScalarUDF,
536        args: Vec<ColumnarValue>,
537        rows: usize,
538        return_type: DataType,
539    ) -> ColumnarValue {
540        udf.invoke_with_args(ScalarFunctionArgs {
541            args,
542            arg_fields: vec![],
543            number_rows: rows,
544            return_field: Arc::new(Field::new("result", return_type, true)),
545            config_options: Arc::new(Default::default()),
546        })
547        .unwrap()
548    }
549
550    fn into_scalar(value: ColumnarValue) -> ScalarValue {
551        match value {
552            ColumnarValue::Scalar(scalar) => scalar,
553            ColumnarValue::Array(_) => panic!("expected a scalar result"),
554        }
555    }
556
557    #[test]
558    fn test_hash_matches_partition_rule() {
559        let udf = iceberg_hash_udf();
560        assert_eq!(udf.name(), "iceberg_hash");
561        assert_eq!(udf.return_type(&[DataType::Utf8]).unwrap(), DataType::Int32);
562
563        // Iceberg table spec, appendix B.
564        let hashed = invoke_udf(
565            &udf,
566            vec![ColumnarValue::Scalar(ScalarValue::Utf8(Some(
567                "iceberg".to_string(),
568            )))],
569            1,
570            DataType::Int32,
571        );
572        assert_eq!(into_scalar(hashed), ScalarValue::Int32(Some(1210000089)));
573
574        // An untyped NULL reaches the UDF as ScalarValue::Null.
575        let untyped_null = invoke_udf(
576            &udf,
577            vec![ColumnarValue::Scalar(ScalarValue::Null)],
578            1,
579            DataType::Int32,
580        );
581        assert_eq!(into_scalar(untyped_null), ScalarValue::Int32(None));
582
583        // Integers hash as Iceberg longs, and NULL hashes to NULL.
584        let array = invoke_udf(
585            &udf,
586            vec![ColumnarValue::Array(Arc::new(Int64Array::from(vec![
587                Some(34),
588                None,
589            ])))],
590            2,
591            DataType::Int32,
592        )
593        .to_array(2)
594        .unwrap();
595        let array = array.as_primitive::<Int32Type>();
596        assert_eq!(array.value(0), 2017239379);
597        assert!(array.is_null(1));
598    }
599
600    #[test]
601    fn test_bounds_equal_split() {
602        let function = IcebergHashBoundsFunction::default();
603        assert_eq!(function.name(), "iceberg_hash_bounds");
604        assert_eq!(
605            function.return_type(&[DataType::Int64]).unwrap(),
606            DataType::Utf8
607        );
608
609        let cases = [
610            (2, "0"),
611            (3, "-715827883, 715827882"),
612            (4, "-1073741824, 0, 1073741824"),
613            (
614                8,
615                "-1610612736, -1073741824, -536870912, 0, 536870912, \
616                 1073741824, 1610612736",
617            ),
618        ];
619        for (buckets, expected) in cases {
620            let bounds = invoke(
621                &function,
622                vec![ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets)))],
623                1,
624                DataType::Utf8,
625            );
626            assert_eq!(
627                into_scalar(bounds),
628                ScalarValue::Utf8(Some(expected.to_string())),
629                "buckets: {buckets}"
630            );
631        }
632
633        // Every integer width is a constant count; small widths must not be
634        // rejected as non-integer input.
635        for buckets in [
636            ScalarValue::Int8(Some(4)),
637            ScalarValue::Int16(Some(4)),
638            ScalarValue::UInt8(Some(4)),
639            ScalarValue::UInt16(Some(4)),
640            ScalarValue::UInt32(Some(4)),
641            ScalarValue::UInt64(Some(4)),
642        ] {
643            let label = format!("{buckets:?}");
644            let bounds = invoke(
645                &function,
646                vec![ColumnarValue::Scalar(buckets)],
647                1,
648                DataType::Utf8,
649            );
650            assert_eq!(
651                into_scalar(bounds),
652                ScalarValue::Utf8(Some("-1073741824, 0, 1073741824".to_string())),
653                "scalar: {label}"
654            );
655        }
656    }
657
658    #[test]
659    fn test_breakpoints_sorts_and_dedups() {
660        let function = IcebergHashBreakpointsFunction::default();
661        assert_eq!(function.name(), "iceberg_hash_breakpoints");
662        assert_eq!(
663            function.return_type(&[DataType::Utf8]).unwrap(),
664            DataType::Utf8
665        );
666
667        // Unsorted strings: 'iceberg', 'a', and 'iceberg' again (dedup).
668        let bounds = invoke(
669            &function,
670            vec![
671                ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))),
672                ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string()))),
673                ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))),
674            ],
675            1,
676            DataType::Utf8,
677        );
678        let iceberg = IcebergHash::evaluate_value(&Value::String("iceberg".into()))
679            .unwrap()
680            .as_i64()
681            .unwrap() as i32;
682        let a = IcebergHash::evaluate_value(&Value::String("a".into()))
683            .unwrap()
684            .as_i64()
685            .unwrap() as i32;
686        let expected = match (iceberg, a) {
687            (min, max) if min < max => format!("{min}, {max}"),
688            (min, max) => format!("{max}, {min}"),
689        };
690        assert_eq!(into_scalar(bounds), ScalarValue::Utf8(Some(expected)));
691
692        // Integer widths share one encoding, so they mix.
693        let bounds = invoke(
694            &function,
695            vec![
696                ColumnarValue::Scalar(ScalarValue::Int64(Some(34))),
697                ColumnarValue::Scalar(ScalarValue::Int32(Some(-1))),
698                ColumnarValue::Scalar(ScalarValue::UInt8(Some(0))),
699            ],
700            1,
701            DataType::Utf8,
702        );
703        assert_eq!(
704            into_scalar(bounds),
705            ScalarValue::Utf8(Some(format!(
706                "{}, {}, {}",
707                IcebergHash::evaluate_value(&Value::Int32(-1))
708                    .unwrap()
709                    .as_i64()
710                    .unwrap() as i32,
711                IcebergHash::evaluate_value(&Value::UInt8(0))
712                    .unwrap()
713                    .as_i64()
714                    .unwrap() as i32,
715                IcebergHash::evaluate_value(&Value::Int64(34))
716                    .unwrap()
717                    .as_i64()
718                    .unwrap() as i32,
719            )))
720        );
721    }
722
723    #[test]
724    fn test_breakpoints_rejects_invalid_input() {
725        let function = IcebergHashBreakpointsFunction::default();
726        let call = |args: Vec<ColumnarValue>| {
727            function.invoke_with_args(ScalarFunctionArgs {
728                args,
729                arg_fields: vec![],
730                number_rows: 1,
731                return_field: Arc::new(Field::new("result", DataType::Utf8, true)),
732                config_options: Arc::new(Default::default()),
733            })
734        };
735
736        // Empty list cannot form a breakpoint list.
737        let err = call(vec![]).unwrap_err().to_string();
738        assert!(err.contains("at least one value"), "{err}");
739
740        // NULL can never be a breakpoint: it falls in the lowest bucket.
741        let err = call(vec![
742            ColumnarValue::Scalar(ScalarValue::Utf8(Some("a".to_string()))),
743            ColumnarValue::Scalar(ScalarValue::Null),
744        ])
745        .unwrap_err()
746        .to_string();
747        assert!(err.contains("cannot use NULL as a breakpoint"), "{err}");
748
749        // A column cannot be hashed at planning time.
750        let err = call(vec![ColumnarValue::Array(Arc::new(Int64Array::from(
751            vec![34_i64],
752        )))])
753        .unwrap_err()
754        .to_string();
755        assert!(err.contains("constant values, not a column"), "{err}");
756
757        // Unsupported value type is named explicitly.
758        let err = call(vec![ColumnarValue::Scalar(ScalarValue::Float64(Some(1.0)))])
759            .unwrap_err()
760            .to_string();
761        assert!(err.contains("expects string or integer values"), "{err}");
762
763        // A string and an integer hash through different encodings, so mixing
764        // them cannot describe one column.
765        let err = call(vec![
766            ColumnarValue::Scalar(ScalarValue::Utf8(Some("iceberg".to_string()))),
767            ColumnarValue::Scalar(ScalarValue::Int64(Some(34))),
768        ])
769        .unwrap_err()
770        .to_string();
771        assert!(
772            err.contains("one hash encoding")
773                && err.contains("argument 2 is integer")
774                && err.contains("earlier values are string"),
775            "{err}"
776        );
777    }
778
779    #[test]
780    fn test_bounds_rejects_invalid_input() {
781        let function = IcebergHashBoundsFunction::default();
782        let call = |arg: ColumnarValue| {
783            function.invoke_with_args(ScalarFunctionArgs {
784                args: vec![arg],
785                arg_fields: vec![],
786                number_rows: 1,
787                return_field: Arc::new(Field::new("result", DataType::Utf8, true)),
788                config_options: Arc::new(Default::default()),
789            })
790        };
791
792        for buckets in [i64::MIN, -1, 0, 1, MAX_BUCKETS + 1] {
793            let err = call(ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets))))
794                .unwrap_err()
795                .to_string();
796            assert!(
797                err.contains("bucket count in [2, 1024]"),
798                "unexpected error for {buckets}: {err}"
799            );
800        }
801
802        let err = call(ColumnarValue::Scalar(ScalarValue::Utf8(Some(
803            "4".to_string(),
804        ))))
805        .unwrap_err()
806        .to_string();
807        assert!(err.contains("integer bucket count"), "{err}");
808
809        let err = call(ColumnarValue::Array(Arc::new(Int64Array::from(vec![
810            4_i64,
811        ]))))
812        .unwrap_err()
813        .to_string();
814        assert!(err.contains("constant bucket count"), "{err}");
815
816        // A NULL bucket count propagates instead of failing.
817        let null = call(ColumnarValue::Scalar(ScalarValue::Int64(None))).unwrap();
818        assert_eq!(into_scalar(null), ScalarValue::Utf8(None));
819    }
820
821    #[test]
822    fn test_ranges_sql_renders_rule_list() {
823        let function = IcebergHashRangesSqlFunction::default();
824        assert_eq!(function.name(), "iceberg_hash_ranges_sql");
825        assert_eq!(
826            function
827                .return_type(&[DataType::Utf8, DataType::Int64])
828                .unwrap(),
829            DataType::Utf8
830        );
831
832        let render = |name: &str, buckets: i64| {
833            let rendered = invoke(
834                &function,
835                vec![
836                    ColumnarValue::Scalar(ScalarValue::Utf8(Some(name.to_string()))),
837                    ColumnarValue::Scalar(ScalarValue::Int64(Some(buckets))),
838                ],
839                1,
840                DataType::Utf8,
841            );
842            into_scalar(rendered)
843        };
844
845        let four_buckets = [
846            "iceberg_hash(\"host\") < -1073741824",
847            "iceberg_hash(\"host\") >= -1073741824 AND iceberg_hash(\"host\") < 0",
848            "iceberg_hash(\"host\") >= 0 AND iceberg_hash(\"host\") < 1073741824",
849            "iceberg_hash(\"host\") >= 1073741824",
850        ]
851        .join(",\n");
852        assert_eq!(render("host", 4), ScalarValue::Utf8(Some(four_buckets)));
853        assert_eq!(
854            render("tenant", 2),
855            ScalarValue::Utf8(Some(
856                "iceberg_hash(\"tenant\") < 0,\niceberg_hash(\"tenant\") >= 0".to_string()
857            ))
858        );
859
860        // Names that are not plain lowercase identifiers must stay one
861        // identifier: dashes, spaces and embedded quotes are quoted/escaped.
862        assert_eq!(
863            render("host-name", 2),
864            ScalarValue::Utf8(Some(
865                "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0".to_string()
866            ))
867        );
868        assert_eq!(
869            render("he\"llo", 2),
870            ScalarValue::Utf8(Some(
871                "iceberg_hash(\"he\"\"llo\") < 0,\niceberg_hash(\"he\"\"llo\") >= 0".to_string()
872            ))
873        );
874
875        // A column name can arrive in any Arrow string representation. An
876        // explicit `Utf8View` (for example from `arrow_cast`) must render
877        // exactly like a plain literal instead of being rejected as non-string.
878        for name in [
879            ScalarValue::LargeUtf8(Some("host-name".to_string())),
880            ScalarValue::Utf8View(Some("host-name".to_string())),
881        ] {
882            let rendered = invoke(
883                &function,
884                vec![
885                    ColumnarValue::Scalar(name),
886                    ColumnarValue::Scalar(ScalarValue::Int64(Some(2))),
887                ],
888                1,
889                DataType::Utf8,
890            );
891            assert_eq!(
892                into_scalar(rendered),
893                ScalarValue::Utf8(Some(
894                    "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0"
895                        .to_string()
896                ))
897            );
898        }
899
900        // A NULL name or bucket count propagates.
901        let call = |args: Vec<ColumnarValue>| {
902            let rendered = function
903                .invoke_with_args(ScalarFunctionArgs {
904                    args,
905                    arg_fields: vec![],
906                    number_rows: 1,
907                    return_field: Arc::new(Field::new("result", DataType::Utf8, true)),
908                    config_options: Arc::new(Default::default()),
909                })
910                .unwrap();
911            into_scalar(rendered)
912        };
913        assert_eq!(
914            call(vec![
915                ColumnarValue::Scalar(ScalarValue::Utf8(None)),
916                ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
917            ]),
918            ScalarValue::Utf8(None)
919        );
920        assert_eq!(
921            call(vec![
922                ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))),
923                ColumnarValue::Scalar(ScalarValue::Int64(None)),
924            ]),
925            ScalarValue::Utf8(None)
926        );
927    }
928
929    /// Rendered rules must be valid partition expressions for the quoted
930    /// column, including names that need quoting.
931    #[test]
932    fn test_ranges_sql_output_parses_as_partition_rule() {
933        use sql::dialect::GreptimeDbDialect;
934        use sql::parser::{ParseOptions, ParserContext};
935
936        for column in ["host", "host-name", "HOST", "he\"llo", "a b"] {
937            let rendered = into_scalar(invoke(
938                &IcebergHashRangesSqlFunction::default(),
939                vec![
940                    ColumnarValue::Scalar(ScalarValue::Utf8(Some(column.to_string()))),
941                    ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
942                ],
943                1,
944                DataType::Utf8,
945            ));
946            let ScalarValue::Utf8(Some(rules)) = rendered else {
947                panic!("expected rendered rules for {column}");
948            };
949            let quoted = quoted_identifier(column);
950            let ddl = format!(
951                "CREATE TABLE t ({quoted} STRING, ts TIMESTAMP TIME INDEX, PRIMARY KEY ({quoted})) \
952                 PARTITION ON COLUMNS ({quoted}) ({rules})"
953            );
954            let statements = ParserContext::create_with_dialect(
955                &ddl,
956                &GreptimeDbDialect {},
957                ParseOptions::default(),
958            )
959            .unwrap_or_else(|error| {
960                panic!("generated rules must parse for {column}: {error}\n{ddl}")
961            });
962            assert_eq!(1, statements.len(), "{column}");
963        }
964    }
965
966    #[test]
967    fn test_ranges_sql_rejects_invalid_input() {
968        let function = IcebergHashRangesSqlFunction::default();
969        let call = |args: Vec<ColumnarValue>| {
970            function
971                .invoke_with_args(ScalarFunctionArgs {
972                    args,
973                    arg_fields: vec![],
974                    number_rows: 1,
975                    return_field: Arc::new(Field::new("result", DataType::Utf8, true)),
976                    config_options: Arc::new(Default::default()),
977                })
978                .unwrap_err()
979                .to_string()
980        };
981
982        // Bucket count outside the accepted range names the shared limit and
983        // the function the user actually called.
984        let err = call(vec![
985            ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))),
986            ColumnarValue::Scalar(ScalarValue::Int64(Some(1))),
987        ]);
988        assert!(err.contains("bucket count in [2, 1024]"), "{err}");
989        assert!(
990            err.contains("iceberg_hash_ranges_sql expects"),
991            "error must name the caller: {err}"
992        );
993
994        // Non-integer bucket count names the shared type error.
995        let err = call(vec![
996            ColumnarValue::Scalar(ScalarValue::Utf8(Some("host".to_string()))),
997            ColumnarValue::Scalar(ScalarValue::Utf8(Some("4".to_string()))),
998        ]);
999        assert!(err.contains("integer bucket count"), "{err}");
1000        assert!(
1001            err.contains("iceberg_hash_ranges_sql expects"),
1002            "error must name the caller: {err}"
1003        );
1004
1005        // Non-string column name.
1006        let err = call(vec![
1007            ColumnarValue::Scalar(ScalarValue::Int64(Some(1))),
1008            ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
1009        ]);
1010        assert!(err.contains("column name string"), "{err}");
1011
1012        // Empty column name.
1013        let err = call(vec![
1014            ColumnarValue::Scalar(ScalarValue::Utf8(Some(String::new()))),
1015            ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
1016        ]);
1017        assert!(err.contains("non-empty column name"), "{err}");
1018
1019        // Columns cannot be hashed at planning time.
1020        let err = call(vec![
1021            ColumnarValue::Array(Arc::new(Int64Array::from(vec![1_i64]))),
1022            ColumnarValue::Scalar(ScalarValue::Int64(Some(4))),
1023        ]);
1024        assert!(err.contains("constant arguments"), "{err}");
1025
1026        // Wrong arity.
1027        let err = call(vec![ColumnarValue::Scalar(ScalarValue::Int64(Some(4)))]);
1028        assert!(err.contains("expects (column, buckets)"), "{err}");
1029    }
1030
1031    /// The SQL function must be the same `ScalarUDFImpl` the partition planner
1032    /// builds, so a query expression compares equal to a rule expression.
1033    #[test]
1034    fn test_registered_hash_matches_partition_rule_expression() {
1035        use datafusion::prelude::col;
1036
1037        let sql_expr = FUNCTION_REGISTRY
1038            .get_function("iceberg_hash")
1039            .expect("iceberg_hash is registered")
1040            .provide(crate::function::FunctionContext::default())
1041            .call(vec![col("host")]);
1042        // The exact expression `Operand::IcebergHash` builds while planning a
1043        // partition rule.
1044        let rule_expr = IcebergHash::new("host").to_logical_expr();
1045        assert_eq!(
1046            rule_expr, sql_expr,
1047            "the registered iceberg_hash must be the UDF partition rules plan"
1048        );
1049    }
1050
1051    /// Functions that share a signature must stay distinct `ScalarUDF`s:
1052    /// DataFusion compares expressions structurally, and treating `isnull` and
1053    /// `iceberg_hash` as the same function corrupted `GROUP BY` planning
1054    /// (`rebase_expr` matched `isnull(x)` against the grouped
1055    /// `iceberg_hash(x)`).
1056    #[test]
1057    fn test_same_signature_functions_stay_distinct() {
1058        use std::collections::HashSet;
1059        use std::collections::hash_map::DefaultHasher;
1060        use std::hash::{Hash, Hasher};
1061
1062        use datafusion::prelude::col;
1063
1064        let provide = |name: &str| {
1065            FUNCTION_REGISTRY
1066                .get_function(name)
1067                .unwrap_or_else(|| panic!("{name} is not registered"))
1068                .provide(crate::function::FunctionContext::default())
1069        };
1070        let isnull = provide("isnull");
1071        let hash = provide("iceberg_hash");
1072        let bounds = provide("iceberg_hash_bounds");
1073
1074        // All three share `Signature::any(1, Immutable)` but are not equal.
1075        assert!(isnull != hash);
1076        assert!(isnull != bounds);
1077        assert!(hash != bounds);
1078        assert_ne!(
1079            isnull.call(vec![col("x")]),
1080            hash.call(vec![col("x")]),
1081            "isnull(x) and iceberg_hash(x) must not compare equal"
1082        );
1083
1084        let hash_of = |udf: &datafusion::logical_expr::ScalarUDF| {
1085            let mut hasher = DefaultHasher::new();
1086            udf.hash(&mut hasher);
1087            hasher.finish()
1088        };
1089        // Equal objects keep hashing equally, so the registry still finds them.
1090        let hash_again = provide("iceberg_hash");
1091        assert_eq!(hash, hash_again);
1092        assert_eq!(hash_of(&hash), hash_of(&hash_again));
1093        // Distinct functions remain separable keys in hash-based containers.
1094        let udfs: HashSet<_> = [isnull, hash, bounds].into_iter().collect();
1095        assert_eq!(3, udfs.len());
1096    }
1097
1098    /// `isnull` and `iceberg_hash` share a signature; grouping by one while
1099    /// selecting the other must still plan (regression for the identity bug).
1100    #[tokio::test]
1101    async fn test_group_by_with_same_signature_functions() {
1102        use datafusion::arrow::array::{ArrayRef, Int64Array};
1103        use datafusion::arrow::record_batch::RecordBatch;
1104        use datafusion::prelude::SessionContext;
1105
1106        use crate::function::FunctionContext;
1107
1108        let ctx = SessionContext::new();
1109        for name in ["isnull", "iceberg_hash"] {
1110            let udf = FUNCTION_REGISTRY
1111                .get_function(name)
1112                .unwrap()
1113                .provide(FunctionContext::default());
1114            ctx.register_udf(udf);
1115        }
1116        ctx.register_batch(
1117            "t",
1118            RecordBatch::try_from_iter([(
1119                "x",
1120                Arc::new(Int64Array::from(vec![Some(34), None])) as ArrayRef,
1121            )])
1122            .unwrap(),
1123        )
1124        .unwrap();
1125
1126        for sql in [
1127            "SELECT isnull(x) FROM t GROUP BY x, iceberg_hash(x)",
1128            "SELECT iceberg_hash(x) FROM t GROUP BY x, isnull(x)",
1129        ] {
1130            let batches = ctx
1131                .sql(sql)
1132                .await
1133                .unwrap_or_else(|error| panic!("{sql} must plan: {error}"))
1134                .collect()
1135                .await
1136                .unwrap_or_else(|error| panic!("{sql} must execute: {error}"));
1137            assert_eq!(
1138                2,
1139                batches.iter().map(|batch| batch.num_rows()).sum::<usize>(),
1140                "{sql}"
1141            );
1142        }
1143    }
1144
1145    /// Both functions must resolve and run through a plain SQL session, not just
1146    /// through the [Function] trait.
1147    #[tokio::test]
1148    async fn test_functions_run_through_sql() {
1149        use datafusion::prelude::SessionContext;
1150
1151        use crate::function::FunctionContext;
1152
1153        // Register what the registry actually exposes, which also pins the
1154        // `iceberg_hash` registration to the raw partition-rule UDF.
1155        let ctx = SessionContext::new();
1156        for name in [
1157            "iceberg_hash",
1158            "iceberg_hash_bounds",
1159            "iceberg_hash_breakpoints",
1160            "iceberg_hash_ranges_sql",
1161        ] {
1162            let udf = FUNCTION_REGISTRY
1163                .get_function(name)
1164                .unwrap_or_else(|| panic!("{name} is not registered"))
1165                .provide(FunctionContext::default());
1166            ctx.register_udf(udf);
1167        }
1168
1169        let batches = ctx
1170            .sql(
1171                "SELECT iceberg_hash('iceberg') AS h, iceberg_hash(34) AS i, \
1172                 iceberg_hash(NULL) AS n, iceberg_hash_bounds(4) AS b, \
1173                 iceberg_hash_bounds(CAST(4 AS SMALLINT)) AS sb, \
1174                 iceberg_hash_breakpoints('iceberg', 'a') AS bp, \
1175                 iceberg_hash_ranges_sql('host-name', 2) AS rs, \
1176                 iceberg_hash_ranges_sql(arrow_cast('host-name', 'Utf8View'), 2) AS rsv",
1177            )
1178            .await
1179            .unwrap()
1180            .collect()
1181            .await
1182            .unwrap();
1183        assert_eq!(batches.len(), 1);
1184        assert_eq!(batches[0].num_rows(), 1);
1185        assert_eq!(
1186            batches[0].column(0).as_primitive::<Int32Type>().value(0),
1187            1210000089
1188        );
1189        assert_eq!(
1190            batches[0].column(1).as_primitive::<Int32Type>().value(0),
1191            2017239379
1192        );
1193        assert!(batches[0].column(2).as_primitive::<Int32Type>().is_null(0));
1194        assert_eq!(
1195            batches[0].column(3).as_string::<i32>().value(0),
1196            "-1073741824, 0, 1073741824"
1197        );
1198        assert_eq!(
1199            batches[0].column(4).as_string::<i32>().value(0),
1200            "-1073741824, 0, 1073741824"
1201        );
1202        // Sorted hash values of the two strings, computed by the shared hash.
1203        let iceberg = IcebergHash::evaluate_value(&Value::String("iceberg".into()))
1204            .unwrap()
1205            .as_i64()
1206            .unwrap() as i32;
1207        let a = IcebergHash::evaluate_value(&Value::String("a".into()))
1208            .unwrap()
1209            .as_i64()
1210            .unwrap() as i32;
1211        let expected_breakpoints = if iceberg < a {
1212            format!("{iceberg}, {a}")
1213        } else {
1214            format!("{a}, {iceberg}")
1215        };
1216        assert_eq!(
1217            batches[0].column(5).as_string::<i32>().value(0),
1218            expected_breakpoints
1219        );
1220        // Ready-to-paste rule list, with the column name quoted.
1221        let rendered_rules = "iceberg_hash(\"host-name\") < 0,\niceberg_hash(\"host-name\") >= 0";
1222        assert_eq!(
1223            batches[0].column(6).as_string::<i32>().value(0),
1224            rendered_rules
1225        );
1226        // An explicit `Utf8View` column name renders the same rules.
1227        assert_eq!(
1228            batches[0].column(7).as_string::<i32>().value(0),
1229            rendered_rules
1230        );
1231    }
1232
1233    #[test]
1234    fn test_hash_functions_are_registered() {
1235        for name in [
1236            "iceberg_hash",
1237            "iceberg_hash_bounds",
1238            "iceberg_hash_breakpoints",
1239            "iceberg_hash_ranges_sql",
1240        ] {
1241            assert!(
1242                FUNCTION_REGISTRY.get_function(name).is_some(),
1243                "{name} is not registered"
1244            );
1245        }
1246    }
1247}