Skip to main content

datafusion_expr/
expr_fn.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Functions for creating logical expressions
6
7use crate::expr::{
8    AggregateFunction, BinaryExpr, Cast, Exists, GroupingSet, InList, InSubquery, Lambda,
9    LambdaVariable, NullTreatment, Placeholder, TryCast, Unnest, WildcardOptions,
10    WindowFunction,
11};
12use crate::function::{
13    AccumulatorArgs, AccumulatorFactoryFunction, PartitionEvaluatorFactory,
14    StateFieldsArgs,
15};
16use crate::ptr_eq::PtrEq;
17use crate::select_expr::SelectExpr;
18use crate::{
19    AggregateUDF, Expr, LimitEffect, LogicalPlan, Operator, PartitionEvaluator,
20    ScalarFunctionArgs, ScalarFunctionImplementation, ScalarUDF, Signature, Volatility,
21    conditional_expressions::CaseBuilder, expr::Sort, logical_plan::Subquery,
22};
23use crate::{
24    AggregateUDFImpl, ColumnarValue, ScalarUDFImpl, WindowFrame, WindowUDF, WindowUDFImpl,
25};
26use arrow::compute::kernels::cast_utils::{
27    parse_interval_day_time, parse_interval_month_day_nano, parse_interval_year_month,
28};
29use arrow::datatypes::{DataType, Field, FieldRef};
30use datafusion_common::{Column, Result, ScalarValue, Spans, TableReference, plan_err};
31use datafusion_functions_window_common::field::WindowUDFFieldArgs;
32use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
33use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
34use std::collections::HashMap;
35use std::fmt::Debug;
36use std::hash::Hash;
37use std::ops::Not;
38use std::sync::Arc;
39
40/// Create a column expression based on a qualified or unqualified column name. Will
41/// normalize unquoted identifiers according to SQL rules (identifiers will become lowercase).
42///
43/// For example:
44///
45/// ```rust
46/// # use datafusion_expr::col;
47/// let c1 = col("a");
48/// let c2 = col("A");
49/// assert_eq!(c1, c2);
50///
51/// // note how quoting with double quotes preserves the case
52/// let c3 = col(r#""A""#);
53/// assert_ne!(c1, c3);
54/// ```
55pub fn col(ident: impl Into<Column>) -> Expr {
56    Expr::Column(ident.into())
57}
58
59/// Create an out reference column which hold a reference that has been resolved to a field
60/// outside of the current plan.
61/// The expression created by this function does not preserve the metadata of the outer column.
62/// Please use `out_ref_col_with_metadata` if you want to preserve the metadata.
63pub fn out_ref_col(dt: DataType, ident: impl Into<Column>) -> Expr {
64    out_ref_col_with_metadata(dt, HashMap::new(), ident)
65}
66
67/// Create an out reference column from an existing field (preserving metadata)
68pub fn out_ref_col_with_metadata(
69    dt: DataType,
70    metadata: HashMap<String, String>,
71    ident: impl Into<Column>,
72) -> Expr {
73    let column = ident.into();
74    let field: FieldRef =
75        Arc::new(Field::new(column.name(), dt, true).with_metadata(metadata));
76    Expr::OuterReferenceColumn(field, column)
77}
78
79/// Create an unqualified column expression from the provided name, without normalizing
80/// the column.
81///
82/// For example:
83///
84/// ```rust
85/// # use datafusion_expr::{col, ident};
86/// let c1 = ident("A"); // not normalized staying as column 'A'
87/// let c2 = col("A"); // normalized via SQL rules becoming column 'a'
88/// assert_ne!(c1, c2);
89///
90/// let c3 = col(r#""A""#);
91/// assert_eq!(c1, c3);
92///
93/// let c4 = col("t1.a"); // parses as relation 't1' column 'a'
94/// let c5 = ident("t1.a"); // parses as column 't1.a'
95/// assert_ne!(c4, c5);
96/// ```
97pub fn ident(name: impl Into<String>) -> Expr {
98    Expr::Column(Column::from_name(name))
99}
100
101/// Create placeholder value that will be filled in (such as `$1`)
102///
103/// Note the parameter type can be inferred using [`Expr::infer_placeholder_types`]
104///
105/// # Example
106///
107/// ```rust
108/// # use datafusion_expr::{placeholder};
109/// let p = placeholder("$1"); // $1, refers to parameter 1
110/// assert_eq!(p.to_string(), "$1")
111/// ```
112pub fn placeholder(id: impl Into<String>) -> Expr {
113    Expr::Placeholder(Placeholder {
114        id: id.into(),
115        field: None,
116    })
117}
118
119/// Create an '*' [`Expr::Wildcard`] expression that matches all columns
120///
121/// # Example
122///
123/// ```rust
124/// # use datafusion_expr::{wildcard};
125/// let p = wildcard();
126/// assert_eq!(p.to_string(), "*")
127/// ```
128pub fn wildcard() -> SelectExpr {
129    SelectExpr::Wildcard(WildcardOptions::default())
130}
131
132/// Create an '*' [`Expr::Wildcard`] expression with the wildcard options
133pub fn wildcard_with_options(options: WildcardOptions) -> SelectExpr {
134    SelectExpr::Wildcard(options)
135}
136
137/// Create an 't.*' [`Expr::Wildcard`] expression that matches all columns from a specific table
138///
139/// # Example
140///
141/// ```rust
142/// # use datafusion_common::TableReference;
143/// # use datafusion_expr::{qualified_wildcard};
144/// let p = qualified_wildcard(TableReference::bare("t"));
145/// assert_eq!(p.to_string(), "t.*")
146/// ```
147pub fn qualified_wildcard(qualifier: impl Into<TableReference>) -> SelectExpr {
148    SelectExpr::QualifiedWildcard(qualifier.into(), WildcardOptions::default())
149}
150
151/// Create an 't.*' [`Expr::Wildcard`] expression with the wildcard options
152pub fn qualified_wildcard_with_options(
153    qualifier: impl Into<TableReference>,
154    options: WildcardOptions,
155) -> SelectExpr {
156    SelectExpr::QualifiedWildcard(qualifier.into(), options)
157}
158
159/// Return a new expression `left <op> right`
160pub fn binary_expr(left: Expr, op: Operator, right: Expr) -> Expr {
161    Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right)))
162}
163
164/// Return a new expression with a logical AND
165pub fn and(left: Expr, right: Expr) -> Expr {
166    Expr::BinaryExpr(BinaryExpr::new(
167        Box::new(left),
168        Operator::And,
169        Box::new(right),
170    ))
171}
172
173/// Return a new expression with a logical OR
174pub fn or(left: Expr, right: Expr) -> Expr {
175    Expr::BinaryExpr(BinaryExpr::new(
176        Box::new(left),
177        Operator::Or,
178        Box::new(right),
179    ))
180}
181
182/// Return a new expression with a logical NOT
183pub fn not(expr: Expr) -> Expr {
184    expr.not()
185}
186
187/// Return a new expression with bitwise AND
188pub fn bitwise_and(left: Expr, right: Expr) -> Expr {
189    Expr::BinaryExpr(BinaryExpr::new(
190        Box::new(left),
191        Operator::BitwiseAnd,
192        Box::new(right),
193    ))
194}
195
196/// Return a new expression with bitwise OR
197pub fn bitwise_or(left: Expr, right: Expr) -> Expr {
198    Expr::BinaryExpr(BinaryExpr::new(
199        Box::new(left),
200        Operator::BitwiseOr,
201        Box::new(right),
202    ))
203}
204
205/// Return a new expression with bitwise XOR
206pub fn bitwise_xor(left: Expr, right: Expr) -> Expr {
207    Expr::BinaryExpr(BinaryExpr::new(
208        Box::new(left),
209        Operator::BitwiseXor,
210        Box::new(right),
211    ))
212}
213
214/// Return a new expression with bitwise SHIFT RIGHT
215pub fn bitwise_shift_right(left: Expr, right: Expr) -> Expr {
216    Expr::BinaryExpr(BinaryExpr::new(
217        Box::new(left),
218        Operator::BitwiseShiftRight,
219        Box::new(right),
220    ))
221}
222
223/// Return a new expression with bitwise SHIFT LEFT
224pub fn bitwise_shift_left(left: Expr, right: Expr) -> Expr {
225    Expr::BinaryExpr(BinaryExpr::new(
226        Box::new(left),
227        Operator::BitwiseShiftLeft,
228        Box::new(right),
229    ))
230}
231
232/// Create an in_list expression
233pub fn in_list(expr: Expr, list: Vec<Expr>, negated: bool) -> Expr {
234    Expr::InList(InList::new(Box::new(expr), list, negated))
235}
236
237/// Create an EXISTS subquery expression
238pub fn exists(subquery: Arc<LogicalPlan>) -> Expr {
239    let outer_ref_columns = subquery.all_out_ref_exprs();
240    Expr::Exists(Exists {
241        subquery: Subquery {
242            subquery,
243            outer_ref_columns,
244            spans: Spans::new(),
245        },
246        negated: false,
247    })
248}
249
250/// Create a NOT EXISTS subquery expression
251pub fn not_exists(subquery: Arc<LogicalPlan>) -> Expr {
252    let outer_ref_columns = subquery.all_out_ref_exprs();
253    Expr::Exists(Exists {
254        subquery: Subquery {
255            subquery,
256            outer_ref_columns,
257            spans: Spans::new(),
258        },
259        negated: true,
260    })
261}
262
263/// Create an IN subquery expression
264pub fn in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {
265    let outer_ref_columns = subquery.all_out_ref_exprs();
266    Expr::InSubquery(InSubquery::new(
267        Box::new(expr),
268        Subquery {
269            subquery,
270            outer_ref_columns,
271            spans: Spans::new(),
272        },
273        false,
274    ))
275}
276
277/// Create a NOT IN subquery expression
278pub fn not_in_subquery(expr: Expr, subquery: Arc<LogicalPlan>) -> Expr {
279    let outer_ref_columns = subquery.all_out_ref_exprs();
280    Expr::InSubquery(InSubquery::new(
281        Box::new(expr),
282        Subquery {
283            subquery,
284            outer_ref_columns,
285            spans: Spans::new(),
286        },
287        true,
288    ))
289}
290
291/// Create a scalar subquery expression
292pub fn scalar_subquery(subquery: Arc<LogicalPlan>) -> Expr {
293    let outer_ref_columns = subquery.all_out_ref_exprs();
294    Expr::ScalarSubquery(Subquery {
295        subquery,
296        outer_ref_columns,
297        spans: Spans::new(),
298    })
299}
300
301/// Create a grouping set
302pub fn grouping_set(exprs: Vec<Vec<Expr>>) -> Expr {
303    Expr::GroupingSet(GroupingSet::GroupingSets(exprs))
304}
305
306/// Create a grouping set for all combination of `exprs`
307pub fn cube(exprs: Vec<Expr>) -> Expr {
308    Expr::GroupingSet(GroupingSet::Cube(exprs))
309}
310
311/// Create a grouping set for rollup
312pub fn rollup(exprs: Vec<Expr>) -> Expr {
313    Expr::GroupingSet(GroupingSet::Rollup(exprs))
314}
315
316/// Create a cast expression
317pub fn cast(expr: Expr, data_type: DataType) -> Expr {
318    Expr::Cast(Cast::new(Box::new(expr), data_type))
319}
320
321/// Create a try cast expression
322pub fn try_cast(expr: Expr, data_type: DataType) -> Expr {
323    Expr::TryCast(TryCast::new(Box::new(expr), data_type))
324}
325
326/// Create is null expression
327pub fn is_null(expr: Expr) -> Expr {
328    Expr::IsNull(Box::new(expr))
329}
330
331/// Create is not null expression
332pub fn is_not_null(expr: Expr) -> Expr {
333    Expr::IsNotNull(Box::new(expr))
334}
335
336/// Create is true expression
337pub fn is_true(expr: Expr) -> Expr {
338    Expr::IsTrue(Box::new(expr))
339}
340
341/// Create is not true expression
342pub fn is_not_true(expr: Expr) -> Expr {
343    Expr::IsNotTrue(Box::new(expr))
344}
345
346/// Create is false expression
347pub fn is_false(expr: Expr) -> Expr {
348    Expr::IsFalse(Box::new(expr))
349}
350
351/// Create is not false expression
352pub fn is_not_false(expr: Expr) -> Expr {
353    Expr::IsNotFalse(Box::new(expr))
354}
355
356/// Create is unknown expression
357pub fn is_unknown(expr: Expr) -> Expr {
358    Expr::IsUnknown(Box::new(expr))
359}
360
361/// Create is not unknown expression
362pub fn is_not_unknown(expr: Expr) -> Expr {
363    Expr::IsNotUnknown(Box::new(expr))
364}
365
366/// Create a CASE WHEN statement with literal WHEN expressions for comparison to the base expression.
367pub fn case(expr: Expr) -> CaseBuilder {
368    CaseBuilder::new(Some(Box::new(expr)), vec![], vec![], None)
369}
370
371/// Create a CASE WHEN statement with boolean WHEN expressions and no base expression.
372pub fn when(when: Expr, then: Expr) -> CaseBuilder {
373    CaseBuilder::new(None, vec![when], vec![then], None)
374}
375
376/// Create a Unnest expression with default (non-outer) semantics.
377pub fn unnest(expr: Expr) -> Expr {
378    Expr::Unnest(Unnest {
379        expr: Box::new(expr),
380        outer: false,
381    })
382}
383
384/// Convenience method to create a new user defined scalar function (UDF) with a
385/// specific signature and specific return type.
386///
387/// Note this function does not expose all available features of [`ScalarUDF`],
388/// such as
389///
390/// * computing return types based on input types
391/// * multiple [`Signature`]s
392/// * aliases
393///
394/// See [`ScalarUDF`] for details and examples on how to use the full
395/// functionality.
396pub fn create_udf(
397    name: &str,
398    input_types: Vec<DataType>,
399    return_type: DataType,
400    volatility: Volatility,
401    fun: ScalarFunctionImplementation,
402) -> ScalarUDF {
403    ScalarUDF::from(SimpleScalarUDF::new(
404        name,
405        input_types,
406        return_type,
407        volatility,
408        fun,
409    ))
410}
411
412/// Implements [`ScalarUDFImpl`] for functions that have a single signature and
413/// return type.
414#[derive(PartialEq, Eq, Hash)]
415pub struct SimpleScalarUDF {
416    name: String,
417    signature: Signature,
418    return_type: DataType,
419    fun: PtrEq<ScalarFunctionImplementation>,
420}
421
422impl Debug for SimpleScalarUDF {
423    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
424        f.debug_struct("SimpleScalarUDF")
425            .field("name", &self.name)
426            .field("signature", &self.signature)
427            .field("return_type", &self.return_type)
428            .field("fun", &"<FUNC>")
429            .finish()
430    }
431}
432
433impl SimpleScalarUDF {
434    /// Create a new `SimpleScalarUDF` from a name, input types, return type and
435    /// implementation. Implementing [`ScalarUDFImpl`] allows more flexibility
436    pub fn new(
437        name: impl Into<String>,
438        input_types: Vec<DataType>,
439        return_type: DataType,
440        volatility: Volatility,
441        fun: ScalarFunctionImplementation,
442    ) -> Self {
443        Self::new_with_signature(
444            name,
445            Signature::exact(input_types, volatility),
446            return_type,
447            fun,
448        )
449    }
450
451    /// Create a new `SimpleScalarUDF` from a name, signature, return type and
452    /// implementation. Implementing [`ScalarUDFImpl`] allows more flexibility
453    pub fn new_with_signature(
454        name: impl Into<String>,
455        signature: Signature,
456        return_type: DataType,
457        fun: ScalarFunctionImplementation,
458    ) -> Self {
459        Self {
460            name: name.into(),
461            signature,
462            return_type,
463            fun: fun.into(),
464        }
465    }
466}
467
468impl ScalarUDFImpl for SimpleScalarUDF {
469    fn name(&self) -> &str {
470        &self.name
471    }
472
473    fn signature(&self) -> &Signature {
474        &self.signature
475    }
476
477    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
478        Ok(self.return_type.clone())
479    }
480
481    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
482        (self.fun)(&args.args)
483    }
484}
485
486/// Creates a new UDAF with a specific signature, state type and return type.
487/// The signature and state type must match the `Accumulator's implementation`.
488pub fn create_udaf(
489    name: &str,
490    input_type: Vec<DataType>,
491    return_type: Arc<DataType>,
492    volatility: Volatility,
493    accumulator: AccumulatorFactoryFunction,
494    state_type: Arc<Vec<DataType>>,
495) -> AggregateUDF {
496    let return_type = Arc::unwrap_or_clone(return_type);
497    let state_type = Arc::unwrap_or_clone(state_type);
498    let state_fields = state_type
499        .into_iter()
500        .enumerate()
501        .map(|(i, t)| Field::new(format!("{i}"), t, true))
502        .map(Arc::new)
503        .collect::<Vec<_>>();
504    AggregateUDF::from(SimpleAggregateUDF::new(
505        name,
506        input_type,
507        return_type,
508        volatility,
509        accumulator,
510        state_fields,
511    ))
512}
513
514/// Implements [`AggregateUDFImpl`] for functions that have a single signature and
515/// return type.
516#[derive(PartialEq, Eq, Hash)]
517pub struct SimpleAggregateUDF {
518    name: String,
519    signature: Signature,
520    return_type: DataType,
521    accumulator: PtrEq<AccumulatorFactoryFunction>,
522    state_fields: Vec<FieldRef>,
523}
524
525impl Debug for SimpleAggregateUDF {
526    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
527        f.debug_struct("SimpleAggregateUDF")
528            .field("name", &self.name)
529            .field("signature", &self.signature)
530            .field("return_type", &self.return_type)
531            .field("fun", &"<FUNC>")
532            .finish()
533    }
534}
535
536impl SimpleAggregateUDF {
537    /// Create a new `SimpleAggregateUDF` from a name, input types, return type, state type and
538    /// implementation. Implementing [`AggregateUDFImpl`] allows more flexibility
539    pub fn new(
540        name: impl Into<String>,
541        input_type: Vec<DataType>,
542        return_type: DataType,
543        volatility: Volatility,
544        accumulator: AccumulatorFactoryFunction,
545        state_fields: Vec<FieldRef>,
546    ) -> Self {
547        let name = name.into();
548        let signature = Signature::exact(input_type, volatility);
549        Self {
550            name,
551            signature,
552            return_type,
553            accumulator: accumulator.into(),
554            state_fields,
555        }
556    }
557
558    /// Create a new `SimpleAggregateUDF` from a name, signature, return type, state type and
559    /// implementation. Implementing [`AggregateUDFImpl`] allows more flexibility
560    pub fn new_with_signature(
561        name: impl Into<String>,
562        signature: Signature,
563        return_type: DataType,
564        accumulator: AccumulatorFactoryFunction,
565        state_fields: Vec<FieldRef>,
566    ) -> Self {
567        let name = name.into();
568        Self {
569            name,
570            signature,
571            return_type,
572            accumulator: accumulator.into(),
573            state_fields,
574        }
575    }
576}
577
578impl AggregateUDFImpl for SimpleAggregateUDF {
579    fn name(&self) -> &str {
580        &self.name
581    }
582
583    fn signature(&self) -> &Signature {
584        &self.signature
585    }
586
587    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
588        Ok(self.return_type.clone())
589    }
590
591    fn accumulator(
592        &self,
593        acc_args: AccumulatorArgs,
594    ) -> Result<Box<dyn crate::Accumulator>> {
595        (self.accumulator)(acc_args)
596    }
597
598    fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
599        Ok(self.state_fields.clone())
600    }
601}
602
603/// Creates a new UDWF with a specific signature, state type and return type.
604///
605/// The signature and state type must match the [`PartitionEvaluator`]'s implementation`.
606///
607/// [`PartitionEvaluator`]: crate::PartitionEvaluator
608pub fn create_udwf(
609    name: &str,
610    input_type: DataType,
611    return_type: Arc<DataType>,
612    volatility: Volatility,
613    partition_evaluator_factory: PartitionEvaluatorFactory,
614) -> WindowUDF {
615    let return_type = Arc::unwrap_or_clone(return_type);
616    WindowUDF::from(SimpleWindowUDF::new(
617        name,
618        input_type,
619        return_type,
620        volatility,
621        partition_evaluator_factory,
622    ))
623}
624
625/// Implements [`WindowUDFImpl`] for functions that have a single signature and
626/// return type.
627#[derive(PartialEq, Eq, Hash)]
628pub struct SimpleWindowUDF {
629    name: String,
630    signature: Signature,
631    return_type: DataType,
632    partition_evaluator_factory: PtrEq<PartitionEvaluatorFactory>,
633}
634
635impl Debug for SimpleWindowUDF {
636    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
637        f.debug_struct("WindowUDF")
638            .field("name", &self.name)
639            .field("signature", &self.signature)
640            .field("return_type", &"<func>")
641            .field("partition_evaluator_factory", &"<FUNC>")
642            .finish()
643    }
644}
645
646impl SimpleWindowUDF {
647    /// Create a new `SimpleWindowUDF` from a name, input types, return type and
648    /// implementation. Implementing [`WindowUDFImpl`] allows more flexibility
649    pub fn new(
650        name: impl Into<String>,
651        input_type: DataType,
652        return_type: DataType,
653        volatility: Volatility,
654        partition_evaluator_factory: PartitionEvaluatorFactory,
655    ) -> Self {
656        let name = name.into();
657        let signature = Signature::exact([input_type].to_vec(), volatility);
658        Self {
659            name,
660            signature,
661            return_type,
662            partition_evaluator_factory: partition_evaluator_factory.into(),
663        }
664    }
665}
666
667impl WindowUDFImpl for SimpleWindowUDF {
668    fn name(&self) -> &str {
669        &self.name
670    }
671
672    fn signature(&self) -> &Signature {
673        &self.signature
674    }
675
676    fn partition_evaluator(
677        &self,
678        _partition_evaluator_args: PartitionEvaluatorArgs,
679    ) -> Result<Box<dyn PartitionEvaluator>> {
680        (self.partition_evaluator_factory)()
681    }
682
683    fn field(&self, field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
684        Ok(Arc::new(Field::new(
685            field_args.name(),
686            self.return_type.clone(),
687            true,
688        )))
689    }
690
691    fn limit_effect(&self, _args: &[Arc<dyn PhysicalExpr>]) -> LimitEffect {
692        LimitEffect::Unknown
693    }
694}
695
696pub fn interval_year_month_lit(value: &str) -> Expr {
697    let interval = parse_interval_year_month(value).ok();
698    Expr::Literal(ScalarValue::IntervalYearMonth(interval), None)
699}
700
701pub fn interval_datetime_lit(value: &str) -> Expr {
702    let interval = parse_interval_day_time(value).ok();
703    Expr::Literal(ScalarValue::IntervalDayTime(interval), None)
704}
705
706pub fn interval_month_day_nano_lit(value: &str) -> Expr {
707    let interval = parse_interval_month_day_nano(value).ok();
708    Expr::Literal(ScalarValue::IntervalMonthDayNano(interval), None)
709}
710
711/// Create a lambda expression
712pub fn lambda(params: impl IntoIterator<Item = impl Into<String>>, body: Expr) -> Expr {
713    Expr::Lambda(Lambda::new(
714        params.into_iter().map(Into::into).collect(),
715        body,
716    ))
717}
718
719/// Create an unresolved lambda variable expression
720///
721/// The expression tree or [`LogicalPlan`] which
722/// owns this variable must be resolved before usage with either
723/// [`Expr::resolve_lambda_variables`] or [`LogicalPlan::resolve_lambda_variables`].
724///
725/// [LogicalPlan::resolve_lambda_variables]: crate::LogicalPlan::resolve_lambda_variables
726pub fn lambda_var(name: impl Into<String>) -> Expr {
727    Expr::LambdaVariable(LambdaVariable::new(name.into(), None))
728}
729
730/// Extensions for configuring [`Expr::AggregateFunction`] or [`Expr::WindowFunction`]
731///
732/// Adds methods to [`Expr`] that make it easy to set optional options
733/// such as `ORDER BY`, `FILTER` and `DISTINCT`
734///
735/// # Example
736/// ```no_run
737/// # use datafusion_common::Result;
738/// # use datafusion_expr::expr::NullTreatment;
739/// # use datafusion_expr::test::function_stub::count;
740/// # use datafusion_expr::{ExprFunctionExt, lit, Expr, col};
741/// # // first_value is an aggregate function in another crate
742/// # fn first_value(_arg: Expr) -> Expr {
743/// unimplemented!() }
744/// # fn main() -> Result<()> {
745/// // Create an aggregate count, filtering on column y > 5
746/// let agg = count(col("x")).filter(col("y").gt(lit(5))).build()?;
747///
748/// // Find the first value in an aggregate sorted by column y
749/// // equivalent to:
750/// // `FIRST_VALUE(x ORDER BY y ASC IGNORE NULLS)`
751/// let sort_expr = col("y").sort(true, true);
752/// let agg = first_value(col("x"))
753///     .order_by(vec![sort_expr])
754///     .null_treatment(NullTreatment::IgnoreNulls)
755///     .build()?;
756///
757/// // Create a window expression for percent rank partitioned on column a
758/// // equivalent to:
759/// // `PERCENT_RANK() OVER (PARTITION BY a ORDER BY b ASC NULLS LAST IGNORE NULLS)`
760/// // percent_rank is an udwf function in another crate
761/// # fn percent_rank() -> Expr {
762/// unimplemented!() }
763/// let window = percent_rank()
764///     .partition_by(vec![col("a")])
765///     .order_by(vec![col("b").sort(true, true)])
766///     .null_treatment(NullTreatment::IgnoreNulls)
767///     .build()?;
768/// #     Ok(())
769/// # }
770/// ```
771pub trait ExprFunctionExt {
772    /// Add `ORDER BY <order_by>`
773    fn order_by(self, order_by: Vec<Sort>) -> ExprFuncBuilder;
774    /// Add `FILTER <filter>`
775    fn filter(self, filter: Expr) -> ExprFuncBuilder;
776    /// Add `DISTINCT`
777    fn distinct(self) -> ExprFuncBuilder;
778    /// Add `RESPECT NULLS` or `IGNORE NULLS`
779    fn null_treatment(
780        self,
781        null_treatment: impl Into<Option<NullTreatment>>,
782    ) -> ExprFuncBuilder;
783    /// Add `PARTITION BY`
784    fn partition_by(self, partition_by: Vec<Expr>) -> ExprFuncBuilder;
785    /// Add appropriate window frame conditions
786    fn window_frame(self, window_frame: WindowFrame) -> ExprFuncBuilder;
787}
788
789#[derive(Debug, Clone)]
790pub enum ExprFuncKind {
791    Aggregate(AggregateFunction),
792    Window(Box<WindowFunction>),
793}
794
795/// Implementation of [`ExprFunctionExt`].
796///
797/// See [`ExprFunctionExt`] for usage and examples
798#[derive(Debug, Clone)]
799pub struct ExprFuncBuilder {
800    fun: Option<ExprFuncKind>,
801    order_by: Option<Vec<Sort>>,
802    filter: Option<Expr>,
803    distinct: bool,
804    null_treatment: Option<NullTreatment>,
805    partition_by: Option<Vec<Expr>>,
806    window_frame: Option<WindowFrame>,
807}
808
809impl ExprFuncBuilder {
810    /// Create a new `ExprFuncBuilder`, see [`ExprFunctionExt`]
811    fn new(fun: Option<ExprFuncKind>) -> Self {
812        Self {
813            fun,
814            order_by: None,
815            filter: None,
816            distinct: false,
817            null_treatment: None,
818            partition_by: None,
819            window_frame: None,
820        }
821    }
822
823    /// Updates and returns the in progress [`Expr::AggregateFunction`] or [`Expr::WindowFunction`]
824    ///
825    /// # Errors:
826    ///
827    /// Returns an error if this builder  [`ExprFunctionExt`] was used with an
828    /// `Expr` variant other than [`Expr::AggregateFunction`] or [`Expr::WindowFunction`]
829    pub fn build(self) -> Result<Expr> {
830        let Self {
831            fun,
832            order_by,
833            filter,
834            distinct,
835            null_treatment,
836            partition_by,
837            window_frame,
838        } = self;
839
840        let Some(fun) = fun else {
841            return plan_err!(
842                "ExprFunctionExt can only be used with Expr::AggregateFunction or Expr::WindowFunction"
843            );
844        };
845
846        let fun_expr = match fun {
847            ExprFuncKind::Aggregate(mut udaf) => {
848                udaf.params.order_by = order_by.unwrap_or_default();
849                udaf.params.filter = filter.map(Box::new);
850                udaf.params.distinct = distinct;
851                udaf.params.null_treatment = null_treatment;
852                Expr::AggregateFunction(udaf)
853            }
854            ExprFuncKind::Window(mut udwf) => {
855                let has_order_by = order_by.as_ref().map(|o| !o.is_empty());
856                udwf.params.partition_by = partition_by.unwrap_or_default();
857                udwf.params.order_by = order_by.unwrap_or_default();
858                udwf.params.window_frame =
859                    window_frame.unwrap_or_else(|| WindowFrame::new(has_order_by));
860                udwf.params.filter = filter.map(Box::new);
861                udwf.params.null_treatment = null_treatment;
862                udwf.params.distinct = distinct;
863                Expr::WindowFunction(udwf)
864            }
865        };
866
867        Ok(fun_expr)
868    }
869}
870
871impl ExprFunctionExt for ExprFuncBuilder {
872    /// Add `ORDER BY <order_by>`
873    fn order_by(mut self, order_by: Vec<Sort>) -> ExprFuncBuilder {
874        self.order_by = Some(order_by);
875        self
876    }
877
878    /// Add `FILTER <filter>`
879    fn filter(mut self, filter: Expr) -> ExprFuncBuilder {
880        self.filter = Some(filter);
881        self
882    }
883
884    /// Add `DISTINCT`
885    fn distinct(mut self) -> ExprFuncBuilder {
886        self.distinct = true;
887        self
888    }
889
890    /// Add `RESPECT NULLS` or `IGNORE NULLS`
891    fn null_treatment(
892        mut self,
893        null_treatment: impl Into<Option<NullTreatment>>,
894    ) -> ExprFuncBuilder {
895        self.null_treatment = null_treatment.into();
896        self
897    }
898
899    fn partition_by(mut self, partition_by: Vec<Expr>) -> ExprFuncBuilder {
900        self.partition_by = Some(partition_by);
901        self
902    }
903
904    fn window_frame(mut self, window_frame: WindowFrame) -> ExprFuncBuilder {
905        self.window_frame = Some(window_frame);
906        self
907    }
908}
909
910impl ExprFunctionExt for Expr {
911    fn order_by(self, order_by: Vec<Sort>) -> ExprFuncBuilder {
912        let mut builder = match self {
913            Expr::AggregateFunction(udaf) => {
914                ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)))
915            }
916            Expr::WindowFunction(udwf) => {
917                ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)))
918            }
919            _ => ExprFuncBuilder::new(None),
920        };
921        if builder.fun.is_some() {
922            builder.order_by = Some(order_by);
923        }
924        builder
925    }
926    fn filter(self, filter: Expr) -> ExprFuncBuilder {
927        match self {
928            Expr::AggregateFunction(udaf) => {
929                let mut builder =
930                    ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)));
931                builder.filter = Some(filter);
932                builder
933            }
934            _ => ExprFuncBuilder::new(None),
935        }
936    }
937    fn distinct(self) -> ExprFuncBuilder {
938        match self {
939            Expr::AggregateFunction(udaf) => {
940                let mut builder =
941                    ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)));
942                builder.distinct = true;
943                builder
944            }
945            _ => ExprFuncBuilder::new(None),
946        }
947    }
948    fn null_treatment(
949        self,
950        null_treatment: impl Into<Option<NullTreatment>>,
951    ) -> ExprFuncBuilder {
952        let mut builder = match self {
953            Expr::AggregateFunction(udaf) => {
954                ExprFuncBuilder::new(Some(ExprFuncKind::Aggregate(udaf)))
955            }
956            Expr::WindowFunction(udwf) => {
957                ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)))
958            }
959            _ => ExprFuncBuilder::new(None),
960        };
961        if builder.fun.is_some() {
962            builder.null_treatment = null_treatment.into();
963        }
964        builder
965    }
966
967    fn partition_by(self, partition_by: Vec<Expr>) -> ExprFuncBuilder {
968        match self {
969            Expr::WindowFunction(udwf) => {
970                let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)));
971                builder.partition_by = Some(partition_by);
972                builder
973            }
974            _ => ExprFuncBuilder::new(None),
975        }
976    }
977
978    fn window_frame(self, window_frame: WindowFrame) -> ExprFuncBuilder {
979        match self {
980            Expr::WindowFunction(udwf) => {
981                let mut builder = ExprFuncBuilder::new(Some(ExprFuncKind::Window(udwf)));
982                builder.window_frame = Some(window_frame);
983                builder
984            }
985            _ => ExprFuncBuilder::new(None),
986        }
987    }
988}
989
990#[cfg(test)]
991mod test {
992    use super::*;
993
994    #[test]
995    fn filter_is_null_and_is_not_null() {
996        let col_null = col("col1");
997        let col_not_null = ident("col2");
998        assert_eq!(format!("{}", col_null.is_null()), "col1 IS NULL");
999        assert_eq!(
1000            format!("{}", col_not_null.is_not_null()),
1001            "col2 IS NOT NULL"
1002        );
1003    }
1004}