risingwave_frontend/optimizer/plan_visitor/
input_ref_validator.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// Copyright 2024 RisingWave Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use paste::paste;
use risingwave_common::catalog::{Field, Schema};

use super::{DefaultBehavior, Merge};
use crate::expr::ExprVisitor;
use crate::optimizer::plan_node::generic::GenericPlanRef;
use crate::optimizer::plan_node::{Explain, PlanRef, PlanTreeNodeUnary};
use crate::optimizer::plan_visitor::PlanVisitor;

struct ExprVis<'a> {
    schema: &'a Schema,
    string: Option<String>,
}

impl ExprVisitor for ExprVis<'_> {
    fn visit_input_ref(&mut self, input_ref: &crate::expr::InputRef) {
        if input_ref.data_type != self.schema[input_ref.index].data_type {
            self.string.replace(format!(
                "InputRef#{} has type {}, but its type is {} in the input schema",
                input_ref.index, input_ref.data_type, self.schema[input_ref.index].data_type
            ));
        }
    }
}

/// Validates that input references are consistent with the input schema.
///
/// Use `InputRefValidator::validate` as an assertion.
#[derive(Debug, Clone, Default)]
pub struct InputRefValidator;

impl InputRefValidator {
    #[track_caller]
    pub fn validate(mut self, plan: PlanRef) {
        if let Some(err) = self.visit(plan.clone()) {
            panic!(
                "Input references are inconsistent with the input schema: {}, plan:\n{}",
                err,
                plan.explain_to_string()
            );
        }
    }
}

macro_rules! visit_filter {
    ($($convention:ident),*) => {
        $(
            paste! {
                fn [<visit_ $convention _filter>](&mut self, plan: &crate::optimizer::plan_node:: [<$convention:camel Filter>]) -> Option<String> {
                    let input = plan.input();
                    let mut vis = ExprVis {
                        schema: input.schema(),
                        string: None,
                    };
                    plan.predicate().visit_expr(&mut vis);
                    vis.string.or_else(|| {
                        self.visit(input)
                    })
                }
            }
        )*
    };
}

macro_rules! visit_project {
    ($($convention:ident),*) => {
        $(
            paste! {
                fn [<visit_ $convention _project>](&mut self, plan: &crate::optimizer::plan_node:: [<$convention:camel Project>]) -> Option<String> {
                    let input = plan.input();
                    let mut vis = ExprVis {
                        schema: input.schema(),
                        string: None,
                    };
                    for expr in plan.exprs() {
                        vis.visit_expr(expr);
                        if vis.string.is_some() {
                            return vis.string;
                        }
                    }
                    self.visit(input)
                }
            }
        )*
    };
}

impl PlanVisitor for InputRefValidator {
    type Result = Option<String>;

    type DefaultBehavior = impl DefaultBehavior<Self::Result>;

    visit_filter!(logical, batch, stream);

    visit_project!(logical, batch, stream);

    fn default_behavior() -> Self::DefaultBehavior {
        Merge(|a: Option<String>, b| a.or(b))
    }

    fn visit_logical_scan(
        &mut self,
        plan: &crate::optimizer::plan_node::LogicalScan,
    ) -> Option<String> {
        let fields = plan
            .table_desc()
            .columns
            .iter()
            .map(|col| Field::from_with_table_name_prefix(col, plan.table_name()))
            .collect();
        let input_schema = Schema { fields };
        let mut vis = ExprVis {
            schema: &input_schema,
            string: None,
        };
        plan.predicate().visit_expr(&mut vis);
        vis.string
    }

    // TODO: add more checks
}