Skip to main content

risingwave_frontend/binder/expr/
column.rs

1// Copyright 2022 RisingWave Labs
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
15use risingwave_common::types::DataType;
16use risingwave_sqlparser::ast::Ident;
17
18use crate::binder::{Binder, Clause};
19use crate::error::{ErrorCode, Result};
20use crate::expr::{CorrelatedInputRef, ExprImpl, ExprType, FunctionCall, InputRef, Literal};
21
22impl Binder {
23    pub fn bind_column(&mut self, idents: &[Ident]) -> Result<ExprImpl> {
24        // TODO: check quote style of `ident`.
25        let (schema_name, table_name, column_name) = match idents {
26            [column] => (None, None, column.real_value()),
27            [table, column] => (None, Some(table.real_value()), column.real_value()),
28            [schema, table, column] => (
29                Some(schema.real_value()),
30                Some(table.real_value()),
31                column.real_value(),
32            ),
33            _ => {
34                return Err(
35                    ErrorCode::InternalError(format!("Too many idents: {:?}", idents)).into(),
36                );
37            }
38        };
39
40        // If we find `sql_udf_arguments` in the current context, it means we're binding an inline SQL UDF
41        // (without a layer of subquery). This only happens when the function body is a trivial `SELECT`
42        // statement without any `FROM` clause etc. In this case, the column must be a UDF parameter.
43        if self.is_binding_inline_sql_udf() {
44            return self.bind_sql_udf_parameter(&column_name);
45        }
46
47        match self
48            .context
49            .get_column_binding_indices(&schema_name, &table_name, &column_name)
50        {
51            Ok(mut indices) => {
52                match indices.len() {
53                    0 => unreachable!(),
54                    1 => {
55                        let index = indices[0];
56                        let column = &self.context.columns[index];
57                        return Ok(
58                            InputRef::new(column.index, column.field.data_type.clone()).into()
59                        );
60                    }
61                    _ => {
62                        indices.sort(); // make sure we have a consistent result
63                        let inputs = indices
64                            .iter()
65                            .map(|index| {
66                                let column = &self.context.columns[*index];
67                                InputRef::new(column.index, column.field.data_type.clone()).into()
68                            })
69                            .collect::<Vec<_>>();
70                        return Ok(FunctionCall::new(ExprType::Coalesce, inputs)?.into());
71                    }
72                }
73            }
74            Err(e) => {
75                // If a column is referenced using three-level qualification and the table has an alias,
76                // prompt the user to use the table alias instead.
77                if let ErrorCode::ItemNotFound(_) = e {
78                    if let (Some(schema), Some(table)) = (&schema_name, &table_name)
79                        && let Some(index) =
80                            self.context.get_table_alias(schema, table, &column_name)?
81                    {
82                        let column = &self.context.columns[index];
83                        return Err(ErrorCode::InvalidReference(format!(
84                            "missing FROM-clause entry for table \"{}\"\n\
85                            HINT:  Perhaps you meant to reference the table alias \"{}\".",
86                            table, column.table_name
87                        ))
88                        .into());
89                    };
90                } else {
91                    // If the error message is not that the column is not found, throw the error
92                    return Err(e.into());
93                }
94            }
95        }
96
97        // Try to find a correlated column in `upper_contexts`, starting from the innermost context.
98        let mut err = ErrorCode::ItemNotFound(format!("Invalid column: {}", column_name));
99
100        for (context, depth) in self.correlation_contexts() {
101            if matches!(context.clause, Some(Clause::Insert)) {
102                continue;
103            }
104            match context.get_column_binding_index(&schema_name, &table_name, &column_name) {
105                Ok(index) => {
106                    let column = &context.columns[index];
107                    return Ok(CorrelatedInputRef::new(
108                        column.index,
109                        column.field.data_type.clone(),
110                        depth,
111                    )
112                    .into());
113                }
114                Err(e) => {
115                    err = e;
116                }
117            }
118        }
119
120        // `CTID` is a system column in postgres.
121        // https://www.postgresql.org/docs/current/ddl-system-columns.html
122        //
123        // We return an empty string here to support some tools such as DataGrip.
124        //
125        // FIXME: The type of `CTID` should be `tid`.
126        // FIXME: The `CTID` column should be unique, so literal may break something.
127        // FIXME: At least we should add a notice here.
128        if let ErrorCode::ItemNotFound(_) = err
129            && column_name == "ctid"
130        {
131            return Ok(Literal::new(Some("".into()), DataType::Varchar).into());
132        }
133
134        // Failed to resolve the column in current context. Now check if it's a sql udf parameter.
135        if let ErrorCode::ItemNotFound(_) = err
136            && self.is_binding_subquery_sql_udf()
137        {
138            return self.bind_sql_udf_parameter(&column_name);
139        }
140
141        Err(err.into())
142    }
143
144    /// Return visible outer column contexts in name-resolution order, paired with the semantic
145    /// correlation depth at which each context is owned.
146    ///
147    /// A non-empty lateral context represents the left input of a potential `Apply`, so it adds a
148    /// depth boundary. Empty contexts are parser/binder isolation frames and do not. An upper
149    /// query or table-function context always contributes at least one boundary, even if its local
150    /// `FROM` context is empty.
151    fn correlation_contexts(&self) -> Vec<(&crate::binder::BindContext, usize)> {
152        let mut contexts = vec![];
153        let mut depth = 1;
154
155        for lateral_context in self.lateral_contexts.iter().rev() {
156            if lateral_context.is_visible {
157                contexts.push((&lateral_context.context, depth));
158            }
159            if !lateral_context.context.columns.is_empty() {
160                depth += 1;
161            }
162        }
163
164        for (context, lateral_contexts) in self.visible_upper_subquery_contexts_rev() {
165            let entry_depth = depth;
166            contexts.push((context, depth));
167            if !context.columns.is_empty() {
168                depth += 1;
169            }
170
171            for lateral_context in lateral_contexts.iter().rev() {
172                if lateral_context.is_visible {
173                    contexts.push((&lateral_context.context, depth));
174                }
175                if !lateral_context.context.columns.is_empty() {
176                    depth += 1;
177                }
178            }
179
180            depth = depth.max(entry_depth + 1);
181        }
182
183        contexts
184    }
185}