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
237fn extract_tables_from_statement(stmt: &Statement, names: &mut HashSet<ObjectName>) -> bool {
238 match stmt {
239 Statement::Tql(tql) => extract_tables_from_tql(tql, names),
240 Statement::Insert(insert) => {
241 collect_relations(&insert.inner, names);
242 true
243 }
244 Statement::Delete(delete) => {
245 collect_relations(&delete.inner, names);
246 true
247 }
248 Statement::Query(query) => extract_tables_from_query_ast(query, names),
249 Statement::CreateTable(create) => {
250 names.insert(create.name.clone());
251 true
252 }
253 Statement::CreateExternalTable(create) => {
254 names.insert(create.name.clone());
255 true
256 }
257 Statement::AlterTable(alter) => {
258 let current = alter.table_name().clone();
259 names.insert(current.clone());
260 if let AlterTableOperation::RenameTable { new_table_name } = alter.alter_operation() {
261 let mut renamed = current;
262 if let Some(last) = renamed.0.last_mut() {
263 *last = ObjectNamePart::Identifier(Ident::with_quote('"', new_table_name));
264 }
265 names.insert(renamed);
266 }
267 true
268 }
269 Statement::DropTable(drop) => {
270 names.extend(drop.table_names().iter().cloned());
271 true
272 }
273 #[cfg(feature = "enterprise")]
274 Statement::UndropTable(undrop) => {
275 names.insert(undrop.table_name().clone());
276 true
277 }
278 Statement::TruncateTable(truncate) => {
279 names.insert(truncate.table_name().clone());
280 true
281 }
282 Statement::CreateTableLike(create) => {
283 names.extend([create.table_name.clone(), create.source_name.clone()]);
284 true
285 }
286 Statement::CreateView(create) => {
287 names.insert(create.name.clone());
288 extract_tables_from_statement(&create.query, names)
289 }
290 Statement::CreateFlow(create) => {
291 names.insert(create.sink_table_name.clone());
292 extract_tables_from_sql_or_tql(&create.query, names)
293 }
294 #[cfg(feature = "enterprise")]
295 Statement::CreateTrigger(create) => {
296 extract_tables_from_sql_or_tql(&create.trigger_on.query, names)
297 }
298 #[cfg(feature = "enterprise")]
299 Statement::AlterTrigger(alter) => match &alter.operation.trigger_on {
300 Some(trigger_on) => extract_tables_from_sql_or_tql(&trigger_on.query, names),
301 None => true,
302 },
303 Statement::DropView(drop) => {
304 names.insert(drop.view_name.clone());
305 true
306 }
307 Statement::Explain(explain) => extract_tables_from_statement(&explain.statement, names),
308 Statement::DeclareCursor(cursor) => extract_tables_from_query_ast(&cursor.query, names),
309 Statement::DescribeTable(describe) => {
310 names.insert(describe.name().clone());
311 true
312 }
313 Statement::ShowCreateTable(show) => {
314 names.insert(show.table_name.clone());
315 true
316 }
317 Statement::ShowCreateView(show) => {
318 names.insert(show.view_name.clone());
319 true
320 }
321 Statement::ShowColumns(show) => {
322 names.insert(metadata_table_name(&show.table, show.database.as_deref()));
323 true
324 }
325 Statement::ShowIndex(show) => {
326 names.insert(metadata_table_name(&show.table, show.database.as_deref()));
327 true
328 }
329 Statement::ShowRegion(show) => {
330 names.insert(metadata_table_name(&show.table, show.database.as_deref()));
331 true
332 }
333 Statement::Comment(comment) => {
334 if let CommentObject::Table(table) | CommentObject::Column { table, .. } =
335 &comment.object
336 {
337 names.insert(table.clone());
338 }
339 true
340 }
341 Statement::Copy(Copy::CopyTable(copy)) => {
342 let table = match copy {
343 CopyTable::To(args) | CopyTable::From(args) => &args.table_name,
344 };
345 names.insert(table.clone());
346 true
347 }
348 Statement::Copy(Copy::CopyQueryTo(copy)) => {
349 extract_tables_from_statement(©.query, names)
350 }
351 Statement::Copy(Copy::CopyDatabase(_)) => true,
352 Statement::DropDatabase(_)
353 | Statement::DropFlow(_)
354 | Statement::CreateDatabase(_)
355 | Statement::AlterDatabase(_)
356 | Statement::ShowDatabases(_)
357 | Statement::ShowTables(_)
358 | Statement::ShowTableStatus(_)
359 | Statement::ShowCharset(_)
360 | Statement::ShowCollation(_)
361 | Statement::ShowCreateDatabase(_)
362 | Statement::ShowCreateFlow(_)
363 | Statement::ShowFlows(_)
364 | Statement::ShowFlowStatus(_)
365 | Statement::ShowStatus(_)
366 | Statement::ShowSearchPath(_)
367 | Statement::ShowViews(_)
368 | Statement::SetVariables(_)
369 | Statement::ShowVariables(_)
370 | Statement::Use(_)
371 | Statement::Admin(_)
372 | Statement::FetchCursor(_)
373 | Statement::CloseCursor(_)
374 | Statement::Kill(_)
375 | Statement::ShowProcesslist(_) => true,
376 #[cfg(feature = "enterprise")]
377 Statement::DropTrigger(_)
378 | Statement::ShowCreateTrigger(_)
379 | Statement::ShowTriggers(_) => true,
380 }
381}
382
383fn extract_tables_from_query_ast(query: &Query, names: &mut HashSet<ObjectName>) -> bool {
384 extract_tables_from_sql_query(&query.inner, names);
385 extract_tables_from_hybrid_cte_query(query, names)
386}
387
388fn extract_tables_from_sql_or_tql(query: &SqlOrTql, names: &mut HashSet<ObjectName>) -> bool {
389 let (query_names, complete) = extract_tables_from_query_inner(query);
390 names.extend(query_names);
391 complete
392}
393
394fn collect_relations(ast: &impl AstVisit, names: &mut HashSet<ObjectName>) {
395 let _ = ast.visit(&mut RelationCollector::new(names));
396}
397
398fn metadata_table_name(table: &str, database: Option<&str>) -> ObjectName {
399 let mut parts = Vec::with_capacity(usize::from(database.is_some()) + 1);
400 parts.extend(database.map(|db| Ident::with_quote('"', db)));
401 parts.push(Ident::with_quote('"', table));
402 ObjectName::from(parts)
403}
404
405fn extract_tables_from_query_inner(query: &SqlOrTql) -> (HashSet<ObjectName>, bool) {
406 let mut names = HashSet::new();
407
408 let complete = match query {
409 SqlOrTql::Sql(query, _) => {
410 extract_tables_from_sql_query(&query.inner, &mut names);
411 extract_tables_from_hybrid_cte_query(query, &mut names)
412 }
413 SqlOrTql::Tql(tql, _) => extract_tables_from_tql(tql, &mut names),
414 };
415
416 (names, complete)
417}
418
419fn extract_tables_from_hybrid_cte_query(
420 query: &Query,
421 sql_names: &mut HashSet<ObjectName>,
422) -> bool {
423 let Some(hybrid_cte) = &query.hybrid_cte else {
424 return true;
425 };
426
427 let mut complete = true;
428 let cte_names: HashSet<String> = hybrid_cte
429 .cte_tables
430 .iter()
431 .map(|cte| normalize_ident(&cte.name))
432 .collect();
433 remove_cte_names(sql_names, &cte_names);
434
435 for cte in &hybrid_cte.cte_tables {
436 let mut cte_query_names = HashSet::new();
437 match &cte.content {
438 CteContent::Sql(cte_query) => {
439 extract_tables_from_sql_query(cte_query, &mut cte_query_names)
440 }
441 CteContent::Tql(tql) => complete &= extract_tables_from_tql(tql, &mut cte_query_names),
442 }
443 sql_names.extend(cte_query_names);
444 }
445
446 complete
447}
448
449fn remove_cte_names(names: &mut HashSet<ObjectName>, cte_names: &HashSet<String>) {
450 if cte_names.is_empty() {
451 return;
452 }
453
454 names.retain(|name| {
455 if name.0.len() != 1 {
456 return true;
457 }
458 let Some(ident) = name.0[0].as_ident() else {
459 return true;
460 };
461
462 let canonical = normalize_ident(ident);
463 !cte_names.contains(&canonical)
464 });
465}
466
467fn extract_tables_from_tql(tql: &Tql, names: &mut HashSet<ObjectName>) -> bool {
468 let promql = match tql {
469 Tql::Eval(eval) => &eval.query,
470 Tql::Explain(explain) => &explain.query,
471 Tql::Analyze(analyze) => &analyze.query,
472 };
473
474 let Ok(expr) = promql_parser::parser::parse(promql) else {
475 return false;
476 };
477 extract_tables_from_prom_expr(&expr, names)
478}
479
480pub fn extract_tables_from_prom_expr_checked(
483 expr: &PromExpr,
484) -> Option<impl Iterator<Item = ObjectName>> {
485 let mut names = HashSet::new();
486 extract_tables_from_prom_expr(expr, &mut names).then_some(names.into_iter())
487}
488
489pub fn extract_tables_from_prom_expr_partial(expr: &PromExpr) -> Vec<ObjectName> {
492 let mut names = HashSet::new();
493 extract_tables_from_prom_expr(expr, &mut names);
494 names.into_iter().collect()
495}
496
497fn extract_tables_from_prom_expr(expr: &PromExpr, names: &mut HashSet<ObjectName>) -> bool {
498 struct TableCollector<'a> {
499 names: &'a mut HashSet<ObjectName>,
500 complete: bool,
501 default_info_selectors: Vec<*const PromVectorSelector>,
504 }
505
506 impl TableCollector<'_> {
507 fn visit_info(&mut self, args: &[Box<PromExpr>]) -> bool {
510 match args.get(1).map(|labels| labels.as_ref()) {
511 None => {}
512 Some(PromExpr::VectorSelector(labels)) if reads_default_info_metric(labels) => {
513 self.default_info_selectors.push(labels);
514 }
515 Some(_) => return true,
518 }
519 self.names
520 .insert(ObjectName(vec![ObjectNamePart::Identifier(
521 Ident::with_quote('"', DEFAULT_INFO_METRIC),
522 )]));
523 true
524 }
525 }
526
527 impl ExprVisitor for TableCollector<'_> {
528 type Error = ();
529
530 fn pre_visit(&mut self, expr: &PromExpr) -> std::result::Result<bool, Self::Error> {
531 self.complete &= match expr {
532 PromExpr::VectorSelector(selector)
533 if self
534 .default_info_selectors
535 .iter()
536 .any(|seen| std::ptr::eq(*seen, selector)) =>
537 {
538 true
539 }
540 PromExpr::VectorSelector(selector) => {
541 extract_metric_name_from_vector_selector(selector, self.names)
542 }
543 PromExpr::Call(call) if call.func.name == "info" => {
544 self.visit_info(&call.args.args)
545 }
546 PromExpr::MatrixSelector(PromMatrixSelector { vs, .. }) => {
547 extract_metric_name_from_vector_selector(vs, self.names)
548 }
549 PromExpr::Extension(_) => false,
550 _ => true,
551 };
552 Ok(true)
553 }
554 }
555
556 let mut collector = TableCollector {
557 names,
558 complete: true,
559 default_info_selectors: Vec::new(),
560 };
561 let _ = walk_expr(&mut collector, expr);
562 collector.complete
563}
564
565fn extract_metric_name_from_vector_selector(
566 selector: &PromVectorSelector,
567 names: &mut HashSet<ObjectName>,
568) -> bool {
569 if selector.name.is_none() && !selector.matchers.or_matchers.is_empty() {
570 return false;
571 }
572
573 let metric_name = selector.name.clone().or_else(|| {
574 let mut metric_name_matchers = selector.matchers.find_matchers(METRIC_NAME);
575 if metric_name_matchers.len() == 1 && metric_name_matchers[0].op == MatchOp::Equal {
576 metric_name_matchers.pop().map(|matcher| matcher.value)
577 } else {
578 None
579 }
580 });
581 let Some(metric_name) = metric_name else {
582 return false;
583 };
584
585 if selector.matchers.matchers.iter().any(|matcher| {
586 (matcher.name == SCHEMA_MATCHER || matcher.name == DATABASE_MATCHER)
587 && matcher.op != MatchOp::Equal
588 }) {
589 return false;
590 }
591
592 let schema_matcher = selector.matchers.matchers.iter().rev().find(|matcher| {
593 matcher.op == MatchOp::Equal
594 && (matcher.name == SCHEMA_MATCHER || matcher.name == DATABASE_MATCHER)
595 });
596
597 if let Some(schema) = schema_matcher {
598 names.insert(ObjectName(vec![
599 ObjectNamePart::Identifier(Ident::with_quote('"', &schema.value)),
600 ObjectNamePart::Identifier(Ident::with_quote('"', metric_name)),
601 ]));
602 } else {
603 names.insert(ObjectName(vec![ObjectNamePart::Identifier(
604 Ident::with_quote('"', metric_name),
605 )]));
606 }
607 true
608}
609
610pub fn location_to_index(sql: &str, location: &sqlparser::tokenizer::Location) -> usize {
612 let mut index = 0;
613 for (lno, line) in sql.lines().enumerate() {
614 if lno + 1 == location.line as usize {
615 index += location.column as usize;
616 break;
617 } else {
618 index += line.len() + 1; }
620 }
621 index - 1
624}
625
626struct QueryScope {
628 cte_names: Vec<String>,
629 next_cte: usize,
630 recursive: bool,
631 scope_start: usize,
632 add_to_parent_after: Option<String>,
633}
634
635struct RelationCollector<'a> {
636 names: &'a mut HashSet<ObjectName>,
637 ctes_in_scope: Vec<String>,
638 query_scopes: Vec<QueryScope>,
639 #[cfg(test)]
640 query_visits: usize,
641}
642
643impl<'a> RelationCollector<'a> {
644 fn new(names: &'a mut HashSet<ObjectName>) -> Self {
645 Self {
646 names,
647 ctes_in_scope: Vec::new(),
648 query_scopes: Vec::new(),
649 #[cfg(test)]
650 query_visits: 0,
651 }
652 }
653}
654
655impl Visitor for RelationCollector<'_> {
656 type Break = ();
657
658 fn pre_visit_query(&mut self, query: &sqlparser::ast::Query) -> ControlFlow<Self::Break> {
659 #[cfg(test)]
660 {
661 self.query_visits += 1;
662 }
663
664 let parent_cte = self.query_scopes.last_mut().and_then(|scope| {
666 let cte_name = scope.cte_names.get(scope.next_cte)?.clone();
667 scope.next_cte += 1;
668 Some((cte_name, scope.recursive))
669 });
670
671 let add_to_parent_after = match parent_cte {
672 Some((cte_name, true)) => {
673 self.ctes_in_scope.push(cte_name);
674 None
675 }
676 Some((cte_name, false)) => Some(cte_name),
677 None => None,
678 };
679
680 let scope_start = self.ctes_in_scope.len();
681 let (cte_names, recursive) = if let Some(with) = &query.with {
682 (
683 with.cte_tables
684 .iter()
685 .map(|cte| normalize_ident(&cte.alias.name))
686 .collect(),
687 with.recursive,
688 )
689 } else {
690 (Vec::new(), false)
691 };
692
693 self.query_scopes.push(QueryScope {
694 cte_names,
695 next_cte: 0,
696 recursive,
697 scope_start,
698 add_to_parent_after,
699 });
700 ControlFlow::Continue(())
701 }
702
703 fn post_visit_query(&mut self, _query: &sqlparser::ast::Query) -> ControlFlow<Self::Break> {
704 let Some(scope) = self.query_scopes.pop() else {
705 return ControlFlow::Break(());
706 };
707 self.ctes_in_scope.truncate(scope.scope_start);
708 if let Some(cte_name) = scope.add_to_parent_after {
709 self.ctes_in_scope.push(cte_name);
710 }
711 ControlFlow::Continue(())
712 }
713
714 fn pre_visit_relation(&mut self, relation: &ObjectName) -> ControlFlow<Self::Break> {
715 let is_cte = matches!(
716 relation.0.as_slice(),
717 [part]
718 if part.as_ident().is_some_and(|ident| {
719 self.ctes_in_scope.contains(&normalize_ident(ident))
720 })
721 );
722 if !is_cte {
723 self.names.insert(relation.clone());
724 }
725 ControlFlow::Continue(())
726 }
727}
728
729pub fn extract_tables_from_sql_query_ast(query: &sqlparser::ast::Query) -> HashSet<ObjectName> {
733 let mut names = HashSet::new();
734 extract_tables_from_sql_query(query, &mut names);
735 names
736}
737
738pub fn collect_relations_from_ast(ast: &impl AstVisit) -> HashSet<ObjectName> {
741 let mut names = HashSet::new();
742 collect_relations(ast, &mut names);
743 names
744}
745
746fn extract_tables_from_sql_query(query: &sqlparser::ast::Query, names: &mut HashSet<ObjectName>) {
747 let _ = query.visit(&mut RelationCollector::new(names));
748}
749
750#[cfg(test)]
751mod tests {
752 use itertools::Itertools;
753 use sqlparser::tokenizer::Token;
754
755 use super::*;
756 use crate::dialect::GreptimeDbDialect;
757 use crate::parser::{ParseOptions, ParserContext};
758 use crate::statements::statement::Statement;
759
760 #[test]
761 fn test_location_to_index() {
762 let testcases = vec![
763 "SELECT * FROM t WHERE a = 1",
764 r"
766SELECT *
767FROM
768t
769WHERE a =
7701
771",
772 r"SELECT *
773FROM
774t
775WHERE a =
7761
777",
778 r"
779SELECT *
780FROM
781t
782WHERE a =
7831",
784 ];
785
786 for sql in testcases {
787 let mut parser = ParserContext::new(&GreptimeDbDialect {}, sql).unwrap();
788 loop {
789 let token = parser.parser.next_token();
790 if token == Token::EOF {
791 break;
792 }
793 let span = token.span;
794 let subslice =
795 &sql[location_to_index(sql, &span.start)..location_to_index(sql, &span.end)];
796 assert_eq!(token.to_string(), subslice);
797 }
798 }
799 }
800
801 #[test]
802 fn test_extract_tables_from_tql_query() {
803 let testcases = vec![
804 (
805 r#"
806CREATE FLOW calc_reqs SINK TO cnt_reqs AS
807TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests);"#,
808 vec!["http_requests".to_string()],
809 ),
810 (
811 r#"
812CREATE FLOW calc_reqs SINK TO cnt_reqs AS
813TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", {__name__="http_requests"});"#,
814 vec!["http_requests".to_string()],
815 ),
816 ];
817
818 for (sql, expected_tables) in testcases {
819 let mut stmts = ParserContext::create_with_dialect(
820 sql,
821 &GreptimeDbDialect {},
822 ParseOptions::default(),
823 )
824 .unwrap();
825 let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
826 unreachable!()
827 };
828
829 let mut tables = extract_tables_from_query(&create_flow.query)
830 .map(|table| format_raw_object_name(&table))
831 .collect_vec();
832 tables.sort();
833 assert_eq!(expected_tables, tables);
834 }
835 }
836
837 #[test]
838 fn test_extract_tables_from_tql_query_completeness() {
839 let testcases = [
840 ("cpu", true, vec!["cpu"]),
841 ("cpu + mem", true, vec!["cpu", "mem"]),
842 (r#"cpu{__database__="private"}"#, true, vec!["private.cpu"]),
843 ("1 + 2", true, vec![]),
844 (r#"{__name__="cpu"}"#, true, vec!["cpu"]),
845 (r#"cpu{job="api" or instance="host"}"#, true, vec!["cpu"]),
846 (r#"cpu + {job="api"}"#, false, vec!["cpu"]),
847 (r#"{__name__=~"cpu.*"}"#, false, vec![]),
848 (r#"{__name__=~"cpu.*" or job="api"}"#, false, vec![]),
849 (r#"cpu{__schema__=~"private.*"}"#, false, vec![]),
850 ("info(cpu)", true, vec!["cpu", "target_info"]),
852 (
853 r#"info(cpu, {version="v1"})"#,
854 true,
855 vec!["cpu", "target_info"],
856 ),
857 (
858 r#"info(cpu, {__name__="build_info", version="v1"})"#,
859 true,
860 vec!["build_info", "cpu"],
861 ),
862 (r#"info(cpu, {__name__=~".+_info"})"#, false, vec!["cpu"]),
863 (
865 r#"info(cpu, {__schema__="private", version="v1"})"#,
866 false,
867 vec!["cpu"],
868 ),
869 (r#"info(cpu, {version="v1"} offset 1m)"#, false, vec!["cpu"]),
870 (
871 r#"info(cpu, {version="v1" or version="v2"})"#,
872 false,
873 vec!["cpu"],
874 ),
875 ];
876
877 for (promql, expected_complete, expected_tables) in testcases {
878 let expected_tables = expected_tables
879 .into_iter()
880 .map(str::to_string)
881 .collect_vec();
882 let sql = format!("TQL EVAL (0, 10, '5s') {promql}");
883 let mut stmts = ParserContext::create_with_dialect(
884 &sql,
885 &GreptimeDbDialect {},
886 ParseOptions::default(),
887 )
888 .unwrap();
889 let Statement::Tql(tql) = stmts.pop().unwrap() else {
890 unreachable!()
891 };
892
893 let query = SqlOrTql::Tql(tql, sql);
894 let (tables, complete) = extract_tables_from_query_inner(&query);
895 let mut tables = tables
896 .into_iter()
897 .map(|table| format_raw_object_name(&table))
898 .collect_vec();
899 tables.sort();
900 assert_eq!(expected_complete, complete, "{promql}");
901 assert_eq!(expected_tables, tables, "{promql}");
902 assert_eq!(
903 expected_complete,
904 extract_tables_from_query_checked(&query).is_some(),
905 "{promql}"
906 );
907
908 let expr = promql_parser::parser::parse(promql).unwrap();
909 let direct_tables = extract_tables_from_prom_expr_checked(&expr).map(|tables| {
910 let mut tables = tables
911 .map(|table| format_raw_object_name(&table))
912 .collect_vec();
913 tables.sort();
914 tables
915 });
916 assert_eq!(
917 expected_complete.then(|| expected_tables.clone()),
918 direct_tables
919 );
920 }
921 }
922
923 #[test]
924 fn test_extract_tables_from_statement() {
925 for (sql, expected) in [
926 ("SELECT * FROM physical_metric", vec!["physical_metric"]),
927 (
928 "INSERT INTO target SELECT * FROM physical_metric",
929 vec!["physical_metric", "target"],
930 ),
931 (
932 "INSERT INTO target WITH cte AS (SELECT * FROM physical_metric) SELECT * FROM cte",
933 vec!["physical_metric", "target"],
934 ),
935 (
936 "TQL EVAL (0, 10, '5s') physical_metric",
937 vec!["physical_metric"],
938 ),
939 (
940 "CREATE VIEW target AS SELECT * FROM physical_metric",
941 vec!["physical_metric", "target"],
942 ),
943 ("ALTER TABLE old RENAME new", vec!["new", "old"]),
944 #[cfg(feature = "enterprise")]
945 ("UNDROP TABLE restored", vec!["restored"]),
946 ("SHOW TABLES", vec![]),
947 ] {
948 let stmt = ParserContext::create_with_dialect(
949 sql,
950 &GreptimeDbDialect {},
951 ParseOptions::default(),
952 )
953 .unwrap()
954 .remove(0);
955 let mut tables = extract_tables_from_statement_checked(&stmt)
956 .unwrap()
957 .map(|table| format_raw_object_name(&table))
958 .collect_vec();
959 tables.sort();
960 assert_eq!(expected, tables, "{sql}");
961 }
962 }
963
964 #[test]
965 fn test_extract_tables_from_chained_tql_ctes() {
966 let sql = "WITH denied AS (TQL EVAL (0, 10, '5s') allowed), \
967 leak AS (TQL EVAL (0, 10, '5s') denied) \
968 SELECT * FROM leak";
969 let mut stmts =
970 ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
971 .unwrap();
972 let Statement::Query(query) = stmts.pop().unwrap() else {
973 unreachable!()
974 };
975
976 let mut tables = extract_tables_from_query_checked(&SqlOrTql::Sql(*query, sql.to_string()))
977 .unwrap()
978 .map(|table| format_raw_object_name(&table))
979 .collect_vec();
980 tables.sort();
981 assert_eq!(vec!["allowed".to_string(), "denied".to_string()], tables);
982 }
983
984 #[test]
985 fn test_extract_tables_from_sql_query_with_derived_join() {
986 let sql = r#"
987CREATE FLOW flow_batch_join_subquery SINK TO flow_batch_join_sink
988EVAL INTERVAL '1m' AS
989SELECT a.symbol, b.mark_price
990FROM (
991 SELECT inst_id AS symbol, max(ts) AS mark_iv_ts
992 FROM flow_batch_join_opt_summary
993 GROUP BY inst_id
994) a
995LEFT JOIN (
996 SELECT symbol, max(mark_price) AS mark_price
997 FROM flow_batch_join_market_v5
998 WHERE "type" = 'OPTION_MARK'
999 GROUP BY symbol
1000) b ON a.symbol = b.symbol;
1001"#;
1002 let mut stmts =
1003 ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1004 .unwrap();
1005 let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
1006 unreachable!()
1007 };
1008
1009 let mut tables = extract_tables_from_query(&create_flow.query)
1010 .map(|table| format_raw_object_name(&table))
1011 .collect_vec();
1012 tables.sort();
1013 assert_eq!(
1014 vec![
1015 "flow_batch_join_market_v5".to_string(),
1016 "flow_batch_join_opt_summary".to_string(),
1017 ],
1018 tables
1019 );
1020 }
1021
1022 #[test]
1023 fn test_extract_tables_from_sql_query_with_expression_subqueries() {
1024 let sql = r#"
1025SELECT
1026 (SELECT max(value) FROM scalar_source)
1027FROM outer_source
1028WHERE EXISTS (SELECT 1 FROM exists_source)
1029ORDER BY (SELECT max(value) FROM order_source);
1030"#;
1031 let mut stmts =
1032 ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1033 .unwrap();
1034 let Statement::Query(query) = stmts.pop().unwrap() else {
1035 unreachable!()
1036 };
1037
1038 let mut tables = extract_tables_from_query(&SqlOrTql::Sql(*query, sql.to_string()))
1039 .map(|table| format_raw_object_name(&table))
1040 .collect_vec();
1041 tables.sort();
1042 assert_eq!(
1043 vec![
1044 "exists_source".to_string(),
1045 "order_source".to_string(),
1046 "outer_source".to_string(),
1047 "scalar_source".to_string(),
1048 ],
1049 tables
1050 );
1051 }
1052
1053 #[test]
1054 fn test_extract_tables_from_sql_query_with_cte_scopes() {
1055 let testcases = vec![
1056 (
1057 r#"
1058WITH source AS (
1059 SELECT * FROM source
1060)
1061SELECT * FROM source;
1062"#,
1063 vec!["source".to_string()],
1064 ),
1065 (
1066 r#"
1067WITH RECURSIVE source AS (
1068 SELECT * FROM source
1069)
1070SELECT * FROM source;
1071"#,
1072 vec![],
1073 ),
1074 (
1075 r#"
1076WITH first_cte AS (
1077 SELECT * FROM physical_source
1078), second_cte AS (
1079 SELECT * FROM first_cte
1080)
1081SELECT * FROM second_cte;
1082"#,
1083 vec!["physical_source".to_string()],
1084 ),
1085 (
1086 r#"
1087SELECT * FROM (
1088 WITH nested_cte AS (SELECT * FROM nested_source)
1089 SELECT * FROM nested_cte
1090);
1091"#,
1092 vec!["nested_source".to_string()],
1093 ),
1094 (
1095 r#"
1096SELECT * FROM (
1097 WITH nested_cte AS (SELECT * FROM nested_source)
1098 SELECT (SELECT * FROM nested_cte)
1099);
1100"#,
1101 vec!["nested_source".to_string()],
1102 ),
1103 (
1104 "WITH \u{212A}pi AS (SELECT 1) SELECT * FROM kpi;",
1105 vec!["kpi".to_string()],
1106 ),
1107 (
1108 "WITH \u{212A}pi AS (SELECT 1) SELECT * FROM \u{212A}PI;",
1109 vec![],
1110 ),
1111 (
1112 "SELECT * FROM (WITH \u{212A}pi AS (SELECT 1) SELECT * FROM kpi);",
1113 vec!["kpi".to_string()],
1114 ),
1115 ];
1116
1117 for (sql, expected_tables) in testcases {
1118 let mut stmts = ParserContext::create_with_dialect(
1119 sql,
1120 &GreptimeDbDialect {},
1121 ParseOptions::default(),
1122 )
1123 .unwrap();
1124 let Statement::Query(query) = stmts.pop().unwrap() else {
1125 unreachable!()
1126 };
1127
1128 let mut tables = HashSet::new();
1129 extract_tables_from_sql_query(&query.inner, &mut tables);
1130 let mut tables = tables
1131 .into_iter()
1132 .map(|table| format_raw_object_name(&table))
1133 .collect_vec();
1134 tables.sort();
1135 assert_eq!(expected_tables, tables);
1136 }
1137 }
1138
1139 #[test]
1140 fn test_extract_tables_from_deeply_nested_ctes_visits_each_query_once() {
1141 let mut sql = "SELECT * FROM physical_source".to_string();
1142 for depth in 0..20 {
1143 sql = format!("WITH cte_{depth} AS ({sql}) SELECT * FROM cte_{depth}");
1144 }
1145
1146 let mut stmts = ParserContext::create_with_dialect(
1147 &sql,
1148 &GreptimeDbDialect {},
1149 ParseOptions::default(),
1150 )
1151 .unwrap();
1152 let Statement::Query(query) = stmts.pop().unwrap() else {
1153 unreachable!()
1154 };
1155
1156 let mut tables = HashSet::new();
1157 let query_visits = {
1158 let mut collector = RelationCollector::new(&mut tables);
1159 let _ = query.inner.visit(&mut collector);
1160 collector.query_visits
1161 };
1162
1163 assert_eq!(21, query_visits);
1164 assert_eq!(
1165 vec!["physical_source"],
1166 tables
1167 .into_iter()
1168 .map(|table| format_raw_object_name(&table))
1169 .collect_vec()
1170 );
1171 }
1172
1173 #[test]
1174 fn test_extract_tables_from_tql_query_with_schema_matcher() {
1175 let sql = r#"
1176CREATE FLOW calc_reqs SINK TO cnt_reqs AS
1177TQL EVAL (now() - '15s'::interval, now(), '5s') count_values("status_code", http_requests{__schema__="greptime_private"});"#;
1178 let mut stmts =
1179 ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
1180 .unwrap();
1181 let Statement::CreateFlow(create_flow) = stmts.pop().unwrap() else {
1182 unreachable!()
1183 };
1184
1185 let mut tables = extract_tables_from_query(&create_flow.query)
1186 .map(|table| format_raw_object_name(&table))
1187 .collect_vec();
1188 tables.sort();
1189 assert_eq!(vec!["greptime_private.http_requests".to_string()], tables);
1190 }
1191}