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 stmt.is_readonly() {
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
486/// Derives timeout for plan execution.
487fn derive_timeout_for_plan(plan: &LogicalPlan, query_ctx: &QueryContextRef) -> Option<Duration> {
488    let query_timeout = query_ctx.query_timeout()?;
489    if query_timeout.is_zero() {
490        return None;
491    }
492    match query_ctx.channel() {
493        Channel::Mysql if is_readonly_plan(plan) => Some(query_timeout),
494        Channel::Postgres => Some(query_timeout),
495        _ => None,
496    }
497}
498
499fn attach_timeout(output: Output, mut timeout: Duration) -> Result<Output> {
500    if timeout.is_zero() {
501        return StatementTimeoutSnafu.fail();
502    }
503
504    let output = match output.data {
505        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
506        OutputData::Stream(mut stream) => {
507            let schema = stream.schema();
508            let s = Box::pin(stream! {
509                let mut start = tokio::time::Instant::now();
510                while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.map_err(|_| StreamTimeoutSnafu.build())? {
511                    yield item;
512
513                    let now = tokio::time::Instant::now();
514                    timeout = timeout.checked_sub(now - start).unwrap_or(Duration::ZERO);
515                    start = now;
516                    // tokio::time::timeout may not return an error immediately when timeout is 0.
517                    if timeout.is_zero() {
518                        StreamTimeoutSnafu.fail()?;
519                    }
520                }
521            }) as Pin<Box<dyn Stream<Item = _> + Send>>;
522            let stream = RecordBatchStreamWrapper {
523                schema,
524                stream: s,
525                output_ordering: None,
526                metrics: Default::default(),
527                span: Span::current(),
528            };
529            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
530        }
531    };
532
533    Ok(output)
534}
535
536impl Instance {
537    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_query")]
538    async fn do_query_inner(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
539        if self.is_suspended() {
540            return vec![error::SuspendedSnafu {}.fail()];
541        }
542
543        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
544        let query_interceptor = query_interceptor_opt.as_ref();
545        let query = match query_interceptor.pre_parsing(query, query_ctx.clone()) {
546            Ok(q) => q,
547            Err(e) => return vec![Err(e)],
548        };
549
550        let checker_ref = self.plugins.get::<PermissionCheckerRef>();
551        let checker = checker_ref.as_ref();
552
553        match parse_stmt(query.as_ref(), query_ctx.sql_dialect())
554            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))
555        {
556            Ok(stmts) => {
557                if stmts.is_empty() {
558                    return vec![
559                        InvalidSqlSnafu {
560                            err_msg: "empty statements",
561                        }
562                        .fail(),
563                    ];
564                }
565
566                let mut results = Vec::with_capacity(stmts.len());
567                for stmt in stmts {
568                    if let Err(e) = checker
569                        .check_permission(
570                            query_ctx.current_user(),
571                            PermissionReq::SqlStatement(&stmt),
572                        )
573                        .context(PermissionSnafu)
574                    {
575                        results.push(Err(e));
576                        break;
577                    }
578
579                    match self.query_statement(stmt.clone(), query_ctx.clone()).await {
580                        Ok(output) => {
581                            let output_result =
582                                query_interceptor.post_execute(output, query_ctx.clone());
583                            results.push(output_result);
584                        }
585                        Err(e) => {
586                            if e.status_code().should_log_error() {
587                                error!(e; "Failed to execute query: {stmt}");
588                            } else {
589                                debug!("Failed to execute query: {stmt}, {e}");
590                            }
591                            results.push(Err(e));
592                            break;
593                        }
594                    }
595                }
596                results
597            }
598            Err(e) => {
599                vec![Err(e)]
600            }
601        }
602    }
603
604    async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
605        self.query_engine
606            .execute(plan, query_ctx)
607            .await
608            .context(ExecLogicalPlanSnafu)
609    }
610
611    async fn exec_plan_with_timeout(
612        &self,
613        plan: LogicalPlan,
614        query_ctx: QueryContextRef,
615    ) -> Result<Output> {
616        let timeout = derive_timeout_for_plan(&plan, &query_ctx);
617        match timeout {
618            Some(timeout) => {
619                let start = tokio::time::Instant::now();
620                let output = tokio::time::timeout(timeout, self.exec_plan(plan, query_ctx))
621                    .await
622                    .map_err(|_| StatementTimeoutSnafu.build())??;
623                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
624                attach_timeout(output, remaining_timeout)
625            }
626            None => self.exec_plan(plan, query_ctx).await,
627        }
628    }
629
630    async fn do_exec_plan_inner(
631        &self,
632        plan: LogicalPlan,
633        query: String,
634        query_ctx: QueryContextRef,
635    ) -> Result<Output> {
636        ensure!(!self.is_suspended(), error::SuspendedSnafu);
637
638        if is_readonly_plan(&plan) {
639            let slow_query_timer = self
640                .slow_query_options
641                .enable
642                .then(|| self.event_recorder.clone())
643                .flatten()
644                .map(|event_recorder| {
645                    SlowQueryTimer::new(
646                        CatalogQueryStatement::Plan(query.clone()),
647                        self.slow_query_options.threshold,
648                        self.slow_query_options.sample_ratio,
649                        self.slow_query_options.record_type,
650                        event_recorder,
651                    )
652                });
653
654            let ticket = self.process_manager.register_query(
655                query_ctx.current_catalog().to_string(),
656                vec![query_ctx.current_schema()],
657                query,
658                query_ctx.conn_info().to_string(),
659                Some(query_ctx.process_id()),
660                slow_query_timer,
661            );
662
663            let query_fut = self.exec_plan_with_timeout(plan, query_ctx);
664
665            CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
666                .await
667                .map_err(|_| error::CancelledSnafu.build())?
668                .map(|output| {
669                    let Output { meta, data } = output;
670
671                    let data = match data {
672                        OutputData::Stream(stream) => OutputData::Stream(Box::pin(
673                            CancellableStreamWrapper::new(stream, ticket),
674                        )),
675                        other => other,
676                    };
677                    Output { data, meta }
678                })
679        } else {
680            self.exec_plan_with_timeout(plan, query_ctx).await
681        }
682    }
683
684    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_promql_query")]
685    async fn do_promql_query_inner(
686        &self,
687        query: &PromQuery,
688        query_ctx: QueryContextRef,
689    ) -> Vec<Result<Output>> {
690        if self.is_suspended() {
691            return vec![error::SuspendedSnafu {}.fail()];
692        }
693
694        // check will be done in prometheus handler's do_query
695        let result = PrometheusHandler::do_query(self, query, query_ctx)
696            .await
697            .with_context(|_| ExecutePromqlSnafu {
698                query: format!("{query:?}"),
699            });
700        vec![result]
701    }
702
703    async fn do_describe_inner(
704        &self,
705        stmt: Statement,
706        query_ctx: QueryContextRef,
707    ) -> Result<Option<DescribeResult>> {
708        ensure!(!self.is_suspended(), error::SuspendedSnafu);
709
710        if matches!(
711            stmt,
712            Statement::Insert(_) | Statement::Query(_) | Statement::Delete(_)
713        ) {
714            self.plugins
715                .get::<PermissionCheckerRef>()
716                .as_ref()
717                .check_permission(query_ctx.current_user(), PermissionReq::SqlStatement(&stmt))
718                .context(PermissionSnafu)?;
719
720            let plan = self
721                .query_engine
722                .planner()
723                .plan(&QueryStatement::Sql(stmt), query_ctx.clone())
724                .await
725                .context(PlanStatementSnafu)?;
726            self.query_engine
727                .describe(plan, query_ctx)
728                .await
729                .map(Some)
730                .context(error::DescribeStatementSnafu)
731        } else {
732            Ok(None)
733        }
734    }
735
736    async fn is_valid_schema_inner(&self, catalog: &str, schema: &str) -> Result<bool> {
737        self.catalog_manager
738            .schema_exists(catalog, schema, None)
739            .await
740            .context(error::CatalogSnafu)
741    }
742}
743
744#[async_trait]
745impl SqlQueryHandler for Instance {
746    async fn do_query(
747        &self,
748        query: &str,
749        query_ctx: QueryContextRef,
750    ) -> Vec<server_error::Result<Output>> {
751        self.do_query_inner(query, query_ctx)
752            .await
753            .into_iter()
754            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
755            .collect()
756    }
757
758    async fn do_exec_plan(
759        &self,
760        plan: LogicalPlan,
761        query: String,
762        query_ctx: QueryContextRef,
763    ) -> server_error::Result<Output> {
764        self.do_exec_plan_inner(plan, query, query_ctx)
765            .await
766            .map_err(BoxedError::new)
767            .context(server_error::ExecutePlanSnafu)
768    }
769
770    async fn do_promql_query(
771        &self,
772        query: &PromQuery,
773        query_ctx: QueryContextRef,
774    ) -> Vec<server_error::Result<Output>> {
775        self.do_promql_query_inner(query, query_ctx)
776            .await
777            .into_iter()
778            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
779            .collect()
780    }
781
782    async fn do_describe(
783        &self,
784        stmt: Statement,
785        query_ctx: QueryContextRef,
786    ) -> server_error::Result<Option<DescribeResult>> {
787        self.do_describe_inner(stmt, query_ctx)
788            .await
789            .map_err(BoxedError::new)
790            .context(server_error::DescribeStatementSnafu)
791    }
792
793    async fn is_valid_schema(&self, catalog: &str, schema: &str) -> server_error::Result<bool> {
794        self.is_valid_schema_inner(catalog, schema)
795            .await
796            .map_err(BoxedError::new)
797            .context(server_error::CheckDatabaseValiditySnafu)
798    }
799}
800
801/// Attaches a timer to the output and observes it once the output is exhausted.
802pub fn attach_timer(output: Output, timer: HistogramTimer) -> Output {
803    match output.data {
804        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
805        OutputData::Stream(stream) => {
806            let stream = OnDone::new(stream, move || {
807                timer.observe_duration();
808            });
809            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
810        }
811    }
812}
813
814#[async_trait]
815impl PrometheusHandler for Instance {
816    #[tracing::instrument(skip_all)]
817    async fn do_query(
818        &self,
819        query: &PromQuery,
820        query_ctx: QueryContextRef,
821    ) -> server_error::Result<Output> {
822        let interceptor = self
823            .plugins
824            .get::<PromQueryInterceptorRef<server_error::Error>>();
825
826        self.plugins
827            .get::<PermissionCheckerRef>()
828            .as_ref()
829            .check_permission(query_ctx.current_user(), PermissionReq::PromQuery)
830            .context(AuthSnafu)?;
831
832        let stmt = QueryLanguageParser::parse_promql(query, &query_ctx).with_context(|_| {
833            ParsePromQLSnafu {
834                query: query.clone(),
835            }
836        })?;
837
838        let plan = self
839            .statement_executor
840            .plan(&stmt, query_ctx.clone())
841            .await
842            .map_err(BoxedError::new)
843            .context(ExecuteQuerySnafu)?;
844
845        interceptor.pre_execute(query, Some(&plan), query_ctx.clone())?;
846
847        // Take the EvalStmt from the original QueryStatement and use it to create the CatalogQueryStatement.
848        let query_statement = if let QueryStatement::Promql(eval_stmt, alias) = stmt {
849            CatalogQueryStatement::Promql(eval_stmt, alias)
850        } else {
851            // It should not happen since the query is already parsed successfully.
852            return UnexpectedResultSnafu {
853                reason: "The query should always be promql.".to_string(),
854            }
855            .fail();
856        };
857        let query = query_statement.to_string();
858
859        let slow_query_timer = self
860            .slow_query_options
861            .enable
862            .then(|| self.event_recorder.clone())
863            .flatten()
864            .map(|event_recorder| {
865                SlowQueryTimer::new(
866                    query_statement,
867                    self.slow_query_options.threshold,
868                    self.slow_query_options.sample_ratio,
869                    self.slow_query_options.record_type,
870                    event_recorder,
871                )
872            });
873
874        let ticket = self.process_manager.register_query(
875            query_ctx.current_catalog().to_string(),
876            vec![query_ctx.current_schema()],
877            query,
878            query_ctx.conn_info().to_string(),
879            Some(query_ctx.process_id()),
880            slow_query_timer,
881        );
882
883        let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone());
884
885        let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
886            .await
887            .map_err(|_| servers::error::CancelledSnafu.build())?
888            .map(|output| {
889                let Output { meta, data } = output;
890                let data = match data {
891                    OutputData::Stream(stream) => {
892                        OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
893                    }
894                    other => other,
895                };
896                Output { data, meta }
897            })
898            .map_err(BoxedError::new)
899            .context(ExecuteQuerySnafu)?;
900
901        Ok(interceptor.post_execute(output, query_ctx)?)
902    }
903
904    async fn query_metric_names(
905        &self,
906        matchers: Vec<Matcher>,
907        ctx: &QueryContextRef,
908    ) -> server_error::Result<Vec<String>> {
909        self.handle_query_metric_names(matchers, ctx)
910            .await
911            .map_err(BoxedError::new)
912            .context(ExecuteQuerySnafu)
913    }
914
915    async fn query_label_values(
916        &self,
917        metric: String,
918        label_name: String,
919        matchers: Vec<Matcher>,
920        start: SystemTime,
921        end: SystemTime,
922        ctx: &QueryContextRef,
923    ) -> server_error::Result<Vec<String>> {
924        self.handle_query_label_values(metric, label_name, matchers, start, end, ctx)
925            .await
926            .map_err(BoxedError::new)
927            .context(ExecuteQuerySnafu)
928    }
929
930    fn catalog_manager(&self) -> CatalogManagerRef {
931        self.catalog_manager.clone()
932    }
933}
934
935/// Validate `stmt.database` permission if it's presented.
936macro_rules! validate_db_permission {
937    ($stmt: expr, $query_ctx: expr) => {
938        if let Some(database) = &$stmt.database {
939            validate_catalog_and_schema($query_ctx.current_catalog(), database, $query_ctx)
940                .map_err(BoxedError::new)
941                .context(SqlExecInterceptedSnafu)?;
942        }
943    };
944}
945
946pub fn check_permission(
947    plugins: Plugins,
948    stmt: &Statement,
949    query_ctx: &QueryContextRef,
950) -> Result<()> {
951    let need_validate = plugins
952        .get::<QueryOptions>()
953        .map(|opts| opts.disallow_cross_catalog_query)
954        .unwrap_or_default();
955
956    if !need_validate {
957        return Ok(());
958    }
959
960    match stmt {
961        // Will be checked in execution.
962        // TODO(dennis): add a hook for admin commands.
963        Statement::Admin(_) => {}
964        // These are executed by query engine, and will be checked there.
965        Statement::Query(_)
966        | Statement::Explain(_)
967        | Statement::Tql(_)
968        | Statement::Delete(_)
969        | Statement::DeclareCursor(_)
970        | Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(_)) => {}
971        // database ops won't be checked
972        Statement::CreateDatabase(_)
973        | Statement::ShowDatabases(_)
974        | Statement::DropDatabase(_)
975        | Statement::AlterDatabase(_)
976        | Statement::DropFlow(_)
977        | Statement::Use(_) => {}
978        #[cfg(feature = "enterprise")]
979        Statement::DropTrigger(_) => {}
980        Statement::ShowCreateDatabase(stmt) => {
981            validate_database(&stmt.database_name, query_ctx)?;
982        }
983        Statement::ShowCreateTable(stmt) => {
984            validate_param(&stmt.table_name, query_ctx)?;
985        }
986        Statement::ShowCreateFlow(stmt) => {
987            validate_flow(&stmt.flow_name, query_ctx)?;
988        }
989        #[cfg(feature = "enterprise")]
990        Statement::ShowCreateTrigger(stmt) => {
991            validate_param(&stmt.trigger_name, query_ctx)?;
992        }
993        Statement::ShowCreateView(stmt) => {
994            validate_param(&stmt.view_name, query_ctx)?;
995        }
996        Statement::CreateExternalTable(stmt) => {
997            validate_param(&stmt.name, query_ctx)?;
998        }
999        Statement::CreateFlow(stmt) => {
1000            // TODO: should also validate source table name here?
1001            validate_param(&stmt.sink_table_name, query_ctx)?;
1002        }
1003        #[cfg(feature = "enterprise")]
1004        Statement::CreateTrigger(stmt) => {
1005            validate_param(&stmt.trigger_name, query_ctx)?;
1006        }
1007        Statement::CreateView(stmt) => {
1008            validate_param(&stmt.name, query_ctx)?;
1009        }
1010        Statement::AlterTable(stmt) => {
1011            validate_param(stmt.table_name(), query_ctx)?;
1012        }
1013        #[cfg(feature = "enterprise")]
1014        Statement::AlterTrigger(_) => {}
1015        // set/show variable now only alter/show variable in session
1016        Statement::SetVariables(_) | Statement::ShowVariables(_) => {}
1017        // show charset and show collation won't be checked
1018        Statement::ShowCharset(_) | Statement::ShowCollation(_) => {}
1019
1020        Statement::Comment(comment) => match &comment.object {
1021            CommentObject::Table(table) => validate_param(table, query_ctx)?,
1022            CommentObject::Column { table, .. } => validate_param(table, query_ctx)?,
1023            CommentObject::Flow(flow) => validate_flow(flow, query_ctx)?,
1024        },
1025
1026        Statement::Insert(insert) => {
1027            let name = insert.table_name().context(ParseSqlSnafu)?;
1028            validate_param(name, query_ctx)?;
1029        }
1030        Statement::CreateTable(stmt) => {
1031            validate_param(&stmt.name, query_ctx)?;
1032        }
1033        Statement::CreateTableLike(stmt) => {
1034            validate_param(&stmt.table_name, query_ctx)?;
1035            validate_param(&stmt.source_name, query_ctx)?;
1036        }
1037        Statement::DropTable(drop_stmt) => {
1038            for table_name in drop_stmt.table_names() {
1039                validate_param(table_name, query_ctx)?;
1040            }
1041        }
1042        Statement::DropView(stmt) => {
1043            validate_param(&stmt.view_name, query_ctx)?;
1044        }
1045        Statement::ShowTables(stmt) => {
1046            validate_db_permission!(stmt, query_ctx);
1047        }
1048        Statement::ShowTableStatus(stmt) => {
1049            validate_db_permission!(stmt, query_ctx);
1050        }
1051        Statement::ShowColumns(stmt) => {
1052            validate_db_permission!(stmt, query_ctx);
1053        }
1054        Statement::ShowIndex(stmt) => {
1055            validate_db_permission!(stmt, query_ctx);
1056        }
1057        Statement::ShowRegion(stmt) => {
1058            validate_db_permission!(stmt, query_ctx);
1059        }
1060        Statement::ShowViews(stmt) => {
1061            validate_db_permission!(stmt, query_ctx);
1062        }
1063        Statement::ShowFlows(stmt) => {
1064            validate_db_permission!(stmt, query_ctx);
1065        }
1066        #[cfg(feature = "enterprise")]
1067        Statement::ShowTriggers(_stmt) => {
1068            // The trigger is organized based on the catalog dimension, so there
1069            // is no need to check the permission of the database(schema).
1070        }
1071        Statement::ShowStatus(_stmt) => {}
1072        Statement::ShowSearchPath(_stmt) => {}
1073        Statement::DescribeTable(stmt) => {
1074            validate_param(stmt.name(), query_ctx)?;
1075        }
1076        Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => match stmt {
1077            CopyTable::To(copy_table_to) => validate_param(&copy_table_to.table_name, query_ctx)?,
1078            CopyTable::From(copy_table_from) => {
1079                validate_param(&copy_table_from.table_name, query_ctx)?
1080            }
1081        },
1082        Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
1083            match copy_database {
1084                CopyDatabase::To(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1085                CopyDatabase::From(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1086            }
1087        }
1088        Statement::TruncateTable(stmt) => {
1089            validate_param(stmt.table_name(), query_ctx)?;
1090        }
1091        // cursor operations are always allowed once it's created
1092        Statement::FetchCursor(_) | Statement::CloseCursor(_) => {}
1093        // User can only kill process in their own catalog.
1094        Statement::Kill(_) => {}
1095        // SHOW PROCESSLIST
1096        Statement::ShowProcesslist(_) => {}
1097    }
1098    Ok(())
1099}
1100
1101fn validate_param(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1102    let (catalog, schema, _) = table_idents_to_full_name(name, query_ctx)
1103        .map_err(BoxedError::new)
1104        .context(ExternalSnafu)?;
1105
1106    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1107        .map_err(BoxedError::new)
1108        .context(SqlExecInterceptedSnafu)
1109}
1110
1111fn validate_flow(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1112    let catalog = match &name.0[..] {
1113        [_flow] => query_ctx.current_catalog().to_string(),
1114        [catalog, _flow] => catalog.to_string_unquoted(),
1115        _ => {
1116            return InvalidSqlSnafu {
1117                err_msg: format!(
1118                    "expect flow name to be <catalog>.<flow_name> or <flow_name>, actual: {name}",
1119                ),
1120            }
1121            .fail();
1122        }
1123    };
1124
1125    let schema = query_ctx.current_schema();
1126
1127    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1128        .map_err(BoxedError::new)
1129        .context(SqlExecInterceptedSnafu)
1130}
1131
1132fn validate_database(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1133    let (catalog, schema) = match &name.0[..] {
1134        [schema] => (
1135            query_ctx.current_catalog().to_string(),
1136            schema.to_string_unquoted(),
1137        ),
1138        [catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
1139        _ => InvalidSqlSnafu {
1140            err_msg: format!(
1141                "expect database name to be <catalog>.<schema> or <schema>, actual: {name}",
1142            ),
1143        }
1144        .fail()?,
1145    };
1146
1147    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1148        .map_err(BoxedError::new)
1149        .context(SqlExecInterceptedSnafu)
1150}
1151
1152fn is_readonly_plan(plan: &LogicalPlan) -> bool {
1153    !matches!(plan, LogicalPlan::Dml(_) | LogicalPlan::Ddl(_))
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158    use std::collections::HashMap;
1159    use std::sync::atomic::{AtomicBool, Ordering};
1160    use std::sync::{Arc, Barrier};
1161    use std::thread;
1162    use std::time::{Duration, Instant};
1163
1164    use common_base::Plugins;
1165    use query::query_engine::options::QueryOptions;
1166    use session::context::QueryContext;
1167    use sql::dialect::GreptimeDbDialect;
1168    use strfmt::Format;
1169
1170    use super::*;
1171
1172    #[test]
1173    fn test_fast_legacy_check_deadlock_prevention() {
1174        // Create a DashMap to simulate the cache
1175        let cache = DashMap::new();
1176
1177        // Pre-populate cache with some entries
1178        cache.insert("metric1".to_string(), true); // legacy mode
1179        cache.insert("metric2".to_string(), false); // prom mode
1180        cache.insert("metric3".to_string(), true); // legacy mode
1181
1182        // Test case 1: Normal operation with cache hits
1183        let metric1 = "metric1".to_string();
1184        let metric4 = "metric4".to_string();
1185        let names1 = vec![&metric1, &metric4];
1186        let result = fast_legacy_check(&cache, &names1);
1187        assert!(result.is_ok());
1188        assert_eq!(result.unwrap(), Some(true)); // should return legacy mode
1189
1190        // Verify that metric4 was added to cache
1191        assert!(cache.contains_key("metric4"));
1192        assert!(*cache.get("metric4").unwrap().value());
1193
1194        // Test case 2: No cache hits
1195        let metric5 = "metric5".to_string();
1196        let metric6 = "metric6".to_string();
1197        let names2 = vec![&metric5, &metric6];
1198        let result = fast_legacy_check(&cache, &names2);
1199        assert!(result.is_ok());
1200        assert_eq!(result.unwrap(), None); // should return None as no cache hits
1201
1202        // Test case 3: Incompatible modes should return error
1203        let cache_incompatible = DashMap::new();
1204        cache_incompatible.insert("metric1".to_string(), true); // legacy
1205        cache_incompatible.insert("metric2".to_string(), false); // prom
1206        let metric1_test = "metric1".to_string();
1207        let metric2_test = "metric2".to_string();
1208        let names3 = vec![&metric1_test, &metric2_test];
1209        let result = fast_legacy_check(&cache_incompatible, &names3);
1210        assert!(result.is_err()); // should error due to incompatible modes
1211
1212        // Test case 4: Intensive concurrent access to test deadlock prevention
1213        // This test specifically targets the scenario where multiple threads
1214        // access the same cache entries simultaneously
1215        let cache_concurrent = Arc::new(DashMap::new());
1216        cache_concurrent.insert("shared_metric".to_string(), true);
1217
1218        let num_threads = 8;
1219        let operations_per_thread = 100;
1220        let barrier = Arc::new(Barrier::new(num_threads));
1221        let success_flag = Arc::new(AtomicBool::new(true));
1222
1223        let handles: Vec<_> = (0..num_threads)
1224            .map(|thread_id| {
1225                let cache_clone = Arc::clone(&cache_concurrent);
1226                let barrier_clone = Arc::clone(&barrier);
1227                let success_flag_clone = Arc::clone(&success_flag);
1228
1229                thread::spawn(move || {
1230                    // Wait for all threads to be ready
1231                    barrier_clone.wait();
1232
1233                    let start_time = Instant::now();
1234                    for i in 0..operations_per_thread {
1235                        // Each operation references existing cache entry and adds new ones
1236                        let shared_metric = "shared_metric".to_string();
1237                        let new_metric = format!("thread_{}_metric_{}", thread_id, i);
1238                        let names = vec![&shared_metric, &new_metric];
1239
1240                        match fast_legacy_check(&cache_clone, &names) {
1241                            Ok(_) => {}
1242                            Err(_) => {
1243                                success_flag_clone.store(false, Ordering::Relaxed);
1244                                return;
1245                            }
1246                        }
1247
1248                        // If the test takes too long, it likely means deadlock
1249                        if start_time.elapsed() > Duration::from_secs(10) {
1250                            success_flag_clone.store(false, Ordering::Relaxed);
1251                            return;
1252                        }
1253                    }
1254                })
1255            })
1256            .collect();
1257
1258        // Join all threads with timeout
1259        let start_time = Instant::now();
1260        for (i, handle) in handles.into_iter().enumerate() {
1261            let join_result = handle.join();
1262
1263            // Check if we're taking too long (potential deadlock)
1264            if start_time.elapsed() > Duration::from_secs(30) {
1265                panic!("Test timed out - possible deadlock detected!");
1266            }
1267
1268            if join_result.is_err() {
1269                panic!("Thread {} panicked during execution", i);
1270            }
1271        }
1272
1273        // Verify all operations completed successfully
1274        assert!(
1275            success_flag.load(Ordering::Relaxed),
1276            "Some operations failed"
1277        );
1278
1279        // Verify that many new entries were added (proving operations completed)
1280        let final_count = cache_concurrent.len();
1281        assert!(
1282            final_count > 1 + num_threads * operations_per_thread / 2,
1283            "Expected more cache entries, got {}",
1284            final_count
1285        );
1286    }
1287
1288    #[test]
1289    fn test_exec_validation() {
1290        let query_ctx = QueryContext::arc();
1291        let plugins: Plugins = Plugins::new();
1292        plugins.insert(QueryOptions {
1293            disallow_cross_catalog_query: true,
1294        });
1295
1296        let sql = r#"
1297        SELECT * FROM demo;
1298        EXPLAIN SELECT * FROM demo;
1299        CREATE DATABASE test_database;
1300        SHOW DATABASES;
1301        "#;
1302        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1303        assert_eq!(stmts.len(), 4);
1304        for stmt in stmts {
1305            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
1306            re.unwrap();
1307        }
1308
1309        let sql = r#"
1310        SHOW CREATE TABLE demo;
1311        ALTER TABLE demo ADD COLUMN new_col INT;
1312        "#;
1313        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1314        assert_eq!(stmts.len(), 2);
1315        for stmt in stmts {
1316            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
1317            re.unwrap();
1318        }
1319
1320        fn replace_test(template_sql: &str, plugins: Plugins, query_ctx: &QueryContextRef) {
1321            // test right
1322            let right = vec![("", ""), ("", "public."), ("greptime.", "public.")];
1323            for (catalog, schema) in right {
1324                let sql = do_fmt(template_sql, catalog, schema);
1325                do_test(&sql, plugins.clone(), query_ctx, true);
1326            }
1327
1328            let wrong = vec![
1329                ("wrongcatalog.", "public."),
1330                ("wrongcatalog.", "wrongschema."),
1331            ];
1332            for (catalog, schema) in wrong {
1333                let sql = do_fmt(template_sql, catalog, schema);
1334                do_test(&sql, plugins.clone(), query_ctx, false);
1335            }
1336        }
1337
1338        fn do_fmt(template: &str, catalog: &str, schema: &str) -> String {
1339            let vars = HashMap::from([
1340                ("catalog".to_string(), catalog),
1341                ("schema".to_string(), schema),
1342            ]);
1343            template.format(&vars).unwrap()
1344        }
1345
1346        fn do_test(sql: &str, plugins: Plugins, query_ctx: &QueryContextRef, is_ok: bool) {
1347            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1348            let re = check_permission(plugins, stmt, query_ctx);
1349            if is_ok {
1350                re.unwrap();
1351            } else {
1352                assert!(re.is_err());
1353            }
1354        }
1355
1356        // test insert
1357        let sql = "INSERT INTO {catalog}{schema}monitor(host) VALUES ('host1');";
1358        replace_test(sql, plugins.clone(), &query_ctx);
1359
1360        // test create table
1361        let sql = r#"CREATE TABLE {catalog}{schema}demo(
1362                            host STRING,
1363                            ts TIMESTAMP,
1364                            TIME INDEX (ts),
1365                            PRIMARY KEY(host)
1366                        ) engine=mito;"#;
1367        replace_test(sql, plugins.clone(), &query_ctx);
1368
1369        // test drop table
1370        let sql = "DROP TABLE {catalog}{schema}demo;";
1371        replace_test(sql, plugins.clone(), &query_ctx);
1372
1373        // test show tables
1374        let sql = "SHOW TABLES FROM public";
1375        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1376        check_permission(plugins.clone(), &stmt[0], &query_ctx).unwrap();
1377
1378        let sql = "SHOW TABLES FROM private";
1379        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
1380        let re = check_permission(plugins.clone(), &stmt[0], &query_ctx);
1381        assert!(re.is_ok());
1382
1383        // test describe table
1384        let sql = "DESC TABLE {catalog}{schema}demo;";
1385        replace_test(sql, plugins.clone(), &query_ctx);
1386
1387        let comment_flow_cases = [
1388            ("COMMENT ON FLOW my_flow IS 'comment';", true),
1389            ("COMMENT ON FLOW greptime.my_flow IS 'comment';", true),
1390            ("COMMENT ON FLOW wrongcatalog.my_flow IS 'comment';", false),
1391        ];
1392        for (sql, is_ok) in comment_flow_cases {
1393            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1394            let result = check_permission(plugins.clone(), stmt, &query_ctx);
1395            assert_eq!(result.is_ok(), is_ok);
1396        }
1397
1398        let show_flow_cases = [
1399            ("SHOW CREATE FLOW my_flow;", true),
1400            ("SHOW CREATE FLOW greptime.my_flow;", true),
1401            ("SHOW CREATE FLOW wrongcatalog.my_flow;", false),
1402        ];
1403        for (sql, is_ok) in show_flow_cases {
1404            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
1405            let result = check_permission(plugins.clone(), stmt, &query_ctx);
1406            assert_eq!(result.is_ok(), is_ok);
1407        }
1408    }
1409}