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