Skip to main content

sql/
util.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
15use std::collections::HashSet;
16use std::fmt::{Display, Formatter};
17use std::ops::ControlFlow;
18
19use promql_parser::label::{METRIC_NAME, MatchOp};
20use promql_parser::parser::{
21    Expr as PromExpr, MatrixSelector as PromMatrixSelector, VectorSelector as PromVectorSelector,
22};
23use promql_parser::util::{ExprVisitor, walk_expr};
24use serde::Serialize;
25use snafu::ensure;
26use sqlparser::ast::{
27    Array, Expr, Ident, ObjectName, ObjectNamePart, SqlOption, Value, ValueWithSpan,
28    Visit as AstVisit, Visitor,
29};
30use sqlparser_derive::{Visit, VisitMut};
31
32use crate::ast::ObjectNamePartExt;
33use crate::error::{InvalidExprAsOptionValueSnafu, InvalidSqlSnafu, Result};
34use crate::parser::ParserContext;
35use crate::parsers::with_tql_parser::CteContent;
36use crate::statements::alter::AlterTableOperation;
37use crate::statements::comment::CommentObject;
38use crate::statements::copy::{Copy, CopyTable};
39use crate::statements::create::SqlOrTql;
40use crate::statements::query::Query;
41use crate::statements::statement::Statement;
42use crate::statements::tql::Tql;
43
44const SCHEMA_MATCHER: &str = "__schema__";
45const DATABASE_MATCHER: &str = "__database__";
46const FIELD_MATCHER: &str = "__field__";
47/// The table PromQL `info` reads when its label selector names no info metric.
48const DEFAULT_INFO_METRIC: &str = "target_info";
49
50/// Whether `labels`, the second argument of PromQL `info`, selects the default info metric in the
51/// current schema: data label matchers only, with no name, modifier or `or`.
52///
53/// The planner accepts exactly this shape for the default metric in `query`'s `info_input`, and
54/// the two have to agree: a shape claimed here that the planner later reads differently would be
55/// authorized as the wrong table.
56pub fn reads_default_info_metric(labels: &PromVectorSelector) -> bool {
57    labels.name.is_none()
58        && labels.offset.is_none()
59        && labels.at.is_none()
60        && labels.matchers.or_matchers.is_empty()
61        && labels.matchers.matchers.iter().all(|matcher| {
62            ![METRIC_NAME, FIELD_MATCHER, SCHEMA_MATCHER, DATABASE_MATCHER]
63                .contains(&matcher.name.as_str())
64        })
65}
66
67/// Format an [ObjectName] without any quote of its idents.
68pub fn format_raw_object_name(name: &ObjectName) -> String {
69    struct Inner<'a> {
70        name: &'a ObjectName,
71    }
72
73    impl Display for Inner<'_> {
74        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
75            let mut delim = "";
76            for ident in self.name.0.iter() {
77                write!(f, "{delim}")?;
78                delim = ".";
79                write!(f, "{}", ident.to_string_unquoted())?;
80            }
81            Ok(())
82        }
83    }
84
85    format!("{}", Inner { name })
86}
87
88#[derive(Clone, Debug, PartialEq, Eq, Serialize, Visit, VisitMut)]
89pub struct OptionValue(Expr);
90
91impl OptionValue {
92    pub(crate) fn try_new(expr: Expr) -> Result<Self> {
93        ensure!(
94            matches!(
95                expr,
96                Expr::Value(_) | Expr::Identifier(_) | Expr::Array(_) | Expr::Struct { .. }
97            ),
98            InvalidExprAsOptionValueSnafu {
99                error: format!("{expr} not accepted")
100            }
101        );
102        Ok(Self(expr))
103    }
104
105    fn expr_as_string(expr: &Expr) -> Option<&str> {
106        match expr {
107            Expr::Value(ValueWithSpan { value, .. }) => match value {
108                Value::SingleQuotedString(s)
109                | Value::DoubleQuotedString(s)
110                | Value::TripleSingleQuotedString(s)
111                | Value::TripleDoubleQuotedString(s)
112                | Value::SingleQuotedByteStringLiteral(s)
113                | Value::DoubleQuotedByteStringLiteral(s)
114                | Value::TripleSingleQuotedByteStringLiteral(s)
115                | Value::TripleDoubleQuotedByteStringLiteral(s)
116                | Value::SingleQuotedRawStringLiteral(s)
117                | Value::DoubleQuotedRawStringLiteral(s)
118                | Value::TripleSingleQuotedRawStringLiteral(s)
119                | Value::TripleDoubleQuotedRawStringLiteral(s)
120                | Value::EscapedStringLiteral(s)
121                | Value::UnicodeStringLiteral(s)
122                | Value::NationalStringLiteral(s)
123                | Value::HexStringLiteral(s) => Some(s),
124                Value::DollarQuotedString(s) => Some(&s.value),
125                Value::Number(s, _) => Some(s),
126                Value::Boolean(b) => Some(if *b { "true" } else { "false" }),
127                _ => None,
128            },
129            Expr::Identifier(ident) => Some(&ident.value),
130            _ => None,
131        }
132    }
133
134    /// Convert the option value to a string.
135    ///
136    /// Notes: Not all values can be converted to a string, refer to [Self::expr_as_string] for more details.
137    pub fn as_string(&self) -> Option<&str> {
138        Self::expr_as_string(&self.0)
139    }
140
141    pub fn as_list(&self) -> Option<Vec<&str>> {
142        let expr = &self.0;
143        match expr {
144            Expr::Value(_) | Expr::Identifier(_) => self.as_string().map(|s| vec![s]),
145            Expr::Array(array) => array
146                .elem
147                .iter()
148                .map(Self::expr_as_string)
149                .collect::<Option<Vec<_>>>(),
150            _ => None,
151        }
152    }
153}
154
155impl From<String> for OptionValue {
156    fn from(value: String) -> Self {
157        Self(Expr::Identifier(Ident::new(value)))
158    }
159}
160
161impl From<&str> for OptionValue {
162    fn from(value: &str) -> Self {
163        Self(Expr::Identifier(Ident::new(value)))
164    }
165}
166
167impl From<Vec<&str>> for OptionValue {
168    fn from(value: Vec<&str>) -> Self {
169        Self(Expr::Array(Array {
170            elem: value
171                .into_iter()
172                .map(|x| Expr::Identifier(Ident::new(x)))
173                .collect(),
174            named: false,
175        }))
176    }
177}
178
179impl Display for OptionValue {
180    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
181        if let Some(s) = self.as_string() {
182            write!(f, "'{s}'")
183        } else if let Expr::Array(array) = &self.0
184            && array
185                .elem
186                .iter()
187                .all(|expr| Self::expr_as_string(expr).is_some())
188        {
189            f.write_str("[")?;
190            for (index, expr) in array.elem.iter().enumerate() {
191                if index > 0 {
192                    f.write_str(", ")?;
193                }
194                write!(f, "'{}'", Self::expr_as_string(expr).unwrap())?;
195            }
196            f.write_str("]")
197        } else {
198            write!(f, "'{}'", self.0)
199        }
200    }
201}
202
203pub fn parse_option_string(option: SqlOption) -> Result<(String, OptionValue)> {
204    let SqlOption::KeyValue { key, value } = option else {
205        return InvalidSqlSnafu {
206            msg: "Expecting a key-value pair in the option",
207        }
208        .fail();
209    };
210    let v = OptionValue::try_new(value)?;
211    let k = key.value.to_lowercase();
212    Ok((k, v))
213}
214
215/// Walk through a [Query] and extract all the tables referenced in it.
216pub fn extract_tables_from_query(query: &SqlOrTql) -> impl Iterator<Item = ObjectName> {
217    extract_tables_from_query_inner(query).0.into_iter()
218}
219
220/// Walk through a [Query] and extract its referenced tables, returning `None`
221/// if any table reference cannot be resolved statically.
222pub fn extract_tables_from_query_checked(
223    query: &SqlOrTql,
224) -> Option<impl Iterator<Item = ObjectName>> {
225    let (names, complete) = extract_tables_from_query_inner(query);
226    complete.then_some(names.into_iter())
227}
228
229/// Walks through a [`Statement`] and extracts all referenced tables, returning
230/// `None` if any table reference cannot be resolved statically.
231pub fn extract_tables_from_statement_checked(
232    stmt: &Statement,
233) -> Option<impl Iterator<Item = ObjectName>> {
234    let mut names = HashSet::new();
235    extract_tables_from_statement(stmt, &mut names).then_some(names.into_iter())
236}
237
238fn extract_tables_from_statement(stmt: &Statement, names: &mut HashSet<ObjectName>) -> bool {
239    match stmt {
240        Statement::Tql(tql) => extract_tables_from_tql(tql, names),
241        Statement::Insert(insert) => {
242            collect_relations(&insert.inner, names);
243            true
244        }
245        Statement::Delete(delete) => {
246            collect_relations(&delete.inner, names);
247            true
248        }
249        Statement::Query(query) => extract_tables_from_query_ast(query, names),
250        Statement::CreateTable(create) => {
251            names.insert(create.name.clone());
252            true
253        }
254        Statement::CreateExternalTable(create) => {
255            names.insert(create.name.clone());
256            true
257        }
258        Statement::AlterTable(alter) => {
259            let current = alter.table_name().clone();
260            names.insert(current.clone());
261            if let AlterTableOperation::RenameTable { new_table_name } = alter.alter_operation() {
262                let mut renamed = current;
263                if let Some(last) = renamed.0.last_mut() {
264                    *last = ObjectNamePart::Identifier(Ident::new(new_table_name));
265                }
266                names.insert(renamed);
267            }
268            true
269        }
270        Statement::DropTable(drop) => {
271            names.extend(drop.table_names().iter().cloned());
272            true
273        }
274        #[cfg(feature = "enterprise")]
275        Statement::UndropTable(undrop) => {
276            names.insert(undrop.table_name().clone());
277            true
278        }
279        Statement::TruncateTable(truncate) => {
280            names.insert(truncate.table_name().clone());
281            true
282        }
283        Statement::CreateTableLike(create) => {
284            names.extend([create.table_name.clone(), create.source_name.clone()]);
285            true
286        }
287        Statement::CreateView(create) => {
288            names.insert(create.name.clone());
289            extract_tables_from_statement(&create.query, names)
290        }
291        Statement::CreateFlow(create) => {
292            names.insert(create.sink_table_name.clone());
293            extract_tables_from_sql_or_tql(&create.query, names)
294        }
295        #[cfg(feature = "enterprise")]
296        Statement::CreateTrigger(create) => {
297            extract_tables_from_sql_or_tql(&create.trigger_on.query, names)
298        }
299        #[cfg(feature = "enterprise")]
300        Statement::AlterTrigger(alter) => match &alter.operation.trigger_on {
301            Some(trigger_on) => extract_tables_from_sql_or_tql(&trigger_on.query, names),
302            None => true,
303        },
304        Statement::DropView(drop) => {
305            names.insert(drop.view_name.clone());
306            true
307        }
308        Statement::Explain(explain) => extract_tables_from_statement(&explain.statement, names),
309        Statement::DeclareCursor(cursor) => extract_tables_from_query_ast(&cursor.query, names),
310        Statement::DescribeTable(describe) => {
311            names.insert(describe.name().clone());
312            true
313        }
314        Statement::ShowCreateTable(show) => {
315            names.insert(show.table_name.clone());
316            true
317        }
318        Statement::ShowCreateView(show) => {
319            names.insert(show.view_name.clone());
320            true
321        }
322        Statement::ShowColumns(show) => {
323            names.insert(metadata_table_name(&show.table, show.database.as_deref()));
324            true
325        }
326        Statement::ShowIndex(show) => {
327            names.insert(metadata_table_name(&show.table, show.database.as_deref()));
328            true
329        }
330        Statement::ShowRegion(show) => {
331            names.insert(metadata_table_name(&show.table, show.database.as_deref()));
332            true
333        }
334        Statement::Comment(comment) => {
335            if let CommentObject::Table(table) | CommentObject::Column { table, .. } =
336                &comment.object
337            {
338                names.insert(table.clone());
339            }
340            true
341        }
342        Statement::Copy(Copy::CopyTable(copy)) => {
343            let table = match copy {
344                CopyTable::To(args) | CopyTable::From(args) => &args.table_name,
345            };
346            names.insert(table.clone());
347            true
348        }
349        Statement::Copy(Copy::CopyQueryTo(copy)) => {
350            extract_tables_from_statement(&copy.query, names)
351        }
352        Statement::Copy(Copy::CopyDatabase(_)) => true,
353        Statement::DropDatabase(_)
354        | Statement::DropFlow(_)
355        | Statement::CreateDatabase(_)
356        | Statement::AlterDatabase(_)
357        | Statement::ShowDatabases(_)
358        | Statement::ShowTables(_)
359        | Statement::ShowTableStatus(_)
360        | Statement::ShowCharset(_)
361        | Statement::ShowCollation(_)
362        | Statement::ShowCreateDatabase(_)
363        | Statement::ShowCreateFlow(_)
364        | Statement::ShowFlows(_)
365        | Statement::ShowFlowStatus(_)
366        | Statement::ShowStatus(_)
367        | Statement::ShowSearchPath(_)
368        | Statement::ShowViews(_)
369        | Statement::SetVariables(_)
370        | Statement::ShowVariables(_)
371        | Statement::Use(_)
372        | Statement::Admin(_)
373        | Statement::FetchCursor(_)
374        | Statement::CloseCursor(_)
375        | Statement::Kill(_)
376        | Statement::ShowProcesslist(_) => true,
377        #[cfg(feature = "enterprise")]
378        Statement::DropTrigger(_)
379        | Statement::ShowCreateTrigger(_)
380        | Statement::ShowTriggers(_) => true,
381    }
382}
383
384fn extract_tables_from_query_ast(query: &Query, names: &mut HashSet<ObjectName>) -> bool {
385    extract_tables_from_sql_query(&query.inner, names);
386    extract_tables_from_hybrid_cte_query(query, names)
387}
388
389fn extract_tables_from_sql_or_tql(query: &SqlOrTql, names: &mut HashSet<ObjectName>) -> bool {
390    let (query_names, complete) = extract_tables_from_query_inner(query);
391    names.extend(query_names);
392    complete
393}
394
395fn collect_relations(ast: &impl AstVisit, names: &mut HashSet<ObjectName>) {
396    let _ = ast.visit(&mut RelationCollector::new(names));
397}
398
399fn metadata_table_name(table: &str, database: Option<&str>) -> ObjectName {
400    let mut parts = Vec::with_capacity(usize::from(database.is_some()) + 1);
401    parts.extend(database.map(Ident::new));
402    parts.push(Ident::new(table));
403    ObjectName::from(parts)
404}
405
406fn extract_tables_from_query_inner(query: &SqlOrTql) -> (HashSet<ObjectName>, bool) {
407    let mut names = HashSet::new();
408
409    let complete = match query {
410        SqlOrTql::Sql(query, _) => {
411            extract_tables_from_sql_query(&query.inner, &mut names);
412            extract_tables_from_hybrid_cte_query(query, &mut names)
413        }
414        SqlOrTql::Tql(tql, _) => extract_tables_from_tql(tql, &mut names),
415    };
416
417    (names, complete)
418}
419
420fn extract_tables_from_hybrid_cte_query(
421    query: &Query,
422    sql_names: &mut HashSet<ObjectName>,
423) -> bool {
424    let Some(hybrid_cte) = &query.hybrid_cte else {
425        return true;
426    };
427
428    let mut complete = true;
429    let cte_names: HashSet<String> = hybrid_cte
430        .cte_tables
431        .iter()
432        .map(|cte| ParserContext::canonicalize_identifier(cte.name.clone()).value)
433        .collect();
434    remove_cte_names(sql_names, &cte_names);
435
436    for cte in &hybrid_cte.cte_tables {
437        let mut cte_query_names = HashSet::new();
438        match &cte.content {
439            CteContent::Sql(cte_query) => {
440                extract_tables_from_sql_query(cte_query, &mut cte_query_names)
441            }
442            CteContent::Tql(tql) => complete &= extract_tables_from_tql(tql, &mut cte_query_names),
443        }
444        sql_names.extend(cte_query_names);
445    }
446
447    complete
448}
449
450fn remove_cte_names(names: &mut HashSet<ObjectName>, cte_names: &HashSet<String>) {
451    if cte_names.is_empty() {
452        return;
453    }
454
455    names.retain(|name| {
456        if name.0.len() != 1 {
457            return true;
458        }
459        let Some(ident) = name.0[0].as_ident() else {
460            return true;
461        };
462
463        let canonical = ParserContext::canonicalize_identifier(ident.clone()).value;
464        !cte_names.contains(&canonical)
465    });
466}
467
468fn extract_tables_from_tql(tql: &Tql, names: &mut HashSet<ObjectName>) -> bool {
469    let promql = match tql {
470        Tql::Eval(eval) => &eval.query,
471        Tql::Explain(explain) => &explain.query,
472        Tql::Analyze(analyze) => &analyze.query,
473    };
474
475    let Ok(expr) = promql_parser::parser::parse(promql) else {
476        return false;
477    };
478    extract_tables_from_prom_expr(&expr, names)
479}
480
481/// Extracts all tables referenced by a [`PromExpr`], returning `None`
482/// if any table reference cannot be resolved statically.
483pub fn extract_tables_from_prom_expr_checked(
484    expr: &PromExpr,
485) -> Option<impl Iterator<Item = ObjectName>> {
486    let mut names = HashSet::new();
487    extract_tables_from_prom_expr(expr, &mut names).then_some(names.into_iter())
488}
489
490/// Extracts the tables referenced by a [`PromExpr`] that can be resolved statically,
491/// ignoring the ones that cannot.
492pub fn extract_tables_from_prom_expr_partial(expr: &PromExpr) -> Vec<ObjectName> {
493    let mut names = HashSet::new();
494    extract_tables_from_prom_expr(expr, &mut names);
495    names.into_iter().collect()
496}
497
498fn extract_tables_from_prom_expr(expr: &PromExpr, names: &mut HashSet<ObjectName>) -> bool {
499    struct TableCollector<'a> {
500        names: &'a mut HashSet<ObjectName>,
501        complete: bool,
502        /// The label selectors of `info` calls that name no metric. Their call has already
503        /// recorded the table they read, and the walk reaches them after it.
504        default_info_selectors: Vec<*const PromVectorSelector>,
505    }
506
507    impl TableCollector<'_> {
508        /// `info` reads [`DEFAULT_INFO_METRIC`], a table that appears nowhere in the expression,
509        /// when its label selector is absent or [`reads_default_info_metric`].
510        fn visit_info(&mut self, args: &[Box<PromExpr>]) -> bool {
511            match args.get(1).map(|labels| labels.as_ref()) {
512                None => {}
513                Some(PromExpr::VectorSelector(labels)) if reads_default_info_metric(labels) => {
514                    self.default_info_selectors.push(labels);
515                }
516                // Anything else is left to the walk: it records a metric the selector names and
517                // reports every other shape as unresolved.
518                Some(_) => return true,
519            }
520            self.names
521                .insert(ObjectName(vec![ObjectNamePart::Identifier(Ident::new(
522                    DEFAULT_INFO_METRIC,
523                ))]));
524            true
525        }
526    }
527
528    impl ExprVisitor for TableCollector<'_> {
529        type Error = ();
530
531        fn pre_visit(&mut self, expr: &PromExpr) -> std::result::Result<bool, Self::Error> {
532            self.complete &= match expr {
533                PromExpr::VectorSelector(selector)
534                    if self
535                        .default_info_selectors
536                        .iter()
537                        .any(|seen| std::ptr::eq(*seen, selector)) =>
538                {
539                    true
540                }
541                PromExpr::VectorSelector(selector) => {
542                    extract_metric_name_from_vector_selector(selector, self.names)
543                }
544                PromExpr::Call(call) if call.func.name == "info" => {
545                    self.visit_info(&call.args.args)
546                }
547                PromExpr::MatrixSelector(PromMatrixSelector { vs, .. }) => {
548                    extract_metric_name_from_vector_selector(vs, self.names)
549                }
550                PromExpr::Extension(_) => false,
551                _ => true,
552            };
553            Ok(true)
554        }
555    }
556
557    let mut collector = TableCollector {
558        names,
559        complete: true,
560        default_info_selectors: Vec::new(),
561    };
562    let _ = walk_expr(&mut collector, expr);
563    collector.complete
564}
565
566fn extract_metric_name_from_vector_selector(
567    selector: &PromVectorSelector,
568    names: &mut HashSet<ObjectName>,
569) -> bool {
570    if selector.name.is_none() && !selector.matchers.or_matchers.is_empty() {
571        return false;
572    }
573
574    let metric_name = selector.name.clone().or_else(|| {
575        let mut metric_name_matchers = selector.matchers.find_matchers(METRIC_NAME);
576        if metric_name_matchers.len() == 1 && metric_name_matchers[0].op == MatchOp::Equal {
577            metric_name_matchers.pop().map(|matcher| matcher.value)
578        } else {
579            None
580        }
581    });
582    let Some(metric_name) = metric_name else {
583        return false;
584    };
585
586    if selector.matchers.matchers.iter().any(|matcher| {
587        (matcher.name == SCHEMA_MATCHER || matcher.name == DATABASE_MATCHER)
588            && matcher.op != MatchOp::Equal
589    }) {
590        return false;
591    }
592
593    let schema_matcher = selector.matchers.matchers.iter().rev().find(|matcher| {
594        matcher.op == MatchOp::Equal
595            && (matcher.name == SCHEMA_MATCHER || matcher.name == DATABASE_MATCHER)
596    });
597
598    if let Some(schema) = schema_matcher {
599        names.insert(ObjectName(vec![
600            ObjectNamePart::Identifier(Ident::new(&schema.value)),
601            ObjectNamePart::Identifier(Ident::new(metric_name)),
602        ]));
603    } else {
604        names.insert(ObjectName(vec![ObjectNamePart::Identifier(Ident::new(
605            metric_name,
606        ))]));
607    }
608    true
609}
610
611/// translate the start location to the index in the sql string
612pub fn location_to_index(sql: &str, location: &sqlparser::tokenizer::Location) -> usize {
613    let mut index = 0;
614    for (lno, line) in sql.lines().enumerate() {
615        if lno + 1 == location.line as usize {
616            index += location.column as usize;
617            break;
618        } else {
619            index += line.len() + 1; // +1 for the newline
620        }
621    }
622    // -1 because the index is 0-based
623    // and the location is 1-based
624    index - 1
625}
626
627// Tracks CTE aliases as sqlparser's visitor enters their query bodies.
628struct QueryScope {
629    cte_names: Vec<String>,
630    next_cte: usize,
631    recursive: bool,
632    scope_start: usize,
633    add_to_parent_after: Option<String>,
634}
635
636struct RelationCollector<'a> {
637    names: &'a mut HashSet<ObjectName>,
638    ctes_in_scope: Vec<String>,
639    query_scopes: Vec<QueryScope>,
640    #[cfg(test)]
641    query_visits: usize,
642}
643
644impl<'a> RelationCollector<'a> {
645    fn new(names: &'a mut HashSet<ObjectName>) -> Self {
646        Self {
647            names,
648            ctes_in_scope: Vec::new(),
649            query_scopes: Vec::new(),
650            #[cfg(test)]
651            query_visits: 0,
652        }
653    }
654}
655
656impl Visitor for RelationCollector<'_> {
657    type Break = ();
658
659    fn pre_visit_query(&mut self, query: &sqlparser::ast::Query) -> ControlFlow<Self::Break> {
660        #[cfg(test)]
661        {
662            self.query_visits += 1;
663        }
664
665        // Query::visit enters WITH definitions in declaration order before its body.
666        let parent_cte = self.query_scopes.last_mut().and_then(|scope| {
667            let cte_name = scope.cte_names.get(scope.next_cte)?.clone();
668            scope.next_cte += 1;
669            Some((cte_name, scope.recursive))
670        });
671
672        let add_to_parent_after = match parent_cte {
673            Some((cte_name, true)) => {
674                self.ctes_in_scope.push(cte_name);
675                None
676            }
677            Some((cte_name, false)) => Some(cte_name),
678            None => None,
679        };
680
681        let scope_start = self.ctes_in_scope.len();
682        let (cte_names, recursive) = if let Some(with) = &query.with {
683            (
684                with.cte_tables
685                    .iter()
686                    .map(|cte| ParserContext::canonicalize_identifier(cte.alias.name.clone()).value)
687                    .collect(),
688                with.recursive,
689            )
690        } else {
691            (Vec::new(), false)
692        };
693
694        self.query_scopes.push(QueryScope {
695            cte_names,
696            next_cte: 0,
697            recursive,
698            scope_start,
699            add_to_parent_after,
700        });
701        ControlFlow::Continue(())
702    }
703
704    fn post_visit_query(&mut self, _query: &sqlparser::ast::Query) -> ControlFlow<Self::Break> {
705        let Some(scope) = self.query_scopes.pop() else {
706            return ControlFlow::Break(());
707        };
708        self.ctes_in_scope.truncate(scope.scope_start);
709        if let Some(cte_name) = scope.add_to_parent_after {
710            self.ctes_in_scope.push(cte_name);
711        }
712        ControlFlow::Continue(())
713    }
714
715    fn pre_visit_relation(&mut self, relation: &ObjectName) -> ControlFlow<Self::Break> {
716        let is_cte = matches!(
717            relation.0.as_slice(),
718            [part]
719                if part.as_ident().is_some_and(|ident| {
720                    self.ctes_in_scope.contains(
721                        &ParserContext::canonicalize_identifier(ident.clone()).value,
722                    )
723                })
724        );
725        if !is_cte {
726            self.names.insert(relation.clone());
727        }
728        ControlFlow::Continue(())
729    }
730}
731
732/// Helper function for [extract_tables_from_query].
733///
734/// Handle [sqlparser::ast::Query].
735fn extract_tables_from_sql_query(query: &sqlparser::ast::Query, names: &mut HashSet<ObjectName>) {
736    let _ = query.visit(&mut RelationCollector::new(names));
737}
738
739#[cfg(test)]
740mod tests {
741    use itertools::Itertools;
742    use sqlparser::tokenizer::Token;
743
744    use super::*;
745    use crate::dialect::GreptimeDbDialect;
746    use crate::parser::{ParseOptions, ParserContext};
747    use crate::statements::statement::Statement;
748
749    #[test]
750    fn test_location_to_index() {
751        let testcases = vec![
752            "SELECT * FROM t WHERE a = 1",
753            // start or end with newline
754            r"
755SELECT *
756FROM
757t
758WHERE a =
7591
760",
761            r"SELECT *
762FROM
763t
764WHERE a =
7651
766",
767            r"
768SELECT *
769FROM
770t
771WHERE a =
7721",
773        ];
774
775        for sql in testcases {
776            let mut parser = ParserContext::new(&GreptimeDbDialect {}, sql).unwrap();
777            loop {
778                let token = parser.parser.next_token();
779                if token == Token::EOF {
780                    break;
781                }
782                let span = token.span;
783                let subslice =
784                    &sql[location_to_index(sql, &span.start)..location_to_index(sql, &span.end)];
785                assert_eq!(token.to_string(), subslice);
786            }
787        }
788    }
789
790    #[test]
791    fn test_extract_tables_from_tql_query() {
792        let testcases = vec![
793            (
794                r#"
795CREATE FLOW calc_reqs SINK TO cnt_reqs AS
796TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests);"#,
797                vec!["http_requests".to_string()],
798            ),
799            (
800                r#"
801CREATE FLOW calc_reqs SINK TO cnt_reqs AS
802TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", {__name__="http_requests"});"#,
803                vec!["http_requests".to_string()],
804            ),
805        ];
806
807        for (sql, expected_tables) in testcases {
808            let mut stmts = ParserContext::create_with_dialect(
809                sql,
810                &GreptimeDbDialect {},
811                ParseOptions::default(),
812            )
813            .unwrap();
814            let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
815                unreachable!()
816            };
817
818            let mut tables = extract_tables_from_query(&create_flow.query)
819                .map(|table| format_raw_object_name(&table))
820                .collect_vec();
821            tables.sort();
822            assert_eq!(expected_tables, tables);
823        }
824    }
825
826    #[test]
827    fn test_extract_tables_from_tql_query_completeness() {
828        let testcases = [
829            ("cpu", true, vec!["cpu"]),
830            ("cpu + mem", true, vec!["cpu", "mem"]),
831            (r#"cpu{__database__="private"}"#, true, vec!["private.cpu"]),
832            ("1 + 2", true, vec![]),
833            (r#"{__name__="cpu"}"#, true, vec!["cpu"]),
834            (r#"cpu{job="api" or instance="host"}"#, true, vec!["cpu"]),
835            (r#"cpu + {job="api"}"#, false, vec!["cpu"]),
836            (r#"{__name__=~"cpu.*"}"#, false, vec![]),
837            (r#"{__name__=~"cpu.*" or job="api"}"#, false, vec![]),
838            (r#"cpu{__schema__=~"private.*"}"#, false, vec![]),
839            // `info` reads `target_info` unless its label selector names the info metric.
840            ("info(cpu)", true, vec!["cpu", "target_info"]),
841            (
842                r#"info(cpu, {version="v1"})"#,
843                true,
844                vec!["cpu", "target_info"],
845            ),
846            (
847                r#"info(cpu, {__name__="build_info", version="v1"})"#,
848                true,
849                vec!["build_info", "cpu"],
850            ),
851            (r#"info(cpu, {__name__=~".+_info"})"#, false, vec!["cpu"]),
852            // Shapes the planner declines stay unresolved instead of claiming `target_info`.
853            (
854                r#"info(cpu, {__schema__="private", version="v1"})"#,
855                false,
856                vec!["cpu"],
857            ),
858            (r#"info(cpu, {version="v1"} offset 1m)"#, false, vec!["cpu"]),
859            (
860                r#"info(cpu, {version="v1" or version="v2"})"#,
861                false,
862                vec!["cpu"],
863            ),
864        ];
865
866        for (promql, expected_complete, expected_tables) in testcases {
867            let expected_tables = expected_tables
868                .into_iter()
869                .map(str::to_string)
870                .collect_vec();
871            let sql = format!("TQL EVAL (0, 10, '5s') {promql}");
872            let mut stmts = ParserContext::create_with_dialect(
873                &sql,
874                &GreptimeDbDialect {},
875                ParseOptions::default(),
876            )
877            .unwrap();
878            let Statement::Tql(tql) = stmts.pop().unwrap() else {
879                unreachable!()
880            };
881
882            let query = SqlOrTql::Tql(tql, sql);
883            let (tables, complete) = extract_tables_from_query_inner(&query);
884            let mut tables = tables
885                .into_iter()
886                .map(|table| format_raw_object_name(&table))
887                .collect_vec();
888            tables.sort();
889            assert_eq!(expected_complete, complete, "{promql}");
890            assert_eq!(expected_tables, tables, "{promql}");
891            assert_eq!(
892                expected_complete,
893                extract_tables_from_query_checked(&query).is_some(),
894                "{promql}"
895            );
896
897            let expr = promql_parser::parser::parse(promql).unwrap();
898            let direct_tables = extract_tables_from_prom_expr_checked(&expr).map(|tables| {
899                let mut tables = tables
900                    .map(|table| format_raw_object_name(&table))
901                    .collect_vec();
902                tables.sort();
903                tables
904            });
905            assert_eq!(
906                expected_complete.then(|| expected_tables.clone()),
907                direct_tables
908            );
909        }
910    }
911
912    #[test]
913    fn test_extract_tables_from_statement() {
914        for (sql, expected) in [
915            ("SELECT * FROM physical_metric", vec!["physical_metric"]),
916            (
917                "INSERT INTO target SELECT * FROM physical_metric",
918                vec!["physical_metric", "target"],
919            ),
920            (
921                "INSERT INTO target WITH cte AS (SELECT * FROM physical_metric) SELECT * FROM cte",
922                vec!["physical_metric", "target"],
923            ),
924            (
925                "TQL EVAL (0, 10, '5s') physical_metric",
926                vec!["physical_metric"],
927            ),
928            (
929                "CREATE VIEW target AS SELECT * FROM physical_metric",
930                vec!["physical_metric", "target"],
931            ),
932            ("ALTER TABLE old RENAME new", vec!["new", "old"]),
933            #[cfg(feature = "enterprise")]
934            ("UNDROP TABLE restored", vec!["restored"]),
935            ("SHOW TABLES", vec![]),
936        ] {
937            let stmt = ParserContext::create_with_dialect(
938                sql,
939                &GreptimeDbDialect {},
940                ParseOptions::default(),
941            )
942            .unwrap()
943            .remove(0);
944            let mut tables = extract_tables_from_statement_checked(&stmt)
945                .unwrap()
946                .map(|table| format_raw_object_name(&table))
947                .collect_vec();
948            tables.sort();
949            assert_eq!(expected, tables, "{sql}");
950        }
951    }
952
953    #[test]
954    fn test_extract_tables_from_chained_tql_ctes() {
955        let sql = "WITH denied AS (TQL EVAL (0, 10, '5s') allowed), \
956                   leak AS (TQL EVAL (0, 10, '5s') denied) \
957                   SELECT * FROM leak";
958        let mut stmts =
959            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
960                .unwrap();
961        let Statement::Query(query) = stmts.pop().unwrap() else {
962            unreachable!()
963        };
964
965        let mut tables = extract_tables_from_query_checked(&SqlOrTql::Sql(*query, sql.to_string()))
966            .unwrap()
967            .map(|table| format_raw_object_name(&table))
968            .collect_vec();
969        tables.sort();
970        assert_eq!(vec!["allowed".to_string(), "denied".to_string()], tables);
971    }
972
973    #[test]
974    fn test_extract_tables_from_sql_query_with_derived_join() {
975        let sql = r#"
976CREATE FLOW flow_batch_join_subquery SINK TO flow_batch_join_sink
977EVAL INTERVAL '1m' AS
978SELECT a.symbol, b.mark_price
979FROM (
980    SELECT inst_id AS symbol, max(ts) AS mark_iv_ts
981    FROM flow_batch_join_opt_summary
982    GROUP BY inst_id
983) a
984LEFT JOIN (
985    SELECT symbol, max(mark_price) AS mark_price
986    FROM flow_batch_join_market_v5
987    WHERE "type" = 'OPTION_MARK'
988    GROUP BY symbol
989) b ON a.symbol = b.symbol;
990"#;
991        let mut stmts =
992            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
993                .unwrap();
994        let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
995            unreachable!()
996        };
997
998        let mut tables = extract_tables_from_query(&create_flow.query)
999            .map(|table| format_raw_object_name(&table))
1000            .collect_vec();
1001        tables.sort();
1002        assert_eq!(
1003            vec![
1004                "flow_batch_join_market_v5".to_string(),
1005                "flow_batch_join_opt_summary".to_string(),
1006            ],
1007            tables
1008        );
1009    }
1010
1011    #[test]
1012    fn test_extract_tables_from_sql_query_with_expression_subqueries() {
1013        let sql = r#"
1014SELECT
1015    (SELECT max(value) FROM scalar_source)
1016FROM outer_source
1017WHERE EXISTS (SELECT 1 FROM exists_source)
1018ORDER BY (SELECT max(value) FROM order_source);
1019"#;
1020        let mut stmts =
1021            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1022                .unwrap();
1023        let Statement::Query(query) = stmts.pop().unwrap() else {
1024            unreachable!()
1025        };
1026
1027        let mut tables = extract_tables_from_query(&SqlOrTql::Sql(*query, sql.to_string()))
1028            .map(|table| format_raw_object_name(&table))
1029            .collect_vec();
1030        tables.sort();
1031        assert_eq!(
1032            vec![
1033                "exists_source".to_string(),
1034                "order_source".to_string(),
1035                "outer_source".to_string(),
1036                "scalar_source".to_string(),
1037            ],
1038            tables
1039        );
1040    }
1041
1042    #[test]
1043    fn test_extract_tables_from_sql_query_with_cte_scopes() {
1044        let testcases = vec![
1045            (
1046                r#"
1047WITH source AS (
1048    SELECT * FROM source
1049)
1050SELECT * FROM source;
1051"#,
1052                vec!["source".to_string()],
1053            ),
1054            (
1055                r#"
1056WITH RECURSIVE source AS (
1057    SELECT * FROM source
1058)
1059SELECT * FROM source;
1060"#,
1061                vec![],
1062            ),
1063            (
1064                r#"
1065WITH first_cte AS (
1066    SELECT * FROM physical_source
1067), second_cte AS (
1068    SELECT * FROM first_cte
1069)
1070SELECT * FROM second_cte;
1071"#,
1072                vec!["physical_source".to_string()],
1073            ),
1074            (
1075                r#"
1076SELECT * FROM (
1077    WITH nested_cte AS (SELECT * FROM nested_source)
1078    SELECT * FROM nested_cte
1079);
1080"#,
1081                vec!["nested_source".to_string()],
1082            ),
1083            (
1084                r#"
1085SELECT * FROM (
1086    WITH nested_cte AS (SELECT * FROM nested_source)
1087    SELECT (SELECT * FROM nested_cte)
1088);
1089"#,
1090                vec!["nested_source".to_string()],
1091            ),
1092        ];
1093
1094        for (sql, expected_tables) in testcases {
1095            let mut stmts = ParserContext::create_with_dialect(
1096                sql,
1097                &GreptimeDbDialect {},
1098                ParseOptions::default(),
1099            )
1100            .unwrap();
1101            let Statement::Query(query) = stmts.pop().unwrap() else {
1102                unreachable!()
1103            };
1104
1105            let mut tables = HashSet::new();
1106            extract_tables_from_sql_query(&query.inner, &mut tables);
1107            let mut tables = tables
1108                .into_iter()
1109                .map(|table| format_raw_object_name(&table))
1110                .collect_vec();
1111            tables.sort();
1112            assert_eq!(expected_tables, tables);
1113        }
1114    }
1115
1116    #[test]
1117    fn test_extract_tables_from_deeply_nested_ctes_visits_each_query_once() {
1118        let mut sql = "SELECT * FROM physical_source".to_string();
1119        for depth in 0..20 {
1120            sql = format!("WITH cte_{depth} AS ({sql}) SELECT * FROM cte_{depth}");
1121        }
1122
1123        let mut stmts = ParserContext::create_with_dialect(
1124            &sql,
1125            &GreptimeDbDialect {},
1126            ParseOptions::default(),
1127        )
1128        .unwrap();
1129        let Statement::Query(query) = stmts.pop().unwrap() else {
1130            unreachable!()
1131        };
1132
1133        let mut tables = HashSet::new();
1134        let query_visits = {
1135            let mut collector = RelationCollector::new(&mut tables);
1136            let _ = query.inner.visit(&mut collector);
1137            collector.query_visits
1138        };
1139
1140        assert_eq!(21, query_visits);
1141        assert_eq!(
1142            vec!["physical_source"],
1143            tables
1144                .into_iter()
1145                .map(|table| format_raw_object_name(&table))
1146                .collect_vec()
1147        );
1148    }
1149
1150    #[test]
1151    fn test_extract_tables_from_tql_query_with_schema_matcher() {
1152        let sql = r#"
1153CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1154TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests{__schema__="greptime_private"});"#;
1155        let mut stmts =
1156            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1157                .unwrap();
1158        let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
1159            unreachable!()
1160        };
1161
1162        let mut tables = extract_tables_from_query(&create_flow.query)
1163            .map(|table| format_raw_object_name(&table))
1164            .collect_vec();
1165        tables.sort();
1166        assert_eq!(vec!["greptime_private.http_requests".to_string()], tables);
1167    }
1168}