Construct an expression that calculates the aggregate in reverse. Typically the "reverse" expression is itself (e.g. SUM, COUNT). For aggregates that do not support calculation in reverse, returns None (which is the default value).
(&self)
| 914 | /// For aggregates that do not support calculation in reverse, |
| 915 | /// returns None (which is the default value). |
| 916 | pub fn reverse_expr(&self) -> Option<AggregateFunctionExpr> { |
| 917 | match self.fun.reverse_udf() { |
| 918 | ReversedUDAF::NotSupported => None, |
| 919 | ReversedUDAF::Identical => Some(self.clone()), |
| 920 | ReversedUDAF::Reversed(reverse_udf) => { |
| 921 | let was_aliased = self.human_display_alias().is_some(); |
| 922 | let mut name = self.name().to_string(); |
| 923 | let mut human_display = self.human_display.clone(); |
| 924 | // Reversing display follows two paths: |
| 925 | // - aliased display keeps the output `name` unchanged and rewrites only |
| 926 | // the lowered expression in `human_display`. |
| 927 | // - non-aliased display rewrites the canonical `name`, and rewrites |
| 928 | // `human_display` only when present. |
| 929 | // If the function is changed, we need to reverse order_by clause as well |
| 930 | // i.e. First(a order by b asc null first) -> Last(a order by b desc null last) |
| 931 | if !was_aliased && self.fun().name() != reverse_udf.name() { |
| 932 | replace_order_by_clause(&mut name); |
| 933 | } |
| 934 | if !was_aliased { |
| 935 | replace_fn_name_clause( |
| 936 | &mut name, |
| 937 | self.fun.name(), |
| 938 | reverse_udf.name(), |
| 939 | ); |
| 940 | } |
| 941 | |
| 942 | if let Some(human_display) = human_display.as_mut() { |
| 943 | if self.fun().name() != reverse_udf.name() { |
| 944 | replace_order_by_clause(&mut human_display.expression); |
| 945 | } |
| 946 | replace_fn_name_clause( |
| 947 | &mut human_display.expression, |
| 948 | self.fun.name(), |
| 949 | reverse_udf.name(), |
| 950 | ); |
| 951 | } |
| 952 | |
| 953 | let mut builder = |
| 954 | AggregateExprBuilder::new(reverse_udf, self.args.to_vec()) |
| 955 | .order_by(self.order_bys.iter().map(|e| e.reverse()).collect()) |
| 956 | .schema(Arc::new(self.schema.clone())) |
| 957 | .alias(name) |
| 958 | .output_metadata(self.return_field_metadata()) |
| 959 | .with_ignore_nulls(self.ignore_nulls) |
| 960 | .with_distinct(self.is_distinct) |
| 961 | .with_reversed(!self.is_reversed); |
| 962 | if let Some(human_display) = human_display { |
| 963 | builder = builder.human_display(human_display.expression); |
| 964 | if let Some(alias) = human_display.alias { |
| 965 | builder = builder.human_display_alias(alias); |
| 966 | } |
| 967 | } |
| 968 | builder.build().ok() |
| 969 | } |
| 970 | } |
| 971 | } |
| 972 | |
| 973 | /// Returns all expressions used in the [`AggregateFunctionExpr`]. |