1use datafusion::logical_expr::expr::AggregateFunctionParams;
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 lit_with_metadata(value.0, metadata).into()
287 }
288
289 #[staticmethod]
290 pub fn column(value: &str) -> PyExpr {
291 col(value).into()
292 }
293
294 #[pyo3(signature = (name, metadata=None))]
296 pub fn alias(&self, name: &str, metadata: Option<HashMap<String, String>>) -> PyExpr {
297 self.expr.clone().alias_with_metadata(name, metadata).into()
298 }
299
300 #[pyo3(signature = (ascending=true, nulls_first=true))]
302 pub fn sort(&self, ascending: bool, nulls_first: bool) -> PySortExpr {
303 self.expr.clone().sort(ascending, nulls_first).into()
304 }
305
306 pub fn is_null(&self) -> PyExpr {
307 self.expr.clone().is_null().into()
308 }
309
310 pub fn is_not_null(&self) -> PyExpr {
311 self.expr.clone().is_not_null().into()
312 }
313
314 pub fn cast(&self, to: PyArrowType<DataType>) -> PyExpr {
315 let expr = Expr::Cast(Cast::new(Box::new(self.expr.clone()), to.0));
318 expr.into()
319 }
320
321 #[pyo3(signature = (low, high, negated=false))]
322 pub fn between(&self, low: PyExpr, high: PyExpr, negated: bool) -> PyExpr {
323 let expr = Expr::Between(Between::new(
324 Box::new(self.expr.clone()),
325 negated,
326 Box::new(low.into()),
327 Box::new(high.into()),
328 ));
329 expr.into()
330 }
331
332 pub fn rex_type(&self) -> PyResult<RexType> {
336 Ok(match self.expr {
337 Expr::Alias(..) => RexType::Alias,
338 Expr::Column(..) => RexType::Reference,
339 Expr::ScalarVariable(..) | Expr::Literal(..) => RexType::Literal,
340 Expr::BinaryExpr { .. }
341 | Expr::Not(..)
342 | Expr::IsNotNull(..)
343 | Expr::Negative(..)
344 | Expr::IsNull(..)
345 | Expr::Like { .. }
346 | Expr::SimilarTo { .. }
347 | Expr::Between { .. }
348 | Expr::Case { .. }
349 | Expr::Cast { .. }
350 | Expr::TryCast { .. }
351 | Expr::ScalarFunction { .. }
352 | Expr::AggregateFunction { .. }
353 | Expr::WindowFunction { .. }
354 | Expr::InList { .. }
355 | Expr::Exists { .. }
356 | Expr::InSubquery { .. }
357 | Expr::GroupingSet(..)
358 | Expr::IsTrue(..)
359 | Expr::IsFalse(..)
360 | Expr::IsUnknown(_)
361 | Expr::IsNotTrue(..)
362 | Expr::IsNotFalse(..)
363 | Expr::Placeholder { .. }
364 | Expr::OuterReferenceColumn(_, _)
365 | Expr::Unnest(_)
366 | Expr::IsNotUnknown(_) => RexType::Call,
367 Expr::ScalarSubquery(..) => RexType::ScalarSubquery,
368 #[allow(deprecated)]
369 Expr::Wildcard { .. } => {
370 return Err(py_unsupported_variant_err("Expr::Wildcard is unsupported"))
371 }
372 })
373 }
374
375 pub fn types(&self) -> PyResult<DataTypeMap> {
378 Self::_types(&self.expr)
379 }
380
381 pub fn python_value(&self, py: Python) -> PyResult<PyObject> {
383 match &self.expr {
384 Expr::Literal(scalar_value, _) => scalar_to_pyarrow(scalar_value, py),
385 _ => Err(py_type_err(format!(
386 "Non Expr::Literal encountered in types: {:?}",
387 &self.expr
388 ))),
389 }
390 }
391
392 pub fn rex_call_operands(&self) -> PyResult<Vec<PyExpr>> {
396 match &self.expr {
397 Expr::Column(..) | Expr::ScalarVariable(..) | Expr::Literal(..) => {
399 Ok(vec![PyExpr::from(self.expr.clone())])
400 }
401
402 Expr::Alias(alias) => Ok(vec![PyExpr::from(*alias.expr.clone())]),
403
404 Expr::Not(expr)
406 | Expr::IsNull(expr)
407 | Expr::IsNotNull(expr)
408 | Expr::IsTrue(expr)
409 | Expr::IsFalse(expr)
410 | Expr::IsUnknown(expr)
411 | Expr::IsNotTrue(expr)
412 | Expr::IsNotFalse(expr)
413 | Expr::IsNotUnknown(expr)
414 | Expr::Negative(expr)
415 | Expr::Cast(Cast { expr, .. })
416 | Expr::TryCast(TryCast { expr, .. })
417 | Expr::InSubquery(InSubquery { expr, .. }) => Ok(vec![PyExpr::from(*expr.clone())]),
418
419 Expr::AggregateFunction(AggregateFunction {
421 params: AggregateFunctionParams { args, .. },
422 ..
423 })
424 | Expr::ScalarFunction(ScalarFunction { args, .. }) => {
425 Ok(args.iter().map(|arg| PyExpr::from(arg.clone())).collect())
426 }
427 Expr::WindowFunction(boxed_window_fn) => {
428 let args = &boxed_window_fn.params.args;
429 Ok(args.iter().map(|arg| PyExpr::from(arg.clone())).collect())
430 }
431
432 Expr::Case(Case {
434 expr,
435 when_then_expr,
436 else_expr,
437 }) => {
438 let mut operands: Vec<PyExpr> = Vec::new();
439
440 if let Some(e) = expr {
441 for (when, then) in when_then_expr {
442 operands.push(PyExpr::from(Expr::BinaryExpr(BinaryExpr::new(
443 Box::new(*e.clone()),
444 Operator::Eq,
445 Box::new(*when.clone()),
446 ))));
447 operands.push(PyExpr::from(*then.clone()));
448 }
449 } else {
450 for (when, then) in when_then_expr {
451 operands.push(PyExpr::from(*when.clone()));
452 operands.push(PyExpr::from(*then.clone()));
453 }
454 };
455
456 if let Some(e) = else_expr {
457 operands.push(PyExpr::from(*e.clone()));
458 };
459
460 Ok(operands)
461 }
462 Expr::InList(InList { expr, list, .. }) => {
463 let mut operands: Vec<PyExpr> = vec![PyExpr::from(*expr.clone())];
464 for list_elem in list {
465 operands.push(PyExpr::from(list_elem.clone()));
466 }
467
468 Ok(operands)
469 }
470 Expr::BinaryExpr(BinaryExpr { left, right, .. }) => Ok(vec![
471 PyExpr::from(*left.clone()),
472 PyExpr::from(*right.clone()),
473 ]),
474 Expr::Like(Like { expr, pattern, .. }) => Ok(vec![
475 PyExpr::from(*expr.clone()),
476 PyExpr::from(*pattern.clone()),
477 ]),
478 Expr::SimilarTo(Like { expr, pattern, .. }) => Ok(vec![
479 PyExpr::from(*expr.clone()),
480 PyExpr::from(*pattern.clone()),
481 ]),
482 Expr::Between(Between {
483 expr,
484 negated: _,
485 low,
486 high,
487 }) => Ok(vec![
488 PyExpr::from(*expr.clone()),
489 PyExpr::from(*low.clone()),
490 PyExpr::from(*high.clone()),
491 ]),
492
493 Expr::GroupingSet(..)
495 | Expr::Unnest(_)
496 | Expr::OuterReferenceColumn(_, _)
497 | Expr::ScalarSubquery(..)
498 | Expr::Placeholder { .. }
499 | Expr::Exists { .. } => Err(py_runtime_err(format!(
500 "Unimplemented Expr type: {}",
501 self.expr
502 ))),
503
504 #[allow(deprecated)]
505 Expr::Wildcard { .. } => {
506 Err(py_unsupported_variant_err("Expr::Wildcard is unsupported"))
507 }
508 }
509 }
510
511 pub fn rex_call_operator(&self) -> PyResult<String> {
513 Ok(match &self.expr {
514 Expr::BinaryExpr(BinaryExpr {
515 left: _,
516 op,
517 right: _,
518 }) => format!("{op}"),
519 Expr::ScalarFunction(ScalarFunction { func, args: _ }) => func.name().to_string(),
520 Expr::Cast { .. } => "cast".to_string(),
521 Expr::Between { .. } => "between".to_string(),
522 Expr::Case { .. } => "case".to_string(),
523 Expr::IsNull(..) => "is null".to_string(),
524 Expr::IsNotNull(..) => "is not null".to_string(),
525 Expr::IsTrue(_) => "is true".to_string(),
526 Expr::IsFalse(_) => "is false".to_string(),
527 Expr::IsUnknown(_) => "is unknown".to_string(),
528 Expr::IsNotTrue(_) => "is not true".to_string(),
529 Expr::IsNotFalse(_) => "is not false".to_string(),
530 Expr::IsNotUnknown(_) => "is not unknown".to_string(),
531 Expr::InList { .. } => "in list".to_string(),
532 Expr::Negative(..) => "negative".to_string(),
533 Expr::Not(..) => "not".to_string(),
534 Expr::Like(Like {
535 negated,
536 case_insensitive,
537 ..
538 }) => {
539 let name = if *case_insensitive { "ilike" } else { "like" };
540 if *negated {
541 format!("not {name}")
542 } else {
543 name.to_string()
544 }
545 }
546 Expr::SimilarTo(Like { negated, .. }) => {
547 if *negated {
548 "not similar to".to_string()
549 } else {
550 "similar to".to_string()
551 }
552 }
553 _ => {
554 return Err(py_type_err(format!(
555 "Catch all triggered in get_operator_name: {:?}",
556 &self.expr
557 )))
558 }
559 })
560 }
561
562 pub fn column_name(&self, plan: PyLogicalPlan) -> PyResult<String> {
563 self._column_name(&plan.plan()).map_err(py_runtime_err)
564 }
565
566 pub fn order_by(&self, order_by: Vec<PySortExpr>) -> PyExprFuncBuilder {
569 self.expr
570 .clone()
571 .order_by(to_sort_expressions(order_by))
572 .into()
573 }
574
575 pub fn filter(&self, filter: PyExpr) -> PyExprFuncBuilder {
576 self.expr.clone().filter(filter.expr.clone()).into()
577 }
578
579 pub fn distinct(&self) -> PyExprFuncBuilder {
580 self.expr.clone().distinct().into()
581 }
582
583 pub fn null_treatment(&self, null_treatment: NullTreatment) -> PyExprFuncBuilder {
584 self.expr
585 .clone()
586 .null_treatment(Some(null_treatment.into()))
587 .into()
588 }
589
590 pub fn partition_by(&self, partition_by: Vec<PyExpr>) -> PyExprFuncBuilder {
591 let partition_by = partition_by.iter().map(|e| e.expr.clone()).collect();
592 self.expr.clone().partition_by(partition_by).into()
593 }
594
595 pub fn window_frame(&self, window_frame: PyWindowFrame) -> PyExprFuncBuilder {
596 self.expr.clone().window_frame(window_frame.into()).into()
597 }
598
599 #[pyo3(signature = (partition_by=None, window_frame=None, order_by=None, null_treatment=None))]
600 pub fn over(
601 &self,
602 partition_by: Option<Vec<PyExpr>>,
603 window_frame: Option<PyWindowFrame>,
604 order_by: Option<Vec<PySortExpr>>,
605 null_treatment: Option<NullTreatment>,
606 ) -> PyDataFusionResult<PyExpr> {
607 match &self.expr {
608 Expr::AggregateFunction(agg_fn) => {
609 let window_fn = Expr::WindowFunction(Box::new(WindowFunction::new(
610 WindowFunctionDefinition::AggregateUDF(agg_fn.func.clone()),
611 agg_fn.params.args.clone(),
612 )));
613
614 add_builder_fns_to_window(
615 window_fn,
616 partition_by,
617 window_frame,
618 order_by,
619 null_treatment,
620 )
621 }
622 Expr::WindowFunction(_) => add_builder_fns_to_window(
623 self.expr.clone(),
624 partition_by,
625 window_frame,
626 order_by,
627 null_treatment,
628 ),
629 _ => Err(datafusion::error::DataFusionError::Plan(format!(
630 "Using {} with `over` is not allowed. Must use an aggregate or window function.",
631 self.expr.variant_name()
632 ))
633 .into()),
634 }
635 }
636}
637
638#[pyclass(name = "ExprFuncBuilder", module = "datafusion.expr", subclass)]
639#[derive(Debug, Clone)]
640pub struct PyExprFuncBuilder {
641 pub builder: ExprFuncBuilder,
642}
643
644impl From<ExprFuncBuilder> for PyExprFuncBuilder {
645 fn from(builder: ExprFuncBuilder) -> Self {
646 Self { builder }
647 }
648}
649
650#[pymethods]
651impl PyExprFuncBuilder {
652 pub fn order_by(&self, order_by: Vec<PySortExpr>) -> PyExprFuncBuilder {
653 self.builder
654 .clone()
655 .order_by(to_sort_expressions(order_by))
656 .into()
657 }
658
659 pub fn filter(&self, filter: PyExpr) -> PyExprFuncBuilder {
660 self.builder.clone().filter(filter.expr.clone()).into()
661 }
662
663 pub fn distinct(&self) -> PyExprFuncBuilder {
664 self.builder.clone().distinct().into()
665 }
666
667 pub fn null_treatment(&self, null_treatment: NullTreatment) -> PyExprFuncBuilder {
668 self.builder
669 .clone()
670 .null_treatment(Some(null_treatment.into()))
671 .into()
672 }
673
674 pub fn partition_by(&self, partition_by: Vec<PyExpr>) -> PyExprFuncBuilder {
675 let partition_by = partition_by.iter().map(|e| e.expr.clone()).collect();
676 self.builder.clone().partition_by(partition_by).into()
677 }
678
679 pub fn window_frame(&self, window_frame: PyWindowFrame) -> PyExprFuncBuilder {
680 self.builder
681 .clone()
682 .window_frame(window_frame.into())
683 .into()
684 }
685
686 pub fn build(&self) -> PyDataFusionResult<PyExpr> {
687 Ok(self.builder.clone().build().map(|expr| expr.into())?)
688 }
689}
690
691impl PyExpr {
692 pub fn _column_name(&self, plan: &LogicalPlan) -> PyDataFusionResult<String> {
693 let field = Self::expr_to_field(&self.expr, plan)?;
694 Ok(field.name().to_owned())
695 }
696
697 pub fn expr_to_field(expr: &Expr, input_plan: &LogicalPlan) -> PyDataFusionResult<Arc<Field>> {
699 let fields = exprlist_to_fields(&[expr.clone()], input_plan)?;
700 Ok(fields[0].1.clone())
701 }
702 fn _types(expr: &Expr) -> PyResult<DataTypeMap> {
703 match expr {
704 Expr::BinaryExpr(BinaryExpr {
705 left: _,
706 op,
707 right: _,
708 }) => match op {
709 Operator::Eq
710 | Operator::NotEq
711 | Operator::Lt
712 | Operator::LtEq
713 | Operator::Gt
714 | Operator::GtEq
715 | Operator::And
716 | Operator::Or
717 | Operator::IsDistinctFrom
718 | Operator::IsNotDistinctFrom
719 | Operator::RegexMatch
720 | Operator::RegexIMatch
721 | Operator::RegexNotMatch
722 | Operator::RegexNotIMatch
723 | Operator::LikeMatch
724 | Operator::ILikeMatch
725 | Operator::NotLikeMatch
726 | Operator::NotILikeMatch => DataTypeMap::map_from_arrow_type(&DataType::Boolean),
727 Operator::Plus | Operator::Minus | Operator::Multiply | Operator::Modulo => {
728 DataTypeMap::map_from_arrow_type(&DataType::Int64)
729 }
730 Operator::Divide => DataTypeMap::map_from_arrow_type(&DataType::Float64),
731 Operator::StringConcat => DataTypeMap::map_from_arrow_type(&DataType::Utf8),
732 Operator::BitwiseShiftLeft
733 | Operator::BitwiseShiftRight
734 | Operator::BitwiseXor
735 | Operator::BitwiseAnd
736 | Operator::BitwiseOr => DataTypeMap::map_from_arrow_type(&DataType::Binary),
737 Operator::AtArrow
738 | Operator::ArrowAt
739 | Operator::Arrow
740 | Operator::LongArrow
741 | Operator::HashArrow
742 | Operator::HashLongArrow
743 | Operator::AtAt
744 | Operator::IntegerDivide
745 | Operator::HashMinus
746 | Operator::AtQuestion
747 | Operator::Question
748 | Operator::QuestionAnd
749 | Operator::QuestionPipe => Err(py_type_err(format!("Unsupported expr: ${op}"))),
750 },
751 Expr::Cast(Cast { expr: _, data_type }) => DataTypeMap::map_from_arrow_type(data_type),
752 Expr::Literal(scalar_value, _) => DataTypeMap::map_from_scalar_value(scalar_value),
753 _ => Err(py_type_err(format!(
754 "Non Expr::Literal encountered in types: {expr:?}"
755 ))),
756 }
757 }
758}
759
760pub(crate) fn init_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
762 m.add_class::<PyExpr>()?;
763 m.add_class::<PyColumn>()?;
764 m.add_class::<PyLiteral>()?;
765 m.add_class::<PyBinaryExpr>()?;
766 m.add_class::<PyLiteral>()?;
767 m.add_class::<PyAggregateFunction>()?;
768 m.add_class::<PyNot>()?;
769 m.add_class::<PyIsNotNull>()?;
770 m.add_class::<PyIsNull>()?;
771 m.add_class::<PyIsTrue>()?;
772 m.add_class::<PyIsFalse>()?;
773 m.add_class::<PyIsUnknown>()?;
774 m.add_class::<PyIsNotTrue>()?;
775 m.add_class::<PyIsNotFalse>()?;
776 m.add_class::<PyIsNotUnknown>()?;
777 m.add_class::<PyNegative>()?;
778 m.add_class::<PyLike>()?;
779 m.add_class::<PyILike>()?;
780 m.add_class::<PySimilarTo>()?;
781 m.add_class::<PyScalarVariable>()?;
782 m.add_class::<alias::PyAlias>()?;
783 m.add_class::<in_list::PyInList>()?;
784 m.add_class::<exists::PyExists>()?;
785 m.add_class::<subquery::PySubquery>()?;
786 m.add_class::<in_subquery::PyInSubquery>()?;
787 m.add_class::<scalar_subquery::PyScalarSubquery>()?;
788 m.add_class::<placeholder::PyPlaceholder>()?;
789 m.add_class::<grouping_set::PyGroupingSet>()?;
790 m.add_class::<case::PyCase>()?;
791 m.add_class::<conditional_expr::PyCaseBuilder>()?;
792 m.add_class::<cast::PyCast>()?;
793 m.add_class::<cast::PyTryCast>()?;
794 m.add_class::<between::PyBetween>()?;
795 m.add_class::<explain::PyExplain>()?;
796 m.add_class::<limit::PyLimit>()?;
797 m.add_class::<aggregate::PyAggregate>()?;
798 m.add_class::<sort::PySort>()?;
799 m.add_class::<analyze::PyAnalyze>()?;
800 m.add_class::<empty_relation::PyEmptyRelation>()?;
801 m.add_class::<join::PyJoin>()?;
802 m.add_class::<join::PyJoinType>()?;
803 m.add_class::<join::PyJoinConstraint>()?;
804 m.add_class::<union::PyUnion>()?;
805 m.add_class::<unnest::PyUnnest>()?;
806 m.add_class::<unnest_expr::PyUnnestExpr>()?;
807 m.add_class::<extension::PyExtension>()?;
808 m.add_class::<filter::PyFilter>()?;
809 m.add_class::<projection::PyProjection>()?;
810 m.add_class::<table_scan::PyTableScan>()?;
811 m.add_class::<create_memory_table::PyCreateMemoryTable>()?;
812 m.add_class::<create_view::PyCreateView>()?;
813 m.add_class::<distinct::PyDistinct>()?;
814 m.add_class::<sort_expr::PySortExpr>()?;
815 m.add_class::<subquery_alias::PySubqueryAlias>()?;
816 m.add_class::<drop_table::PyDropTable>()?;
817 m.add_class::<repartition::PyPartitioning>()?;
818 m.add_class::<repartition::PyRepartition>()?;
819 m.add_class::<window::PyWindowExpr>()?;
820 m.add_class::<window::PyWindowFrame>()?;
821 m.add_class::<window::PyWindowFrameBound>()?;
822 m.add_class::<copy_to::PyCopyTo>()?;
823 m.add_class::<copy_to::PyFileType>()?;
824 m.add_class::<create_catalog::PyCreateCatalog>()?;
825 m.add_class::<create_catalog_schema::PyCreateCatalogSchema>()?;
826 m.add_class::<create_external_table::PyCreateExternalTable>()?;
827 m.add_class::<create_function::PyCreateFunction>()?;
828 m.add_class::<create_function::PyOperateFunctionArg>()?;
829 m.add_class::<create_function::PyCreateFunctionBody>()?;
830 m.add_class::<create_index::PyCreateIndex>()?;
831 m.add_class::<describe_table::PyDescribeTable>()?;
832 m.add_class::<dml::PyDmlStatement>()?;
833 m.add_class::<drop_catalog_schema::PyDropCatalogSchema>()?;
834 m.add_class::<drop_function::PyDropFunction>()?;
835 m.add_class::<drop_view::PyDropView>()?;
836 m.add_class::<recursive_query::PyRecursiveQuery>()?;
837
838 m.add_class::<statement::PyTransactionStart>()?;
839 m.add_class::<statement::PyTransactionEnd>()?;
840 m.add_class::<statement::PySetVariable>()?;
841 m.add_class::<statement::PyPrepare>()?;
842 m.add_class::<statement::PyExecute>()?;
843 m.add_class::<statement::PyDeallocate>()?;
844 m.add_class::<values::PyValues>()?;
845 m.add_class::<statement::PyTransactionAccessMode>()?;
846 m.add_class::<statement::PyTransactionConclusion>()?;
847 m.add_class::<statement::PyTransactionIsolationLevel>()?;
848
849 Ok(())
850}