Skip to main content

flow/batching_mode/
utils.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! some utils for helping with batching mode
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use std::sync::Arc;
19
20use catalog::CatalogManagerRef;
21use common_error::ext::BoxedError;
22use common_function::aggrs::aggr_wrapper::get_aggr_func;
23use common_telemetry::debug;
24use datafusion::arrow::datatypes::DataType as ArrowDataType;
25use datafusion::datasource::DefaultTableSource;
26use datafusion::error::Result as DfResult;
27use datafusion::logical_expr::Expr;
28use datafusion::sql::unparser::Unparser;
29use datafusion_common::tree_node::{
30    Transformed, TreeNode as _, TreeNodeRecursion, TreeNodeRewriter, TreeNodeVisitor,
31};
32use datafusion_common::{
33    Column, DFSchema, DataFusionError, NullEquality, ScalarValue, TableReference,
34};
35use datafusion_expr::logical_plan::{Aggregate, TableScanBuilder};
36use datafusion_expr::{
37    Distinct, ExprSchemable, JoinType, LogicalPlan, LogicalPlanBuilder, Operator, Projection, and,
38    binary_expr, bitwise_and, bitwise_or, bitwise_xor, is_null, or, when,
39};
40use datatypes::prelude::ConcreteDataType;
41use datatypes::schema::{ColumnSchema, SchemaRef};
42use query::QueryEngineRef;
43use query::parser::{DEFAULT_LOOKBACK_STRING, PromQuery, QueryLanguageParser, QueryStatement};
44use session::context::QueryContextRef;
45use snafu::{OptionExt, ResultExt, ensure};
46use sql::parser::{ParseOptions, ParserContext};
47use sql::statements::statement::Statement;
48use sql::statements::tql::Tql;
49use table::TableRef;
50use table::table::adapter::DfTableProviderAdapter;
51
52use crate::adapter::{AUTO_CREATED_PLACEHOLDER_TS_COL, AUTO_CREATED_UPDATE_AT_TS_COL};
53use crate::df_optimizer::apply_df_optimizer;
54use crate::error::{DatafusionSnafu, ExternalSnafu, InvalidQuerySnafu, TableNotFoundSnafu};
55use crate::{Error, TableName};
56
57#[cfg(test)]
58mod test;
59
60/// Describes how one aggregate output field should be merged with the
61/// corresponding existing field in the sink table.
62///
63/// `output_field_name` is the final output/sink schema field name produced by
64/// the delta plan and read from the sink table. It is not a DataFusion `Column`
65/// reference. It may contain dots or other non-identifier characters when the
66/// query keeps DataFusion's raw aggregate output name, e.g.
67/// `max(numbers_with_ts.number)`.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct IncrementalAggregateMergeColumn {
70    /// Delta-plan field containing the aggregate result/state column. Repeated
71    /// projections intentionally share this field while using distinct outputs.
72    pub input_field_name: String,
73    /// Final output/sink field name for the aggregate result/state column.
74    ///
75    pub output_field_name: String,
76    pub merge_op: IncrementalAggregateMergeOp,
77}
78
79impl IncrementalAggregateMergeColumn {
80    /// Create a new merge column whose delta and output fields have the same name.
81    pub fn new(output_field_name: String, merge_op: IncrementalAggregateMergeOp) -> Self {
82        Self {
83            input_field_name: output_field_name.clone(),
84            output_field_name,
85            merge_op,
86        }
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum IncrementalAggregateMergeOp {
92    Sum,
93    Min,
94    Max,
95    BoolAnd,
96    BoolOr,
97    BitAnd,
98    BitOr,
99    BitXor,
100    StateDeltaMerge {
101        function_name: &'static str,
102        params: Vec<Expr>,
103    },
104}
105
106/// Analysis result for an incremental aggregate plan.
107///
108/// `group_key_names` and each merge column's `output_field_name` are final
109/// output/sink schema field names used to project both the delta plan and the
110/// sink table before the left-join merge. They are not DataFusion logical-plan
111/// `Column` references; callers must attach qualifiers structurally instead of
112/// formatting qualified names as strings.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct IncrementalAggregateAnalysis {
115    /// Final output/sink field names for group keys used as merge join keys.
116    pub group_key_names: Vec<String>,
117    pub merge_columns: Vec<IncrementalAggregateMergeColumn>,
118    /// Literal output fields that can be passed through from the delta plan.
119    pub literal_columns: Vec<String>,
120    /// Final output field order from the original aggregate plan.
121    pub output_field_names: Vec<String>,
122    pub unsupported_exprs: Vec<String>,
123}
124
125fn unqualified_col(name: impl Into<String>) -> Expr {
126    Expr::Column(Column::from_name(name.into()))
127}
128
129fn qualified_col(qualifier: &str, name: impl Into<String>) -> Expr {
130    Expr::Column(Column::new(Some(qualifier), name.into()))
131}
132
133fn qualified_column(qualifier: &str, name: impl Into<String>) -> Column {
134    Column::new(Some(qualifier), name.into())
135}
136
137fn find_group_key_names(plan: &LogicalPlan) -> Result<Vec<String>, Error> {
138    let mut group_finder = FindGroupByFinalName::default();
139    plan.visit(&mut group_finder)
140        .with_context(|_| DatafusionSnafu {
141            context: format!("Failed to inspect group-by columns from logical plan: {plan:?}"),
142        })?;
143
144    let mut group_key_names = group_finder
145        .get_group_expr_names()
146        .unwrap_or_default()
147        .into_iter()
148        .collect::<Vec<_>>();
149    group_key_names.sort();
150    Ok(group_key_names)
151}
152
153fn has_grouping_set(plan: &LogicalPlan) -> bool {
154    match plan {
155        LogicalPlan::Aggregate(aggregate) => aggregate
156            .group_expr
157            .iter()
158            .any(|expr| matches!(expr, Expr::GroupingSet(_))),
159        _ => plan.inputs().into_iter().any(has_grouping_set),
160    }
161}
162
163fn has_aggregate(plan: &LogicalPlan) -> bool {
164    match plan {
165        LogicalPlan::Aggregate(_) => true,
166        _ => plan.inputs().into_iter().any(has_aggregate),
167    }
168}
169
170fn peel_subquery_aliases(mut plan: &LogicalPlan) -> &LogicalPlan {
171    while let LogicalPlan::SubqueryAlias(alias) = plan {
172        plan = alias.input.as_ref();
173    }
174    plan
175}
176
177fn extract_incremental_aggregate(plan: &LogicalPlan) -> Result<Option<&Aggregate>, String> {
178    // Supported final shape: optional output Projection directly over one
179    // Aggregate. Post-aggregate filters (HAVING), ordering, limits,
180    // distinct/window/union/extension nodes are intentionally not accepted.
181    let plan = match plan {
182        LogicalPlan::Projection(projection) => projection.input.as_ref(),
183        _ => plan,
184    };
185
186    match plan {
187        LogicalPlan::Aggregate(aggregate) => {
188            check_input_plan_shape(aggregate.input.as_ref())?;
189            Ok(Some(aggregate))
190        }
191        LogicalPlan::Filter(filter) if has_aggregate(filter.input.as_ref()) => Err(
192            "unsupported post-aggregate filter (HAVING) in incremental aggregate rewrite"
193                .to_string(),
194        ),
195        _ if has_aggregate(plan) => Err(
196            "unsupported post-aggregate plan shape in incremental aggregate rewrite".to_string(),
197        ),
198        _ => Ok(None),
199    }
200}
201
202fn check_input_plan_shape(plan: &LogicalPlan) -> Result<(), String> {
203    let plan = peel_subquery_aliases(plan);
204    match plan {
205        // Supported aggregate input shape: optional WHERE filter over a table scan.
206        // SubqueryAlias is a transparent naming wrapper for `FROM table AS alias`.
207        LogicalPlan::TableScan(_) => Ok(()),
208        LogicalPlan::Filter(filter) => match peel_subquery_aliases(filter.input.as_ref()) {
209            LogicalPlan::TableScan(_) => Ok(()),
210            _ => Err(
211                "unsupported aggregate input plan shape in incremental aggregate rewrite"
212                    .to_string(),
213            ),
214        },
215        _ => Err(
216            "unsupported aggregate input plan shape in incremental aggregate rewrite".to_string(),
217        ),
218    }
219}
220
221#[derive(Debug, Default)]
222struct OutputProjectionInfo {
223    has_top_level_projection: bool,
224    /// Aggregate expression name and projected output field, in projection order.
225    aggregate_outputs: Vec<(String, String)>,
226    literal_columns: HashSet<String>,
227    output_field_names: Vec<String>,
228}
229
230impl OutputProjectionInfo {
231    fn output_field_name_set(&self) -> HashSet<String> {
232        self.output_field_names.iter().cloned().collect()
233    }
234
235    fn duplicate_output_names(&self) -> Vec<String> {
236        let mut seen = HashSet::new();
237        let mut duplicates = BTreeSet::new();
238        for name in &self.output_field_names {
239            if !seen.insert(name.clone()) {
240                duplicates.insert(name.clone());
241            }
242        }
243        duplicates.into_iter().collect()
244    }
245}
246
247fn collect_output_projection_info(plan: &LogicalPlan) -> OutputProjectionInfo {
248    let mut projection_info = OutputProjectionInfo {
249        has_top_level_projection: matches!(plan, LogicalPlan::Projection(_)),
250        output_field_names: plan
251            .schema()
252            .fields()
253            .iter()
254            .map(|field| field.name().clone())
255            .collect(),
256        ..Default::default()
257    };
258
259    if let LogicalPlan::Projection(projection) = plan {
260        for expr in &projection.expr {
261            match expr {
262                Expr::Alias(alias) => {
263                    // Only a direct aggregate output column has the same
264                    // merge semantics as the original resolver. In particular,
265                    // do not mine aggregate columns through CAST/TryCast or
266                    // other output wrappers.
267                    let alias_name = alias.name.clone();
268                    if let Expr::Column(column) = alias.expr.as_ref() {
269                        projection_info
270                            .aggregate_outputs
271                            .push((column.name.clone(), alias_name));
272                    } else if let Expr::Alias(inner_alias) = alias.expr.as_ref()
273                        && inner_alias.name.eq_ignore_ascii_case("count(*)")
274                        && let Expr::Column(column) = inner_alias.expr.as_ref()
275                    {
276                        projection_info
277                            .aggregate_outputs
278                            .push((column.name.clone(), alias_name));
279                    } else if is_passthrough_output_column(&alias_name, alias.expr.as_ref()) {
280                        projection_info.literal_columns.insert(alias_name);
281                    }
282                }
283                Expr::Column(col) => {
284                    projection_info
285                        .aggregate_outputs
286                        .push((col.name.clone(), col.name.clone()));
287                }
288                Expr::Literal(_, _) => {
289                    projection_info
290                        .literal_columns
291                        .insert(expr.qualified_name().1);
292                }
293                _ => {}
294            }
295        }
296    }
297
298    if projection_info
299        .output_field_names
300        .iter()
301        .any(|name| name == AUTO_CREATED_PLACEHOLDER_TS_COL)
302    {
303        projection_info
304            .literal_columns
305            .insert(AUTO_CREATED_PLACEHOLDER_TS_COL.to_string());
306    }
307
308    projection_info
309}
310
311fn is_passthrough_output_column(alias_name: &str, expr: &Expr) -> bool {
312    matches!(expr, Expr::Literal(_, _))
313        || match alias_name {
314            AUTO_CREATED_UPDATE_AT_TS_COL => expr == &datafusion::prelude::now(),
315            AUTO_CREATED_PLACEHOLDER_TS_COL => is_literal_or_cast_literal(expr),
316            _ => false,
317        }
318}
319
320fn is_literal_or_cast_literal(expr: &Expr) -> bool {
321    match expr {
322        Expr::Literal(_, _) => true,
323        Expr::Cast(cast) => is_literal_or_cast_literal(cast.expr.as_ref()),
324        Expr::TryCast(cast) => is_literal_or_cast_literal(cast.expr.as_ref()),
325        _ => false,
326    }
327}
328
329fn merge_op_for_aggregate_expr(
330    aggr_expr: &Expr,
331    input_schema: &DFSchema,
332) -> Result<IncrementalAggregateMergeOp, String> {
333    let Some(aggr_func) = get_aggr_func(aggr_expr) else {
334        return Err(aggr_expr.to_string());
335    };
336    if aggr_func.params.distinct {
337        return Err(format!("unsupported DISTINCT aggregate: {aggr_expr}"));
338    }
339    if !aggr_func.params.order_by.is_empty() {
340        return Err(format!("unsupported aggregate ORDER BY: {aggr_expr}"));
341    }
342    if aggr_func.params.null_treatment.is_some() {
343        return Err(format!("unsupported aggregate NULL treatment: {aggr_expr}"));
344    }
345
346    let state_delta_merge = |function_name, params| {
347        Ok(IncrementalAggregateMergeOp::StateDeltaMerge {
348            function_name,
349            params,
350        })
351    };
352    match aggr_func.func.name().to_ascii_lowercase().as_str() {
353        "sum" | "count" => Ok(IncrementalAggregateMergeOp::Sum),
354        "min" => Ok(IncrementalAggregateMergeOp::Min),
355        "max" => Ok(IncrementalAggregateMergeOp::Max),
356        "bool_and" => Ok(IncrementalAggregateMergeOp::BoolAnd),
357        "bool_or" => Ok(IncrementalAggregateMergeOp::BoolOr),
358        "bit_and" => Ok(IncrementalAggregateMergeOp::BitAnd),
359        "bit_or" => Ok(IncrementalAggregateMergeOp::BitOr),
360        "bit_xor" => Ok(IncrementalAggregateMergeOp::BitXor),
361        // Preserve state-family parameters; value coercion is handled by the aggregate.
362        "avg_state" if aggr_func.params.args.len() == 1 => {
363            state_delta_merge("__avg_state_delta_merge", vec![])
364        }
365        "hll" if aggr_func.params.args.len() == 1 => state_delta_merge("__hll_delta_merge", vec![]),
366        "stddev_pop_state" if aggr_func.params.args.len() == 1 => {
367            state_delta_merge("__stddev_pop_state_delta_merge", vec![])
368        }
369        "uddsketch_state" if aggr_func.params.args.len() == 3 => {
370            let [bucket_size, error_rate, _] = aggr_func.params.args.as_slice() else {
371                unreachable!();
372            };
373            if !matches!(bucket_size, Expr::Literal(ScalarValue::Int64(Some(_)), _))
374                || !matches!(error_rate, Expr::Literal(ScalarValue::Float64(Some(_)), _))
375            {
376                return Err(aggr_expr.to_string());
377            }
378            state_delta_merge(
379                "__uddsketch_state_delta_merge",
380                vec![bucket_size.clone(), error_rate.clone()],
381            )
382        }
383        // AVG's binary merge form is admitted because its state argument is
384        // already the aggregate result stored by the sink.
385        "avg_merge"
386            if aggr_func.params.args.len() == 1
387                && aggr_func.params.args[0].get_type(input_schema).ok()
388                    == Some(ArrowDataType::Binary) =>
389        {
390            state_delta_merge("__avg_state_delta_merge", vec![])
391        }
392        _ => Err(aggr_expr.to_string()),
393    }
394}
395
396fn resolve_aggregate_output_fields(
397    aggr_expr: &Expr,
398    projection_info: &OutputProjectionInfo,
399    output_field_name_set: &HashSet<String>,
400) -> Vec<(String, String)> {
401    // qualified_name() returns (Option<String>, String) where the second
402    // element is the unqualified column/alias name. This relies on
403    // DataFusion's internal naming convention: aggregate expressions
404    // emit a column named after the aggregate itself (e.g. "SUM(x)").
405    // Keep every matching projection occurrence because DataFusion can share
406    // one aggregate input field for identical expressions.
407    let raw_name = aggr_expr.qualified_name().1;
408    if projection_info.has_top_level_projection {
409        projection_info
410            .aggregate_outputs
411            .iter()
412            .filter(|(input_name, _)| input_name == &raw_name)
413            .cloned()
414            .collect()
415    } else if output_field_name_set.contains(&raw_name) {
416        vec![(raw_name.clone(), raw_name)]
417    } else {
418        vec![]
419    }
420}
421
422fn find_uncovered_output_fields(
423    projection_info: &OutputProjectionInfo,
424    group_key_names: &[String],
425    merge_columns: &[IncrementalAggregateMergeColumn],
426) -> Vec<String> {
427    let group_key_names = group_key_names.iter().cloned().collect::<HashSet<_>>();
428    let merge_column_names = merge_columns
429        .iter()
430        .map(|c| c.output_field_name.clone())
431        .collect::<HashSet<_>>();
432
433    projection_info
434        .output_field_names
435        .iter()
436        .filter(|name| {
437            !group_key_names.contains(*name)
438                && !merge_column_names.contains(*name)
439                && !projection_info.literal_columns.contains(*name)
440                // Auto-created sink columns injected by ColumnMatcherRewriter
441                // are not part of the original aggregate semantics and must
442                // not prevent incremental aggregate rewrites.
443                && name.as_str() != AUTO_CREATED_UPDATE_AT_TS_COL
444                && name.as_str() != AUTO_CREATED_PLACEHOLDER_TS_COL
445        })
446        .cloned()
447        .collect()
448}
449
450fn find_unsupported_group_key_projection_outputs(
451    plan: &LogicalPlan,
452    aggregate: &Aggregate,
453    group_key_names: &[String],
454) -> Vec<String> {
455    let LogicalPlan::Projection(projection) = plan else {
456        return vec![];
457    };
458
459    let group_key_names = group_key_names.iter().cloned().collect::<HashSet<_>>();
460    let group_expr_names = aggregate
461        .group_expr
462        .iter()
463        .filter_map(|expr| expr.name_for_alias().ok())
464        .collect::<HashSet<_>>();
465    projection
466        .expr
467        .iter()
468        .filter_map(|expr| {
469            let output_name = expr.qualified_name().1;
470            if !group_key_names.contains(&output_name) {
471                return None;
472            }
473
474            let source_name = match expr {
475                Expr::Alias(alias) => alias.expr.name_for_alias().ok(),
476                _ => expr.name_for_alias().ok(),
477            };
478            if source_name.is_some_and(|name| group_expr_names.contains(&name)) {
479                None
480            } else {
481                Some(format!(
482                    "unsupported group key output field is not a transparent group expression: {output_name}"
483                ))
484            }
485        })
486        .collect()
487}
488
489pub fn analyze_incremental_aggregate_plan(
490    plan: &LogicalPlan,
491) -> Result<Option<IncrementalAggregateAnalysis>, Error> {
492    let group_key_names = find_group_key_names(plan)?;
493    let aggregate = match extract_incremental_aggregate(plan) {
494        Ok(Some(aggregate)) => aggregate,
495        Ok(None) => return Ok(None),
496        Err(reason) => {
497            let projection_info = collect_output_projection_info(plan);
498            let mut unsupported_exprs = projection_info
499                .duplicate_output_names()
500                .into_iter()
501                .map(|name| format!("duplicate output field name: {name}"))
502                .collect::<Vec<_>>();
503            unsupported_exprs.push(reason);
504            return Ok(Some(IncrementalAggregateAnalysis {
505                group_key_names,
506                merge_columns: vec![],
507                literal_columns: vec![],
508                output_field_names: projection_info.output_field_names,
509                unsupported_exprs,
510            }));
511        }
512    };
513    let aggr_exprs = aggregate.aggr_expr.clone();
514    let projection_info = collect_output_projection_info(plan);
515    let output_field_name_set = projection_info.output_field_name_set();
516
517    let mut merge_columns = Vec::with_capacity(aggr_exprs.len());
518    let mut unsupported_exprs = projection_info
519        .duplicate_output_names()
520        .into_iter()
521        .map(|name| format!("duplicate output field name: {name}"))
522        .collect::<Vec<_>>();
523    if has_grouping_set(plan) {
524        unsupported_exprs.push(
525            "unsupported GROUPING SETS/CUBE/ROLLUP in incremental aggregate rewrite".to_string(),
526        );
527    }
528    if group_key_names.is_empty() {
529        unsupported_exprs
530            .push("unsupported global aggregate in incremental aggregate rewrite".to_string());
531    }
532    unsupported_exprs.extend(find_unsupported_group_key_projection_outputs(
533        plan,
534        aggregate,
535        &group_key_names,
536    ));
537    for aggr_expr in aggr_exprs {
538        let merge_op = match merge_op_for_aggregate_expr(&aggr_expr, aggregate.input.schema()) {
539            Ok(merge_op) => merge_op,
540            Err(reason) => {
541                unsupported_exprs.push(reason);
542                continue;
543            }
544        };
545        let aggregate_outputs =
546            resolve_aggregate_output_fields(&aggr_expr, &projection_info, &output_field_name_set);
547        if aggregate_outputs.is_empty() {
548            unsupported_exprs.push(aggr_expr.to_string());
549            continue;
550        }
551        let Some((_, input_field_name)) = aggregate_outputs.first() else {
552            continue;
553        };
554        let input_field_name = input_field_name.clone();
555        for (_, output_field_name) in aggregate_outputs {
556            merge_columns.push(IncrementalAggregateMergeColumn {
557                input_field_name: input_field_name.clone(),
558                output_field_name,
559                merge_op: merge_op.clone(),
560            });
561        }
562    }
563    if projection_info.has_top_level_projection {
564        let output_positions = projection_info
565            .output_field_names
566            .iter()
567            .enumerate()
568            .map(|(position, name)| (name.as_str(), position))
569            .collect::<HashMap<_, _>>();
570        merge_columns.sort_by_key(|column| {
571            output_positions
572                .get(column.output_field_name.as_str())
573                .copied()
574                .unwrap_or(usize::MAX)
575        });
576    }
577    unsupported_exprs.extend(
578        find_uncovered_output_fields(&projection_info, &group_key_names, &merge_columns)
579            .into_iter()
580            .map(|name| format!("unsupported output field: {name}")),
581    );
582    if !unsupported_exprs.is_empty() {
583        merge_columns.clear();
584    }
585    let mut literal_columns = projection_info
586        .literal_columns
587        .into_iter()
588        .collect::<Vec<_>>();
589    literal_columns.sort();
590
591    Ok(Some(IncrementalAggregateAnalysis {
592        group_key_names,
593        merge_columns,
594        literal_columns,
595        output_field_names: projection_info.output_field_names,
596        unsupported_exprs,
597    }))
598}
599
600/// Rewrites one incremental aggregate delta plan by left-joining it with the
601/// existing sink-table state and projecting merged aggregate outputs.
602///
603/// For a grouped aggregate such as:
604///
605/// ```text
606/// SELECT max(number) AS number, ts FROM numbers_with_ts GROUP BY ts
607/// ```
608///
609/// the rewrite is roughly:
610///
611/// ```text
612/// delta = SELECT ts, number FROM <delta_plan> AS __flow_delta
613/// sink_scan = SELECT * FROM <sink_table> [WHERE <sink_dirty_filter>]
614/// sink  = SELECT ts, number FROM sink_scan AS __flow_sink
615/// SELECT
616///   CASE
617///     WHEN __flow_sink.number IS NULL THEN __flow_delta.number
618///     WHEN __flow_delta.number >= __flow_sink.number THEN __flow_delta.number
619///     ELSE __flow_sink.number
620///   END AS number,
621///   __flow_delta.ts AS ts
622/// FROM delta
623/// LEFT JOIN sink
624///   ON __flow_delta.ts IS NOT DISTINCT FROM __flow_sink.ts
625/// ```
626///
627/// If `sink_dirty_filter` is provided, it is applied to the sink table scan
628/// before projection, aliasing, and the left join. The predicate must reference
629/// raw sink table columns structurally (unqualified), before the `__flow_sink`
630/// alias exists.
631pub async fn rewrite_incremental_aggregate_with_sink_merge(
632    delta_plan: &LogicalPlan,
633    analysis: &IncrementalAggregateAnalysis,
634    engine: &QueryEngineRef,
635    sink_table: TableRef,
636    sink_table_name: &TableName,
637    sink_dirty_filter: Option<Expr>,
638) -> Result<LogicalPlan, Error> {
639    ensure!(
640        analysis.unsupported_exprs.is_empty(),
641        InvalidQuerySnafu {
642            reason: format!(
643                "UNSUPPORTED_INCREMENTAL_AGG: unsupported aggregate expressions {:?}",
644                analysis.unsupported_exprs
645            )
646        }
647    );
648
649    ensure!(
650        !analysis.merge_columns.is_empty(),
651        InvalidQuerySnafu {
652            reason:
653                "UNSUPPORTED_INCREMENTAL_AGG: aggregate query has no mergeable aggregate columns"
654                    .to_string()
655        }
656    );
657
658    ensure!(
659        !analysis.group_key_names.is_empty(),
660        InvalidQuerySnafu {
661            reason: "UNSUPPORTED_INCREMENTAL_AGG: global aggregate query is not supported"
662                .to_string()
663        }
664    );
665
666    let delta_alias = "__flow_delta";
667    let sink_alias = "__flow_sink";
668
669    let state_merge = analysis.merge_columns.iter().any(|column| {
670        matches!(
671            &column.merge_op,
672            IncrementalAggregateMergeOp::StateDeltaMerge { .. }
673        )
674    });
675    let mut selected_columns = analysis.group_key_names.clone();
676    selected_columns.extend(
677        analysis
678            .merge_columns
679            .iter()
680            .map(|c| c.output_field_name.clone()),
681    );
682    let mut selected_column_names = HashSet::new();
683    selected_columns.retain(|name| selected_column_names.insert(name.clone()));
684    let mut delta_selected_columns = analysis.group_key_names.clone();
685    delta_selected_columns.extend(
686        analysis
687            .merge_columns
688            .iter()
689            .map(|c| c.input_field_name.clone()),
690    );
691    delta_selected_columns.extend(analysis.literal_columns.iter().cloned());
692    let mut delta_selected_column_names = HashSet::new();
693    delta_selected_columns.retain(|name| delta_selected_column_names.insert(name.clone()));
694
695    let delta_selected_exprs = delta_selected_columns
696        .iter()
697        .cloned()
698        .map(unqualified_col)
699        .collect::<Vec<_>>();
700    let delta_selected = LogicalPlanBuilder::from(delta_plan.clone())
701        .project(delta_selected_exprs)
702        .with_context(|_| DatafusionSnafu {
703            context: "Failed to project delta plan for incremental sink merge".to_string(),
704        })?
705        .alias(delta_alias)
706        .with_context(|_| DatafusionSnafu {
707            context: "Failed to alias delta plan for incremental sink merge".to_string(),
708        })?
709        .build()
710        .with_context(|_| DatafusionSnafu {
711            context: "Failed to build projected delta plan for incremental sink merge".to_string(),
712        })?;
713
714    let table_provider = Arc::new(DfTableProviderAdapter::new(sink_table));
715    let table_source = Arc::new(DefaultTableSource::new(table_provider));
716    let sink_scan = LogicalPlan::TableScan(
717        TableScanBuilder::new(
718            TableReference::Full {
719                catalog: sink_table_name[0].clone().into(),
720                schema: sink_table_name[1].clone().into(),
721                table: sink_table_name[2].clone().into(),
722            },
723            table_source,
724        )
725        .build()
726        .with_context(|_| DatafusionSnafu {
727            context: "Failed to build sink table scan for incremental sink merge".to_string(),
728        })?,
729    );
730
731    let sink_selected_exprs = selected_columns
732        .iter()
733        .cloned()
734        .map(unqualified_col)
735        .collect::<Vec<_>>();
736    let sink_input = if let Some(predicate) = sink_dirty_filter {
737        LogicalPlanBuilder::from(sink_scan)
738            .filter(predicate)
739            .with_context(|_| DatafusionSnafu {
740                context: "Failed to filter sink table scan for incremental sink merge".to_string(),
741            })?
742            .build()
743            .with_context(|_| DatafusionSnafu {
744                context: "Failed to build filtered sink plan for incremental sink merge"
745                    .to_string(),
746            })?
747    } else {
748        sink_scan
749    };
750
751    let sink_selected = LogicalPlanBuilder::from(sink_input)
752        .project(sink_selected_exprs)
753        .with_context(|_| DatafusionSnafu {
754            context: "Failed to project sink table scan for incremental sink merge".to_string(),
755        })?
756        .alias(sink_alias)
757        .with_context(|_| DatafusionSnafu {
758            context: "Failed to alias sink plan for incremental sink merge".to_string(),
759        })?
760        .build()
761        .with_context(|_| DatafusionSnafu {
762            context: "Failed to build projected sink plan for incremental sink merge".to_string(),
763        })?;
764
765    let join_keys = (
766        analysis
767            .group_key_names
768            .iter()
769            .cloned()
770            .map(|c| qualified_column(delta_alias, c))
771            .collect::<Vec<_>>(),
772        analysis
773            .group_key_names
774            .iter()
775            .cloned()
776            .map(|c| qualified_column(sink_alias, c))
777            .collect::<Vec<_>>(),
778    );
779
780    let joined = LogicalPlanBuilder::from(delta_selected)
781        .join_detailed(
782            sink_selected,
783            JoinType::Left,
784            join_keys,
785            None,
786            NullEquality::NullEqualsNull,
787        )
788        .with_context(|_| DatafusionSnafu {
789            context: "Failed to left join delta and sink plans for incremental sink merge"
790                .to_string(),
791        })?
792        .build()
793        .with_context(|_| DatafusionSnafu {
794            context: "Failed to build left join plan for incremental sink merge".to_string(),
795        })?;
796
797    let group_key_names = analysis.group_key_names.iter().collect::<HashSet<_>>();
798    let literal_columns = analysis.literal_columns.iter().collect::<HashSet<_>>();
799    let merge_columns = analysis
800        .merge_columns
801        .iter()
802        .map(|c| (&c.output_field_name, c))
803        .collect::<HashMap<_, _>>();
804
805    let mut ordinary_exprs = Vec::with_capacity(analysis.output_field_names.len());
806    let mut state_aggr_exprs = Vec::new();
807    for output_field_name in &analysis.output_field_names {
808        if group_key_names.contains(output_field_name)
809            || literal_columns.contains(output_field_name)
810        {
811            let expr =
812                qualified_col(delta_alias, output_field_name.clone()).alias(output_field_name);
813            ordinary_exprs.push(expr);
814        } else if let Some(merge_col) = merge_columns.get(output_field_name) {
815            if matches!(
816                &merge_col.merge_op,
817                IncrementalAggregateMergeOp::StateDeltaMerge { .. }
818            ) {
819                state_aggr_exprs.push(build_state_delta_merge_expr(engine, merge_col)?);
820            } else {
821                let expr = build_left_join_merge_expr(delta_alias, sink_alias, merge_col)?;
822                ordinary_exprs.push(expr);
823            }
824        } else {
825            return InvalidQuerySnafu {
826                reason: format!(
827                    "UNSUPPORTED_INCREMENTAL_AGG: output field {output_field_name} is not covered by group keys, literals, or merge columns"
828                ),
829            }
830            .fail();
831        }
832    }
833
834    if state_merge {
835        let aggregated = LogicalPlanBuilder::from(joined)
836            .aggregate(ordinary_exprs, state_aggr_exprs)
837            .with_context(|_| DatafusionSnafu {
838                context: "Failed to aggregate state delta merge plan".to_string(),
839            })?
840            .build()
841            .with_context(|_| DatafusionSnafu {
842                context: "Failed to build state delta merge plan".to_string(),
843            })?;
844        let output_exprs = analysis
845            .output_field_names
846            .iter()
847            .cloned()
848            .map(unqualified_col)
849            .collect::<Vec<_>>();
850        LogicalPlanBuilder::from(aggregated)
851            .project(output_exprs)
852            .with_context(|_| DatafusionSnafu {
853                context: "Failed to project state delta merge plan".to_string(),
854            })?
855            .build()
856            .with_context(|_| DatafusionSnafu {
857                context: "Failed to finalize incremental aggregate sink merge plan".to_string(),
858            })
859    } else {
860        LogicalPlanBuilder::from(joined)
861            .project(ordinary_exprs)
862            .with_context(|_| DatafusionSnafu {
863                context: "Failed to build projection merge plan for incremental sink merge"
864                    .to_string(),
865            })?
866            .build()
867            .with_context(|_| DatafusionSnafu {
868                context: "Failed to finalize incremental aggregate sink merge plan".to_string(),
869            })
870    }
871}
872
873fn build_state_delta_merge_expr(
874    engine: &QueryEngineRef,
875    merge_col: &IncrementalAggregateMergeColumn,
876) -> Result<Expr, Error> {
877    let (function_name, params) = match &merge_col.merge_op {
878        IncrementalAggregateMergeOp::StateDeltaMerge {
879            function_name,
880            params,
881        } => (*function_name, params.clone()),
882        _ => {
883            return InvalidQuerySnafu {
884                reason: "non-state aggregate passed to state delta merge".to_string(),
885            }
886            .fail();
887        }
888    };
889    let Some(udaf) = engine
890        .engine_state()
891        .aggr_function(function_name)
892        .or_else(|| {
893            engine
894                .engine_state()
895                .session_state()
896                .aggregate_functions()
897                .get(function_name)
898                .map(|udaf| udaf.as_ref().clone())
899        })
900    else {
901        return InvalidQuerySnafu {
902            reason: format!("Aggregate function {function_name} is not registered"),
903        }
904        .fail();
905    };
906    let mut args = params;
907    args.push(qualified_col(
908        "__flow_delta",
909        merge_col.input_field_name.clone(),
910    ));
911    args.push(qualified_col(
912        "__flow_sink",
913        merge_col.output_field_name.clone(),
914    ));
915    Ok(udaf.call(args).alias(merge_col.output_field_name.clone()))
916}
917
918fn build_left_join_merge_expr(
919    delta_alias: &str,
920    sink_alias: &str,
921    merge_col: &IncrementalAggregateMergeColumn,
922) -> Result<Expr, Error> {
923    let left = qualified_col(delta_alias, merge_col.input_field_name.clone());
924    let right = qualified_col(sink_alias, merge_col.output_field_name.clone());
925    let merged = match merge_col.merge_op.clone() {
926        IncrementalAggregateMergeOp::Sum => when(is_null(left.clone()), right.clone())
927            .when(is_null(right.clone()), left.clone())
928            .otherwise(binary_expr(left.clone(), Operator::Plus, right.clone()))
929            .with_context(|_| DatafusionSnafu {
930                context: "Failed to build SUM merge expression".to_string(),
931            })?,
932        IncrementalAggregateMergeOp::Min => when(is_null(right.clone()), left.clone())
933            .when(left.clone().lt_eq(right.clone()), left.clone())
934            .otherwise(right.clone())
935            .with_context(|_| DatafusionSnafu {
936                context: "Failed to build MIN merge expression".to_string(),
937            })?,
938        IncrementalAggregateMergeOp::Max => when(is_null(right.clone()), left.clone())
939            .when(left.clone().gt_eq(right.clone()), left.clone())
940            .otherwise(right.clone())
941            .with_context(|_| DatafusionSnafu {
942                context: "Failed to build MAX merge expression".to_string(),
943            })?,
944        IncrementalAggregateMergeOp::BoolAnd => when(is_null(left.clone()), right.clone())
945            .when(is_null(right.clone()), left.clone())
946            .otherwise(and(left.clone(), right.clone()))
947            .with_context(|_| DatafusionSnafu {
948                context: "Failed to build BOOL_AND merge expression".to_string(),
949            })?,
950        IncrementalAggregateMergeOp::BoolOr => when(is_null(left.clone()), right.clone())
951            .when(is_null(right.clone()), left.clone())
952            .otherwise(or(left.clone(), right.clone()))
953            .with_context(|_| DatafusionSnafu {
954                context: "Failed to build BOOL_OR merge expression".to_string(),
955            })?,
956        IncrementalAggregateMergeOp::BitAnd => when(is_null(left.clone()), right.clone())
957            .when(is_null(right.clone()), left.clone())
958            .otherwise(bitwise_and(left.clone(), right.clone()))
959            .with_context(|_| DatafusionSnafu {
960                context: "Failed to build BIT_AND merge expression".to_string(),
961            })?,
962        IncrementalAggregateMergeOp::BitOr => when(is_null(left.clone()), right.clone())
963            .when(is_null(right.clone()), left.clone())
964            .otherwise(bitwise_or(left.clone(), right.clone()))
965            .with_context(|_| DatafusionSnafu {
966                context: "Failed to build BIT_OR merge expression".to_string(),
967            })?,
968        IncrementalAggregateMergeOp::BitXor => when(is_null(left.clone()), right.clone())
969            .when(is_null(right.clone()), left.clone())
970            .otherwise(bitwise_xor(left.clone(), right.clone()))
971            .with_context(|_| DatafusionSnafu {
972                context: "Failed to build BIT_XOR merge expression".to_string(),
973            })?,
974        IncrementalAggregateMergeOp::StateDeltaMerge { .. } => {
975            return InvalidQuerySnafu {
976                reason: "state aggregate must be built with its delta UDAF".to_string(),
977            }
978            .fail();
979        }
980    };
981    Ok(merged.alias(merge_col.output_field_name.clone()))
982}
983
984pub async fn get_table_info_df_schema(
985    catalog_mr: CatalogManagerRef,
986    table_name: TableName,
987) -> Result<(TableRef, Arc<DFSchema>), Error> {
988    let full_table_name = table_name.clone().join(".");
989    let table = catalog_mr
990        .table(&table_name[0], &table_name[1], &table_name[2], None)
991        .await
992        .map_err(BoxedError::new)
993        .context(ExternalSnafu)?
994        .context(TableNotFoundSnafu {
995            name: &full_table_name,
996        })?;
997    let table_info = table.table_info();
998
999    let schema = table_info.meta.schema.clone();
1000
1001    let df_schema: Arc<DFSchema> = Arc::new(
1002        schema
1003            .arrow_schema()
1004            .clone()
1005            .try_into()
1006            .with_context(|_| DatafusionSnafu {
1007                context: format!(
1008                    "Failed to convert arrow schema to datafusion schema, arrow_schema={:?}",
1009                    schema.arrow_schema()
1010                ),
1011            })?,
1012    );
1013    Ok((table, df_schema))
1014}
1015
1016/// Convert sql to datafusion logical plan
1017/// Also support TQL (but only Eval not Explain or Analyze)
1018pub async fn sql_to_df_plan(
1019    query_ctx: QueryContextRef,
1020    engine: QueryEngineRef,
1021    sql: &str,
1022    optimize: bool,
1023) -> Result<LogicalPlan, Error> {
1024    let query_stmt = parse_flow_query(&query_ctx, sql)?;
1025    // The plan's columns are matched against the sink table, so a TQL query must publish the same
1026    // columns whichever PromQL route plans it.
1027    let plan = engine
1028        .planner()
1029        .plan_relation(&query_stmt, query_ctx.clone())
1030        .await
1031        .map_err(BoxedError::new)
1032        .context(ExternalSnafu)?;
1033
1034    let plan = if optimize {
1035        apply_df_optimizer(plan, &query_ctx).await?
1036    } else {
1037        plan
1038    };
1039    Ok(plan)
1040}
1041
1042/// The column the native PromQL route publishes each row's metric name under.
1043const METRIC_NAME_COLUMN: &str = "__name__";
1044
1045/// Plans `sql` unoptimized, to be written into a sink table with `sink_schema`.
1046///
1047/// Before TQL flows were planned with `plan_relation`, a flow on the native PromQL route
1048/// auto-created its sink from the native plan's own columns: the value named by that route, the
1049/// labels, and `__name__` as a primary key column. A sink with `__name__` is still written from the
1050/// statement's own plan, so such a flow keeps writing the same columns and the same series keys.
1051/// `plan_relation` and `plan` only differ for a PromQL statement on the native route.
1052async fn sql_to_df_plan_for_sink(
1053    query_ctx: QueryContextRef,
1054    engine: QueryEngineRef,
1055    sql: &str,
1056    sink_schema: &datatypes::schema::Schema,
1057) -> Result<LogicalPlan, Error> {
1058    if sink_schema
1059        .column_schema_by_name(METRIC_NAME_COLUMN)
1060        .is_none()
1061    {
1062        return sql_to_df_plan(query_ctx, engine, sql, false).await;
1063    }
1064    let query_stmt = parse_flow_query(&query_ctx, sql)?;
1065    engine
1066        .planner()
1067        .plan(&query_stmt, query_ctx)
1068        .await
1069        .map_err(BoxedError::new)
1070        .context(ExternalSnafu)
1071}
1072
1073fn parse_flow_query(query_ctx: &QueryContextRef, sql: &str) -> Result<QueryStatement, Error> {
1074    let scheduled_time = query::options::parse_scheduled_time_datetime(&query_ctx.extensions())
1075        .map_err(BoxedError::new)
1076        .context(ExternalSnafu)?;
1077    let stmts = ParserContext::create_with_dialect(
1078        sql,
1079        query_ctx.sql_dialect(),
1080        ParseOptions { scheduled_time },
1081    )
1082    .map_err(BoxedError::new)
1083    .context(ExternalSnafu)?;
1084
1085    ensure!(
1086        stmts.len() == 1,
1087        InvalidQuerySnafu {
1088            reason: format!("Expect only one statement, found {}", stmts.len())
1089        }
1090    );
1091    let stmt = &stmts[0];
1092    let query_stmt = match stmt {
1093        Statement::Tql(tql) => match tql {
1094            Tql::Eval(eval) => {
1095                let eval = eval.clone();
1096                let promql = PromQuery {
1097                    start: eval.start,
1098                    end: eval.end,
1099                    step: eval.step,
1100                    query: eval.query,
1101                    lookback: eval
1102                        .lookback
1103                        .unwrap_or_else(|| DEFAULT_LOOKBACK_STRING.to_string()),
1104                    alias: eval.alias.clone(),
1105                };
1106
1107                QueryLanguageParser::parse_promql(&promql, query_ctx)
1108                    .map_err(BoxedError::new)
1109                    .context(ExternalSnafu)?
1110            }
1111            _ => InvalidQuerySnafu {
1112                reason: format!("TQL statement {tql:?} is not supported, expect only TQL EVAL"),
1113            }
1114            .fail()?,
1115        },
1116        _ => QueryStatement::Sql(stmt.clone()),
1117    };
1118    Ok(query_stmt)
1119}
1120
1121/// Generate a plan that matches the schema of the sink table
1122/// from given sql by alias and adding auto columns
1123pub(crate) async fn gen_plan_with_matching_schema(
1124    sql: &str,
1125    query_ctx: QueryContextRef,
1126    engine: QueryEngineRef,
1127    sink_table_schema: SchemaRef,
1128    primary_key_indices: &[usize],
1129    allow_partial: bool,
1130) -> Result<LogicalPlan, Error> {
1131    gen_plan_with_matching_schema_and_values(
1132        sql,
1133        query_ctx,
1134        engine,
1135        sink_table_schema,
1136        primary_key_indices,
1137        allow_partial,
1138        &BTreeMap::new(),
1139    )
1140    .await
1141}
1142
1143/// Generate a schema-matching plan with extension-owned typed sink values.
1144pub(crate) async fn gen_plan_with_matching_schema_and_values(
1145    sql: &str,
1146    query_ctx: QueryContextRef,
1147    engine: QueryEngineRef,
1148    sink_table_schema: SchemaRef,
1149    primary_key_indices: &[usize],
1150    allow_partial: bool,
1151    values: &BTreeMap<String, ScalarValue>,
1152) -> Result<LogicalPlan, Error> {
1153    let plan = sql_to_df_plan_for_sink(query_ctx, engine, sql, &sink_table_schema).await?;
1154
1155    let mut add_auto_column = ColumnMatcherRewriter::new_with_values(
1156        sink_table_schema,
1157        primary_key_indices.to_vec(),
1158        allow_partial,
1159        values.clone(),
1160    );
1161    let plan = plan
1162        .clone()
1163        .rewrite(&mut add_auto_column)
1164        .with_context(|_| DatafusionSnafu {
1165            context: "Failed to rewrite plan".to_string(),
1166        })?
1167        .data;
1168    Ok(plan)
1169}
1170
1171pub fn df_plan_to_sql(plan: &LogicalPlan) -> Result<String, Error> {
1172    /// A dialect that forces identifiers to be quoted when they contain
1173    /// anything other than lowercase alphanumerics and underscores, or start
1174    /// with a digit.
1175    ///
1176    /// Unquoted identifiers are normalized to lowercase by the SQL parser, so
1177    /// uppercase letters need quoting to preserve case. Special characters
1178    /// (e.g. ':' in Prometheus-style table names like
1179    /// `kube_pod_cpu_cores:sum`, '.', '-', spaces) and digit-leading names
1180    /// (e.g. `123metrics`) would produce invalid SQL if left unquoted, so they
1181    /// are quoted as well. SQL keywords are intentionally not checked here:
1182    /// quoting every ALL_KEYWORDS member would also quote common column names
1183    /// like `number`; the unparse failure path has an InsertIntoPlan fallback.
1184    struct ForceQuoteIdentifiers;
1185    impl datafusion::sql::unparser::dialect::Dialect for ForceQuoteIdentifiers {
1186        fn identifier_quote_style(&self, identifier: &str) -> Option<char> {
1187            let is_plain = !identifier.is_empty()
1188                && !identifier.starts_with(|c: char| c.is_ascii_digit())
1189                && identifier
1190                    .chars()
1191                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
1192            if is_plain { None } else { Some('"') }
1193        }
1194    }
1195    let unparser = Unparser::new(&ForceQuoteIdentifiers);
1196    // first make all column qualified
1197    let sql = unparser
1198        .plan_to_sql(plan)
1199        .with_context(|_e| DatafusionSnafu {
1200            context: format!("Failed to unparse logical plan {plan:?}"),
1201        })?;
1202    Ok(sql.to_string())
1203}
1204
1205/// Returns whether `expr` directly renames the group by expression `group_expr`.
1206///
1207/// Renames are identified only by expression name. Derived unary expressions are not group
1208/// keys, even when they reference a single group key column. A PromQL `count_values("label",
1209/// metric)` plan lands here too: it groups by the formatted sample value
1210/// (`prom_float_to_string(value)`) and projects that group key column as the generated label.
1211fn is_alias_of_group_expr(group_expr: &Expr, expr: &Expr) -> DfResult<bool> {
1212    Ok(group_expr.name_for_alias()? == expr.name_for_alias()?)
1213}
1214
1215/// Helper to find the innermost group by expr in schema, return None if no group by expr
1216#[derive(Debug, Clone, Default)]
1217pub struct FindGroupByFinalName {
1218    group_exprs: Option<HashSet<datafusion_expr::Expr>>,
1219}
1220
1221impl FindGroupByFinalName {
1222    pub fn get_group_expr_names(&self) -> Option<HashSet<String>> {
1223        self.group_exprs
1224            .as_ref()
1225            .map(|exprs| exprs.iter().map(|expr| expr.qualified_name().1).collect())
1226    }
1227}
1228
1229impl TreeNodeVisitor<'_> for FindGroupByFinalName {
1230    type Node = LogicalPlan;
1231
1232    fn f_down(&mut self, node: &Self::Node) -> datafusion_common::Result<TreeNodeRecursion> {
1233        if let LogicalPlan::Aggregate(aggregate) = node {
1234            self.group_exprs = Some(aggregate.group_expr.iter().cloned().collect());
1235            debug!(
1236                "FindGroupByFinalName: Get Group by exprs from Aggregate: {:?}",
1237                self.group_exprs
1238            );
1239        } else if let LogicalPlan::Distinct(distinct) = node {
1240            debug!("FindGroupByFinalName: Distinct: {}", node);
1241            match distinct {
1242                Distinct::All(input) => {
1243                    if let LogicalPlan::TableScan(table_scan) = &**input {
1244                        // get column from field_qualifier, projection and projected_schema:
1245                        let len = table_scan.projected_schema.fields().len();
1246                        let columns = (0..len)
1247                            .map(|f| {
1248                                let (qualifier, field) =
1249                                    table_scan.projected_schema.qualified_field(f);
1250                                datafusion_common::Column::new(qualifier.cloned(), field.name())
1251                            })
1252                            .map(datafusion_expr::Expr::Column);
1253                        self.group_exprs = Some(columns.collect());
1254                    } else {
1255                        self.group_exprs = Some(input.expressions().iter().cloned().collect())
1256                    }
1257                }
1258                Distinct::On(distinct_on) => {
1259                    self.group_exprs = Some(distinct_on.on_expr.iter().cloned().collect())
1260                }
1261            }
1262            debug!(
1263                "FindGroupByFinalName: Get Group by exprs from Distinct: {:?}",
1264                self.group_exprs
1265            );
1266        }
1267
1268        Ok(TreeNodeRecursion::Continue)
1269    }
1270
1271    /// Applies only direct, name-matched aliases when propagating group expressions upward.
1272    fn f_up(&mut self, node: &Self::Node) -> datafusion_common::Result<TreeNodeRecursion> {
1273        if let LogicalPlan::Projection(projection) = node {
1274            // Only direct aliases of group expressions rename group keys. Derived unary
1275            // expressions remain ordinary projected columns.
1276            for expr in &projection.expr {
1277                let Some(group_exprs) = &mut self.group_exprs else {
1278                    return Ok(TreeNodeRecursion::Continue);
1279                };
1280                if let datafusion_expr::Expr::Alias(alias) = expr {
1281                    // if a alias exist, replace with the new alias
1282                    let mut renamed_group_expr = None;
1283                    for group_expr in group_exprs.iter() {
1284                        if is_alias_of_group_expr(group_expr, alias.expr.as_ref())? {
1285                            renamed_group_expr = Some(group_expr.clone());
1286                            break;
1287                        }
1288                    }
1289                    if let Some(group_expr) = renamed_group_expr {
1290                        group_exprs.remove(&group_expr);
1291                        group_exprs.insert(expr.clone());
1292                    }
1293                }
1294            }
1295        }
1296        debug!("Aliased group by exprs: {:?}", self.group_exprs);
1297        Ok(TreeNodeRecursion::Continue)
1298    }
1299}
1300
1301/// Optionally add to the final select columns like `update_at` if the sink table has such column
1302/// (which doesn't necessary need to have exact name just need to be a extra timestamp column)
1303/// and `__ts_placeholder`(this column need to have exact this name and be a timestamp)
1304/// with values like `now()` and `0`
1305///
1306/// it also give existing columns alias to column in sink table if needed
1307#[derive(Debug)]
1308pub struct ColumnMatcherRewriter {
1309    /// Schema used to match the ordinary flow output. It excludes injected values.
1310    pub schema: SchemaRef,
1311    sink_schema: SchemaRef,
1312    values: BTreeMap<String, ScalarValue>,
1313    pub is_rewritten: bool,
1314    pub primary_key_indices: Vec<usize>,
1315    pub allow_partial: bool,
1316}
1317
1318impl ColumnMatcherRewriter {
1319    pub fn new(schema: SchemaRef, primary_key_indices: Vec<usize>, allow_partial: bool) -> Self {
1320        Self {
1321            schema: schema.clone(),
1322            sink_schema: schema,
1323            values: BTreeMap::new(),
1324            is_rewritten: false,
1325            primary_key_indices,
1326            allow_partial,
1327        }
1328    }
1329
1330    /// Match ordinary output against the sink schema excluding typed values, then inject those
1331    /// values in physical sink-column order.
1332    pub fn new_with_values(
1333        sink_schema: SchemaRef,
1334        primary_key_indices: Vec<usize>,
1335        allow_partial: bool,
1336        values: BTreeMap<String, ScalarValue>,
1337    ) -> Self {
1338        let value_names = values.keys().collect::<BTreeSet<_>>();
1339        let ordinary_columns = sink_schema
1340            .column_schemas()
1341            .iter()
1342            .filter(|column| !value_names.contains(&column.name))
1343            .cloned()
1344            .collect();
1345        let ordinary_schema = Arc::new(datatypes::schema::Schema::new(ordinary_columns));
1346        let ordinary_primary_key_indices = primary_key_indices
1347            .into_iter()
1348            .filter_map(|index| {
1349                let name = &sink_schema.column_schemas()[index].name;
1350                ordinary_schema
1351                    .column_schemas()
1352                    .iter()
1353                    .position(|column| column.name == *name)
1354            })
1355            .collect();
1356        Self {
1357            schema: ordinary_schema,
1358            sink_schema,
1359            values,
1360            is_rewritten: false,
1361            primary_key_indices: ordinary_primary_key_indices,
1362            allow_partial,
1363        }
1364    }
1365
1366    fn validate_values(&self, output_exprs: &[Expr]) -> DfResult<()> {
1367        let output_names = output_exprs
1368            .iter()
1369            .map(|expr| expr.qualified_name().1)
1370            .collect::<Vec<_>>();
1371        let duplicated = duplicate_names(&output_names);
1372        if !duplicated.is_empty() {
1373            return Err(DataFusionError::Plan(format!(
1374                "Flow output schema contains duplicate column(s) {:?}. {}",
1375                duplicated,
1376                format_flow_sink_schema_mismatch(output_exprs, self.sink_schema.as_ref())
1377            )));
1378        }
1379        for (name, value) in &self.values {
1380            let Some(column) = self
1381                .sink_schema
1382                .column_schemas()
1383                .iter()
1384                .find(|column| column.name == *name)
1385            else {
1386                return Err(DataFusionError::Plan(format!(
1387                    "Injected flow value column '{name}' is not found in sink schema"
1388                )));
1389            };
1390            if output_names.iter().any(|output| output == name) {
1391                return Err(DataFusionError::Plan(format!(
1392                    "Injected flow value column '{name}' collides with flow output"
1393                )));
1394            }
1395            let value_type = ConcreteDataType::from_arrow_type(&value.data_type());
1396            if value_type != column.data_type {
1397                return Err(DataFusionError::Plan(format!(
1398                    "Injected flow value column '{name}' has type {:?}, but sink column has type {:?}",
1399                    value_type, column.data_type
1400                )));
1401            }
1402        }
1403        Ok(())
1404    }
1405
1406    fn inject_values_in_physical_order(&self, exprs: Vec<Expr>) -> DfResult<Vec<Expr>> {
1407        if self.values.is_empty() {
1408            return Ok(exprs);
1409        }
1410        let mut ordinary = exprs
1411            .into_iter()
1412            .map(|expr| (expr.qualified_name().1, expr))
1413            .collect::<HashMap<_, _>>();
1414        self.sink_schema
1415            .column_schemas()
1416            .iter()
1417            .map(|column| {
1418                if let Some(value) = self.values.get(&column.name) {
1419                    Ok(Expr::Literal(value.clone(), None).alias(column.name.clone()))
1420                } else {
1421                    ordinary.remove(&column.name).ok_or_else(|| {
1422                        DataFusionError::Plan(format!(
1423                            "Flow output is missing sink column '{}' after schema matching",
1424                            column.name
1425                        ))
1426                    })
1427                }
1428            })
1429            .collect()
1430    }
1431
1432    /// modify the exprs in place so that it matches the schema and some auto columns are added
1433    fn modify_project_exprs(
1434        &mut self,
1435        mut exprs: Vec<Expr>,
1436        input_schema: &DFSchema,
1437    ) -> DfResult<Vec<Expr>> {
1438        self.validate_values(&exprs)?;
1439        if self.allow_partial {
1440            let exprs = self.modify_project_exprs_with_partial(exprs)?;
1441            return self.inject_values_in_physical_order(exprs);
1442        }
1443
1444        let original_exprs = exprs.clone();
1445
1446        let all_names = self
1447            .schema
1448            .column_schemas()
1449            .iter()
1450            .map(|c| c.name.clone())
1451            .collect::<BTreeSet<_>>();
1452        // add columns if have different column count
1453        let query_col_cnt = exprs.len();
1454        let table_col_cnt = self.schema.column_schemas().len();
1455        debug!("query_col_cnt={query_col_cnt}, table_col_cnt={table_col_cnt}");
1456
1457        let placeholder_ts_expr =
1458            datafusion::logical_expr::lit(ScalarValue::TimestampMillisecond(Some(0), None))
1459                .alias(AUTO_CREATED_PLACEHOLDER_TS_COL);
1460
1461        if query_col_cnt == table_col_cnt {
1462            // still need to add alias, see below
1463        } else if query_col_cnt + 1 == table_col_cnt {
1464            let last_col_schema = self.schema.column_schemas().last().unwrap();
1465
1466            // if time index column is auto created add it
1467            if last_col_schema.name == AUTO_CREATED_PLACEHOLDER_TS_COL
1468                && self.schema.timestamp_index() == Some(table_col_cnt - 1)
1469            {
1470                exprs.push(placeholder_ts_expr);
1471            } else if last_col_schema.data_type.is_timestamp() {
1472                // is the update at column
1473                exprs.push(datafusion::prelude::now().alias(&last_col_schema.name));
1474            } else {
1475                return Err(DataFusionError::Plan(format_flow_sink_schema_mismatch(
1476                    &original_exprs,
1477                    self.schema.as_ref(),
1478                )));
1479            }
1480        } else if query_col_cnt + 2 == table_col_cnt {
1481            let mut col_iter = self.schema.column_schemas().iter().rev();
1482            let last_col_schema = col_iter.next().unwrap();
1483            let second_last_col_schema = col_iter.next().unwrap();
1484            if second_last_col_schema.data_type.is_timestamp() {
1485                exprs.push(datafusion::prelude::now().alias(&second_last_col_schema.name));
1486            } else {
1487                return Err(DataFusionError::Plan(format!(
1488                    "Expect the second last column in the table to be timestamp column, found column {} with type {:?}",
1489                    second_last_col_schema.name, second_last_col_schema.data_type
1490                )));
1491            }
1492
1493            if last_col_schema.name == AUTO_CREATED_PLACEHOLDER_TS_COL
1494                && self.schema.timestamp_index() == Some(table_col_cnt - 1)
1495            {
1496                exprs.push(placeholder_ts_expr);
1497            } else {
1498                return Err(DataFusionError::Plan(format!(
1499                    "Expect timestamp column {}, found {:?}",
1500                    AUTO_CREATED_PLACEHOLDER_TS_COL, last_col_schema
1501                )));
1502            }
1503        } else {
1504            return Err(DataFusionError::Plan(format_flow_sink_schema_mismatch(
1505                &original_exprs,
1506                self.schema.as_ref(),
1507            )));
1508        }
1509
1510        self.inject_values_in_physical_order(self.match_extra_output_columns(
1511            exprs,
1512            input_schema,
1513            &original_exprs,
1514            &all_names,
1515        )?)
1516    }
1517
1518    /// Match flow output columns whose names are not in the sink schema by the same position only.
1519    ///
1520    /// This keeps the legacy "omit output aliases and map by position" behavior, but only when the
1521    /// sink column at the same index is actually missing from the flow output. If the extra output
1522    /// would be aliased to a sink column that already exists elsewhere, report a schema mismatch
1523    /// instead of guessing another sink column by type.
1524    ///
1525    /// In particular, this intentionally rejects cross-position remaps like
1526    /// `record_time_window2 -> record_time_window`: they are easy to confuse with real schema
1527    /// mismatches and should be fixed by giving the flow output the sink column name explicitly.
1528    fn match_extra_output_columns(
1529        &self,
1530        mut exprs: Vec<Expr>,
1531        input_schema: &DFSchema,
1532        original_exprs: &[Expr],
1533        all_names: &BTreeSet<String>,
1534    ) -> DfResult<Vec<Expr>> {
1535        let mut output_names = exprs
1536            .iter()
1537            .map(|expr| expr.qualified_name().1)
1538            .collect::<Vec<_>>();
1539        let output_name_set = output_names.iter().cloned().collect::<BTreeSet<_>>();
1540        let extra_expr_indices = output_names
1541            .iter()
1542            .enumerate()
1543            .filter_map(|(idx, name)| (!all_names.contains(name)).then_some(idx))
1544            .collect::<Vec<_>>();
1545        let missing_sink_indices = self
1546            .schema
1547            .column_schemas()
1548            .iter()
1549            .enumerate()
1550            .filter_map(|(idx, column)| (!output_name_set.contains(&column.name)).then_some(idx))
1551            .collect::<Vec<_>>();
1552
1553        if extra_expr_indices.is_empty() && missing_sink_indices.is_empty() {
1554            return Ok(exprs);
1555        }
1556
1557        if extra_expr_indices.len() != missing_sink_indices.len() {
1558            return Err(DataFusionError::Plan(format_flow_sink_schema_mismatch(
1559                original_exprs,
1560                self.schema.as_ref(),
1561            )));
1562        }
1563
1564        let mut positional_matches = Vec::new();
1565        for expr_idx in extra_expr_indices {
1566            if !missing_sink_indices.contains(&expr_idx) {
1567                return Err(DataFusionError::Plan(format_flow_sink_schema_mismatch(
1568                    original_exprs,
1569                    self.schema.as_ref(),
1570                )));
1571            }
1572
1573            let target_col_schema = &self.schema.column_schemas()[expr_idx];
1574            let expr_type =
1575                ConcreteDataType::from_arrow_type(&exprs[expr_idx].get_type(input_schema)?);
1576            if is_obviously_incompatible_positional_match(&expr_type, &target_col_schema.data_type)
1577            {
1578                return Err(DataFusionError::Plan(format!(
1579                    "Cannot match flow output column '{}' to sink column '{}' by position: incompatible data types, flow output type is {:?}, sink column type is {:?}. {}",
1580                    output_names[expr_idx],
1581                    target_col_schema.name,
1582                    expr_type,
1583                    target_col_schema.data_type,
1584                    format_flow_sink_schema_mismatch(original_exprs, self.schema.as_ref())
1585                )));
1586            }
1587
1588            let target_name = target_col_schema.name.clone();
1589            positional_matches.push(format!(
1590                "{} -> {} (flow output type: {:?}, sink column type: {:?})",
1591                output_names[expr_idx], target_name, expr_type, target_col_schema.data_type
1592            ));
1593            exprs[expr_idx] = exprs[expr_idx].clone().alias(target_name.clone());
1594            output_names[expr_idx] = target_name;
1595        }
1596
1597        if !positional_matches.is_empty() {
1598            debug!(
1599                "Matched flow output columns to sink columns by position: {:?}",
1600                positional_matches
1601            );
1602        }
1603
1604        let duplicated_output_names = duplicate_names(&output_names);
1605        if !duplicated_output_names.is_empty() {
1606            return Err(DataFusionError::Plan(format!(
1607                "Flow output schema contains duplicate column(s) after schema matching {:?}. {}",
1608                duplicated_output_names,
1609                format_flow_sink_schema_mismatch(&exprs, self.schema.as_ref())
1610            )));
1611        }
1612
1613        Ok(exprs)
1614    }
1615
1616    fn modify_project_exprs_with_partial(&mut self, exprs: Vec<Expr>) -> DfResult<Vec<Expr>> {
1617        let table_col_cnt = self.schema.column_schemas().len();
1618        let query_col_cnt = exprs.len();
1619
1620        if query_col_cnt > table_col_cnt {
1621            return Err(DataFusionError::Plan(format_flow_sink_schema_mismatch(
1622                &exprs,
1623                self.schema.as_ref(),
1624            )));
1625        }
1626
1627        let name_to_expr: HashMap<String, Expr> = exprs
1628            .clone()
1629            .into_iter()
1630            .map(|e| (e.qualified_name().1, e))
1631            .collect();
1632
1633        let required_columns = self.required_columns_for_partial();
1634        let missing: Vec<_> = required_columns
1635            .iter()
1636            .filter(|name| !name_to_expr.contains_key(*name))
1637            .cloned()
1638            .collect();
1639        if !missing.is_empty() {
1640            return Err(DataFusionError::Plan(format!(
1641                "Column(s) {:?} required by sink table are missing from flow output when merge_mode=last_non_null. {}",
1642                missing,
1643                format_flow_sink_schema_mismatch(&exprs, self.schema.as_ref())
1644            )));
1645        }
1646
1647        let placeholder_ts_expr =
1648            datafusion::logical_expr::lit(ScalarValue::TimestampMillisecond(Some(0), None))
1649                .alias(AUTO_CREATED_PLACEHOLDER_TS_COL);
1650
1651        let timestamp_index = self.schema.timestamp_index();
1652        let mut remap = name_to_expr;
1653        let mut new_exprs = Vec::with_capacity(table_col_cnt);
1654
1655        for (idx, col_schema) in self.schema.column_schemas().iter().enumerate() {
1656            let col_name = col_schema.name.clone();
1657            if let Some(expr) = remap.remove(&col_name) {
1658                let expr = if expr.qualified_name().1 == col_name {
1659                    expr
1660                } else {
1661                    expr.alias(col_name.clone())
1662                };
1663                new_exprs.push(expr);
1664                continue;
1665            }
1666
1667            if col_name == AUTO_CREATED_PLACEHOLDER_TS_COL && timestamp_index == Some(idx) {
1668                new_exprs.push(placeholder_ts_expr.clone());
1669                continue;
1670            }
1671
1672            if col_name == AUTO_CREATED_UPDATE_AT_TS_COL && col_schema.data_type.is_timestamp() {
1673                new_exprs.push(datafusion::prelude::now().alias(&col_name));
1674                continue;
1675            }
1676
1677            new_exprs.push(Self::null_expr(col_schema));
1678        }
1679
1680        if !remap.is_empty() {
1681            let extra: Vec<_> = remap.keys().cloned().collect();
1682            return Err(DataFusionError::Plan(format!(
1683                "Flow output has extra column(s) {:?} not found in sink schema when merge_mode=last_non_null. {}",
1684                extra,
1685                format_flow_sink_schema_mismatch(&exprs, self.schema.as_ref())
1686            )));
1687        }
1688
1689        Ok(new_exprs)
1690    }
1691
1692    fn null_expr(col_schema: &ColumnSchema) -> Expr {
1693        Expr::Literal(ScalarValue::Null, None).alias(col_schema.name.clone())
1694    }
1695
1696    fn required_columns_for_partial(&self) -> HashSet<String> {
1697        let mut required = HashSet::new();
1698        for idx in &self.primary_key_indices {
1699            if let Some(col) = self.schema.column_schemas().get(*idx) {
1700                required.insert(col.name.clone());
1701            }
1702        }
1703
1704        if let Some(ts_idx) = self.schema.timestamp_index()
1705            && let Some(col) = self.schema.column_schemas().get(ts_idx)
1706            && col.name != AUTO_CREATED_PLACEHOLDER_TS_COL
1707        {
1708            required.insert(col.name.clone());
1709        }
1710
1711        required
1712    }
1713}
1714
1715fn is_obviously_incompatible_positional_match(
1716    expr_type: &ConcreteDataType,
1717    sink_type: &ConcreteDataType,
1718) -> bool {
1719    // This is a coarse type-family guard for legacy positional aliasing, not a strict type equality
1720    // check. For example, numeric width/sign differences are allowed here and left to downstream
1721    // coercion, and untyped NULL can be coerced to any target type. Clearly different families such
1722    // as timestamp vs string are rejected early.
1723    if expr_type.is_null() || expr_type == sink_type {
1724        return false;
1725    }
1726
1727    expr_type.is_timestamp() != sink_type.is_timestamp()
1728        || expr_type.is_string() != sink_type.is_string()
1729        || expr_type.is_boolean() != sink_type.is_boolean()
1730        || expr_type.is_json() != sink_type.is_json()
1731        || expr_type.is_vector() != sink_type.is_vector()
1732}
1733
1734fn duplicate_names(names: &[String]) -> Vec<String> {
1735    let mut seen = HashSet::new();
1736    let mut duplicated = BTreeSet::new();
1737    for name in names {
1738        if !seen.insert(name.as_str()) {
1739            duplicated.insert(name.as_str());
1740        }
1741    }
1742    duplicated.into_iter().map(str::to_string).collect()
1743}
1744
1745fn format_flow_sink_schema_mismatch(
1746    query_exprs: &[Expr],
1747    sink_schema: &datatypes::schema::Schema,
1748) -> String {
1749    let flow_output_columns = query_exprs
1750        .iter()
1751        .map(|expr| expr.qualified_name().1)
1752        .collect::<Vec<_>>();
1753    let sink_table_columns = sink_schema
1754        .column_schemas()
1755        .iter()
1756        .map(|col| col.name.clone())
1757        .collect::<Vec<_>>();
1758
1759    let flow_output_set = flow_output_columns.iter().cloned().collect::<HashSet<_>>();
1760    let sink_table_set = sink_table_columns.iter().cloned().collect::<HashSet<_>>();
1761
1762    let mut extra_flow_columns = flow_output_columns
1763        .iter()
1764        .filter(|name| !sink_table_set.contains(*name))
1765        .cloned()
1766        .collect::<Vec<_>>();
1767    extra_flow_columns.sort();
1768    extra_flow_columns.dedup();
1769
1770    let mut missing_sink_columns = sink_table_columns
1771        .iter()
1772        .filter(|name| !flow_output_set.contains(*name))
1773        .cloned()
1774        .collect::<Vec<_>>();
1775    missing_sink_columns.sort();
1776    missing_sink_columns.dedup();
1777
1778    format!(
1779        "Flow output schema does not match sink table schema: found {} flow output columns and {} sink table columns. flow output columns: {:?}, sink table columns: {:?}, extra flow columns not in sink: {:?}, missing sink columns from flow output: {:?}",
1780        flow_output_columns.len(),
1781        sink_table_columns.len(),
1782        flow_output_columns,
1783        sink_table_columns,
1784        extra_flow_columns,
1785        missing_sink_columns
1786    )
1787}
1788
1789impl TreeNodeRewriter for ColumnMatcherRewriter {
1790    type Node = LogicalPlan;
1791    fn f_down(&mut self, mut node: Self::Node) -> DfResult<Transformed<Self::Node>> {
1792        if self.is_rewritten {
1793            return Ok(Transformed::no(node));
1794        }
1795
1796        // if is distinct all, wrap it in a projection
1797        if let LogicalPlan::Distinct(Distinct::All(_)) = &node {
1798            let mut exprs = vec![];
1799
1800            for field in node.schema().fields().iter() {
1801                exprs.push(Expr::Column(datafusion::common::Column::new_unqualified(
1802                    field.name(),
1803                )));
1804            }
1805
1806            let projection =
1807                LogicalPlan::Projection(Projection::try_new(exprs, Arc::new(node.clone()))?);
1808
1809            node = projection;
1810        }
1811        // handle table_scan by wrap it in a projection
1812        else if let LogicalPlan::TableScan(table_scan) = node {
1813            let mut exprs = vec![];
1814
1815            for field in table_scan.projected_schema.fields().iter() {
1816                exprs.push(Expr::Column(datafusion::common::Column::new(
1817                    Some(table_scan.table_name.clone()),
1818                    field.name(),
1819                )));
1820            }
1821
1822            let projection = LogicalPlan::Projection(Projection::try_new(
1823                exprs,
1824                Arc::new(LogicalPlan::TableScan(table_scan)),
1825            )?);
1826
1827            node = projection;
1828        }
1829
1830        // only do rewrite if found the outermost projection
1831        // if the outermost node is projection, can rewrite the exprs
1832        // if not, wrap it in a projection
1833        if let LogicalPlan::Projection(project) = &node {
1834            let exprs = project.expr.clone();
1835            let exprs = self.modify_project_exprs(exprs, project.input.schema())?;
1836
1837            self.is_rewritten = true;
1838            let new_plan =
1839                node.with_new_exprs(exprs, node.inputs().into_iter().cloned().collect())?;
1840            Ok(Transformed::yes(new_plan))
1841        } else {
1842            // wrap the logical plan in a projection
1843            let mut exprs = vec![];
1844            for field in node.schema().fields().iter() {
1845                exprs.push(Expr::Column(datafusion::common::Column::new_unqualified(
1846                    field.name(),
1847                )));
1848            }
1849            let exprs = self.modify_project_exprs(exprs, node.schema())?;
1850            self.is_rewritten = true;
1851            let new_plan =
1852                LogicalPlan::Projection(Projection::try_new(exprs, Arc::new(node.clone()))?);
1853            Ok(Transformed::yes(new_plan))
1854        }
1855    }
1856
1857    /// We might add new columns, so we need to recompute the schema
1858    fn f_up(&mut self, node: Self::Node) -> DfResult<Transformed<Self::Node>> {
1859        node.recompute_schema().map(Transformed::yes)
1860    }
1861}
1862
1863/// Find out the `Filter` Node corresponding to innermost(deepest) `WHERE` and add a new filter expr to it
1864#[derive(Debug)]
1865pub struct AddFilterRewriter {
1866    extra_filter: Expr,
1867    is_rewritten: bool,
1868}
1869
1870impl AddFilterRewriter {
1871    pub fn new(filter: Expr) -> Self {
1872        Self {
1873            extra_filter: filter,
1874            is_rewritten: false,
1875        }
1876    }
1877}
1878
1879impl TreeNodeRewriter for AddFilterRewriter {
1880    type Node = LogicalPlan;
1881    fn f_up(&mut self, node: Self::Node) -> DfResult<Transformed<Self::Node>> {
1882        if self.is_rewritten {
1883            return Ok(Transformed::no(node));
1884        }
1885        match node {
1886            LogicalPlan::Filter(mut filter) => {
1887                filter.predicate = filter.predicate.and(self.extra_filter.clone());
1888                self.is_rewritten = true;
1889                Ok(Transformed::yes(LogicalPlan::Filter(filter)))
1890            }
1891            LogicalPlan::TableScan(_) => {
1892                // add a new filter
1893                let filter =
1894                    datafusion_expr::Filter::try_new(self.extra_filter.clone(), Arc::new(node))?;
1895                self.is_rewritten = true;
1896                Ok(Transformed::yes(LogicalPlan::Filter(filter)))
1897            }
1898            _ => Ok(Transformed::no(node)),
1899        }
1900    }
1901}