datafusion_proto/logical_plan/
from_proto.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use datafusion::execution::registry::FunctionRegistry;
21use datafusion_common::{
22    exec_datafusion_err, internal_err, plan_datafusion_err, RecursionUnnestOption,
23    Result, ScalarValue, TableReference, UnnestOptions,
24};
25use datafusion_expr::dml::InsertOp;
26use datafusion_expr::expr::{Alias, Placeholder, Sort};
27use datafusion_expr::expr::{Unnest, WildcardOptions};
28use datafusion_expr::{
29    expr::{self, InList, WindowFunction},
30    logical_plan::{PlanType, StringifiedPlan},
31    Between, BinaryExpr, Case, Cast, Expr, GroupingSet,
32    GroupingSet::GroupingSets,
33    JoinConstraint, JoinType, Like, Operator, TryCast, WindowFrame, WindowFrameBound,
34    WindowFrameUnits,
35};
36use datafusion_expr::{ExprFunctionExt, WriteOp};
37use datafusion_proto_common::{from_proto::FromOptionalField, FromProtoError as Error};
38
39use crate::protobuf::plan_type::PlanTypeEnum::{
40    FinalPhysicalPlanWithSchema, InitialPhysicalPlanWithSchema,
41};
42use crate::protobuf::{
43    self,
44    plan_type::PlanTypeEnum::{
45        AnalyzedLogicalPlan, FinalAnalyzedLogicalPlan, FinalLogicalPlan,
46        FinalPhysicalPlan, FinalPhysicalPlanWithStats, InitialLogicalPlan,
47        InitialPhysicalPlan, InitialPhysicalPlanWithStats, OptimizedLogicalPlan,
48        OptimizedPhysicalPlan, PhysicalPlanError,
49    },
50    AnalyzedLogicalPlanType, CubeNode, GroupingSetNode, OptimizedLogicalPlanType,
51    OptimizedPhysicalPlanType, PlaceholderNode, RollupNode,
52};
53
54use super::LogicalExtensionCodec;
55
56impl From<&protobuf::UnnestOptions> for UnnestOptions {
57    fn from(opts: &protobuf::UnnestOptions) -> Self {
58        Self {
59            preserve_nulls: opts.preserve_nulls,
60            recursions: opts
61                .recursions
62                .iter()
63                .map(|r| RecursionUnnestOption {
64                    input_column: r.input_column.as_ref().unwrap().into(),
65                    output_column: r.output_column.as_ref().unwrap().into(),
66                    depth: r.depth as usize,
67                })
68                .collect::<Vec<_>>(),
69        }
70    }
71}
72
73impl From<protobuf::WindowFrameUnits> for WindowFrameUnits {
74    fn from(units: protobuf::WindowFrameUnits) -> Self {
75        match units {
76            protobuf::WindowFrameUnits::Rows => Self::Rows,
77            protobuf::WindowFrameUnits::Range => Self::Range,
78            protobuf::WindowFrameUnits::Groups => Self::Groups,
79        }
80    }
81}
82
83impl TryFrom<protobuf::TableReference> for TableReference {
84    type Error = Error;
85
86    fn try_from(value: protobuf::TableReference) -> Result<Self, Self::Error> {
87        use protobuf::table_reference::TableReferenceEnum;
88        let table_reference_enum = value
89            .table_reference_enum
90            .ok_or_else(|| Error::required("table_reference_enum"))?;
91
92        match table_reference_enum {
93            TableReferenceEnum::Bare(protobuf::BareTableReference { table }) => {
94                Ok(TableReference::bare(table))
95            }
96            TableReferenceEnum::Partial(protobuf::PartialTableReference {
97                schema,
98                table,
99            }) => Ok(TableReference::partial(schema, table)),
100            TableReferenceEnum::Full(protobuf::FullTableReference {
101                catalog,
102                schema,
103                table,
104            }) => Ok(TableReference::full(catalog, schema, table)),
105        }
106    }
107}
108
109impl From<&protobuf::StringifiedPlan> for StringifiedPlan {
110    fn from(stringified_plan: &protobuf::StringifiedPlan) -> Self {
111        Self {
112            plan_type: match stringified_plan
113                .plan_type
114                .as_ref()
115                .and_then(|pt| pt.plan_type_enum.as_ref())
116                .unwrap_or_else(|| {
117                    panic!(
118                        "Cannot create protobuf::StringifiedPlan from {stringified_plan:?}"
119                    )
120                }) {
121                InitialLogicalPlan(_) => PlanType::InitialLogicalPlan,
122                AnalyzedLogicalPlan(AnalyzedLogicalPlanType { analyzer_name }) => {
123                    PlanType::AnalyzedLogicalPlan {
124                        analyzer_name:analyzer_name.clone()
125                    }
126                }
127                FinalAnalyzedLogicalPlan(_) => PlanType::FinalAnalyzedLogicalPlan,
128                OptimizedLogicalPlan(OptimizedLogicalPlanType { optimizer_name }) => {
129                    PlanType::OptimizedLogicalPlan {
130                        optimizer_name: optimizer_name.clone(),
131                    }
132                }
133                FinalLogicalPlan(_) => PlanType::FinalLogicalPlan,
134                InitialPhysicalPlan(_) => PlanType::InitialPhysicalPlan,
135                InitialPhysicalPlanWithStats(_) => PlanType::InitialPhysicalPlanWithStats,
136                InitialPhysicalPlanWithSchema(_) => PlanType::InitialPhysicalPlanWithSchema,
137                OptimizedPhysicalPlan(OptimizedPhysicalPlanType { optimizer_name }) => {
138                    PlanType::OptimizedPhysicalPlan {
139                        optimizer_name: optimizer_name.clone(),
140                    }
141                }
142                FinalPhysicalPlan(_) => PlanType::FinalPhysicalPlan,
143                FinalPhysicalPlanWithStats(_) => PlanType::FinalPhysicalPlanWithStats,
144                FinalPhysicalPlanWithSchema(_) => PlanType::FinalPhysicalPlanWithSchema,
145                PhysicalPlanError(_) => PlanType::PhysicalPlanError,
146            },
147            plan: Arc::new(stringified_plan.plan.clone()),
148        }
149    }
150}
151
152impl TryFrom<protobuf::WindowFrame> for WindowFrame {
153    type Error = Error;
154
155    fn try_from(window: protobuf::WindowFrame) -> Result<Self, Self::Error> {
156        let units = protobuf::WindowFrameUnits::try_from(window.window_frame_units)
157            .map_err(|_| Error::unknown("WindowFrameUnits", window.window_frame_units))?
158            .into();
159        let start_bound = window.start_bound.required("start_bound")?;
160        let end_bound = window
161            .end_bound
162            .map(|end_bound| match end_bound {
163                protobuf::window_frame::EndBound::Bound(end_bound) => {
164                    end_bound.try_into()
165                }
166            })
167            .transpose()?
168            .unwrap_or(WindowFrameBound::CurrentRow);
169        Ok(WindowFrame::new_bounds(units, start_bound, end_bound))
170    }
171}
172
173impl TryFrom<protobuf::WindowFrameBound> for WindowFrameBound {
174    type Error = Error;
175
176    fn try_from(bound: protobuf::WindowFrameBound) -> Result<Self, Self::Error> {
177        let bound_type =
178            protobuf::WindowFrameBoundType::try_from(bound.window_frame_bound_type)
179                .map_err(|_| {
180                    Error::unknown("WindowFrameBoundType", bound.window_frame_bound_type)
181                })?;
182        match bound_type {
183            protobuf::WindowFrameBoundType::CurrentRow => Ok(Self::CurrentRow),
184            protobuf::WindowFrameBoundType::Preceding => match bound.bound_value {
185                Some(x) => Ok(Self::Preceding(ScalarValue::try_from(&x)?)),
186                None => Ok(Self::Preceding(ScalarValue::UInt64(None))),
187            },
188            protobuf::WindowFrameBoundType::Following => match bound.bound_value {
189                Some(x) => Ok(Self::Following(ScalarValue::try_from(&x)?)),
190                None => Ok(Self::Following(ScalarValue::UInt64(None))),
191            },
192        }
193    }
194}
195
196impl From<protobuf::JoinType> for JoinType {
197    fn from(t: protobuf::JoinType) -> Self {
198        match t {
199            protobuf::JoinType::Inner => JoinType::Inner,
200            protobuf::JoinType::Left => JoinType::Left,
201            protobuf::JoinType::Right => JoinType::Right,
202            protobuf::JoinType::Full => JoinType::Full,
203            protobuf::JoinType::Leftsemi => JoinType::LeftSemi,
204            protobuf::JoinType::Rightsemi => JoinType::RightSemi,
205            protobuf::JoinType::Leftanti => JoinType::LeftAnti,
206            protobuf::JoinType::Rightanti => JoinType::RightAnti,
207            protobuf::JoinType::Leftmark => JoinType::LeftMark,
208        }
209    }
210}
211
212impl From<protobuf::JoinConstraint> for JoinConstraint {
213    fn from(t: protobuf::JoinConstraint) -> Self {
214        match t {
215            protobuf::JoinConstraint::On => JoinConstraint::On,
216            protobuf::JoinConstraint::Using => JoinConstraint::Using,
217        }
218    }
219}
220
221impl From<protobuf::dml_node::Type> for WriteOp {
222    fn from(t: protobuf::dml_node::Type) -> Self {
223        match t {
224            protobuf::dml_node::Type::Update => WriteOp::Update,
225            protobuf::dml_node::Type::Delete => WriteOp::Delete,
226            protobuf::dml_node::Type::InsertAppend => WriteOp::Insert(InsertOp::Append),
227            protobuf::dml_node::Type::InsertOverwrite => {
228                WriteOp::Insert(InsertOp::Overwrite)
229            }
230            protobuf::dml_node::Type::InsertReplace => WriteOp::Insert(InsertOp::Replace),
231            protobuf::dml_node::Type::Ctas => WriteOp::Ctas,
232        }
233    }
234}
235
236pub fn parse_expr(
237    proto: &protobuf::LogicalExprNode,
238    registry: &dyn FunctionRegistry,
239    codec: &dyn LogicalExtensionCodec,
240) -> Result<Expr, Error> {
241    use protobuf::{logical_expr_node::ExprType, window_expr_node};
242
243    let expr_type = proto
244        .expr_type
245        .as_ref()
246        .ok_or_else(|| Error::required("expr_type"))?;
247
248    match expr_type {
249        ExprType::BinaryExpr(binary_expr) => {
250            let op = from_proto_binary_op(&binary_expr.op)?;
251            let operands = parse_exprs(&binary_expr.operands, registry, codec)?;
252
253            if operands.len() < 2 {
254                return Err(proto_error(
255                    "A binary expression must always have at least 2 operands",
256                ));
257            }
258
259            // Reduce the linearized operands (ordered by left innermost to right
260            // outermost) into a single expression tree.
261            Ok(operands
262                .into_iter()
263                .reduce(|left, right| {
264                    Expr::BinaryExpr(BinaryExpr::new(Box::new(left), op, Box::new(right)))
265                })
266                .expect("Binary expression could not be reduced to a single expression."))
267        }
268        ExprType::Column(column) => Ok(Expr::Column(column.into())),
269        ExprType::Literal(literal) => {
270            let scalar_value: ScalarValue = literal.try_into()?;
271            Ok(Expr::Literal(scalar_value))
272        }
273        ExprType::WindowExpr(expr) => {
274            let window_function = expr
275                .window_function
276                .as_ref()
277                .ok_or_else(|| Error::required("window_function"))?;
278            let partition_by = parse_exprs(&expr.partition_by, registry, codec)?;
279            let mut order_by = parse_sorts(&expr.order_by, registry, codec)?;
280            let window_frame = expr
281                .window_frame
282                .as_ref()
283                .map::<Result<WindowFrame, _>, _>(|window_frame| {
284                    let window_frame: WindowFrame = window_frame.clone().try_into()?;
285                    window_frame
286                        .regularize_order_bys(&mut order_by)
287                        .map(|_| window_frame)
288                })
289                .transpose()?
290                .ok_or_else(|| {
291                    exec_datafusion_err!("missing window frame during deserialization")
292                })?;
293
294            // TODO: support proto for null treatment
295            match window_function {
296                window_expr_node::WindowFunction::Udaf(udaf_name) => {
297                    let udaf_function = match &expr.fun_definition {
298                        Some(buf) => codec.try_decode_udaf(udaf_name, buf)?,
299                        None => registry.udaf(udaf_name)?,
300                    };
301
302                    let args = parse_exprs(&expr.exprs, registry, codec)?;
303                    Expr::WindowFunction(WindowFunction::new(
304                        expr::WindowFunctionDefinition::AggregateUDF(udaf_function),
305                        args,
306                    ))
307                    .partition_by(partition_by)
308                    .order_by(order_by)
309                    .window_frame(window_frame)
310                    .build()
311                    .map_err(Error::DataFusionError)
312                }
313                window_expr_node::WindowFunction::Udwf(udwf_name) => {
314                    let udwf_function = match &expr.fun_definition {
315                        Some(buf) => codec.try_decode_udwf(udwf_name, buf)?,
316                        None => registry.udwf(udwf_name)?,
317                    };
318
319                    let args = parse_exprs(&expr.exprs, registry, codec)?;
320                    Expr::WindowFunction(WindowFunction::new(
321                        expr::WindowFunctionDefinition::WindowUDF(udwf_function),
322                        args,
323                    ))
324                    .partition_by(partition_by)
325                    .order_by(order_by)
326                    .window_frame(window_frame)
327                    .build()
328                    .map_err(Error::DataFusionError)
329                }
330            }
331        }
332        ExprType::Alias(alias) => Ok(Expr::Alias(Alias::new(
333            parse_required_expr(alias.expr.as_deref(), registry, "expr", codec)?,
334            alias
335                .relation
336                .first()
337                .map(|r| TableReference::try_from(r.clone()))
338                .transpose()?,
339            alias.alias.clone(),
340        ))),
341        ExprType::IsNullExpr(is_null) => Ok(Expr::IsNull(Box::new(parse_required_expr(
342            is_null.expr.as_deref(),
343            registry,
344            "expr",
345            codec,
346        )?))),
347        ExprType::IsNotNullExpr(is_not_null) => Ok(Expr::IsNotNull(Box::new(
348            parse_required_expr(is_not_null.expr.as_deref(), registry, "expr", codec)?,
349        ))),
350        ExprType::NotExpr(not) => Ok(Expr::Not(Box::new(parse_required_expr(
351            not.expr.as_deref(),
352            registry,
353            "expr",
354            codec,
355        )?))),
356        ExprType::IsTrue(msg) => Ok(Expr::IsTrue(Box::new(parse_required_expr(
357            msg.expr.as_deref(),
358            registry,
359            "expr",
360            codec,
361        )?))),
362        ExprType::IsFalse(msg) => Ok(Expr::IsFalse(Box::new(parse_required_expr(
363            msg.expr.as_deref(),
364            registry,
365            "expr",
366            codec,
367        )?))),
368        ExprType::IsUnknown(msg) => Ok(Expr::IsUnknown(Box::new(parse_required_expr(
369            msg.expr.as_deref(),
370            registry,
371            "expr",
372            codec,
373        )?))),
374        ExprType::IsNotTrue(msg) => Ok(Expr::IsNotTrue(Box::new(parse_required_expr(
375            msg.expr.as_deref(),
376            registry,
377            "expr",
378            codec,
379        )?))),
380        ExprType::IsNotFalse(msg) => Ok(Expr::IsNotFalse(Box::new(parse_required_expr(
381            msg.expr.as_deref(),
382            registry,
383            "expr",
384            codec,
385        )?))),
386        ExprType::IsNotUnknown(msg) => Ok(Expr::IsNotUnknown(Box::new(
387            parse_required_expr(msg.expr.as_deref(), registry, "expr", codec)?,
388        ))),
389        ExprType::Between(between) => Ok(Expr::Between(Between::new(
390            Box::new(parse_required_expr(
391                between.expr.as_deref(),
392                registry,
393                "expr",
394                codec,
395            )?),
396            between.negated,
397            Box::new(parse_required_expr(
398                between.low.as_deref(),
399                registry,
400                "expr",
401                codec,
402            )?),
403            Box::new(parse_required_expr(
404                between.high.as_deref(),
405                registry,
406                "expr",
407                codec,
408            )?),
409        ))),
410        ExprType::Like(like) => Ok(Expr::Like(Like::new(
411            like.negated,
412            Box::new(parse_required_expr(
413                like.expr.as_deref(),
414                registry,
415                "expr",
416                codec,
417            )?),
418            Box::new(parse_required_expr(
419                like.pattern.as_deref(),
420                registry,
421                "pattern",
422                codec,
423            )?),
424            parse_escape_char(&like.escape_char)?,
425            false,
426        ))),
427        ExprType::Ilike(like) => Ok(Expr::Like(Like::new(
428            like.negated,
429            Box::new(parse_required_expr(
430                like.expr.as_deref(),
431                registry,
432                "expr",
433                codec,
434            )?),
435            Box::new(parse_required_expr(
436                like.pattern.as_deref(),
437                registry,
438                "pattern",
439                codec,
440            )?),
441            parse_escape_char(&like.escape_char)?,
442            true,
443        ))),
444        ExprType::SimilarTo(like) => Ok(Expr::SimilarTo(Like::new(
445            like.negated,
446            Box::new(parse_required_expr(
447                like.expr.as_deref(),
448                registry,
449                "expr",
450                codec,
451            )?),
452            Box::new(parse_required_expr(
453                like.pattern.as_deref(),
454                registry,
455                "pattern",
456                codec,
457            )?),
458            parse_escape_char(&like.escape_char)?,
459            false,
460        ))),
461        ExprType::Case(case) => {
462            let when_then_expr = case
463                .when_then_expr
464                .iter()
465                .map(|e| {
466                    let when_expr = parse_required_expr(
467                        e.when_expr.as_ref(),
468                        registry,
469                        "when_expr",
470                        codec,
471                    )?;
472                    let then_expr = parse_required_expr(
473                        e.then_expr.as_ref(),
474                        registry,
475                        "then_expr",
476                        codec,
477                    )?;
478                    Ok((Box::new(when_expr), Box::new(then_expr)))
479                })
480                .collect::<Result<Vec<(Box<Expr>, Box<Expr>)>, Error>>()?;
481            Ok(Expr::Case(Case::new(
482                parse_optional_expr(case.expr.as_deref(), registry, codec)?.map(Box::new),
483                when_then_expr,
484                parse_optional_expr(case.else_expr.as_deref(), registry, codec)?
485                    .map(Box::new),
486            )))
487        }
488        ExprType::Cast(cast) => {
489            let expr = Box::new(parse_required_expr(
490                cast.expr.as_deref(),
491                registry,
492                "expr",
493                codec,
494            )?);
495            let data_type = cast.arrow_type.as_ref().required("arrow_type")?;
496            Ok(Expr::Cast(Cast::new(expr, data_type)))
497        }
498        ExprType::TryCast(cast) => {
499            let expr = Box::new(parse_required_expr(
500                cast.expr.as_deref(),
501                registry,
502                "expr",
503                codec,
504            )?);
505            let data_type = cast.arrow_type.as_ref().required("arrow_type")?;
506            Ok(Expr::TryCast(TryCast::new(expr, data_type)))
507        }
508        ExprType::Negative(negative) => Ok(Expr::Negative(Box::new(
509            parse_required_expr(negative.expr.as_deref(), registry, "expr", codec)?,
510        ))),
511        ExprType::Unnest(unnest) => {
512            let mut exprs = parse_exprs(&unnest.exprs, registry, codec)?;
513            if exprs.len() != 1 {
514                return Err(proto_error("Unnest must have exactly one expression"));
515            }
516            Ok(Expr::Unnest(Unnest::new(exprs.swap_remove(0))))
517        }
518        ExprType::InList(in_list) => Ok(Expr::InList(InList::new(
519            Box::new(parse_required_expr(
520                in_list.expr.as_deref(),
521                registry,
522                "expr",
523                codec,
524            )?),
525            parse_exprs(&in_list.list, registry, codec)?,
526            in_list.negated,
527        ))),
528        ExprType::Wildcard(protobuf::Wildcard { qualifier }) => {
529            let qualifier = qualifier.to_owned().map(|x| x.try_into()).transpose()?;
530            #[expect(deprecated)]
531            Ok(Expr::Wildcard {
532                qualifier,
533                options: Box::new(WildcardOptions::default()),
534            })
535        }
536        ExprType::ScalarUdfExpr(protobuf::ScalarUdfExprNode {
537            fun_name,
538            args,
539            fun_definition,
540        }) => {
541            let scalar_fn = match fun_definition {
542                Some(buf) => codec.try_decode_udf(fun_name, buf)?,
543                None => registry.udf(fun_name.as_str())?,
544            };
545            Ok(Expr::ScalarFunction(expr::ScalarFunction::new_udf(
546                scalar_fn,
547                parse_exprs(args, registry, codec)?,
548            )))
549        }
550        ExprType::AggregateUdfExpr(pb) => {
551            let agg_fn = match &pb.fun_definition {
552                Some(buf) => codec.try_decode_udaf(&pb.fun_name, buf)?,
553                None => registry.udaf(&pb.fun_name)?,
554            };
555
556            Ok(Expr::AggregateFunction(expr::AggregateFunction::new_udf(
557                agg_fn,
558                parse_exprs(&pb.args, registry, codec)?,
559                pb.distinct,
560                parse_optional_expr(pb.filter.as_deref(), registry, codec)?.map(Box::new),
561                match pb.order_by.len() {
562                    0 => None,
563                    _ => Some(parse_sorts(&pb.order_by, registry, codec)?),
564                },
565                None,
566            )))
567        }
568
569        ExprType::GroupingSet(GroupingSetNode { expr }) => {
570            Ok(Expr::GroupingSet(GroupingSets(
571                expr.iter()
572                    .map(|expr_list| parse_exprs(&expr_list.expr, registry, codec))
573                    .collect::<Result<Vec<_>, Error>>()?,
574            )))
575        }
576        ExprType::Cube(CubeNode { expr }) => Ok(Expr::GroupingSet(GroupingSet::Cube(
577            parse_exprs(expr, registry, codec)?,
578        ))),
579        ExprType::Rollup(RollupNode { expr }) => Ok(Expr::GroupingSet(
580            GroupingSet::Rollup(parse_exprs(expr, registry, codec)?),
581        )),
582        ExprType::Placeholder(PlaceholderNode { id, data_type }) => match data_type {
583            None => Ok(Expr::Placeholder(Placeholder::new(id.clone(), None))),
584            Some(data_type) => Ok(Expr::Placeholder(Placeholder::new(
585                id.clone(),
586                Some(data_type.try_into()?),
587            ))),
588        },
589    }
590}
591
592/// Parse a vector of `protobuf::LogicalExprNode`s.
593pub fn parse_exprs<'a, I>(
594    protos: I,
595    registry: &dyn FunctionRegistry,
596    codec: &dyn LogicalExtensionCodec,
597) -> Result<Vec<Expr>, Error>
598where
599    I: IntoIterator<Item = &'a protobuf::LogicalExprNode>,
600{
601    let res = protos
602        .into_iter()
603        .map(|elem| {
604            parse_expr(elem, registry, codec).map_err(|e| plan_datafusion_err!("{}", e))
605        })
606        .collect::<Result<Vec<_>>>()?;
607    Ok(res)
608}
609
610pub fn parse_sorts<'a, I>(
611    protos: I,
612    registry: &dyn FunctionRegistry,
613    codec: &dyn LogicalExtensionCodec,
614) -> Result<Vec<Sort>, Error>
615where
616    I: IntoIterator<Item = &'a protobuf::SortExprNode>,
617{
618    protos
619        .into_iter()
620        .map(|sort| parse_sort(sort, registry, codec))
621        .collect::<Result<Vec<Sort>, Error>>()
622}
623
624pub fn parse_sort(
625    sort: &protobuf::SortExprNode,
626    registry: &dyn FunctionRegistry,
627    codec: &dyn LogicalExtensionCodec,
628) -> Result<Sort, Error> {
629    Ok(Sort::new(
630        parse_required_expr(sort.expr.as_ref(), registry, "expr", codec)?,
631        sort.asc,
632        sort.nulls_first,
633    ))
634}
635
636/// Parse an optional escape_char for Like, ILike, SimilarTo
637fn parse_escape_char(s: &str) -> Result<Option<char>> {
638    match s.len() {
639        0 => Ok(None),
640        1 => Ok(s.chars().next()),
641        _ => internal_err!("Invalid length for escape char"),
642    }
643}
644
645pub fn from_proto_binary_op(op: &str) -> Result<Operator, Error> {
646    match op {
647        "And" => Ok(Operator::And),
648        "Or" => Ok(Operator::Or),
649        "Eq" => Ok(Operator::Eq),
650        "NotEq" => Ok(Operator::NotEq),
651        "LtEq" => Ok(Operator::LtEq),
652        "Lt" => Ok(Operator::Lt),
653        "Gt" => Ok(Operator::Gt),
654        "GtEq" => Ok(Operator::GtEq),
655        "Plus" => Ok(Operator::Plus),
656        "Minus" => Ok(Operator::Minus),
657        "Multiply" => Ok(Operator::Multiply),
658        "Divide" => Ok(Operator::Divide),
659        "Modulo" => Ok(Operator::Modulo),
660        "IsDistinctFrom" => Ok(Operator::IsDistinctFrom),
661        "IsNotDistinctFrom" => Ok(Operator::IsNotDistinctFrom),
662        "BitwiseAnd" => Ok(Operator::BitwiseAnd),
663        "BitwiseOr" => Ok(Operator::BitwiseOr),
664        "BitwiseXor" => Ok(Operator::BitwiseXor),
665        "BitwiseShiftLeft" => Ok(Operator::BitwiseShiftLeft),
666        "BitwiseShiftRight" => Ok(Operator::BitwiseShiftRight),
667        "RegexIMatch" => Ok(Operator::RegexIMatch),
668        "RegexMatch" => Ok(Operator::RegexMatch),
669        "RegexNotIMatch" => Ok(Operator::RegexNotIMatch),
670        "RegexNotMatch" => Ok(Operator::RegexNotMatch),
671        "StringConcat" => Ok(Operator::StringConcat),
672        "AtArrow" => Ok(Operator::AtArrow),
673        "ArrowAt" => Ok(Operator::ArrowAt),
674        other => Err(proto_error(format!(
675            "Unsupported binary operator '{other:?}'"
676        ))),
677    }
678}
679
680fn parse_optional_expr(
681    p: Option<&protobuf::LogicalExprNode>,
682    registry: &dyn FunctionRegistry,
683    codec: &dyn LogicalExtensionCodec,
684) -> Result<Option<Expr>, Error> {
685    match p {
686        Some(expr) => parse_expr(expr, registry, codec).map(Some),
687        None => Ok(None),
688    }
689}
690
691fn parse_required_expr(
692    p: Option<&protobuf::LogicalExprNode>,
693    registry: &dyn FunctionRegistry,
694    field: impl Into<String>,
695    codec: &dyn LogicalExtensionCodec,
696) -> Result<Expr, Error> {
697    match p {
698        Some(expr) => parse_expr(expr, registry, codec),
699        None => Err(Error::required(field)),
700    }
701}
702
703fn proto_error<S: Into<String>>(message: S) -> Error {
704    Error::General(message.into())
705}