Skip to main content

frontend/
instance.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
15pub mod builder;
16mod dashboard;
17mod grpc;
18mod influxdb;
19mod jaeger;
20mod log_handler;
21mod logs;
22mod opentsdb;
23mod otlp;
24pub mod prom_store;
25mod promql;
26mod region_query;
27pub mod standalone;
28
29use std::pin::Pin;
30use std::sync::atomic::AtomicBool;
31use std::sync::{Arc, atomic};
32use std::time::{Duration, SystemTime};
33
34use async_stream::stream;
35use async_trait::async_trait;
36use auth::{PermissionChecker, PermissionCheckerRef, PermissionReq};
37use catalog::CatalogManagerRef;
38use catalog::process_manager::{
39    ProcessManagerRef, QueryStatement as CatalogQueryStatement, SlowQueryTimer,
40};
41use client::OutputData;
42use common_base::Plugins;
43use common_base::cancellation::CancellableFuture;
44use common_error::ext::{BoxedError, ErrorExt};
45use common_event_recorder::EventRecorderRef;
46use common_meta::cache_invalidator::CacheInvalidatorRef;
47use common_meta::key::TableMetadataManagerRef;
48use common_meta::key::table_name::TableNameKey;
49use common_meta::node_manager::NodeManagerRef;
50use common_meta::procedure_executor::ProcedureExecutorRef;
51use common_query::Output;
52use common_recordbatch::RecordBatchStreamWrapper;
53use common_recordbatch::error::StreamTimeoutSnafu;
54use common_telemetry::logging::SlowQueryOptions;
55use common_telemetry::{debug, error, tracing};
56use dashmap::DashMap;
57use datafusion_expr::LogicalPlan;
58use futures::{Stream, StreamExt};
59use lazy_static::lazy_static;
60use operator::delete::DeleterRef;
61use operator::insert::InserterRef;
62use operator::statement::{StatementExecutor, StatementExecutorRef};
63use partition::manager::PartitionRuleManagerRef;
64use pipeline::pipeline_operator::PipelineOperator;
65use prometheus::HistogramTimer;
66use promql_parser::label::Matcher;
67use query::QueryEngineRef;
68use query::metrics::OnDone;
69use query::parser::{PromQuery, QueryLanguageParser, QueryStatement};
70use query::query_engine::DescribeResult;
71use query::query_engine::options::{QueryOptions, validate_catalog_and_schema};
72use servers::error::{
73    self as server_error, AuthSnafu, CommonMetaSnafu, ExecuteQuerySnafu,
74    OtlpMetricModeIncompatibleSnafu, ParsePromQLSnafu, UnexpectedResultSnafu,
75};
76use servers::interceptor::{
77    PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, SqlQueryInterceptorRef,
78};
79use servers::otlp::metrics::legacy_normalize_otlp_name;
80use servers::prometheus_handler::PrometheusHandler;
81use servers::query_handler::sql::SqlQueryHandler;
82use session::context::{Channel, QueryContextRef};
83use session::table_name::table_idents_to_full_name;
84use snafu::prelude::*;
85use sql::ast::ObjectNamePartExt;
86use sql::dialect::Dialect;
87use sql::parser::{ParseOptions, ParserContext};
88use sql::statements::comment::CommentObject;
89use sql::statements::copy::{CopyDatabase, CopyTable};
90use sql::statements::statement::Statement;
91use sql::statements::tql::Tql;
92use sqlparser::ast::ObjectName;
93pub use standalone::StandaloneDatanodeManager;
94use table::requests::{OTLP_METRIC_COMPAT_KEY, OTLP_METRIC_COMPAT_PROM};
95use tracing::Span;
96
97use crate::error::{
98    self, Error, ExecLogicalPlanSnafu, ExecutePromqlSnafu, ExternalSnafu, InvalidSqlSnafu,
99    ParseSqlSnafu, PermissionSnafu, PlanStatementSnafu, Result, SqlExecInterceptedSnafu,
100    StatementTimeoutSnafu, TableOperationSnafu,
101};
102use crate::stream_wrapper::CancellableStreamWrapper;
103
104lazy_static! {
105    static ref OTLP_LEGACY_DEFAULT_VALUE: String = "legacy".to_string();
106}
107
108/// The frontend instance contains necessary components, and implements many
109/// traits, like [`servers::query_handler::grpc::GrpcQueryHandler`],
110/// [`servers::query_handler::sql::SqlQueryHandler`], etc.
111#[derive(Clone)]
112pub struct Instance {
113    catalog_manager: CatalogManagerRef,
114    pipeline_operator: Arc<PipelineOperator>,
115    statement_executor: Arc<StatementExecutor>,
116    query_engine: QueryEngineRef,
117    plugins: Plugins,
118    inserter: InserterRef,
119    deleter: DeleterRef,
120    table_metadata_manager: TableMetadataManagerRef,
121    event_recorder: Option<EventRecorderRef>,
122    process_manager: ProcessManagerRef,
123    slow_query_options: SlowQueryOptions,
124    suspend: Arc<AtomicBool>,
125
126    // cache for otlp metrics
127    // first layer key: db-string
128    // key: direct input metric name
129    // value: if runs in legacy mode
130    otlp_metrics_table_legacy_cache: DashMap<String, DashMap<String, bool>>,
131}
132
133impl Instance {
134    pub fn catalog_manager(&self) -> &CatalogManagerRef {
135        &self.catalog_manager
136    }
137
138    pub fn query_engine(&self) -> &QueryEngineRef {
139        &self.query_engine
140    }
141
142    pub fn plugins(&self) -> &Plugins {
143        &self.plugins
144    }
145
146    pub fn statement_executor(&self) -> &StatementExecutorRef {
147        &self.statement_executor
148    }
149
150    pub fn table_metadata_manager(&self) -> &TableMetadataManagerRef {
151        &self.table_metadata_manager
152    }
153
154    pub fn inserter(&self) -> &InserterRef {
155        &self.inserter
156    }
157
158    pub fn process_manager(&self) -> &ProcessManagerRef {
159        &self.process_manager
160    }
161
162    pub fn node_manager(&self) -> &NodeManagerRef {
163        self.inserter.node_manager()
164    }
165
166    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
167        self.inserter.partition_manager()
168    }
169
170    pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
171        self.statement_executor.cache_invalidator()
172    }
173
174    pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
175        self.statement_executor.procedure_executor()
176    }
177
178    pub fn suspend_state(&self) -> Arc<AtomicBool> {
179        self.suspend.clone()
180    }
181
182    pub(crate) fn is_suspended(&self) -> bool {
183        self.suspend.load(atomic::Ordering::Relaxed)
184    }
185}
186
187fn parse_stmt(sql: &str, dialect: &(dyn Dialect + Send + Sync)) -> Result<Vec<Statement>> {
188    ParserContext::create_with_dialect(sql, dialect, ParseOptions::default()).context(ParseSqlSnafu)
189}
190
191impl Instance {
192    async fn query_statement(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
193        check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
194
195        let query_interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
196        let query_interceptor = query_interceptor.as_ref();
197
198        if should_capture_statement(Some(&stmt)) {
199            let slow_query_timer = self
200                .slow_query_options
201                .enable
202                .then(|| self.event_recorder.clone())
203                .flatten()
204                .map(|event_recorder| {
205                    SlowQueryTimer::new(
206                        CatalogQueryStatement::Sql(stmt.clone()),
207                        self.slow_query_options.threshold,
208                        self.slow_query_options.sample_ratio,
209                        self.slow_query_options.record_type,
210                        event_recorder,
211                    )
212                });
213
214            let ticket = self.process_manager.register_query(
215                query_ctx.current_catalog().to_string(),
216                vec![query_ctx.current_schema()],
217                stmt.to_string(),
218                query_ctx.conn_info().to_string(),
219                Some(query_ctx.process_id()),
220                slow_query_timer,
221            );
222
223            let query_fut = self.exec_statement_with_timeout(stmt, query_ctx, query_interceptor);
224
225            CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
226                .await
227                .map_err(|_| error::CancelledSnafu.build())?
228                .map(|output| {
229                    let Output { meta, data } = output;
230
231                    let data = match data {
232                        OutputData::Stream(stream) => OutputData::Stream(Box::pin(
233                            CancellableStreamWrapper::new(stream, ticket),
234                        )),
235                        other => other,
236                    };
237                    Output { data, meta }
238                })
239        } else {
240            self.exec_statement_with_timeout(stmt, query_ctx, query_interceptor)
241                .await
242        }
243    }
244
245    async fn exec_statement_with_timeout(
246        &self,
247        stmt: Statement,
248        query_ctx: QueryContextRef,
249        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
250    ) -> Result<Output> {
251        let timeout = derive_timeout(&stmt, &query_ctx);
252        match timeout {
253            Some(timeout) => {
254                let start = tokio::time::Instant::now();
255                let output = tokio::time::timeout(
256                    timeout,
257                    self.exec_statement(stmt, query_ctx, query_interceptor),
258                )
259                .await
260                .map_err(|_| StatementTimeoutSnafu.build())??;
261                // compute remaining timeout
262                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
263                attach_timeout(output, remaining_timeout)
264            }
265            None => {
266                self.exec_statement(stmt, query_ctx, query_interceptor)
267                    .await
268            }
269        }
270    }
271
272    async fn exec_statement(
273        &self,
274        stmt: Statement,
275        query_ctx: QueryContextRef,
276        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
277    ) -> Result<Output> {
278        match stmt {
279            Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
280                // TODO: remove this when format is supported in datafusion
281                if let Statement::Explain(explain) = &stmt
282                    && let Some(format) = explain.format()
283                {
284                    query_ctx.set_explain_format(format.to_string());
285                }
286
287                self.plan_and_exec_sql(stmt, &query_ctx, query_interceptor)
288                    .await
289            }
290            Statement::Tql(tql) => {
291                self.plan_and_exec_tql(&query_ctx, query_interceptor, tql)
292                    .await
293            }
294            _ => {
295                query_interceptor.pre_execute(&stmt, None, query_ctx.clone())?;
296                self.statement_executor
297                    .execute_sql(stmt, query_ctx)
298                    .await
299                    .context(TableOperationSnafu)
300            }
301        }
302    }
303
304    async fn plan_and_exec_sql(
305        &self,
306        stmt: Statement,
307        query_ctx: &QueryContextRef,
308        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
309    ) -> Result<Output> {
310        let stmt = QueryStatement::Sql(stmt);
311        let plan = self
312            .statement_executor
313            .plan(&stmt, query_ctx.clone())
314            .await?;
315        let QueryStatement::Sql(stmt) = stmt else {
316            unreachable!()
317        };
318        query_interceptor.pre_execute(&stmt, Some(&plan), query_ctx.clone())?;
319
320        self.statement_executor
321            .exec_plan(plan, query_ctx.clone())
322            .await
323            .context(TableOperationSnafu)
324    }
325
326    async fn plan_and_exec_tql(
327        &self,
328        query_ctx: &QueryContextRef,
329        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
330        tql: Tql,
331    ) -> Result<Output> {
332        let plan = self
333            .statement_executor
334            .plan_tql(tql.clone(), query_ctx)
335            .await?;
336        query_interceptor.pre_execute(&Statement::Tql(tql), Some(&plan), query_ctx.clone())?;
337        self.statement_executor
338            .exec_plan(plan, query_ctx.clone())
339            .await
340            .context(TableOperationSnafu)
341    }
342
343    async fn check_otlp_legacy(
344        &self,
345        names: &[&String],
346        ctx: QueryContextRef,
347    ) -> server_error::Result<bool> {
348        let db_string = ctx.get_db_string();
349        // fast cache check
350        let cache = self
351            .otlp_metrics_table_legacy_cache
352            .entry(db_string.clone())
353            .or_default();
354        if let Some(flag) = fast_legacy_check(&cache, names)? {
355            return Ok(flag);
356        }
357        // release cache reference to avoid lock contention
358        drop(cache);
359
360        let catalog = ctx.current_catalog();
361        let schema = ctx.current_schema();
362
363        // query legacy table names
364        let normalized_names = names
365            .iter()
366            .map(|n| legacy_normalize_otlp_name(n))
367            .collect::<Vec<_>>();
368        let table_names = normalized_names
369            .iter()
370            .map(|n| TableNameKey::new(catalog, &schema, n))
371            .collect::<Vec<_>>();
372        let table_values = self
373            .table_metadata_manager()
374            .table_name_manager()
375            .batch_get(table_names)
376            .await
377            .context(CommonMetaSnafu)?;
378        let table_ids = table_values
379            .into_iter()
380            .filter_map(|v| v.map(|vi| vi.table_id()))
381            .collect::<Vec<_>>();
382
383        // means no existing table is found, use new mode
384        if table_ids.is_empty() {
385            let cache = self
386                .otlp_metrics_table_legacy_cache
387                .entry(db_string)
388                .or_default();
389            names.iter().for_each(|name| {
390                cache.insert((*name).clone(), false);
391            });
392            return Ok(false);
393        }
394
395        // has existing table, check table options
396        let table_infos = self
397            .table_metadata_manager()
398            .table_info_manager()
399            .batch_get(&table_ids)
400            .await
401            .context(CommonMetaSnafu)?;
402        let options = table_infos
403            .values()
404            .map(|info| {
405                info.table_info
406                    .meta
407                    .options
408                    .extra_options
409                    .get(OTLP_METRIC_COMPAT_KEY)
410                    .unwrap_or(&OTLP_LEGACY_DEFAULT_VALUE)
411            })
412            .collect::<Vec<_>>();
413        let cache = self
414            .otlp_metrics_table_legacy_cache
415            .entry(db_string)
416            .or_default();
417        if !options.is_empty() {
418            // check value consistency
419            let has_prom = options.iter().any(|opt| *opt == OTLP_METRIC_COMPAT_PROM);
420            let has_legacy = options
421                .iter()
422                .any(|opt| *opt == OTLP_LEGACY_DEFAULT_VALUE.as_str());
423            ensure!(!(has_prom && has_legacy), OtlpMetricModeIncompatibleSnafu);
424            let flag = has_legacy;
425            names.iter().for_each(|name| {
426                cache.insert((*name).clone(), flag);
427            });
428            Ok(flag)
429        } else {
430            // no table info, use new mode
431            names.iter().for_each(|name| {
432                cache.insert((*name).clone(), false);
433            });
434            Ok(false)
435        }
436    }
437}
438
439fn fast_legacy_check(
440    cache: &DashMap<String, bool>,
441    names: &[&String],
442) -> server_error::Result<Option<bool>> {
443    let hit_cache = names
444        .iter()
445        .filter_map(|name| cache.get(*name))
446        .collect::<Vec<_>>();
447    if !hit_cache.is_empty() {
448        let hit_legacy = hit_cache.iter().any(|en| *en.value());
449        let hit_prom = hit_cache.iter().any(|en| !*en.value());
450
451        // hit but have true and false, means both legacy and new mode are used
452        // we cannot handle this case, so return error
453        // add doc links in err msg later
454        ensure!(!(hit_legacy && hit_prom), OtlpMetricModeIncompatibleSnafu);
455
456        let flag = hit_legacy;
457        // drop hit_cache to release references before inserting to avoid deadlock
458        drop(hit_cache);
459
460        // set cache for all names
461        names.iter().for_each(|name| {
462            if !cache.contains_key(*name) {
463                cache.insert((*name).clone(), flag);
464            }
465        });
466        Ok(Some(flag))
467    } else {
468        Ok(None)
469    }
470}
471
472/// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements.
473/// For MySQL, it applies only to read-only statements.
474fn derive_timeout(stmt: &Statement, query_ctx: &QueryContextRef) -> Option<Duration> {
475    let query_timeout = query_ctx.query_timeout()?;
476    if query_timeout.is_zero() {
477        return None;
478    }
479    match query_ctx.channel() {
480        Channel::Mysql if stmt.is_readonly() => Some(query_timeout),
481        Channel::Postgres => Some(query_timeout),
482        _ => None,
483    }
484}
485
486fn attach_timeout(output: Output, mut timeout: Duration) -> Result<Output> {
487    if timeout.is_zero() {
488        return StatementTimeoutSnafu.fail();
489    }
490
491    let output = match output.data {
492        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
493        OutputData::Stream(mut stream) => {
494            let schema = stream.schema();
495            let s = Box::pin(stream! {
496                let mut start = tokio::time::Instant::now();
497                while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.map_err(|_| StreamTimeoutSnafu.build())? {
498                    yield item;
499
500                    let now = tokio::time::Instant::now();
501                    timeout = timeout.checked_sub(now - start).unwrap_or(Duration::ZERO);
502                    start = now;
503                    // tokio::time::timeout may not return an error immediately when timeout is 0.
504                    if timeout.is_zero() {
505                        StreamTimeoutSnafu.fail()?;
506                    }
507                }
508            }) as Pin<Box<dyn Stream<Item = _> + Send>>;
509            let stream = RecordBatchStreamWrapper {
510                schema,
511                stream: s,
512                output_ordering: None,
513                metrics: Default::default(),
514                span: Span::current(),
515            };
516            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
517        }
518    };
519
520    Ok(output)
521}
522
523impl Instance {
524    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_query")]
525    async fn do_query_inner(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
526        if self.is_suspended() {
527            return vec![error::SuspendedSnafu {}.fail()];
528        }
529
530        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
531        let query_interceptor = query_interceptor_opt.as_ref();
532        let query = match query_interceptor.pre_parsing(query, query_ctx.clone()) {
533            Ok(q) => q,
534            Err(e) => return vec![Err(e)],
535        };
536
537        let checker_ref = self.plugins.get::<PermissionCheckerRef>();
538        let checker = checker_ref.as_ref();
539
540        match parse_stmt(query.as_ref(), query_ctx.sql_dialect())
541            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))
542        {
543            Ok(stmts) => {
544                if stmts.is_empty() {
545                    return vec![
546                        InvalidSqlSnafu {
547                            err_msg: "empty statements",
548                        }
549                        .fail(),
550                    ];
551                }
552
553                let mut results = Vec::with_capacity(stmts.len());
554                for stmt in stmts {
555                    if let Err(e) = checker
556                        .check_permission(
557                            query_ctx.current_user(),
558                            PermissionReq::SqlStatement(&stmt),
559                        )
560                        .context(PermissionSnafu)
561                    {
562                        results.push(Err(e));
563                        break;
564                    }
565
566                    match self.query_statement(stmt.clone(), query_ctx.clone()).await {
567                        Ok(output) => {
568                            let output_result =
569                                query_interceptor.post_execute(output, query_ctx.clone());
570                            results.push(output_result);
571                        }
572                        Err(e) => {
573                            if e.status_code().should_log_error() {
574                                error!(e; "Failed to execute query: {stmt}");
575                            } else {
576                                debug!("Failed to execute query: {stmt}, {e}");
577                            }
578                            results.push(Err(e));
579                            break;
580                        }
581                    }
582                }
583                results
584            }
585            Err(e) => {
586                vec![Err(e)]
587            }
588        }
589    }
590
591    async fn do_exec_plan_inner(
592        &self,
593        stmt: Option<Statement>,
594        plan: LogicalPlan,
595        query_ctx: QueryContextRef,
596    ) -> Result<Output> {
597        ensure!(!self.is_suspended(), error::SuspendedSnafu);
598
599        if should_capture_statement(stmt.as_ref()) {
600            // It's safe to unwrap here because we've already checked the type.
601            let stmt = stmt.unwrap();
602            let query = stmt.to_string();
603            let slow_query_timer = self
604                .slow_query_options
605                .enable
606                .then(|| self.event_recorder.clone())
607                .flatten()
608                .map(|event_recorder| {
609                    SlowQueryTimer::new(
610                        CatalogQueryStatement::Sql(stmt.clone()),
611                        self.slow_query_options.threshold,
612                        self.slow_query_options.sample_ratio,
613                        self.slow_query_options.record_type,
614                        event_recorder,
615                    )
616                });
617
618            let ticket = self.process_manager.register_query(
619                query_ctx.current_catalog().to_string(),
620                vec![query_ctx.current_schema()],
621                query,
622                query_ctx.conn_info().to_string(),
623                Some(query_ctx.process_id()),
624                slow_query_timer,
625            );
626
627            let query_fut = self.query_engine.execute(plan.clone(), query_ctx);
628
629            CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
630                .await
631                .map_err(|_| error::CancelledSnafu.build())?
632                .map(|output| {
633                    let Output { meta, data } = output;
634
635                    let data = match data {
636                        OutputData::Stream(stream) => OutputData::Stream(Box::pin(
637                            CancellableStreamWrapper::new(stream, ticket),
638                        )),
639                        other => other,
640                    };
641                    Output { data, meta }
642                })
643                .context(ExecLogicalPlanSnafu)
644        } else {
645            // plan should be prepared before exec
646            // we'll do check there
647            self.query_engine
648                .execute(plan.clone(), query_ctx)
649                .await
650                .context(ExecLogicalPlanSnafu)
651        }
652    }
653
654    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_promql_query")]
655    async fn do_promql_query_inner(
656        &self,
657        query: &PromQuery,
658        query_ctx: QueryContextRef,
659    ) -> Vec<Result<Output>> {
660        if self.is_suspended() {
661            return vec![error::SuspendedSnafu {}.fail()];
662        }
663
664        // check will be done in prometheus handler's do_query
665        let result = PrometheusHandler::do_query(self, query, query_ctx)
666            .await
667            .with_context(|_| ExecutePromqlSnafu {
668                query: format!("{query:?}"),
669            });
670        vec![result]
671    }
672
673    async fn do_describe_inner(
674        &self,
675        stmt: Statement,
676        query_ctx: QueryContextRef,
677    ) -> Result<Option<DescribeResult>> {
678        ensure!(!self.is_suspended(), error::SuspendedSnafu);
679
680        if matches!(
681            stmt,
682            Statement::Insert(_) | Statement::Query(_) | Statement::Delete(_)
683        ) {
684            self.plugins
685                .get::<PermissionCheckerRef>()
686                .as_ref()
687                .check_permission(query_ctx.current_user(), PermissionReq::SqlStatement(&stmt))
688                .context(PermissionSnafu)?;
689
690            let plan = self
691                .query_engine
692                .planner()
693                .plan(&QueryStatement::Sql(stmt), query_ctx.clone())
694                .await
695                .context(PlanStatementSnafu)?;
696            self.query_engine
697                .describe(plan, query_ctx)
698                .await
699                .map(Some)
700                .context(error::DescribeStatementSnafu)
701        } else {
702            Ok(None)
703        }
704    }
705
706    async fn is_valid_schema_inner(&self, catalog: &str, schema: &str) -> Result<bool> {
707        self.catalog_manager
708            .schema_exists(catalog, schema, None)
709            .await
710            .context(error::CatalogSnafu)
711    }
712}
713
714#[async_trait]
715impl SqlQueryHandler for Instance {
716    async fn do_query(
717        &self,
718        query: &str,
719        query_ctx: QueryContextRef,
720    ) -> Vec<server_error::Result<Output>> {
721        self.do_query_inner(query, query_ctx)
722            .await
723            .into_iter()
724            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
725            .collect()
726    }
727
728    async fn do_exec_plan(
729        &self,
730        stmt: Option<Statement>,
731        plan: LogicalPlan,
732        query_ctx: QueryContextRef,
733    ) -> server_error::Result<Output> {
734        self.do_exec_plan_inner(stmt, plan, query_ctx)
735            .await
736            .map_err(BoxedError::new)
737            .context(server_error::ExecutePlanSnafu)
738    }
739
740    async fn do_promql_query(
741        &self,
742        query: &PromQuery,
743        query_ctx: QueryContextRef,
744    ) -> Vec<server_error::Result<Output>> {
745        self.do_promql_query_inner(query, query_ctx)
746            .await
747            .into_iter()
748            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
749            .collect()
750    }
751
752    async fn do_describe(
753        &self,
754        stmt: Statement,
755        query_ctx: QueryContextRef,
756    ) -> server_error::Result<Option<DescribeResult>> {
757        self.do_describe_inner(stmt, query_ctx)
758            .await
759            .map_err(BoxedError::new)
760            .context(server_error::DescribeStatementSnafu)
761    }
762
763    async fn is_valid_schema(&self, catalog: &str, schema: &str) -> server_error::Result<bool> {
764        self.is_valid_schema_inner(catalog, schema)
765            .await
766            .map_err(BoxedError::new)
767            .context(server_error::CheckDatabaseValiditySnafu)
768    }
769}
770
771/// Attaches a timer to the output and observes it once the output is exhausted.
772pub fn attach_timer(output: Output, timer: HistogramTimer) -> Output {
773    match output.data {
774        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
775        OutputData::Stream(stream) => {
776            let stream = OnDone::new(stream, move || {
777                timer.observe_duration();
778            });
779            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
780        }
781    }
782}
783
784#[async_trait]
785impl PrometheusHandler for Instance {
786    #[tracing::instrument(skip_all)]
787    async fn do_query(
788        &self,
789        query: &PromQuery,
790        query_ctx: QueryContextRef,
791    ) -> server_error::Result<Output> {
792        let interceptor = self
793            .plugins
794            .get::<PromQueryInterceptorRef<server_error::Error>>();
795
796        self.plugins
797            .get::<PermissionCheckerRef>()
798            .as_ref()
799            .check_permission(query_ctx.current_user(), PermissionReq::PromQuery)
800            .context(AuthSnafu)?;
801
802        let stmt = QueryLanguageParser::parse_promql(query, &query_ctx).with_context(|_| {
803            ParsePromQLSnafu {
804                query: query.clone(),
805            }
806        })?;
807
808        let plan = self
809            .statement_executor
810            .plan(&stmt, query_ctx.clone())
811            .await
812            .map_err(BoxedError::new)
813            .context(ExecuteQuerySnafu)?;
814
815        interceptor.pre_execute(query, Some(&plan), query_ctx.clone())?;
816
817        // Take the EvalStmt from the original QueryStatement and use it to create the CatalogQueryStatement.
818        let query_statement = if let QueryStatement::Promql(eval_stmt, alias) = stmt {
819            CatalogQueryStatement::Promql(eval_stmt, alias)
820        } else {
821            // It should not happen since the query is already parsed successfully.
822            return UnexpectedResultSnafu {
823                reason: "The query should always be promql.".to_string(),
824            }
825            .fail();
826        };
827        let query = query_statement.to_string();
828
829        let slow_query_timer = self
830            .slow_query_options
831            .enable
832            .then(|| self.event_recorder.clone())
833            .flatten()
834            .map(|event_recorder| {
835                SlowQueryTimer::new(
836                    query_statement,
837                    self.slow_query_options.threshold,
838                    self.slow_query_options.sample_ratio,
839                    self.slow_query_options.record_type,
840                    event_recorder,
841                )
842            });
843
844        let ticket = self.process_manager.register_query(
845            query_ctx.current_catalog().to_string(),
846            vec![query_ctx.current_schema()],
847            query,
848            query_ctx.conn_info().to_string(),
849            Some(query_ctx.process_id()),
850            slow_query_timer,
851        );
852
853        let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone());
854
855        let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
856            .await
857            .map_err(|_| servers::error::CancelledSnafu.build())?
858            .map(|output| {
859                let Output { meta, data } = output;
860                let data = match data {
861                    OutputData::Stream(stream) => {
862                        OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
863                    }
864                    other => other,
865                };
866                Output { data, meta }
867            })
868            .map_err(BoxedError::new)
869            .context(ExecuteQuerySnafu)?;
870
871        Ok(interceptor.post_execute(output, query_ctx)?)
872    }
873
874    async fn query_metric_names(
875        &self,
876        matchers: Vec<Matcher>,
877        ctx: &QueryContextRef,
878    ) -> server_error::Result<Vec<String>> {
879        self.handle_query_metric_names(matchers, ctx)
880            .await
881            .map_err(BoxedError::new)
882            .context(ExecuteQuerySnafu)
883    }
884
885    async fn query_label_values(
886        &self,
887        metric: String,
888        label_name: String,
889        matchers: Vec<Matcher>,
890        start: SystemTime,
891        end: SystemTime,
892        ctx: &QueryContextRef,
893    ) -> server_error::Result<Vec<String>> {
894        self.handle_query_label_values(metric, label_name, matchers, start, end, ctx)
895            .await
896            .map_err(BoxedError::new)
897            .context(ExecuteQuerySnafu)
898    }
899
900    fn catalog_manager(&self) -> CatalogManagerRef {
901        self.catalog_manager.clone()
902    }
903}
904
905/// Validate `stmt.database` permission if it's presented.
906macro_rules! validate_db_permission {
907    ($stmt: expr, $query_ctx: expr) => {
908        if let Some(database) = &$stmt.database {
909            validate_catalog_and_schema($query_ctx.current_catalog(), database, $query_ctx)
910                .map_err(BoxedError::new)
911                .context(SqlExecInterceptedSnafu)?;
912        }
913    };
914}
915
916pub fn check_permission(
917    plugins: Plugins,
918    stmt: &Statement,
919    query_ctx: &QueryContextRef,
920) -> Result<()> {
921    let need_validate = plugins
922        .get::<QueryOptions>()
923        .map(|opts| opts.disallow_cross_catalog_query)
924        .unwrap_or_default();
925
926    if !need_validate {
927        return Ok(());
928    }
929
930    match stmt {
931        // Will be checked in execution.
932        // TODO(dennis): add a hook for admin commands.
933        Statement::Admin(_) => {}
934        // These are executed by query engine, and will be checked there.
935        Statement::Query(_)
936        | Statement::Explain(_)
937        | Statement::Tql(_)
938        | Statement::Delete(_)
939        | Statement::DeclareCursor(_)
940        | Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(_)) => {}
941        // database ops won't be checked
942        Statement::CreateDatabase(_)
943        | Statement::ShowDatabases(_)
944        | Statement::DropDatabase(_)
945        | Statement::AlterDatabase(_)
946        | Statement::DropFlow(_)
947        | Statement::Use(_) => {}
948        #[cfg(feature = "enterprise")]
949        Statement::DropTrigger(_) => {}
950        Statement::ShowCreateDatabase(stmt) => {
951            validate_database(&stmt.database_name, query_ctx)?;
952        }
953        Statement::ShowCreateTable(stmt) => {
954            validate_param(&stmt.table_name, query_ctx)?;
955        }
956        Statement::ShowCreateFlow(stmt) => {
957            validate_flow(&stmt.flow_name, query_ctx)?;
958        }
959        #[cfg(feature = "enterprise")]
960        Statement::ShowCreateTrigger(stmt) => {
961            validate_param(&stmt.trigger_name, query_ctx)?;
962        }
963        Statement::ShowCreateView(stmt) => {
964            validate_param(&stmt.view_name, query_ctx)?;
965        }
966        Statement::CreateExternalTable(stmt) => {
967            validate_param(&stmt.name, query_ctx)?;
968        }
969        Statement::CreateFlow(stmt) => {
970            // TODO: should also validate source table name here?
971            validate_param(&stmt.sink_table_name, query_ctx)?;
972        }
973        #[cfg(feature = "enterprise")]
974        Statement::CreateTrigger(stmt) => {
975            validate_param(&stmt.trigger_name, query_ctx)?;
976        }
977        Statement::CreateView(stmt) => {
978            validate_param(&stmt.name, query_ctx)?;
979        }
980        Statement::AlterTable(stmt) => {
981            validate_param(stmt.table_name(), query_ctx)?;
982        }
983        #[cfg(feature = "enterprise")]
984        Statement::AlterTrigger(_) => {}
985        // set/show variable now only alter/show variable in session
986        Statement::SetVariables(_) | Statement::ShowVariables(_) => {}
987        // show charset and show collation won't be checked
988        Statement::ShowCharset(_) | Statement::ShowCollation(_) => {}
989
990        Statement::Comment(comment) => match &comment.object {
991            CommentObject::Table(table) => validate_param(table, query_ctx)?,
992            CommentObject::Column { table, .. } => validate_param(table, query_ctx)?,
993            CommentObject::Flow(flow) => validate_flow(flow, query_ctx)?,
994        },
995
996        Statement::Insert(insert) => {
997            let name = insert.table_name().context(ParseSqlSnafu)?;
998            validate_param(name, query_ctx)?;
999        }
1000        Statement::CreateTable(stmt) => {
1001            validate_param(&stmt.name, query_ctx)?;
1002        }
1003        Statement::CreateTableLike(stmt) => {
1004            validate_param(&stmt.table_name, query_ctx)?;
1005            validate_param(&stmt.source_name, query_ctx)?;
1006        }
1007        Statement::DropTable(drop_stmt) => {
1008            for table_name in drop_stmt.table_names() {
1009                validate_param(table_name, query_ctx)?;
1010            }
1011        }
1012        Statement::DropView(stmt) => {
1013            validate_param(&stmt.view_name, query_ctx)?;
1014        }
1015        Statement::ShowTables(stmt) => {
1016            validate_db_permission!(stmt, query_ctx);
1017        }
1018        Statement::ShowTableStatus(stmt) => {
1019            validate_db_permission!(stmt, query_ctx);
1020        }
1021        Statement::ShowColumns(stmt) => {
1022            validate_db_permission!(stmt, query_ctx);
1023        }
1024        Statement::ShowIndex(stmt) => {
1025            validate_db_permission!(stmt, query_ctx);
1026        }
1027        Statement::ShowRegion(stmt) => {
1028            validate_db_permission!(stmt, query_ctx);
1029        }
1030        Statement::ShowViews(stmt) => {
1031            validate_db_permission!(stmt, query_ctx);
1032        }
1033        Statement::ShowFlows(stmt) => {
1034            validate_db_permission!(stmt, query_ctx);
1035        }
1036        #[cfg(feature = "enterprise")]
1037        Statement::ShowTriggers(_stmt) => {
1038            // The trigger is organized based on the catalog dimension, so there
1039            // is no need to check the permission of the database(schema).
1040        }
1041        Statement::ShowStatus(_stmt) => {}
1042        Statement::ShowSearchPath(_stmt) => {}
1043        Statement::DescribeTable(stmt) => {
1044            validate_param(stmt.name(), query_ctx)?;
1045        }
1046        Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => match stmt {
1047            CopyTable::To(copy_table_to) => validate_param(&copy_table_to.table_name, query_ctx)?,
1048            CopyTable::From(copy_table_from) => {
1049                validate_param(&copy_table_from.table_name, query_ctx)?
1050            }
1051        },
1052        Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
1053            match copy_database {
1054                CopyDatabase::To(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1055                CopyDatabase::From(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1056            }
1057        }
1058        Statement::TruncateTable(stmt) => {
1059            validate_param(stmt.table_name(), query_ctx)?;
1060        }
1061        // cursor operations are always allowed once it's created
1062        Statement::FetchCursor(_) | Statement::CloseCursor(_) => {}
1063        // User can only kill process in their own catalog.
1064        Statement::Kill(_) => {}
1065        // SHOW PROCESSLIST
1066        Statement::ShowProcesslist(_) => {}
1067    }
1068    Ok(())
1069}
1070
1071fn validate_param(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1072    let (catalog, schema, _) = table_idents_to_full_name(name, query_ctx)
1073        .map_err(BoxedError::new)
1074        .context(ExternalSnafu)?;
1075
1076    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1077        .map_err(BoxedError::new)
1078        .context(SqlExecInterceptedSnafu)
1079}
1080
1081fn validate_flow(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1082    let catalog = match &name.0[..] {
1083        [_flow] => query_ctx.current_catalog().to_string(),
1084        [catalog, _flow] => catalog.to_string_unquoted(),
1085        _ => {
1086            return InvalidSqlSnafu {
1087                err_msg: format!(
1088                    "expect flow name to be <catalog>.<flow_name> or <flow_name>, actual: {name}",
1089                ),
1090            }
1091            .fail();
1092        }
1093    };
1094
1095    let schema = query_ctx.current_schema();
1096
1097    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1098        .map_err(BoxedError::new)
1099        .context(SqlExecInterceptedSnafu)
1100}
1101
1102fn validate_database(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1103    let (catalog, schema) = match &name.0[..] {
1104        [schema] => (
1105            query_ctx.current_catalog().to_string(),
1106            schema.to_string_unquoted(),
1107        ),
1108        [catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
1109        _ => InvalidSqlSnafu {
1110            err_msg: format!(
1111                "expect database name to be <catalog>.<schema> or <schema>, actual: {name}",
1112            ),
1113        }
1114        .fail()?,
1115    };
1116
1117    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1118        .map_err(BoxedError::new)
1119        .context(SqlExecInterceptedSnafu)
1120}
1121
1122// Create a query ticket and slow query timer if the statement is a query or readonly statement.
1123fn should_capture_statement(stmt: Option<&Statement>) -> bool {
1124    if let Some(stmt) = stmt {
1125        matches!(stmt, Statement::Query(_)) || stmt.is_readonly()
1126    } else {
1127        false
1128    }
1129}
1130
1131#[cfg(test)]
1132mod tests {
1133    use std::collections::HashMap;
1134    use std::sync::atomic::{AtomicBool, Ordering};
1135    use std::sync::{Arc, Barrier};
1136    use std::thread;
1137    use std::time::{Duration, Instant};
1138
1139    use common_base::Plugins;
1140    use query::query_engine::options::QueryOptions;
1141    use session::context::QueryContext;
1142    use sql::dialect::GreptimeDbDialect;
1143    use strfmt::Format;
1144
1145    use super::*;
1146
1147    #[test]
1148    fn test_fast_legacy_check_deadlock_prevention() {
1149        // Create a DashMap to simulate the cache
1150        let cache = DashMap::new();
1151
1152        // Pre-populate cache with some entries
1153        cache.insert("metric1".to_string(), true); // legacy mode
1154        cache.insert("metric2".to_string(), false); // prom mode
1155        cache.insert("metric3".to_string(), true); // legacy mode
1156
1157        // Test case 1: Normal operation with cache hits
1158        let metric1 = "metric1".to_string();
1159        let metric4 = "metric4".to_string();
1160        let names1 = vec![&metric1, &metric4];
1161        let result = fast_legacy_check(&cache, &names1);
1162        assert!(result.is_ok());
1163        assert_eq!(result.unwrap(), Some(true)); // should return legacy mode
1164
1165        // Verify that metric4 was added to cache
1166        assert!(cache.contains_key("metric4"));
1167        assert!(*cache.get("metric4").unwrap().value());
1168
1169        // Test case 2: No cache hits
1170        let metric5 = "metric5".to_string();
1171        let metric6 = "metric6".to_string();
1172        let names2 = vec![&metric5, &metric6];
1173        let result = fast_legacy_check(&cache, &names2);
1174        assert!(result.is_ok());
1175        assert_eq!(result.unwrap(), None); // should return None as no cache hits
1176
1177        // Test case 3: Incompatible modes should return error
1178        let cache_incompatible = DashMap::new();
1179        cache_incompatible.insert("metric1".to_string(), true); // legacy
1180        cache_incompatible.insert("metric2".to_string(), false); // prom
1181        let metric1_test = "metric1".to_string();
1182        let metric2_test = "metric2".to_string();
1183        let names3 = vec![&metric1_test, &metric2_test];
1184        let result = fast_legacy_check(&cache_incompatible, &names3);
1185        assert!(result.is_err()); // should error due to incompatible modes
1186
1187        // Test case 4: Intensive concurrent access to test deadlock prevention
1188        // This test specifically targets the scenario where multiple threads
1189        // access the same cache entries simultaneously
1190        let cache_concurrent = Arc::new(DashMap::new());
1191        cache_concurrent.insert("shared_metric".to_string(), true);
1192
1193        let num_threads = 8;
1194        let operations_per_thread = 100;
1195        let barrier = Arc::new(Barrier::new(num_threads));
1196        let success_flag = Arc::new(AtomicBool::new(true));
1197
1198        let handles: Vec<_> = (0..num_threads)
1199            .map(|thread_id| {
1200                let cache_clone = Arc::clone(&cache_concurrent);
1201                let barrier_clone = Arc::clone(&barrier);
1202                let success_flag_clone = Arc::clone(&success_flag);
1203
1204                thread::spawn(move || {
1205                    // Wait for all threads to be ready
1206                    barrier_clone.wait();
1207
1208                    let start_time = Instant::now();
1209                    for i in 0..operations_per_thread {
1210                        // Each operation references existing cache entry and adds new ones
1211                        let shared_metric = "shared_metric".to_string();
1212                        let new_metric = format!("thread_{}_metric_{}", thread_id, i);
1213                        let names = vec![&shared_metric, &new_metric];
1214
1215                        match fast_legacy_check(&cache_clone, &names) {
1216                            Ok(_) => {}
1217                            Err(_) => {
1218                                success_flag_clone.store(false, Ordering::Relaxed);
1219                                return;
1220                            }
1221                        }
1222
1223                        // If the test takes too long, it likely means deadlock
1224                        if start_time.elapsed() > Duration::from_secs(10) {
1225                            success_flag_clone.store(false, Ordering::Relaxed);
1226                            return;
1227                        }
1228                    }
1229                })
1230            })
1231            .collect();
1232
1233        // Join all threads with timeout
1234        let start_time = Instant::now();
1235        for (i, handle) in handles.into_iter().enumerate() {
1236            let join_result = handle.join();
1237
1238            // Check if we're taking too long (potential deadlock)
1239            if start_time.elapsed() > Duration::from_secs(30) {
1240                panic!("Test timed out - possible deadlock detected!");
1241            }
1242
1243            if join_result.is_err() {
1244                panic!("Thread {} panicked during execution", i);
1245            }
1246        }
1247
1248        // Verify all operations completed successfully
1249        assert!(
1250            success_flag.load(Ordering::Relaxed),
1251            "Some operations failed"
1252        );
1253
1254        // Verify that many new entries were added (proving operations completed)
1255        let final_count = cache_concurrent.len();
1256        assert!(
1257            final_count > 1 + num_threads * operations_per_thread / 2,
1258            "Expected more cache entries, got {}",
1259            final_count
1260        );
1261    }
1262
1263    #[test]
1264    fn test_exec_validation() {
1265        let query_ctx = QueryContext::arc();
1266        let plugins: Plugins = Plugins::new();
1267        plugins.insert(QueryOptions {
1268            disallow_cross_catalog_query: true,
1269        });
1270
1271        let sql = r#"
1272        SELECT * FROM demo;
1273        EXPLAIN SELECT * FROM demo;
1274        CREATE DATABASE test_database;
1275        SHOW DATABASES;
1276        "#;
1277        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1278        assert_eq!(stmts.len(), 4);
1279        for stmt in stmts {
1280            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
1281            re.unwrap();
1282        }
1283
1284        let sql = r#"
1285        SHOW CREATE TABLE demo;
1286        ALTER TABLE demo ADD COLUMN new_col INT;
1287        "#;
1288        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1289        assert_eq!(stmts.len(), 2);
1290        for stmt in stmts {
1291            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
1292            re.unwrap();
1293        }
1294
1295        fn replace_test(template_sql: &str, plugins: Plugins, query_ctx: &QueryContextRef) {
1296            // test right
1297            let right = vec![("", ""), ("", "public."), ("greptime.", "public.")];
1298            for (catalog, schema) in right {
1299                let sql = do_fmt(template_sql, catalog, schema);
1300                do_test(&sql, plugins.clone(), query_ctx, true);
1301            }
1302
1303            let wrong = vec![
1304                ("wrongcatalog.", "public."),
1305                ("wrongcatalog.", "wrongschema."),
1306            ];
1307            for (catalog, schema) in wrong {
1308                let sql = do_fmt(template_sql, catalog, schema);
1309                do_test(&sql, plugins.clone(), query_ctx, false);
1310            }
1311        }
1312
1313        fn do_fmt(template: &str, catalog: &str, schema: &str) -> String {
1314            let vars = HashMap::from([
1315                ("catalog".to_string(), catalog),
1316                ("schema".to_string(), schema),
1317            ]);
1318            template.format(&vars).unwrap()
1319        }
1320
1321        fn do_test(sql: &str, plugins: Plugins, query_ctx: &QueryContextRef, is_ok: bool) {
1322            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1323            let re = check_permission(plugins, stmt, query_ctx);
1324            if is_ok {
1325                re.unwrap();
1326            } else {
1327                assert!(re.is_err());
1328            }
1329        }
1330
1331        // test insert
1332        let sql = "INSERT INTO {catalog}{schema}monitor(host) VALUES ('host1');";
1333        replace_test(sql, plugins.clone(), &query_ctx);
1334
1335        // test create table
1336        let sql = r#"CREATE TABLE {catalog}{schema}demo(
1337                            host STRING,
1338                            ts TIMESTAMP,
1339                            TIME INDEX (ts),
1340                            PRIMARY KEY(host)
1341                        ) engine=mito;"#;
1342        replace_test(sql, plugins.clone(), &query_ctx);
1343
1344        // test drop table
1345        let sql = "DROP TABLE {catalog}{schema}demo;";
1346        replace_test(sql, plugins.clone(), &query_ctx);
1347
1348        // test show tables
1349        let sql = "SHOW TABLES FROM public";
1350        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1351        check_permission(plugins.clone(), &stmt[0], &query_ctx).unwrap();
1352
1353        let sql = "SHOW TABLES FROM private";
1354        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1355        let re = check_permission(plugins.clone(), &stmt[0], &query_ctx);
1356        assert!(re.is_ok());
1357
1358        // test describe table
1359        let sql = "DESC TABLE {catalog}{schema}demo;";
1360        replace_test(sql, plugins.clone(), &query_ctx);
1361
1362        let comment_flow_cases = [
1363            ("COMMENT ON FLOW my_flow IS 'comment';", true),
1364            ("COMMENT ON FLOW greptime.my_flow IS 'comment';", true),
1365            ("COMMENT ON FLOW wrongcatalog.my_flow IS 'comment';", false),
1366        ];
1367        for (sql, is_ok) in comment_flow_cases {
1368            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1369            let result = check_permission(plugins.clone(), stmt, &query_ctx);
1370            assert_eq!(result.is_ok(), is_ok);
1371        }
1372
1373        let show_flow_cases = [
1374            ("SHOW CREATE FLOW my_flow;", true),
1375            ("SHOW CREATE FLOW greptime.my_flow;", true),
1376            ("SHOW CREATE FLOW wrongcatalog.my_flow;", false),
1377        ];
1378        for (sql, is_ok) in show_flow_cases {
1379            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1380            let result = check_permission(plugins.clone(), stmt, &query_ctx);
1381            assert_eq!(result.is_ok(), is_ok);
1382        }
1383    }
1384}