1use datafusion::logical_expr::expr::{AggregateFunctionParams, FieldMetadata};
19use datafusion::logical_expr::utils::exprlist_to_fields;
20use datafusion::logical_expr::{
21 lit_with_metadata, ExprFuncBuilder, ExprFunctionExt, LogicalPlan, WindowFunctionDefinition,
22};
23use pyo3::IntoPyObjectExt;
24use pyo3::{basic::CompareOp, prelude::*};
25use std::collections::HashMap;
26use std::convert::{From, Into};
27use std::sync::Arc;
28use window::PyWindowFrame;
29
30use datafusion::arrow::datatypes::{DataType, Field};
31use datafusion::arrow::pyarrow::PyArrowType;
32use datafusion::functions::core::expr_ext::FieldAccessor;
33use datafusion::logical_expr::{
34 col,
35 expr::{AggregateFunction, InList, InSubquery, ScalarFunction, WindowFunction},
36 lit, Between, BinaryExpr, Case, Cast, Expr, Like, Operator, TryCast,
37};
38
39use crate::common::data_type::{DataTypeMap, NullTreatment, PyScalarValue, RexType};
40use crate::errors::{py_runtime_err, py_type_err, py_unsupported_variant_err, PyDataFusionResult};
41use crate::expr::aggregate_expr::PyAggregateFunction;
42use crate::expr::binary_expr::PyBinaryExpr;
43use crate::expr::column::PyColumn;
44use crate::expr::literal::PyLiteral;
45use crate::functions::add_builder_fns_to_window;
46use crate::pyarrow_util::scalar_to_pyarrow;
47use crate::sql::logical::PyLogicalPlan;
48
49use self::alias::PyAlias;
50use self::bool_expr::{
51 PyIsFalse, PyIsNotFalse, PyIsNotNull, PyIsNotTrue, PyIsNotUnknown, PyIsNull, PyIsTrue,
52 PyIsUnknown, PyNegative, PyNot,
53};
54use self::like::{PyILike, PyLike, PySimilarTo};
55use self::scalar_variable::PyScalarVariable;
56
57pub mod aggregate;
58pub mod aggregate_expr;
59pub mod alias;
60pub mod analyze;
61pub mod between;
62pub mod binary_expr;
63pub mod bool_expr;
64pub mod case;
65pub mod cast;
66pub mod column;
67pub mod conditional_expr;
68pub mod copy_to;
69pub mod create_catalog;
70pub mod create_catalog_schema;
71pub mod create_external_table;
72pub mod create_function;
73pub mod create_index;
74pub mod create_memory_table;
75pub mod create_view;
76pub mod describe_table;
77pub mod distinct;
78pub mod dml;
79pub mod drop_catalog_schema;
80pub mod drop_function;
81pub mod drop_table;
82pub mod drop_view;
83pub mod empty_relation;
84pub mod exists;
85pub mod explain;
86pub mod extension;
87pub mod filter;
88pub mod grouping_set;
89pub mod in_list;
90pub mod in_subquery;
91pub mod join;
92pub mod like;
93pub mod limit;
94pub mod literal;
95pub mod logical_node;
96pub mod placeholder;
97pub mod projection;
98pub mod recursive_query;
99pub mod repartition;
100pub mod scalar_subquery;
101pub mod scalar_variable;
102pub mod signature;
103pub mod sort;
104pub mod sort_expr;
105pub mod statement;
106pub mod subquery;
107pub mod subquery_alias;
108pub mod table_scan;
109pub mod union;
110pub mod unnest;
111pub mod unnest_expr;
112pub mod values;
113pub mod window;
114
115use sort_expr::{to_sort_expressions, PySortExpr};
116
117#[pyclass(name = "RawExpr", module = "datafusion.expr", subclass)]
119#[derive(Debug, Clone)]
120pub struct PyExpr {
121 pub expr: Expr,
122}
123
124impl From<PyExpr> for Expr {
125 fn from(expr: PyExpr) -> Expr {
126 expr.expr
127 }
128}
129
130impl From<Expr> for PyExpr {
131 fn from(expr: Expr) -> PyExpr {
132 PyExpr { expr }
133 }
134}
135
136pub fn py_expr_list(expr: &[Expr]) -> PyResult<Vec<PyExpr>> {
138 Ok(expr.iter().map(|e| PyExpr::from(e.clone())).collect())
139}
140
141#[pymethods]
142impl PyExpr {
143 fn to_variant<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
145 Python::with_gil(|_| {
146 match &self.expr {
147 Expr::Alias(alias) => Ok(PyAlias::from(alias.clone()).into_bound_py_any(py)?),
148 Expr::Column(col) => Ok(PyColumn::from(col.clone()).into_bound_py_any(py)?),
149 Expr::ScalarVariable(data_type, variables) => {
150 Ok(PyScalarVariable::new(data_type, variables).into_bound_py_any(py)?)
151 }
152 Expr::Like(value) => Ok(PyLike::from(value.clone()).into_bound_py_any(py)?),
153 Expr::Literal(value, metadata) => Ok(PyLiteral::new_with_metadata(value.clone(), metadata.clone()).into_bound_py_any(py)?),
154 Expr::BinaryExpr(expr) => Ok(PyBinaryExpr::from(expr.clone()).into_bound_py_any(py)?),
155 Expr::Not(expr) => Ok(PyNot::new(*expr.clone()).into_bound_py_any(py)?),
156 Expr::IsNotNull(expr) => Ok(PyIsNotNull::new(*expr.clone()).into_bound_py_any(py)?),
157 Expr::IsNull(expr) => Ok(PyIsNull::new(*expr.clone()).into_bound_py_any(py)?),
158 Expr::IsTrue(expr) => Ok(PyIsTrue::new(*expr.clone()).into_bound_py_any(py)?),
159 Expr::IsFalse(expr) => Ok(PyIsFalse::new(*expr.clone()).into_bound_py_any(py)?),
160 Expr::IsUnknown(expr) => Ok(PyIsUnknown::new(*expr.clone()).into_bound_py_any(py)?),
161 Expr::IsNotTrue(expr) => Ok(PyIsNotTrue::new(*expr.clone()).into_bound_py_any(py)?),
162 Expr::IsNotFalse(expr) => Ok(PyIsNotFalse::new(*expr.clone()).into_bound_py_any(py)?),
163 Expr::IsNotUnknown(expr) => Ok(PyIsNotUnknown::new(*expr.clone()).into_bound_py_any(py)?),
164 Expr::Negative(expr) => Ok(PyNegative::new(*expr.clone()).into_bound_py_any(py)?),
165 Expr::AggregateFunction(expr) => {
166 Ok(PyAggregateFunction::from(expr.clone()).into_bound_py_any(py)?)
167 }
168 Expr::SimilarTo(value) => Ok(PySimilarTo::from(value.clone()).into_bound_py_any(py)?),
169 Expr::Between(value) => Ok(between::PyBetween::from(value.clone()).into_bound_py_any(py)?),
170 Expr::Case(value) => Ok(case::PyCase::from(value.clone()).into_bound_py_any(py)?),
171 Expr::Cast(value) => Ok(cast::PyCast::from(value.clone()).into_bound_py_any(py)?),
172 Expr::TryCast(value) => Ok(cast::PyTryCast::from(value.clone()).into_bound_py_any(py)?),
173 Expr::ScalarFunction(value) => Err(py_unsupported_variant_err(format!(
174 "Converting Expr::ScalarFunction to a Python object is not implemented: {value:?}"
175 ))),
176 Expr::WindowFunction(value) => Err(py_unsupported_variant_err(format!(
177 "Converting Expr::WindowFunction to a Python object is not implemented: {value:?}"
178 ))),
179 Expr::InList(value) => Ok(in_list::PyInList::from(value.clone()).into_bound_py_any(py)?),
180 Expr::Exists(value) => Ok(exists::PyExists::from(value.clone()).into_bound_py_any(py)?),
181 Expr::InSubquery(value) => {
182 Ok(in_subquery::PyInSubquery::from(value.clone()).into_bound_py_any(py)?)
183 }
184 Expr::ScalarSubquery(value) => {
185 Ok(scalar_subquery::PyScalarSubquery::from(value.clone()).into_bound_py_any(py)?)
186 }
187 #[allow(deprecated)]
188 Expr::Wildcard { qualifier, options } => Err(py_unsupported_variant_err(format!(
189 "Converting Expr::Wildcard to a Python object is not implemented : {qualifier:?} {options:?}"
190 ))),
191 Expr::GroupingSet(value) => {
192 Ok(grouping_set::PyGroupingSet::from(value.clone()).into_bound_py_any(py)?)
193 }
194 Expr::Placeholder(value) => {
195 Ok(placeholder::PyPlaceholder::from(value.clone()).into_bound_py_any(py)?)
196 }
197 Expr::OuterReferenceColumn(data_type, column) => Err(py_unsupported_variant_err(format!(
198 "Converting Expr::OuterReferenceColumn to a Python object is not implemented: {data_type:?} - {column:?}"
199 ))),
200 Expr::Unnest(value) => Ok(unnest_expr::PyUnnestExpr::from(value.clone()).into_bound_py_any(py)?),
201 }
202 })
203 }
204
205 fn schema_name(&self) -> PyResult<String> {
208 Ok(format!("{}", self.expr.schema_name()))
209 }
210
211 fn canonical_name(&self) -> PyResult<String> {
213 Ok(format!("{}", self.expr))
214 }
215
216 fn variant_name(&self) -> PyResult<&str> {
219 Ok(self.expr.variant_name())
220 }
221
222 fn __richcmp__(&self, other: PyExpr, op: CompareOp) -> PyExpr {
223 let expr = match op {
224 CompareOp::Lt => self.expr.clone().lt(other.expr),
225 CompareOp::Le => self.expr.clone().lt_eq(other.expr),
226 CompareOp::Eq => self.expr.clone().eq(other.expr),
227 CompareOp::Ne => self.expr.clone().not_eq(other.expr),
228 CompareOp::Gt => self.expr.clone().gt(other.expr),
229 CompareOp::Ge => self.expr.clone().gt_eq(other.expr),
230 };
231 expr.into()
232 }
233
234 fn __repr__(&self) -> PyResult<String> {
235 Ok(format!("Expr({})", self.expr))
236 }
237
238 fn __add__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
239 Ok((self.expr.clone() + rhs.expr).into())
240 }
241
242 fn __sub__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
243 Ok((self.expr.clone() - rhs.expr).into())
244 }
245
246 fn __truediv__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
247 Ok((self.expr.clone() / rhs.expr).into())
248 }
249
250 fn __mul__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
251 Ok((self.expr.clone() * rhs.expr).into())
252 }
253
254 fn __mod__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
255 let expr = self.expr.clone() % rhs.expr;
256 Ok(expr.into())
257 }
258
259 fn __and__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
260 Ok(self.expr.clone().and(rhs.expr).into())
261 }
262
263 fn __or__(&self, rhs: PyExpr) -> PyResult<PyExpr> {
264 Ok(self.expr.clone().or(rhs.expr).into())
265 }
266
267 fn __invert__(&self) -> PyResult<PyExpr> {
268 let expr = !self.expr.clone();
269 Ok(expr.into())
270 }
271
272 fn __getitem__(&self, key: &str) -> PyResult<PyExpr> {
273 Ok(self.expr.clone().field(key).into())
274 }
275
276 #[staticmethod]
277 pub fn literal(value: PyScalarValue) -> PyExpr {
278 lit(value.0).into()
279 }
280
281 #[staticmethod]
282 pub fn literal_with_metadata(
283 value: PyScalarValue,
284 metadata: HashMap<String, String>,
285 ) -> PyExpr {
286 let metadata = FieldMetadata::new(metadata.into_iter().collect());
287 lit_with_metadata(value.0, Some(metadata)).into()
288 }
289
290 #[staticmethod]
291 pub fn column(value: &str) -> PyExpr {
292 col(value).into()
293 }
294
295 #[pyo3(signature = (name, metadata=None))]
297 pub fn alias(&self, name: &str, metadata: Option<HashMap<String, String>>) -> PyExpr {
298 let metadata = metadata.map(|m| FieldMetadata::new(m.into_iter().collect()));
299 self.expr.clone().alias_with_metadata(name, metadata).into()
300 }
301
302 #[pyo3(signature = (ascending=true, nulls_first=true))]
304 pub fn sort(&self, ascending: bool, nulls_first: bool) -> PySortExpr {
305 self.expr.clone().sort(ascending, nulls_first).into()
306 }
307
308 pub fn is_null(&self) -> PyExpr {
309 self.expr.clone().is_null().into()
310 }
311
312 pub fn is_not_null(&self) -> PyExpr {
313 self.expr.clone().is_not_null().into()
314 }
315
316 pub fn cast(&self, to: PyArrowType<DataType>) -> PyExpr {
317 let expr = Expr::Cast(Cast::new(Box::new(self.expr.clone()), to.0));
320 expr.into()
321 }
322
323 #[pyo3(signature = (low, high, negated=false))]
324 pub fn between(&self, low: PyExpr, high: PyExpr, negated: bool) -> PyExpr {
325 let expr = Expr::Between(Between::new(
326 Box::new(self.expr.clone()),
327 negated,
328 Box::new(low.into()),
329 Box::new(high.into()),
330 ));
331 expr.into()
332 }
333
334 pub fn rex_type(&self) -> PyResult<RexType> {
338 Ok(match self.expr {
339 Expr::Alias(..) => RexType::Alias,
340 Expr::Column(..) => RexType::Reference,
341 Expr::ScalarVariable(..) | Expr::Literal(..) => RexType::Literal,
342 Expr::BinaryExpr { .. }
343 | Expr::Not(..)
344 | Expr::IsNotNull(..)
345 | Expr::Negative(..)
346 | Expr::IsNull(..)
347 | Expr::Like { .. }
348 | Expr::SimilarTo { .. }
349 | Expr::Between { .. }
350 | Expr::Case { .. }
351 | Expr::Cast { .. }
352 | Expr::TryCast { .. }
353 | Expr::ScalarFunction { .. }
354 | Expr::AggregateFunction { .. }
355 | Expr::WindowFunction { .. }
356 | Expr::InList { .. }
357 | Expr::Exists { .. }
358 | Expr::InSubquery { .. }
359 | Expr::GroupingSet(..)
360 | Expr::IsTrue(..)
361 | Expr::IsFalse(..)
362 | Expr::IsUnknown(_)
363 | Expr::IsNotTrue(..)
364 | Expr::IsNotFalse(..)
365 | Expr::Placeholder { .. }
366 | Expr::OuterReferenceColumn(_, _)
367 | Expr::Unnest(_)
368 | Expr::IsNotUnknown(_) => RexType::Call,
369 Expr::ScalarSubquery(..) => RexType::ScalarSubquery,
370 #[allow(deprecated)]
371 Expr::Wildcard { .. } => {
372 return Err(py_unsupported_variant_err("Expr::Wildcard is unsupported"))
373 }
374 })
375 }
376
377 pub fn types(&self) -> PyResult<DataTypeMap> {
380 Self::_types(&self.expr)
381 }
382
383 pub fn python_value(&self, py: Python) -> PyResult<PyObject> {
385 match &self.expr {
386 Expr::Literal(scalar_value, _) => scalar_to_pyarrow(scalar_value, py),
387 _ => Err(py_type_err(format!(
388 "Non Expr::Literal encountered in types: {:?}",
389 &self.expr
390 ))),
391 }
392 }
393
394 pub fn rex_call_operands(&self) -> PyResult<Vec<PyExpr>> {
398 match &self.expr {
399 Expr::Column(..) | Expr::ScalarVariable(..) | Expr::Literal(..) => {
401 Ok(vec![PyExpr::from(self.expr.clone())])
402 }
403
404 Expr::Alias(alias) => Ok(vec![PyExpr::from(*alias.expr.clone())]),
405
406 Expr::Not(expr)
408 | Expr::IsNull(expr)
409 | Expr::IsNotNull(expr)
410 | Expr::IsTrue(expr)
411 | Expr::IsFalse(expr)
412 | Expr::IsUnknown(expr)
413 | Expr::IsNotTrue(expr)
414 | Expr::IsNotFalse(expr)
415 | Expr::IsNotUnknown(expr)
416 | Expr::Negative(expr)
417 | Expr::Cast(Cast { expr, .. })
418 | Expr::TryCast(TryCast { expr, .. })
419 | Expr::InSubquery(InSubquery { expr, .. }) => Ok(vec![PyExpr::from(*expr.clone())]),
420
421 Expr::AggregateFunction(AggregateFunction {
423 params: AggregateFunctionParams { args, .. },
424 ..
425 })
426 | Expr::ScalarFunction(ScalarFunction { args, .. }) => {
427 Ok(args.iter().map(|arg| PyExpr::from(arg.clone())).collect())
428 }
429 Expr::WindowFunction(boxed_window_fn) => {
430 let args = &boxed_window_fn.params.args;
431 Ok(args.iter().map(|arg| PyExpr::from(arg.clone())).collect())
432 }
433
434 Expr::Case(Case {
436 expr,
437 when_then_expr,
438 else_expr,
439 }) => {
440 let mut operands: Vec<PyExpr> = Vec::new();
441
442 if let Some(e) = expr {
443 for (when, then) in when_then_expr {
444 operands.push(PyExpr::from(Expr::BinaryExpr(BinaryExpr::new(
445 Box::new(*e.clone()),
446 Operator::Eq,
447 Box::new(*when.clone()),
448 ))));
449 operands.push(PyExpr::from(*then.clone()));
450 }
451 } else {
452 for (when, then) in when_then_expr {
453 operands.push(PyExpr::from(*when.clone()));
454 operands.push(PyExpr::from(*then.clone()));
455 }
456 };
457
458 if let Some(e) = else_expr {
459 operands.push(PyExpr::from(*e.clone()));
460 };
461
462 Ok(operands)
463 }
464 Expr::InList(InList { expr, list, .. }) => {
465 let mut operands: Vec<PyExpr> = vec![PyExpr::from(*expr.clone())];
466 for list_elem in list {
467 operands.push(PyExpr::from(list_elem.clone()));
468 }
469
470 Ok(operands)
471 }
472 Expr::BinaryExpr(BinaryExpr { left, right, .. }) => Ok(vec![
473 PyExpr::from(*left.clone()),
474 PyExpr::from(*right.clone()),
475 ]),
476 Expr::Like(Like { expr, pattern, .. }) => Ok(vec![
477 PyExpr::from(*expr.clone()),
478 PyExpr::from(*pattern.clone()),
479 ]),
480 Expr::SimilarTo(Like { expr, pattern, .. }) => Ok(vec![
481 PyExpr::from(*expr.clone()),
482 PyExpr::from(*pattern.clone()),
483 ]),
484 Expr::Between(Between {
485 expr,
486 negated: _,
487 low,
488 high,
489 }) => Ok(vec![
490 PyExpr::from(*expr.clone()),
491 PyExpr::from(*low.clone()),
492 PyExpr::from(*high.clone()),
493 ]),
494
495 Expr::GroupingSet(..)
497 | Expr::Unnest(_)
498 | Expr::OuterReferenceColumn(_, _)
499 | Expr::ScalarSubquery(..)
500 | Expr::Placeholder { .. }
501 | Expr::Exists { .. } => Err(py_runtime_err(format!(
502 "Unimplemented Expr type: {}",
503 self.expr
504 ))),
505
506 #[allow(deprecated)]
507 Expr::Wildcard { .. } => {
508 Err(py_unsupported_variant_err("Expr::Wildcard is unsupported"))
509 }
510 }
511 }
512
513 pub fn rex_call_operator(&self) -> PyResult<String> {
515 Ok(match &self.expr {
516 Expr::BinaryExpr(BinaryExpr {
517 left: _,
518 op,
519 right: _,
520 }) => format!("{op}"),
521 Expr::ScalarFunction(ScalarFunction { func, args: _ }) => func.name().to_string(),
522 Expr::Cast { .. } => "cast".to_string(),
523 Expr::Between { .. } => "between".to_string(),
524 Expr::Case { .. } => "case".to_string(),
525 Expr::IsNull(..) => "is null".to_string(),
526 Expr::IsNotNull(..) => "is not null".to_string(),
527 Expr::IsTrue(_) => "is true".to_string(),
528 Expr::IsFalse(_) => "is false".to_string(),
529 Expr::IsUnknown(_) => "is unknown".to_string(),
530 Expr::IsNotTrue(_) => "is not true".to_string(),
531 Expr::IsNotFalse(_) => "is not false".to_string(),
532 Expr::IsNotUnknown(_) => "is not unknown".to_string(),
533 Expr::InList { .. } => "in list".to_string(),
534 Expr::Negative(..) => "negative".to_string(),
535 Expr::Not(..) => "not".to_string(),
536 Expr::Like(Like {
537 negated,
538 case_insensitive,
539 ..
540 }) => {
541 let name = if *case_insensitive { "ilike" } else { "like" };
542 if *negated {
543 format!("not {name}")
544 } else {
545 name.to_string()
546 }
547 }
548 Expr::SimilarTo(Like { negated, .. }) => {
549 if *negated {
550 "not similar to".to_string()
551 } else {
552 "similar to".to_string()
553 }
554 }
555 _ => {
556 return Err(py_type_err(format!(
557 "Catch all triggered in get_operator_name: {:?}",
558 &self.expr
559 )))
560 }
561 })
562 }
563
564 pub fn column_name(&self, plan: PyLogicalPlan) -> PyResult<String> {
565 self._column_name(&plan.plan()).map_err(py_runtime_err)
566 }
567
568 pub fn order_by(&self, order_by: Vec<PySortExpr>) -> PyExprFuncBuilder {
571 self.expr
572 .clone()
573 .order_by(to_sort_expressions(order_by))
574 .into()
575 }
576
577 pub fn filter(&self, filter: PyExpr) -> PyExprFuncBuilder {
578 self.expr.clone().filter(filter.expr.clone()).into()
579 }
580
581 pub fn distinct(&self) -> PyExprFuncBuilder {
582 self.expr.clone().distinct().into()
583 }
584
585 pub fn null_treatment(&self, null_treatment: NullTreatment) -> PyExprFuncBuilder {
586 self.expr
587 .clone()
588 .null_treatment(Some(null_treatment.into()))
589 .into()
590 }
591
592 pub fn partition_by(&self, partition_by: Vec<PyExpr>) -> PyExprFuncBuilder {
593 let partition_by = partition_by.iter().map(|e| e.expr.clone()).collect();
594 self.expr.clone().partition_by(partition_by).into()
595 }
596
597 pub fn window_frame(&self, window_frame: PyWindowFrame) -> PyExprFuncBuilder {
598 self.expr.clone().window_frame(window_frame.into()).into()
599 }
600
601 #[pyo3(signature = (partition_by=None, window_frame=None, order_by=None, null_treatment=None))]
602 pub fn over(
603 &self,
604 partition_by: Option<Vec<PyExpr>>,
605 window_frame: Option<PyWindowFrame>,
606 order_by: Option<Vec<PySortExpr>>,
607 null_treatment: Option<NullTreatment>,
608 ) -> PyDataFusionResult<PyExpr> {
609 match &self.expr {
610 Expr::AggregateFunction(agg_fn) => {
611 let window_fn = Expr::WindowFunction(Box::new(WindowFunction::new(
612 WindowFunctionDefinition::AggregateUDF(agg_fn.func.clone()),
613 agg_fn.params.args.clone(),
614 )));
615
616 add_builder_fns_to_window(
617 window_fn,
618 partition_by,
619 window_frame,
620 order_by,
621 null_treatment,
622 )
623 }
624 Expr::WindowFunction(_) => add_builder_fns_to_window(
625 self.expr.clone(),
626 partition_by,
627 window_frame,
628 order_by,
629 null_treatment,
630 ),
631 _ => Err(datafusion::error::DataFusionError::Plan(format!(
632 "Using {} with `over` is not allowed. Must use an aggregate or window function.",
633 self.expr.variant_name()
634 ))
635 .into()),
636 }
637 }
638}
639
640#[pyclass(name = "ExprFuncBuilder", module = "datafusion.expr", subclass)]
641#[derive(Debug, Clone)]
642pub struct PyExprFuncBuilder {
643 pub builder: ExprFuncBuilder,
644}
645
646impl From<ExprFuncBuilder> for PyExprFuncBuilder {
647 fn from(builder: ExprFuncBuilder) -> Self {
648 Self { builder }
649 }
650}
651
652#[pymethods]
653impl PyExprFuncBuilder {
654 pub fn order_by(&self, order_by: Vec<PySortExpr>) -> PyExprFuncBuilder {
655 self.builder
656 .clone()
657 .order_by(to_sort_expressions(order_by))
658 .into()
659 }
660
661 pub fn filter(&self, filter: PyExpr) -> PyExprFuncBuilder {
662 self.builder.clone().filter(filter.expr.clone()).into()
663 }
664
665 pub fn distinct(&self) -> PyExprFuncBuilder {
666 self.builder.clone().distinct().into()
667 }
668
669 pub fn null_treatment(&self, null_treatment: NullTreatment) -> PyExprFuncBuilder {
670 self.builder
671 .clone()
672 .null_treatment(Some(null_treatment.into()))
673 .into()
674 }
675
676 pub fn partition_by(&self, partition_by: Vec<PyExpr>) -> PyExprFuncBuilder {
677 let partition_by = partition_by.iter().map(|e| e.expr.clone()).collect();
678 self.builder.clone().partition_by(partition_by).into()
679 }
680
681 pub fn window_frame(&self, window_frame: PyWindowFrame) -> PyExprFuncBuilder {
682 self.builder
683 .clone()
684 .window_frame(window_frame.into())
685 .into()
686 }
687
688 pub fn build(&self) -> PyDataFusionResult<PyExpr> {
689 Ok(self.builder.clone().build().map(|expr| expr.into())?)
690 }
691}
692
693impl PyExpr {
694 pub fn _column_name(&self, plan: &LogicalPlan) -> PyDataFusionResult<String> {
695 let field = Self::expr_to_field(&self.expr, plan)?;
696 Ok(field.name().to_owned())
697 }
698
699 pub fn expr_to_field(expr: &Expr, input_plan: &LogicalPlan) -> PyDataFusionResult<Arc<Field>> {
701 let fields = exprlist_to_fields(std::slice::from_ref(expr), input_plan)?;
702 Ok(fields[0].1.clone())
703 }
704 fn _types(expr: &Expr) -> PyResult<DataTypeMap> {
705 match expr {
706 Expr::BinaryExpr(BinaryExpr {
707 left: _,
708 op,
709 right: _,
710 }) => match op {
711 Operator::Eq
712 | Operator::NotEq
713 | Operator::Lt
714 | Operator::LtEq
715 | Operator::Gt
716 | Operator::GtEq
717 | Operator::And
718 | Operator::Or
719 | Operator::IsDistinctFrom
720 | Operator::IsNotDistinctFrom
721 | Operator::RegexMatch
722 | Operator::RegexIMatch
723 | Operator::RegexNotMatch
724 | Operator::RegexNotIMatch
725 | Operator::LikeMatch
726 | Operator::ILikeMatch
727 | Operator::NotLikeMatch
728 | Operator::NotILikeMatch => DataTypeMap::map_from_arrow_type(&DataType::Boolean),
729 Operator::Plus | Operator::Minus | Operator::Multiply | Operator::Modulo => {
730 DataTypeMap::map_from_arrow_type(&DataType::Int64)
731 }
732 Operator::Divide => DataTypeMap::map_from_arrow_type(&DataType::Float64),
733 Operator::StringConcat => DataTypeMap::map_from_arrow_type(&DataType::Utf8),
734 Operator::BitwiseShiftLeft
735 | Operator::BitwiseShiftRight
736 | Operator::BitwiseXor
737 | Operator::BitwiseAnd
738 | Operator::BitwiseOr => DataTypeMap::map_from_arrow_type(&DataType::Binary),
739 Operator::AtArrow
740 | Operator::ArrowAt
741 | Operator::Arrow
742 | Operator::LongArrow
743 | Operator::HashArrow
744 | Operator::HashLongArrow
745 | Operator::AtAt
746 | Operator::IntegerDivide
747 | Operator::HashMinus
748 | Operator::AtQuestion
749 | Operator::Question
750 | Operator::QuestionAnd
751 | Operator::QuestionPipe => Err(py_type_err(format!("Unsupported expr: ${op}"))),
752 },
753 Expr::Cast(Cast { expr: _, data_type }) => DataTypeMap::map_from_arrow_type(data_type),
754 Expr::Literal(scalar_value, _) => DataTypeMap::map_from_scalar_value(scalar_value),
755 _ => Err(py_type_err(format!(
756 "Non Expr::Literal encountered in types: {expr:?}"
757 ))),
758 }
759 }
760}
761
762pub(crate) fn init_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
764 m.add_class::<PyExpr>()?;
765 m.add_class::<PyColumn>()?;
766 m.add_class::<PyLiteral>()?;
767 m.add_class::<PyBinaryExpr>()?;
768 m.add_class::<PyLiteral>()?;
769 m.add_class::<PyAggregateFunction>()?;
770 m.add_class::<PyNot>()?;
771 m.add_class::<PyIsNotNull>()?;
772 m.add_class::<PyIsNull>()?;
773 m.add_class::<PyIsTrue>()?;
774 m.add_class::<PyIsFalse>()?;
775 m.add_class::<PyIsUnknown>()?;
776 m.add_class::<PyIsNotTrue>()?;
777 m.add_class::<PyIsNotFalse>()?;
778 m.add_class::<PyIsNotUnknown>()?;
779 m.add_class::<PyNegative>()?;
780 m.add_class::<PyLike>()?;
781 m.add_class::<PyILike>()?;
782 m.add_class::<PySimilarTo>()?;
783 m.add_class::<PyScalarVariable>()?;
784 m.add_class::<alias::PyAlias>()?;
785 m.add_class::<in_list::PyInList>()?;
786 m.add_class::<exists::PyExists>()?;
787 m.add_class::<subquery::PySubquery>()?;
788 m.add_class::<in_subquery::PyInSubquery>()?;
789 m.add_class::<scalar_subquery::PyScalarSubquery>()?;
790 m.add_class::<placeholder::PyPlaceholder>()?;
791 m.add_class::<grouping_set::PyGroupingSet>()?;
792 m.add_class::<case::PyCase>()?;
793 m.add_class::<conditional_expr::PyCaseBuilder>()?;
794 m.add_class::<cast::PyCast>()?;
795 m.add_class::<cast::PyTryCast>()?;
796 m.add_class::<between::PyBetween>()?;
797 m.add_class::<explain::PyExplain>()?;
798 m.add_class::<limit::PyLimit>()?;
799 m.add_class::<aggregate::PyAggregate>()?;
800 m.add_class::<sort::PySort>()?;
801 m.add_class::<analyze::PyAnalyze>()?;
802 m.add_class::<empty_relation::PyEmptyRelation>()?;
803 m.add_class::<join::PyJoin>()?;
804 m.add_class::<join::PyJoinType>()?;
805 m.add_class::<join::PyJoinConstraint>()?;
806 m.add_class::<union::PyUnion>()?;
807 m.add_class::<unnest::PyUnnest>()?;
808 m.add_class::<unnest_expr::PyUnnestExpr>()?;
809 m.add_class::<extension::PyExtension>()?;
810 m.add_class::<filter::PyFilter>()?;
811 m.add_class::<projection::PyProjection>()?;
812 m.add_class::<table_scan::PyTableScan>()?;
813 m.add_class::<create_memory_table::PyCreateMemoryTable>()?;
814 m.add_class::<create_view::PyCreateView>()?;
815 m.add_class::<distinct::PyDistinct>()?;
816 m.add_class::<sort_expr::PySortExpr>()?;
817 m.add_class::<subquery_alias::PySubqueryAlias>()?;
818 m.add_class::<drop_table::PyDropTable>()?;
819 m.add_class::<repartition::PyPartitioning>()?;
820 m.add_class::<repartition::PyRepartition>()?;
821 m.add_class::<window::PyWindowExpr>()?;
822 m.add_class::<window::PyWindowFrame>()?;
823 m.add_class::<window::PyWindowFrameBound>()?;
824 m.add_class::<copy_to::PyCopyTo>()?;
825 m.add_class::<copy_to::PyFileType>()?;
826 m.add_class::<create_catalog::PyCreateCatalog>()?;
827 m.add_class::<create_catalog_schema::PyCreateCatalogSchema>()?;
828 m.add_class::<create_external_table::PyCreateExternalTable>()?;
829 m.add_class::<create_function::PyCreateFunction>()?;
830 m.add_class::<create_function::PyOperateFunctionArg>()?;
831 m.add_class::<create_function::PyCreateFunctionBody>()?;
832 m.add_class::<create_index::PyCreateIndex>()?;
833 m.add_class::<describe_table::PyDescribeTable>()?;
834 m.add_class::<dml::PyDmlStatement>()?;
835 m.add_class::<drop_catalog_schema::PyDropCatalogSchema>()?;
836 m.add_class::<drop_function::PyDropFunction>()?;
837 m.add_class::<drop_view::PyDropView>()?;
838 m.add_class::<recursive_query::PyRecursiveQuery>()?;
839
840 m.add_class::<statement::PyTransactionStart>()?;
841 m.add_class::<statement::PyTransactionEnd>()?;
842 m.add_class::<statement::PySetVariable>()?;
843 m.add_class::<statement::PyPrepare>()?;
844 m.add_class::<statement::PyExecute>()?;
845 m.add_class::<statement::PyDeallocate>()?;
846 m.add_class::<values::PyValues>()?;
847 m.add_class::<statement::PyTransactionAccessMode>()?;
848 m.add_class::<statement::PyTransactionConclusion>()?;
849 m.add_class::<statement::PyTransactionIsolationLevel>()?;
850
851 Ok(())
852}