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 entity_graph;
18mod grpc;
19mod influxdb;
20mod jaeger;
21mod log_handler;
22mod logs;
23mod opentsdb;
24mod otlp;
25pub mod prom_store;
26mod promql;
27mod region_query;
28
29use std::collections::HashSet;
30use std::pin::Pin;
31use std::sync::atomic::AtomicBool;
32use std::sync::{Arc, atomic};
33use std::time::{Duration, SystemTime};
34
35use async_stream::stream;
36use async_trait::async_trait;
37use auth::{
38    PROMQL_QUERY, PermissionChecker, PermissionCheckerRef, PermissionReq, PermissionTableTarget,
39    PermissionTableTargets,
40};
41use catalog::CatalogManagerRef;
42use catalog::process_manager::{
43    ProcessManagerRef, QueryStatement as CatalogQueryStatement, SlowQueryRecorder, SlowQueryTimer,
44};
45use client::OutputData;
46use common_base::Plugins;
47use common_base::cancellation::CancellableFuture;
48use common_error::ext::{BoxedError, ErrorExt};
49use common_event_recorder::EventRecorderRef;
50use common_meta::cache::TableFlownodeSetCacheRef;
51use common_meta::cache_invalidator::CacheInvalidatorRef;
52use common_meta::key::TableMetadataManagerRef;
53use common_meta::key::table_name::TableNameKey;
54use common_meta::node_manager::NodeManagerRef;
55use common_meta::procedure_executor::ProcedureExecutorRef;
56use common_query::Output;
57use common_recordbatch::RecordBatchStreamWrapper;
58use common_recordbatch::error::StreamTimeoutSnafu;
59use common_telemetry::logging::SlowQueryOptions;
60use common_telemetry::{debug, error, tracing};
61use dashmap::DashMap;
62use datafusion::physical_plan::ExecutionPlan;
63use datafusion_expr::LogicalPlan;
64use futures::{Stream, StreamExt, future};
65use lazy_static::lazy_static;
66use operator::delete::DeleterRef;
67use operator::insert::InserterRef;
68use operator::statement::{StatementExecutor, StatementExecutorRef};
69use partition::manager::PartitionRuleManagerRef;
70use pipeline::pipeline_operator::PipelineOperator;
71use prometheus::HistogramTimer;
72use promql_parser::label::Matcher;
73use query::QueryEngineRef;
74use query::metrics::OnDone;
75use query::parser::{PromQuery, QueryStatement};
76use query::query_engine::DescribeResult;
77use query::query_engine::options::{QueryOptions, validate_catalog_and_schema};
78use servers::error::{
79    self as server_error, AuthSnafu, CommonMetaSnafu, ExecuteQuerySnafu,
80    OtlpMetricModeIncompatibleSnafu, UnexpectedResultSnafu,
81};
82use servers::interceptor::{
83    PromQueryInterceptor, PromQueryInterceptorRef, SqlQueryInterceptor, SqlQueryInterceptorRef,
84};
85use servers::otlp::metrics::legacy_normalize_otlp_name;
86use servers::prometheus_handler::{
87    ParsedPromQuery, PrometheusHandler, resolve_schema_from_matchers,
88};
89use servers::query_handler::sql::SqlQueryHandler;
90use session::context::{Channel, QueryContextRef};
91use session::table_name::table_idents_to_full_name;
92use snafu::prelude::*;
93use sql::ast::ObjectNamePartExt;
94use sql::dialect::Dialect;
95use sql::parser::{ParseOptions, ParserContext};
96use sql::statements::comment::CommentObject;
97use sql::statements::copy::{CopyDatabase, CopyTable};
98use sql::statements::statement::Statement;
99use sql::statements::tql::Tql;
100use sql::util::{extract_tables_from_prom_expr_checked, extract_tables_from_statement_checked};
101use sqlparser::ast::{AnalyzeFormat, ObjectName};
102use table::requests::{OTLP_METRIC_COMPAT_KEY, OTLP_METRIC_COMPAT_PROM};
103use tracing::Span;
104
105use crate::error::{
106    self, CollectRecordbatchSnafu, Error, ExecLogicalPlanSnafu, ExecutePromqlSnafu, ExternalSnafu,
107    InvalidSqlSnafu, ParseSqlSnafu, PermissionSnafu, PlanStatementSnafu, Result,
108    SqlExecInterceptedSnafu, StatementTimeoutSnafu, TableOperationSnafu,
109};
110use crate::service_config::InfluxdbMergeMode;
111use crate::stream_wrapper::CancellableStreamWrapper;
112
113lazy_static! {
114    static ref OTLP_LEGACY_DEFAULT_VALUE: String = "legacy".to_string();
115}
116
117/// The frontend instance contains necessary components, and implements many
118/// traits, like [`servers::query_handler::grpc::GrpcQueryHandler`],
119/// [`servers::query_handler::sql::SqlQueryHandler`], etc.
120#[derive(Clone)]
121pub struct Instance {
122    frontend_peer_addr: String,
123    catalog_manager: CatalogManagerRef,
124    pipeline_operator: Arc<PipelineOperator>,
125    statement_executor: Arc<StatementExecutor>,
126    query_engine: QueryEngineRef,
127    plugins: Plugins,
128    inserter: InserterRef,
129    deleter: DeleterRef,
130    table_metadata_manager: TableMetadataManagerRef,
131    event_recorder: EventRecorderRef,
132    slow_query_recorder: EventRecorderRef,
133    process_manager: ProcessManagerRef,
134    slow_query_options: SlowQueryOptions,
135    influxdb_default_merge_mode: InfluxdbMergeMode,
136    trace_ingest_chunk_size: usize,
137    suspend: Arc<AtomicBool>,
138
139    // cache for otlp metrics
140    // first layer key: db-string
141    // key: direct input metric name
142    // value: if runs in legacy mode
143    otlp_metrics_table_legacy_cache: DashMap<String, DashMap<String, bool>>,
144}
145
146impl Instance {
147    pub fn frontend_peer_addr(&self) -> &str {
148        &self.frontend_peer_addr
149    }
150
151    pub fn catalog_manager(&self) -> &CatalogManagerRef {
152        &self.catalog_manager
153    }
154
155    pub fn query_engine(&self) -> &QueryEngineRef {
156        &self.query_engine
157    }
158
159    pub fn plugins(&self) -> &Plugins {
160        &self.plugins
161    }
162
163    fn check_permission(
164        &self,
165        ctx: &QueryContextRef,
166        req: PermissionReq<'_>,
167    ) -> server_error::Result<()> {
168        self.plugins
169            .get::<PermissionCheckerRef>()
170            .as_ref()
171            .check_permission(ctx.current_user(), req)
172            .context(AuthSnafu)?;
173        Ok(())
174    }
175
176    pub fn statement_executor(&self) -> &StatementExecutorRef {
177        &self.statement_executor
178    }
179
180    pub fn table_metadata_manager(&self) -> &TableMetadataManagerRef {
181        &self.table_metadata_manager
182    }
183
184    pub fn inserter(&self) -> &InserterRef {
185        &self.inserter
186    }
187
188    pub fn process_manager(&self) -> &ProcessManagerRef {
189        &self.process_manager
190    }
191
192    /// Returns the event recorder configured for this frontend instance.
193    pub fn event_recorder(&self) -> EventRecorderRef {
194        self.event_recorder.clone()
195    }
196
197    pub fn node_manager(&self) -> &NodeManagerRef {
198        self.inserter.node_manager()
199    }
200
201    pub fn partition_manager(&self) -> &PartitionRuleManagerRef {
202        self.inserter.partition_manager()
203    }
204
205    pub fn table_flownode_set_cache(&self) -> &TableFlownodeSetCacheRef {
206        self.inserter.table_flownode_set_cache()
207    }
208
209    pub fn cache_invalidator(&self) -> &CacheInvalidatorRef {
210        self.statement_executor.cache_invalidator()
211    }
212
213    pub fn procedure_executor(&self) -> &ProcedureExecutorRef {
214        self.statement_executor.procedure_executor()
215    }
216
217    pub fn suspend_state(&self) -> Arc<AtomicBool> {
218        self.suspend.clone()
219    }
220
221    pub(crate) fn is_suspended(&self) -> bool {
222        self.suspend.load(atomic::Ordering::Relaxed)
223    }
224}
225
226fn parse_stmt(sql: &str, dialect: &(dyn Dialect + Send + Sync)) -> Result<Vec<Statement>> {
227    ParserContext::create_with_dialect(sql, dialect, ParseOptions::default()).context(ParseSqlSnafu)
228}
229
230fn is_explain_analyze_verbose(stmt: &Statement) -> bool {
231    matches!(stmt, Statement::Explain(explain) if explain.analyze && explain.verbose)
232}
233
234fn validate_analyze_stream_statement(stmt: &mut Statement) -> Result<()> {
235    let Statement::Explain(explain) = stmt else {
236        return InvalidSqlSnafu {
237            err_msg: "only EXPLAIN ANALYZE VERBOSE statement is supported",
238        }
239        .fail();
240    };
241    ensure!(
242        explain.analyze && explain.verbose,
243        InvalidSqlSnafu {
244            err_msg: "statement must be EXPLAIN ANALYZE VERBOSE"
245        }
246    );
247    match explain.format {
248        None | Some(AnalyzeFormat::JSON) => {
249            // Keep explicit FORMAT JSON accepted, but pass JSON through
250            // QueryContext.explain_format instead of the statement to avoid the
251            // planner's current `EXPLAIN VERBOSE with FORMAT` limitation.
252            explain.format = None;
253            Ok(())
254        }
255        Some(_) => InvalidSqlSnafu {
256            err_msg: "only FORMAT JSON is supported for analyze stream",
257        }
258        .fail(),
259    }
260}
261
262impl Instance {
263    fn statement_slow_query_timer(
264        &self,
265        stmt: &Statement,
266        schema_name: String,
267    ) -> Option<SlowQueryTimer> {
268        if !stmt.is_readonly() || !self.slow_query_options.enable {
269            return None;
270        }
271
272        Some(SlowQueryTimer::new(
273            CatalogQueryStatement::Sql(stmt.clone()),
274            schema_name,
275            self.slow_query_options.threshold,
276            self.slow_query_options.sample_ratio,
277            self.slow_query_options.record_type,
278            self.slow_query_recorder.clone(),
279        ))
280    }
281
282    async fn query_statement(&self, stmt: Statement, query_ctx: QueryContextRef) -> Result<Output> {
283        check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
284
285        let query_interceptor = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
286        let query_interceptor = query_interceptor.as_ref();
287
288        if should_track_statement_process(&stmt) {
289            let catalog_name = query_ctx.current_catalog().to_string();
290            let schema_name = query_ctx.current_schema();
291            let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone());
292            let timeout_recorder = is_explain_analyze_verbose(&stmt)
293                .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
294                .flatten();
295
296            let ticket = self.process_manager.register_query(
297                catalog_name,
298                vec![schema_name],
299                stmt.to_string(),
300                query_ctx.conn_info().to_string(),
301                Some(query_ctx.process_id()),
302                slow_query_timer,
303            );
304
305            let query_fut = self.exec_statement_with_timeout(
306                stmt,
307                query_ctx,
308                query_interceptor,
309                timeout_recorder,
310            );
311
312            CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
313                .await
314                .map_err(|_| error::CancelledSnafu.build())?
315                .map(|output| {
316                    let Output { meta, data } = output;
317
318                    let data = match data {
319                        OutputData::Stream(stream) => OutputData::Stream(Box::pin(
320                            CancellableStreamWrapper::new(stream, ticket),
321                        )),
322                        other => other,
323                    };
324                    Output { data, meta }
325                })
326        } else {
327            self.exec_statement_with_timeout(stmt, query_ctx, query_interceptor, None)
328                .await
329        }
330    }
331
332    async fn exec_statement_with_timeout(
333        &self,
334        stmt: Statement,
335        query_ctx: QueryContextRef,
336        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
337        timeout_recorder: Option<SlowQueryRecorder>,
338    ) -> Result<Output> {
339        let timeout = derive_timeout(&stmt, &query_ctx);
340        match timeout {
341            Some(timeout) => {
342                let start = tokio::time::Instant::now();
343                let output = tokio::time::timeout(
344                    timeout,
345                    self.exec_statement(stmt, query_ctx, query_interceptor),
346                )
347                .await
348                .map_err(|_| StatementTimeoutSnafu.build())??;
349                let output = map_query_output(output)?;
350                // compute remaining timeout
351                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
352                attach_timeout(output, remaining_timeout, timeout_recorder)
353            }
354            None => self
355                .exec_statement(stmt, query_ctx, query_interceptor)
356                .await
357                .and_then(map_query_output),
358        }
359    }
360
361    async fn exec_statement(
362        &self,
363        stmt: Statement,
364        query_ctx: QueryContextRef,
365        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
366    ) -> Result<Output> {
367        match stmt {
368            Statement::Query(_) | Statement::Explain(_) | Statement::Delete(_) => {
369                // TODO: remove this when format is supported in datafusion
370                if let Statement::Explain(explain) = &stmt
371                    && let Some(format) = explain.format()
372                {
373                    query_ctx.set_explain_format(format.to_string());
374                }
375
376                self.plan_and_exec_sql(stmt, &query_ctx, query_interceptor)
377                    .await
378            }
379            Statement::Tql(tql) => {
380                self.plan_and_exec_tql(&query_ctx, query_interceptor, tql)
381                    .await
382            }
383            _ => {
384                query_interceptor.pre_execute(Some(&stmt), None, query_ctx.clone())?;
385                self.statement_executor
386                    .execute_sql(stmt, query_ctx)
387                    .await
388                    .context(TableOperationSnafu)
389            }
390        }
391    }
392
393    async fn plan_and_exec_sql(
394        &self,
395        stmt: Statement,
396        query_ctx: &QueryContextRef,
397        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
398    ) -> Result<Output> {
399        let stmt = QueryStatement::Sql(stmt);
400        let plan = self
401            .statement_executor
402            .plan(&stmt, query_ctx.clone())
403            .await?;
404        let QueryStatement::Sql(stmt) = stmt else {
405            unreachable!()
406        };
407        query_interceptor.pre_execute(Some(&stmt), Some(&plan), query_ctx.clone())?;
408
409        self.statement_executor
410            .exec_plan(plan, query_ctx.clone())
411            .await
412            .context(TableOperationSnafu)
413    }
414
415    async fn plan_and_exec_tql(
416        &self,
417        query_ctx: &QueryContextRef,
418        query_interceptor: Option<&SqlQueryInterceptorRef<Error>>,
419        tql: Tql,
420    ) -> Result<Output> {
421        let plan = self
422            .statement_executor
423            .plan_tql(tql.clone(), query_ctx)
424            .await?;
425        query_interceptor.pre_execute(
426            Some(&Statement::Tql(tql)),
427            Some(&plan),
428            query_ctx.clone(),
429        )?;
430        self.statement_executor
431            .exec_plan(plan, query_ctx.clone())
432            .await
433            .context(TableOperationSnafu)
434    }
435
436    async fn check_otlp_legacy(
437        &self,
438        names: &[String],
439        ctx: &QueryContextRef,
440    ) -> server_error::Result<bool> {
441        let db_string = ctx.get_db_string();
442        // fast cache check
443        let cache = self
444            .otlp_metrics_table_legacy_cache
445            .entry(db_string.clone())
446            .or_default();
447        if let Some(flag) = fast_legacy_check(&cache, names)? {
448            return Ok(flag);
449        }
450        // release cache reference to avoid lock contention
451        drop(cache);
452
453        let catalog = ctx.current_catalog();
454        let schema = ctx.current_schema();
455
456        // query legacy table names
457        let normalized_names = names
458            .iter()
459            .map(|n| legacy_normalize_otlp_name(n))
460            .collect::<Vec<_>>();
461        let table_names = normalized_names
462            .iter()
463            .map(|n| TableNameKey::new(catalog, &schema, n))
464            .collect::<Vec<_>>();
465        let table_values = self
466            .table_metadata_manager()
467            .table_name_manager()
468            .batch_get(table_names)
469            .await
470            .context(CommonMetaSnafu)?;
471        let table_ids = table_values
472            .into_iter()
473            .filter_map(|v| v.map(|vi| vi.table_id()))
474            .collect::<Vec<_>>();
475
476        // means no existing table is found, use new mode
477        if table_ids.is_empty() {
478            return Ok(false);
479        }
480
481        // has existing table, check table options
482        let table_infos = self
483            .table_metadata_manager()
484            .table_info_manager()
485            .batch_get(&table_ids)
486            .await
487            .context(CommonMetaSnafu)?;
488        let options = table_infos
489            .values()
490            .map(|info| {
491                info.table_info
492                    .meta
493                    .options
494                    .extra_options
495                    .get(OTLP_METRIC_COMPAT_KEY)
496                    .unwrap_or(&OTLP_LEGACY_DEFAULT_VALUE)
497            })
498            .collect::<Vec<_>>();
499        if !options.is_empty() {
500            // check value consistency
501            let has_prom = options.iter().any(|opt| *opt == OTLP_METRIC_COMPAT_PROM);
502            let has_legacy = options
503                .iter()
504                .any(|opt| *opt == OTLP_LEGACY_DEFAULT_VALUE.as_str());
505            ensure!(!(has_prom && has_legacy), OtlpMetricModeIncompatibleSnafu);
506            Ok(has_legacy)
507        } else {
508            // no table info, use new mode
509            Ok(false)
510        }
511    }
512
513    fn cache_otlp_legacy(
514        &self,
515        names: &[String],
516        ctx: &QueryContextRef,
517        is_legacy: bool,
518    ) -> server_error::Result<()> {
519        let cache = self
520            .otlp_metrics_table_legacy_cache
521            .entry(ctx.get_db_string())
522            .or_default();
523        cache_legacy_mode(&cache, names, is_legacy)
524    }
525}
526
527fn fast_legacy_check(
528    cache: &DashMap<String, bool>,
529    names: &[String],
530) -> server_error::Result<Option<bool>> {
531    let hit_cache = names
532        .iter()
533        .filter_map(|name| cache.get(name))
534        .collect::<Vec<_>>();
535    if !hit_cache.is_empty() {
536        let hit_legacy = hit_cache.iter().any(|en| *en.value());
537        let hit_prom = hit_cache.iter().any(|en| !*en.value());
538
539        // hit but have true and false, means both legacy and new mode are used
540        // we cannot handle this case, so return error
541        // add doc links in err msg later
542        ensure!(!(hit_legacy && hit_prom), OtlpMetricModeIncompatibleSnafu);
543
544        Ok(Some(hit_legacy))
545    } else {
546        Ok(None)
547    }
548}
549
550fn cache_legacy_mode(
551    cache: &DashMap<String, bool>,
552    names: &[String],
553    is_legacy: bool,
554) -> server_error::Result<()> {
555    for name in names {
556        let cached = cache.entry(name.clone()).or_insert(is_legacy);
557        ensure!(*cached == is_legacy, OtlpMetricModeIncompatibleSnafu);
558    }
559    Ok(())
560}
561
562/// If the relevant variables are set, the timeout is enforced for all PostgreSQL statements.
563/// For MySQL, it applies only to read-only statements.
564fn derive_timeout(stmt: &Statement, query_ctx: &QueryContextRef) -> Option<Duration> {
565    let query_timeout = query_ctx.query_timeout()?;
566    if query_timeout.is_zero() {
567        return None;
568    }
569    match query_ctx.channel() {
570        Channel::Mysql if stmt.is_readonly() => Some(query_timeout),
571        Channel::Postgres => Some(query_timeout),
572        _ => None,
573    }
574}
575
576/// Derives timeout for plan execution.
577fn derive_timeout_for_plan(plan: &LogicalPlan, query_ctx: &QueryContextRef) -> Option<Duration> {
578    let query_timeout = query_ctx.query_timeout()?;
579    if query_timeout.is_zero() {
580        return None;
581    }
582    match query_ctx.channel() {
583        Channel::Mysql if is_readonly_plan(plan) => Some(query_timeout),
584        Channel::Postgres => Some(query_timeout),
585        _ => None,
586    }
587}
588
589fn record_explain_analyze_timeout(
590    recorder: Option<&SlowQueryRecorder>,
591    plan: Option<&Arc<dyn ExecutionPlan>>,
592) {
593    let Some(recorder) = recorder else {
594        return;
595    };
596    let metrics = plan
597        .and_then(|plan| query::analyze_plan_metrics_to_json_value(plan, true).ok())
598        .unwrap_or_else(|| serde_json::json!([]));
599    recorder.force_record_with_payload(serde_json::json!({
600        "timed_out": true,
601        "metrics": metrics,
602    }));
603}
604
605fn attach_timeout(
606    output: Output,
607    mut timeout: Duration,
608    timeout_recorder: Option<SlowQueryRecorder>,
609) -> Result<Output> {
610    if timeout.is_zero() {
611        return StatementTimeoutSnafu.fail();
612    }
613
614    let plan = timeout_recorder
615        .as_ref()
616        .and_then(|_| output.meta.plan.clone());
617    let output = match output.data {
618        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
619        OutputData::Stream(mut stream) => {
620            let schema = stream.schema();
621            let s = Box::pin(stream! {
622                let mut start = tokio::time::Instant::now();
623                while let Some(item) = tokio::time::timeout(timeout, stream.next()).await.map_err(|_| {
624                    record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
625                    StreamTimeoutSnafu.build()
626                })? {
627                    yield item;
628
629                    let now = tokio::time::Instant::now();
630                    timeout = timeout.checked_sub(now - start).unwrap_or(Duration::ZERO);
631                    start = now;
632                    // tokio::time::timeout may not return an error immediately when timeout is 0.
633                    if timeout.is_zero() {
634                        record_explain_analyze_timeout(timeout_recorder.as_ref(), plan.as_ref());
635                        StreamTimeoutSnafu.fail()?;
636                    }
637                }
638            }) as Pin<Box<dyn Stream<Item = _> + Send>>;
639            let stream = RecordBatchStreamWrapper {
640                schema,
641                stream: s,
642                output_ordering: None,
643                metrics: Default::default(),
644                span: Span::current(),
645            };
646            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
647        }
648    };
649
650    Ok(output)
651}
652
653impl Instance {
654    async fn check_sql_permission(
655        &self,
656        stmt: &Statement,
657        query_ctx: &QueryContextRef,
658    ) -> Result<()> {
659        self.plugins
660            .get::<PermissionCheckerRef>()
661            .as_ref()
662            .check_permission_with_context(
663                query_ctx.current_user(),
664                PermissionReq::SqlStatement(stmt),
665                Some(&query_ctx.current_schema()),
666            )
667            .context(PermissionSnafu)?;
668
669        let targets = match extract_tables_from_statement_checked(stmt) {
670            Some(tables) => PermissionTableTargets::resolved(
671                tables
672                    .map(|name| {
673                        table_idents_to_full_name(&name, query_ctx).map(
674                            |(catalog, schema, table)| {
675                                PermissionTableTarget::new(catalog, schema, table)
676                            },
677                        )
678                    })
679                    .collect::<std::result::Result<Vec<_>, _>>()
680                    .map_err(BoxedError::new)
681                    .context(ExternalSnafu)?,
682            ),
683            None => PermissionTableTargets::Unresolved,
684        };
685        let targets = self
686            .resolve_query_permission_targets(targets, query_ctx)
687            .await
688            .map_err(BoxedError::new)
689            .context(ExternalSnafu)?;
690        self.check_table_permission(query_ctx, PermissionReq::SqlStatement(stmt), targets)
691            .context(PermissionSnafu)?;
692        Ok(())
693    }
694
695    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_analyze_stream_query")]
696    async fn do_analyze_stream_query_inner(
697        &self,
698        query: &str,
699        query_ctx: QueryContextRef,
700    ) -> Result<Output> {
701        ensure!(!self.is_suspended(), error::SuspendedSnafu);
702
703        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
704        let query_interceptor = query_interceptor_opt.as_ref();
705        let query = query_interceptor.pre_parsing(query, query_ctx.clone())?;
706        let mut stmts = parse_stmt(query.as_ref(), query_ctx.sql_dialect())
707            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))?;
708
709        ensure!(
710            stmts.len() == 1,
711            InvalidSqlSnafu {
712                err_msg: "only single EXPLAIN ANALYZE VERBOSE statement is supported"
713            }
714        );
715        let mut stmt = stmts.remove(0);
716        validate_analyze_stream_statement(&mut stmt)?;
717        query_ctx.set_explain_format(AnalyzeFormat::JSON.to_string());
718
719        self.check_sql_permission(&stmt, &query_ctx).await?;
720        check_permission(self.plugins.clone(), &stmt, &query_ctx)?;
721        let catalog_name = query_ctx.current_catalog().to_string();
722        let schema_name = query_ctx.current_schema();
723        let slow_query_timer = self.statement_slow_query_timer(&stmt, schema_name.clone());
724        let ticket = self.process_manager.register_query(
725            catalog_name,
726            vec![schema_name],
727            stmt.to_string(),
728            query_ctx.conn_info().to_string(),
729            Some(query_ctx.process_id()),
730            slow_query_timer,
731        );
732        let query_fut =
733            self.exec_statement_with_timeout(stmt, query_ctx.clone(), query_interceptor, None);
734        let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
735            .await
736            .map_err(|_| error::CancelledSnafu.build())??;
737        let Output { meta, data } = output;
738        let data = match data {
739            OutputData::Stream(stream) => OutputData::Stream(Box::pin(
740                CancellableStreamWrapper::new_cancel_on_drop(stream, ticket),
741            )),
742            other => other,
743        };
744        query_interceptor.post_execute(Output { data, meta }, query_ctx)
745    }
746
747    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_query")]
748    async fn do_query_inner(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
749        if self.is_suspended() {
750            return vec![error::SuspendedSnafu {}.fail()];
751        }
752
753        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
754        let query_interceptor = query_interceptor_opt.as_ref();
755        let query = match query_interceptor.pre_parsing(query, query_ctx.clone()) {
756            Ok(q) => q,
757            Err(e) => return vec![Err(e)],
758        };
759
760        match parse_stmt(query.as_ref(), query_ctx.sql_dialect())
761            .and_then(|stmts| query_interceptor.post_parsing(stmts, query_ctx.clone()))
762        {
763            Ok(stmts) => {
764                if stmts.is_empty() {
765                    return vec![
766                        InvalidSqlSnafu {
767                            err_msg: "empty statements",
768                        }
769                        .fail(),
770                    ];
771                }
772
773                let mut results = Vec::with_capacity(stmts.len());
774                for stmt in stmts {
775                    if let Err(e) = self.check_sql_permission(&stmt, &query_ctx).await {
776                        results.push(Err(e));
777                        break;
778                    }
779
780                    match self.query_statement(stmt.clone(), query_ctx.clone()).await {
781                        Ok(output) => {
782                            let output_result =
783                                query_interceptor.post_execute(output, query_ctx.clone());
784                            results.push(output_result);
785                        }
786                        Err(e) => {
787                            if e.status_code().should_log_error() {
788                                error!(e; "Failed to execute query: {stmt}");
789                            } else {
790                                debug!("Failed to execute query: {stmt}, {e}");
791                            }
792                            results.push(Err(e));
793                            break;
794                        }
795                    }
796                }
797                results
798            }
799            Err(e) => {
800                vec![Err(e)]
801            }
802        }
803    }
804
805    async fn exec_plan(&self, plan: LogicalPlan, query_ctx: QueryContextRef) -> Result<Output> {
806        self.query_engine
807            .execute(plan, query_ctx)
808            .await
809            .context(ExecLogicalPlanSnafu)
810    }
811
812    async fn exec_plan_with_timeout(
813        &self,
814        plan: LogicalPlan,
815        query_ctx: QueryContextRef,
816        timeout_recorder: Option<SlowQueryRecorder>,
817    ) -> Result<Output> {
818        let timeout = derive_timeout_for_plan(&plan, &query_ctx);
819        match timeout {
820            Some(timeout) => {
821                let start = tokio::time::Instant::now();
822                let output = tokio::time::timeout(timeout, self.exec_plan(plan, query_ctx))
823                    .await
824                    .map_err(|_| StatementTimeoutSnafu.build())??;
825                let output = map_query_output(output)?;
826                let remaining_timeout = timeout.checked_sub(start.elapsed()).unwrap_or_default();
827                attach_timeout(output, remaining_timeout, timeout_recorder)
828            }
829            None => self
830                .exec_plan(plan, query_ctx)
831                .await
832                .and_then(map_query_output),
833        }
834    }
835
836    async fn do_exec_plan_inner(
837        &self,
838        plan: LogicalPlan,
839        stmt: Option<Statement>,
840        query_ctx: QueryContextRef,
841    ) -> Result<Output> {
842        ensure!(!self.is_suspended(), error::SuspendedSnafu);
843
844        let query_interceptor_opt = self.plugins.get::<SqlQueryInterceptorRef<Error>>();
845        let query_interceptor = query_interceptor_opt.as_ref();
846
847        query_interceptor.pre_execute(stmt.as_ref(), Some(&plan), query_ctx.clone())?;
848
849        let query = stmt
850            .as_ref()
851            .map(|s| s.to_string())
852            .unwrap_or_else(|| plan.display_indent().to_string());
853
854        let plan_is_readonly = is_readonly_plan(&plan);
855        let result = if should_track_plan_process(stmt.as_ref(), &plan) {
856            let catalog_name = query_ctx.current_catalog().to_string();
857            let schema_name = query_ctx.current_schema();
858            let slow_query_timer = if plan_is_readonly {
859                self.slow_query_options.enable.then(|| {
860                    SlowQueryTimer::new(
861                        CatalogQueryStatement::Plan(query.clone()),
862                        schema_name.clone(),
863                        self.slow_query_options.threshold,
864                        self.slow_query_options.sample_ratio,
865                        self.slow_query_options.record_type,
866                        self.slow_query_recorder.clone(),
867                    )
868                })
869            } else {
870                None
871            };
872
873            let timeout_recorder = stmt
874                .as_ref()
875                .is_some_and(is_explain_analyze_verbose)
876                .then(|| slow_query_timer.as_ref().map(SlowQueryTimer::recorder))
877                .flatten();
878            let ticket = self.process_manager.register_query(
879                catalog_name,
880                vec![schema_name],
881                query,
882                query_ctx.conn_info().to_string(),
883                Some(query_ctx.process_id()),
884                slow_query_timer,
885            );
886
887            let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder);
888
889            CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
890                .await
891                .map_err(|_| error::CancelledSnafu.build())?
892                .map(|output| {
893                    let Output { meta, data } = output;
894
895                    let data = match data {
896                        OutputData::Stream(stream) => OutputData::Stream(Box::pin(
897                            CancellableStreamWrapper::new(stream, ticket),
898                        )),
899                        other => other,
900                    };
901                    Output { data, meta }
902                })
903        } else {
904            self.exec_plan_with_timeout(plan, query_ctx.clone(), None)
905                .await
906        };
907
908        result.and_then(|output| query_interceptor.post_execute(output, query_ctx))
909    }
910
911    #[tracing::instrument(skip_all, name = "SqlQueryHandler::do_promql_query")]
912    async fn do_promql_query_inner(
913        &self,
914        query: &PromQuery,
915        query_ctx: QueryContextRef,
916    ) -> Vec<Result<Output>> {
917        if self.is_suspended() {
918            return vec![error::SuspendedSnafu {}.fail()];
919        }
920
921        // check will be done in prometheus handler's do_query
922        let result = PrometheusHandler::do_query(self, query, query_ctx)
923            .await
924            .with_context(|_| ExecutePromqlSnafu {
925                query: format!("{query:?}"),
926            });
927        vec![result]
928    }
929
930    async fn do_describe_inner(
931        &self,
932        stmt: Statement,
933        query_ctx: QueryContextRef,
934    ) -> Result<Option<DescribeResult>> {
935        ensure!(!self.is_suspended(), error::SuspendedSnafu);
936
937        // EXPLAIN / EXPLAIN ANALYZE wrap an inner statement; describe them when the
938        // wrapped statement is something we already plan (so that bind parameters
939        // in the inner query get their types inferred). See #8029.
940        let is_inner_plannable = |s: &Statement| {
941            matches!(
942                s,
943                Statement::Insert(_) | Statement::Query(_) | Statement::Delete(_)
944            )
945        };
946        let plannable = is_inner_plannable(&stmt)
947            || matches!(&stmt, Statement::Explain(explain) if is_inner_plannable(explain.statement.as_ref()));
948
949        if plannable {
950            self.check_sql_permission(&stmt, &query_ctx).await?;
951
952            let plan = self
953                .query_engine
954                .planner()
955                .plan(&QueryStatement::Sql(stmt), query_ctx.clone())
956                .await
957                .context(PlanStatementSnafu)?;
958            self.query_engine
959                .describe(plan, query_ctx)
960                .await
961                .map(Some)
962                .context(error::DescribeStatementSnafu)
963        } else {
964            Ok(None)
965        }
966    }
967
968    async fn is_valid_schema_inner(&self, catalog: &str, schema: &str) -> Result<bool> {
969        self.catalog_manager
970            .schema_exists(catalog, schema, None)
971            .await
972            .context(error::CatalogSnafu)
973    }
974}
975
976#[async_trait]
977impl SqlQueryHandler for Instance {
978    async fn do_query(
979        &self,
980        query: &str,
981        query_ctx: QueryContextRef,
982    ) -> Vec<server_error::Result<Output>> {
983        self.do_query_inner(query, query_ctx)
984            .await
985            .into_iter()
986            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
987            .collect()
988    }
989
990    async fn do_analyze_stream_query(
991        &self,
992        query: &str,
993        query_ctx: QueryContextRef,
994    ) -> server_error::Result<Output> {
995        self.do_analyze_stream_query_inner(query, query_ctx)
996            .await
997            .map_err(BoxedError::new)
998            .context(ExecuteQuerySnafu)
999    }
1000
1001    async fn do_exec_plan(
1002        &self,
1003        plan: LogicalPlan,
1004        stmt: Option<Statement>,
1005        query_ctx: QueryContextRef,
1006    ) -> server_error::Result<Output> {
1007        self.do_exec_plan_inner(plan, stmt, query_ctx)
1008            .await
1009            .map_err(BoxedError::new)
1010            .context(server_error::ExecutePlanSnafu)
1011    }
1012
1013    async fn do_promql_query(
1014        &self,
1015        query: &PromQuery,
1016        query_ctx: QueryContextRef,
1017    ) -> Vec<server_error::Result<Output>> {
1018        self.do_promql_query_inner(query, query_ctx)
1019            .await
1020            .into_iter()
1021            .map(|result| result.map_err(BoxedError::new).context(ExecuteQuerySnafu))
1022            .collect()
1023    }
1024
1025    async fn do_describe(
1026        &self,
1027        stmt: Statement,
1028        query_ctx: QueryContextRef,
1029    ) -> server_error::Result<Option<DescribeResult>> {
1030        self.do_describe_inner(stmt, query_ctx)
1031            .await
1032            .map_err(BoxedError::new)
1033            .context(server_error::DescribeStatementSnafu)
1034    }
1035
1036    async fn is_valid_schema(&self, catalog: &str, schema: &str) -> server_error::Result<bool> {
1037        self.is_valid_schema_inner(catalog, schema)
1038            .await
1039            .map_err(BoxedError::new)
1040            .context(server_error::CheckDatabaseValiditySnafu)
1041    }
1042}
1043
1044/// Expands scan-time dictionaries only when a query result leaves the frontend.
1045pub(crate) fn map_query_output(output: Output) -> Result<Output> {
1046    output
1047        .map_dictionary_to_values()
1048        .context(CollectRecordbatchSnafu)
1049}
1050
1051/// Attaches a timer to the output and observes it once the output is exhausted.
1052pub fn attach_timer(output: Output, timer: HistogramTimer) -> Output {
1053    match output.data {
1054        OutputData::AffectedRows(_) | OutputData::RecordBatches(_) => output,
1055        OutputData::Stream(stream) => {
1056            let stream = OnDone::new(stream, move || {
1057                timer.observe_duration();
1058            });
1059            Output::new(OutputData::Stream(Box::pin(stream)), output.meta)
1060        }
1061    }
1062}
1063
1064impl Instance {
1065    fn check_prom_query_privilege(&self, query_ctx: &QueryContextRef) -> server_error::Result<()> {
1066        self.plugins
1067            .get::<PermissionCheckerRef>()
1068            .as_ref()
1069            .check_permission(
1070                query_ctx.current_user(),
1071                PermissionReq::Action(PROMQL_QUERY),
1072            )
1073            .context(AuthSnafu)?;
1074        Ok(())
1075    }
1076
1077    fn prom_expr_permission_targets(
1078        &self,
1079        expr: &promql_parser::parser::Expr,
1080        query_ctx: &QueryContextRef,
1081    ) -> server_error::Result<Option<Vec<PermissionTableTarget>>> {
1082        extract_tables_from_prom_expr_checked(expr)
1083            .map(|tables| {
1084                tables
1085                    .map(|name| {
1086                        table_idents_to_full_name(&name, query_ctx).map(
1087                            |(catalog, schema, table)| {
1088                                PermissionTableTarget::new(catalog, schema, table)
1089                            },
1090                        )
1091                    })
1092                    .collect::<std::result::Result<Vec<_>, _>>()
1093                    .map_err(BoxedError::new)
1094                    .context(ExecuteQuerySnafu)
1095            })
1096            .transpose()
1097    }
1098
1099    async fn is_physical_query_permission_target(
1100        &self,
1101        target: &PermissionTableTarget,
1102        query_ctx: &QueryContextRef,
1103    ) -> server_error::Result<bool> {
1104        self.catalog_manager
1105            .table(
1106                &target.catalog,
1107                &target.schema,
1108                &target.table,
1109                Some(query_ctx),
1110            )
1111            .await
1112            .map(|table| table.is_some_and(|table| table.table_info().is_physical_table()))
1113            .map_err(BoxedError::new)
1114            .context(ExecuteQuerySnafu)
1115    }
1116
1117    async fn resolve_query_permission_targets(
1118        &self,
1119        targets: PermissionTableTargets,
1120        query_ctx: &QueryContextRef,
1121    ) -> server_error::Result<PermissionTableTargets> {
1122        const CONCURRENCY: usize = 8;
1123
1124        let checker = self.plugins.get::<PermissionCheckerRef>();
1125        if !checker.as_ref().uses_table_targets() {
1126            return Ok(targets);
1127        }
1128
1129        let PermissionTableTargets::Resolved(mut targets) = targets else {
1130            return Ok(PermissionTableTargets::Unresolved);
1131        };
1132        if targets.len() > 1 {
1133            let mut seen = HashSet::with_capacity(targets.len());
1134            targets.retain(|target| seen.insert(target.clone()));
1135        }
1136        if let [target] = targets.as_slice() {
1137            return if self
1138                .is_physical_query_permission_target(target, query_ctx)
1139                .await?
1140            {
1141                Ok(PermissionTableTargets::Unresolved)
1142            } else {
1143                Ok(PermissionTableTargets::resolved(targets))
1144            };
1145        }
1146
1147        // Bound catalog load and inspect results in target order to preserve serial semantics.
1148        for chunk in targets.chunks(CONCURRENCY) {
1149            let results = future::join_all(
1150                chunk
1151                    .iter()
1152                    .map(|target| self.is_physical_query_permission_target(target, query_ctx)),
1153            )
1154            .await;
1155            for result in results {
1156                if result? {
1157                    return Ok(PermissionTableTargets::Unresolved);
1158                }
1159            }
1160        }
1161
1162        Ok(PermissionTableTargets::resolved(targets))
1163    }
1164
1165    fn prom_queries_permission_targets(
1166        &self,
1167        queries: &[ParsedPromQuery],
1168        query_ctx: &QueryContextRef,
1169    ) -> server_error::Result<PermissionTableTargets> {
1170        let mut targets = Vec::new();
1171        let mut resolved = true;
1172
1173        for query in queries {
1174            let QueryStatement::Promql(eval_stmt, _) = query.statement() else {
1175                unreachable!("query is parsed from promql");
1176            };
1177
1178            if let Some(query_targets) =
1179                self.prom_expr_permission_targets(&eval_stmt.expr, query_ctx)?
1180            {
1181                targets.extend(query_targets);
1182            } else {
1183                resolved = false;
1184            }
1185        }
1186
1187        Ok(if resolved {
1188            PermissionTableTargets::resolved(targets)
1189        } else {
1190            PermissionTableTargets::Unresolved
1191        })
1192    }
1193}
1194
1195#[async_trait]
1196impl PrometheusHandler for Instance {
1197    #[tracing::instrument(skip_all)]
1198    async fn do_query(
1199        &self,
1200        query: &PromQuery,
1201        query_ctx: QueryContextRef,
1202    ) -> server_error::Result<Output> {
1203        let query = ParsedPromQuery::parse(query.clone(), &query_ctx)?;
1204        self.do_query_parsed(query, query_ctx).await
1205    }
1206
1207    #[tracing::instrument(skip_all)]
1208    async fn do_query_parsed(
1209        &self,
1210        query: ParsedPromQuery,
1211        query_ctx: QueryContextRef,
1212    ) -> server_error::Result<Output> {
1213        let interceptor = self
1214            .plugins
1215            .get::<PromQueryInterceptorRef<server_error::Error>>();
1216
1217        self.check_prom_query_privilege(&query_ctx)?;
1218
1219        let targets =
1220            self.prom_queries_permission_targets(std::slice::from_ref(&query), &query_ctx)?;
1221        self.check_query_target_permission(targets, &query_ctx)
1222            .await?;
1223
1224        let (query, stmt) = query.into_parts();
1225
1226        let QueryStatement::Promql(eval_stmt, _) = &stmt else {
1227            unreachable!("query is parsed from promql");
1228        };
1229
1230        let plan = self
1231            .statement_executor
1232            .plan(&stmt, query_ctx.clone())
1233            .await
1234            .map_err(BoxedError::new)
1235            .context(ExecuteQuerySnafu)?;
1236
1237        interceptor.pre_execute(&query, &eval_stmt.expr, Some(&plan), query_ctx.clone())?;
1238
1239        // Take the EvalStmt from the original QueryStatement and use it to create the CatalogQueryStatement.
1240        let query_statement = if let QueryStatement::Promql(eval_stmt, alias) = stmt {
1241            CatalogQueryStatement::Promql(eval_stmt, alias)
1242        } else {
1243            // It should not happen since the query is already parsed successfully.
1244            return UnexpectedResultSnafu {
1245                reason: "The query should always be promql.".to_string(),
1246            }
1247            .fail();
1248        };
1249        let raw_query = query_statement.to_string();
1250
1251        let slow_query_timer = self.slow_query_options.enable.then(|| {
1252            SlowQueryTimer::new(
1253                query_statement,
1254                query_ctx.current_schema(),
1255                self.slow_query_options.threshold,
1256                self.slow_query_options.sample_ratio,
1257                self.slow_query_options.record_type,
1258                self.slow_query_recorder.clone(),
1259            )
1260        });
1261
1262        let ticket = self.process_manager.register_query(
1263            query_ctx.current_catalog().to_string(),
1264            vec![query_ctx.current_schema()],
1265            raw_query,
1266            query_ctx.conn_info().to_string(),
1267            Some(query_ctx.process_id()),
1268            slow_query_timer,
1269        );
1270
1271        let query_fut = self.statement_executor.exec_plan(plan, query_ctx.clone());
1272
1273        let output = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone())
1274            .await
1275            .map_err(|_| servers::error::CancelledSnafu.build())?
1276            .map_err(BoxedError::new)
1277            .context(ExecuteQuerySnafu)?;
1278        let output = map_query_output(output)
1279            .map_err(BoxedError::new)
1280            .context(ExecuteQuerySnafu)?;
1281        let Output { meta, data } = output;
1282        let data = match data {
1283            OutputData::Stream(stream) => {
1284                OutputData::Stream(Box::pin(CancellableStreamWrapper::new(stream, ticket)))
1285            }
1286            other => other,
1287        };
1288        let output = Output { data, meta };
1289        Ok(interceptor.post_execute(output, query_ctx)?)
1290    }
1291
1292    async fn check_query_permission(
1293        &self,
1294        queries: &[PromQuery],
1295        query_ctx: &QueryContextRef,
1296    ) -> server_error::Result<()> {
1297        let queries = queries
1298            .iter()
1299            .cloned()
1300            .map(|query| ParsedPromQuery::parse(query, query_ctx))
1301            .collect::<server_error::Result<Vec<_>>>()?;
1302        self.check_query_permission_parsed(&queries, query_ctx)
1303            .await
1304    }
1305
1306    async fn check_query_permission_parsed(
1307        &self,
1308        queries: &[ParsedPromQuery],
1309        query_ctx: &QueryContextRef,
1310    ) -> server_error::Result<()> {
1311        self.check_prom_query_privilege(query_ctx)?;
1312        let targets = self.prom_queries_permission_targets(queries, query_ctx)?;
1313        self.check_query_target_permission(targets, query_ctx).await
1314    }
1315
1316    async fn check_query_target_permission(
1317        &self,
1318        targets: PermissionTableTargets,
1319        query_ctx: &QueryContextRef,
1320    ) -> server_error::Result<()> {
1321        let targets = self
1322            .resolve_query_permission_targets(targets, query_ctx)
1323            .await?;
1324        self.check_table_permission(query_ctx, PermissionReq::Action(PROMQL_QUERY), targets)
1325            .context(AuthSnafu)?;
1326        Ok(())
1327    }
1328
1329    async fn filter_metadata_metric_names(
1330        &self,
1331        metric_names: Vec<String>,
1332        schema: &str,
1333        query_ctx: &QueryContextRef,
1334    ) -> server_error::Result<Vec<String>> {
1335        let checker = self.plugins.get::<PermissionCheckerRef>();
1336        if !checker.as_ref().uses_table_targets() {
1337            let Some(metric) = metric_names.first() else {
1338                return Ok(metric_names);
1339            };
1340            let target =
1341                PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
1342            let result = checker
1343                .as_ref()
1344                .check_permission_with_table_targets(
1345                    query_ctx.current_user(),
1346                    PermissionReq::Action(PROMQL_QUERY),
1347                    PermissionTableTargets::resolved(vec![target]),
1348                )
1349                .context(AuthSnafu);
1350            return match result {
1351                Ok(_) => Ok(metric_names),
1352                Err(error)
1353                    if error.status_code()
1354                        == common_error::status_code::StatusCode::PermissionDenied =>
1355                {
1356                    Ok(Vec::new())
1357                }
1358                Err(error) => Err(error),
1359            };
1360        }
1361
1362        let mut allowed = Vec::with_capacity(metric_names.len());
1363        for metric in metric_names {
1364            let target =
1365                PermissionTableTarget::new(query_ctx.current_catalog(), schema, metric.as_str());
1366            match checker
1367                .as_ref()
1368                .check_permission_with_table_targets(
1369                    query_ctx.current_user(),
1370                    PermissionReq::Action(PROMQL_QUERY),
1371                    PermissionTableTargets::resolved(vec![target]),
1372                )
1373                .context(AuthSnafu)
1374            {
1375                Ok(_) => allowed.push(metric),
1376                Err(error)
1377                    if error.status_code()
1378                        == common_error::status_code::StatusCode::PermissionDenied => {}
1379                Err(error) => return Err(error),
1380            }
1381        }
1382        Ok(allowed)
1383    }
1384
1385    async fn query_metric_names(
1386        &self,
1387        matchers: Vec<Matcher>,
1388        schema: &str,
1389        ctx: &QueryContextRef,
1390    ) -> server_error::Result<Vec<String>> {
1391        self.handle_query_metric_names(matchers, schema, ctx)
1392            .await
1393            .map_err(BoxedError::new)
1394            .context(ExecuteQuerySnafu)
1395    }
1396
1397    async fn query_label_values(
1398        &self,
1399        metric: String,
1400        label_name: String,
1401        matchers: Vec<Matcher>,
1402        start: SystemTime,
1403        end: SystemTime,
1404        ctx: &QueryContextRef,
1405    ) -> server_error::Result<Vec<String>> {
1406        let schema =
1407            resolve_schema_from_matchers(&matchers)?.unwrap_or_else(|| ctx.current_schema());
1408        let target = PermissionTableTarget::new(ctx.current_catalog(), schema.as_str(), &metric);
1409        self.check_query_target_permission(
1410            PermissionTableTargets::resolved(vec![target.clone()]),
1411            ctx,
1412        )
1413        .await?;
1414
1415        self.handle_query_label_values(target, label_name, matchers, start, end, ctx)
1416            .await
1417            .map_err(BoxedError::new)
1418            .context(ExecuteQuerySnafu)
1419    }
1420
1421    fn catalog_manager(&self) -> CatalogManagerRef {
1422        self.catalog_manager.clone()
1423    }
1424}
1425
1426/// Validate `stmt.database` permission if it's presented.
1427macro_rules! validate_db_permission {
1428    ($stmt: expr, $query_ctx: expr) => {
1429        if let Some(database) = &$stmt.database {
1430            validate_catalog_and_schema($query_ctx.current_catalog(), database, $query_ctx)
1431                .map_err(BoxedError::new)
1432                .context(SqlExecInterceptedSnafu)?;
1433        }
1434    };
1435}
1436
1437pub fn check_permission(
1438    plugins: Plugins,
1439    stmt: &Statement,
1440    query_ctx: &QueryContextRef,
1441) -> Result<()> {
1442    let need_validate = plugins
1443        .get::<QueryOptions>()
1444        .map(|opts| opts.disallow_cross_catalog_query)
1445        .unwrap_or_default();
1446
1447    if !need_validate {
1448        return Ok(());
1449    }
1450
1451    match stmt {
1452        // Will be checked in execution.
1453        // TODO(dennis): add a hook for admin commands.
1454        Statement::Admin(_) => {}
1455        // These are executed by query engine, and will be checked there.
1456        Statement::Query(_)
1457        | Statement::Explain(_)
1458        | Statement::Tql(_)
1459        | Statement::Delete(_)
1460        | Statement::DeclareCursor(_)
1461        | Statement::Copy(sql::statements::copy::Copy::CopyQueryTo(_)) => {}
1462        // database ops won't be checked
1463        Statement::CreateDatabase(_)
1464        | Statement::ShowDatabases(_)
1465        | Statement::DropDatabase(_)
1466        | Statement::AlterDatabase(_)
1467        | Statement::DropFlow(_)
1468        | Statement::Use(_) => {}
1469        #[cfg(feature = "enterprise")]
1470        Statement::DropTrigger(_) => {}
1471        Statement::ShowCreateDatabase(stmt) => {
1472            validate_database(&stmt.database_name, query_ctx)?;
1473        }
1474        Statement::ShowCreateTable(stmt) => {
1475            validate_param(&stmt.table_name, query_ctx)?;
1476        }
1477        Statement::ShowCreateFlow(stmt) => {
1478            validate_flow(&stmt.flow_name, query_ctx)?;
1479        }
1480        #[cfg(feature = "enterprise")]
1481        Statement::ShowCreateTrigger(stmt) => {
1482            validate_param(&stmt.trigger_name, query_ctx)?;
1483        }
1484        Statement::ShowCreateView(stmt) => {
1485            validate_param(&stmt.view_name, query_ctx)?;
1486        }
1487        Statement::CreateExternalTable(stmt) => {
1488            validate_param(&stmt.name, query_ctx)?;
1489        }
1490        Statement::CreateFlow(stmt) => {
1491            // TODO: should also validate source table name here?
1492            validate_param(&stmt.sink_table_name, query_ctx)?;
1493        }
1494        #[cfg(feature = "enterprise")]
1495        Statement::CreateTrigger(stmt) => {
1496            validate_param(&stmt.trigger_name, query_ctx)?;
1497        }
1498        Statement::CreateView(stmt) => {
1499            validate_param(&stmt.name, query_ctx)?;
1500        }
1501        Statement::AlterTable(stmt) => {
1502            validate_param(stmt.table_name(), query_ctx)?;
1503        }
1504        #[cfg(feature = "enterprise")]
1505        Statement::AlterTrigger(_) => {}
1506        // set/show variable now only alter/show variable in session
1507        Statement::SetVariables(_) | Statement::ShowVariables(_) => {}
1508        // show charset and show collation won't be checked
1509        Statement::ShowCharset(_) | Statement::ShowCollation(_) => {}
1510
1511        Statement::Comment(comment) => match &comment.object {
1512            CommentObject::Table(table) => validate_param(table, query_ctx)?,
1513            CommentObject::Column { table, .. } => validate_param(table, query_ctx)?,
1514            CommentObject::Flow(flow) => validate_flow(flow, query_ctx)?,
1515        },
1516
1517        Statement::Insert(insert) => {
1518            let name = insert.table_name().context(ParseSqlSnafu)?;
1519            validate_param(name, query_ctx)?;
1520        }
1521        Statement::CreateTable(stmt) => {
1522            validate_param(&stmt.name, query_ctx)?;
1523        }
1524        Statement::CreateTableLike(stmt) => {
1525            validate_param(&stmt.table_name, query_ctx)?;
1526            validate_param(&stmt.source_name, query_ctx)?;
1527        }
1528        Statement::DropTable(drop_stmt) => {
1529            for table_name in drop_stmt.table_names() {
1530                validate_param(table_name, query_ctx)?;
1531            }
1532        }
1533        #[cfg(feature = "enterprise")]
1534        Statement::UndropTable(stmt) => {
1535            validate_param(stmt.table_name(), query_ctx)?;
1536        }
1537        Statement::DropView(stmt) => {
1538            validate_param(&stmt.view_name, query_ctx)?;
1539        }
1540        Statement::ShowTables(stmt) => {
1541            validate_db_permission!(stmt, query_ctx);
1542        }
1543        Statement::ShowTableStatus(stmt) => {
1544            validate_db_permission!(stmt, query_ctx);
1545        }
1546        Statement::ShowColumns(stmt) => {
1547            validate_db_permission!(stmt, query_ctx);
1548        }
1549        Statement::ShowIndex(stmt) => {
1550            validate_db_permission!(stmt, query_ctx);
1551        }
1552        Statement::ShowRegion(stmt) => {
1553            validate_db_permission!(stmt, query_ctx);
1554        }
1555        Statement::ShowViews(stmt) => {
1556            validate_db_permission!(stmt, query_ctx);
1557        }
1558        Statement::ShowFlows(stmt) => {
1559            validate_db_permission!(stmt, query_ctx);
1560        }
1561        Statement::ShowFlowStatus(_stmt) => {
1562            // Flow statistics are organized based on the catalog dimension and
1563            // filtered by the current catalog, so there is no need to check the
1564            // permission of the database(schema).
1565        }
1566        #[cfg(feature = "enterprise")]
1567        Statement::ShowTriggers(_stmt) => {
1568            // The trigger is organized based on the catalog dimension, so there
1569            // is no need to check the permission of the database(schema).
1570        }
1571        Statement::ShowStatus(_stmt) => {}
1572        Statement::ShowSearchPath(_stmt) => {}
1573        Statement::DescribeTable(stmt) => {
1574            validate_param(stmt.name(), query_ctx)?;
1575        }
1576        Statement::Copy(sql::statements::copy::Copy::CopyTable(stmt)) => match stmt {
1577            CopyTable::To(copy_table_to) => validate_param(&copy_table_to.table_name, query_ctx)?,
1578            CopyTable::From(copy_table_from) => {
1579                validate_param(&copy_table_from.table_name, query_ctx)?
1580            }
1581        },
1582        Statement::Copy(sql::statements::copy::Copy::CopyDatabase(copy_database)) => {
1583            match copy_database {
1584                CopyDatabase::To(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1585                CopyDatabase::From(stmt) => validate_database(&stmt.database_name, query_ctx)?,
1586            }
1587        }
1588        Statement::TruncateTable(stmt) => {
1589            validate_param(stmt.table_name(), query_ctx)?;
1590        }
1591        // cursor operations are always allowed once it's created
1592        Statement::FetchCursor(_) | Statement::CloseCursor(_) => {}
1593        // User can only kill process in their own catalog.
1594        Statement::Kill(_) => {}
1595        // SHOW PROCESSLIST
1596        Statement::ShowProcesslist(_) => {}
1597    }
1598    Ok(())
1599}
1600
1601fn validate_param(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1602    let (catalog, schema, _) = table_idents_to_full_name(name, query_ctx)
1603        .map_err(BoxedError::new)
1604        .context(ExternalSnafu)?;
1605
1606    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1607        .map_err(BoxedError::new)
1608        .context(SqlExecInterceptedSnafu)
1609}
1610
1611fn validate_flow(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1612    let catalog = match &name.0[..] {
1613        [_flow] => query_ctx.current_catalog().to_string(),
1614        [catalog, _flow] => catalog.to_string_unquoted(),
1615        _ => {
1616            return InvalidSqlSnafu {
1617                err_msg: format!(
1618                    "expect flow name to be <catalog>.<flow_name> or <flow_name>, actual: {name}",
1619                ),
1620            }
1621            .fail();
1622        }
1623    };
1624
1625    let schema = query_ctx.current_schema();
1626
1627    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1628        .map_err(BoxedError::new)
1629        .context(SqlExecInterceptedSnafu)
1630}
1631
1632fn validate_database(name: &ObjectName, query_ctx: &QueryContextRef) -> Result<()> {
1633    let (catalog, schema) = match &name.0[..] {
1634        [schema] => (
1635            query_ctx.current_catalog().to_string(),
1636            schema.to_string_unquoted(),
1637        ),
1638        [catalog, schema] => (catalog.to_string_unquoted(), schema.to_string_unquoted()),
1639        _ => InvalidSqlSnafu {
1640            err_msg: format!(
1641                "expect database name to be <catalog>.<schema> or <schema>, actual: {name}",
1642            ),
1643        }
1644        .fail()?,
1645    };
1646
1647    validate_catalog_and_schema(&catalog, &schema, query_ctx)
1648        .map_err(BoxedError::new)
1649        .context(SqlExecInterceptedSnafu)
1650}
1651
1652fn is_readonly_plan(plan: &LogicalPlan) -> bool {
1653    !matches!(plan, LogicalPlan::Dml(_) | LogicalPlan::Ddl(_))
1654}
1655
1656fn should_track_statement_process(stmt: &Statement) -> bool {
1657    stmt.is_readonly()
1658        || matches!(stmt, Statement::Insert(insert) if insert.has_non_values_query_source())
1659}
1660
1661fn should_track_plan_process(stmt: Option<&Statement>, plan: &LogicalPlan) -> bool {
1662    is_readonly_plan(plan)
1663        || matches!(stmt, Some(Statement::Insert(insert)) if insert.has_non_values_query_source())
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668    use std::collections::HashMap;
1669    use std::future::Future;
1670    use std::pin::Pin;
1671    use std::sync::Arc;
1672    use std::task::{Context, Poll};
1673    use std::time::Duration;
1674
1675    use api::prom_store::remote::label_matcher::Type as PromMatcherType;
1676    use api::prom_store::remote::{
1677        Label, LabelMatcher, Query as RemoteQuery, ReadRequest, ReadResponse, Sample,
1678    };
1679    use api::v1::meta::{ProcedureDetailResponse, ReconcileRequest, ReconcileResponse};
1680    use auth::{
1681        DASHBOARD_DELETE, DASHBOARD_QUERY, DASHBOARD_SAVE, JAEGER_QUERY, PIPELINE_DELETE,
1682        PIPELINE_INSERT, PIPELINE_QUERY, PermissionAction, PermissionResp, UserInfoRef,
1683    };
1684    use catalog::process_manager::{ProcessManager, QueryStatement, SlowQueryTimer};
1685    use common_base::Plugins;
1686    use common_catalog::consts::DEFAULT_PRIVATE_SCHEMA_NAME;
1687    use common_error::ext::{BoxedError, ErrorExt, PlainError};
1688    use common_error::status_code::StatusCode;
1689    use common_event_recorder::{Event, EventRecorder, EventTypeFilter, EventTypeFilterRef};
1690    use common_frontend::slow_query_event::SlowQueryEvent;
1691    use common_meta::cache::LayeredCacheRegistryBuilder;
1692    use common_meta::kv_backend::memory::MemoryKvBackend;
1693    use common_meta::procedure_executor::{ExecutorContext, ProcedureExecutor};
1694    use common_meta::rpc::ddl::{DdlTask, SubmitDdlTaskRequest, SubmitDdlTaskResponse};
1695    use common_meta::rpc::procedure::{
1696        MigrateRegionRequest, MigrateRegionResponse, ProcedureStateResponse,
1697    };
1698    use common_query::prelude::greptime_value;
1699    use common_query::{Output, OutputMeta};
1700    use common_recordbatch::{
1701        OrderOption, RecordBatch, RecordBatchStream, SendableRecordBatchStream,
1702    };
1703    use common_telemetry::logging::SlowQueriesRecordType;
1704    use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
1705    use datafusion::physical_plan::empty::EmptyExec;
1706    use datafusion_expr::dml::InsertOp;
1707    use datafusion_expr::{LogicalPlanBuilder, LogicalTableSource};
1708    use datatypes::prelude::ConcreteDataType;
1709    use datatypes::schema::{ColumnSchema, Schema as GtSchema, SchemaRef as GtSchemaRef};
1710    use datatypes::vectors::{
1711        Float64Vector, StringVector, TimestampMillisecondVector, TimestampNanosecondVector,
1712        VectorRef,
1713    };
1714    use log_query::LogQuery;
1715    use prost::Message;
1716    use query::query_engine::options::QueryOptions;
1717    use servers::query_handler::{
1718        DashboardHandler, JaegerQueryHandler, LogQueryHandler, PipelineHandler, PipelineHandlerRef,
1719        PromStoreProtocolHandler,
1720    };
1721    use session::context::{Channel, ConnInfo, QueryContext, QueryContextBuilder};
1722    use snafu::{Location, Snafu};
1723    use sql::dialect::GreptimeDbDialect;
1724    use store_api::data_source::DataSource;
1725    use store_api::metric_engine_consts::{
1726        LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
1727    };
1728    use store_api::storage::ScanRequest;
1729    use strfmt::Format;
1730    use table::metadata::{
1731        FilterPushDownType, TableInfo, TableInfoBuilder, TableMetaBuilder, TableType,
1732    };
1733    use table::table_name::TableName;
1734    use table::test_util::{EmptyTable, MemTable};
1735    use table::{Table, TableRef};
1736    use tokio::sync::{mpsc, oneshot};
1737    use tower::ServiceExt;
1738
1739    use super::*;
1740    use crate::frontend::FrontendOptions;
1741    use crate::instance::builder::FrontendBuilder;
1742
1743    fn parse_test_sql(sql: &str) -> Vec<Statement> {
1744        parse_stmt(sql, &GreptimeDbDialect {}).unwrap()
1745    }
1746
1747    #[derive(Debug, Default)]
1748    struct RecordingSlowQueryEventRecorder {
1749        payloads: std::sync::Mutex<Vec<serde_json::Value>>,
1750    }
1751
1752    impl EventRecorder for RecordingSlowQueryEventRecorder {
1753        fn record(&self, event: Box<dyn Event>) {
1754            let event = event
1755                .as_any()
1756                .downcast_ref::<SlowQueryEvent>()
1757                .expect("expected a slow query event");
1758            self.payloads.lock().unwrap().push(event.payload.clone());
1759        }
1760
1761        fn event_type_filter(&self) -> EventTypeFilterRef {
1762            Arc::new(EventTypeFilter::All)
1763        }
1764
1765        fn close(&self) {}
1766    }
1767
1768    #[test]
1769    fn test_validate_analyze_stream_statement_strictness() {
1770        for sql in [
1771            "select 1",
1772            "explain analyze select 1",
1773            "explain analyze verbose format text select 1",
1774            "explain analyze verbose format graphviz select 1",
1775        ] {
1776            let mut stmts = parse_test_sql(sql);
1777            assert!(
1778                validate_analyze_stream_statement(&mut stmts[0]).is_err(),
1779                "{sql}"
1780            );
1781        }
1782
1783        for sql in [
1784            "explain analyze verbose select 1",
1785            "explain analyze verbose format json select 1",
1786        ] {
1787            let mut stmts = parse_test_sql(sql);
1788            assert!(
1789                validate_analyze_stream_statement(&mut stmts[0]).is_ok(),
1790                "{sql}"
1791            );
1792            let Statement::Explain(explain) = &stmts[0] else {
1793                unreachable!();
1794            };
1795            assert!(explain.format.is_none());
1796        }
1797
1798        assert_eq!(
1799            parse_test_sql("explain analyze verbose select 1; select 2").len(),
1800            2
1801        );
1802
1803        assert!(is_explain_analyze_verbose(
1804            &parse_test_sql("explain analyze verbose select 1")[0]
1805        ));
1806        for sql in [
1807            "select 1",
1808            "explain select 1",
1809            "explain analyze select 1",
1810            "explain verbose select 1",
1811        ] {
1812            assert!(
1813                !is_explain_analyze_verbose(&parse_test_sql(sql)[0]),
1814                "{sql}"
1815            );
1816        }
1817    }
1818
1819    #[derive(Debug, Snafu)]
1820    enum TestError {
1821        #[snafu(display("Failed to build test cache registry"))]
1822        BuildCacheRegistry {
1823            source: cache::error::Error,
1824            #[snafu(implicit)]
1825            location: Location,
1826        },
1827
1828        #[snafu(display("Failed to build test table meta for table: {table_name}"))]
1829        BuildTableMeta {
1830            table_name: String,
1831            source: table::metadata::TableMetaBuilderError,
1832            #[snafu(implicit)]
1833            location: Location,
1834        },
1835
1836        #[snafu(display("Failed to build test table info for table: {table_name}"))]
1837        BuildTableInfo {
1838            table_name: String,
1839            source: table::metadata::TableInfoBuilderError,
1840            #[snafu(implicit)]
1841            location: Location,
1842        },
1843
1844        #[snafu(display("Failed to register test table: {table_name}"))]
1845        RegisterTable {
1846            table_name: String,
1847            source: catalog::error::Error,
1848            #[snafu(implicit)]
1849            location: Location,
1850        },
1851
1852        #[snafu(display("Failed to build test frontend instance"))]
1853        BuildFrontend {
1854            source: crate::error::Error,
1855            #[snafu(implicit)]
1856            location: Location,
1857        },
1858
1859        #[snafu(display("Expected exactly one output for SQL `{sql}`, got {actual}"))]
1860        UnexpectedOutputCount {
1861            sql: String,
1862            actual: usize,
1863            #[snafu(implicit)]
1864            location: Location,
1865        },
1866
1867        #[snafu(display("Failed to execute SQL `{sql}`"))]
1868        ExecuteSql {
1869            sql: String,
1870            source: crate::error::Error,
1871            #[snafu(implicit)]
1872            location: Location,
1873        },
1874
1875        #[snafu(display("Timed out waiting for insert-select start notification"))]
1876        InsertStartTimeout {
1877            source: tokio::time::error::Elapsed,
1878            #[snafu(implicit)]
1879            location: Location,
1880        },
1881
1882        #[snafu(display("Insert-select start notification channel closed"))]
1883        InsertStartChannelClosed {
1884            #[snafu(implicit)]
1885            location: Location,
1886        },
1887
1888        #[snafu(display("Failed to release blocking insert-select interceptor"))]
1889        ReleaseBlockedInsert {
1890            #[snafu(implicit)]
1891            location: Location,
1892        },
1893
1894        #[snafu(display("Timed out waiting for insert-select source to be polled"))]
1895        SourcePollTimeout {
1896            source: tokio::time::error::Elapsed,
1897            #[snafu(implicit)]
1898            location: Location,
1899        },
1900
1901        #[snafu(display("Insert-select source poll notification channel closed"))]
1902        SourcePollChannelClosed {
1903            source: oneshot::error::RecvError,
1904            #[snafu(implicit)]
1905            location: Location,
1906        },
1907
1908        #[snafu(display("Timed out waiting for insert task to finish"))]
1909        InsertTaskTimeout {
1910            source: tokio::time::error::Elapsed,
1911            #[snafu(implicit)]
1912            location: Location,
1913        },
1914
1915        #[snafu(display("Insert task panicked"))]
1916        InsertTaskPanic {
1917            source: tokio::task::JoinError,
1918            #[snafu(implicit)]
1919            location: Location,
1920        },
1921
1922        #[snafu(display("Expected insert-select to be cancelled"))]
1923        InsertSelectNotCancelled {
1924            #[snafu(implicit)]
1925            location: Location,
1926        },
1927    }
1928
1929    type TestResult<T> = std::result::Result<T, TestError>;
1930
1931    fn parse_one_sql(sql: &str) -> Statement {
1932        parse_stmt(sql, &GreptimeDbDialect {}).unwrap().remove(0)
1933    }
1934
1935    fn test_query_ctx(process_id: u32) -> QueryContextRef {
1936        Arc::new(
1937            QueryContextBuilder::default()
1938                .channel(Channel::Mysql)
1939                .conn_info(ConnInfo::new(None, Channel::Mysql))
1940                .process_id(process_id)
1941                .build(),
1942        )
1943    }
1944
1945    struct RejectUnresolvedPermissionChecker;
1946
1947    impl PermissionChecker for RejectUnresolvedPermissionChecker {
1948        fn check_permission(
1949            &self,
1950            _user_info: UserInfoRef,
1951            _req: PermissionReq,
1952        ) -> auth::error::Result<PermissionResp> {
1953            Ok(PermissionResp::Allow)
1954        }
1955
1956        fn check_permission_with_table_targets(
1957            &self,
1958            _user_info: UserInfoRef,
1959            _req: PermissionReq,
1960            targets: PermissionTableTargets,
1961        ) -> auth::error::Result<PermissionResp> {
1962            let reject = match targets {
1963                PermissionTableTargets::Unresolved => true,
1964                PermissionTableTargets::Resolved(targets) => {
1965                    targets.iter().any(|target| target.table == "denied")
1966                }
1967            };
1968            Ok(if reject {
1969                PermissionResp::Reject
1970            } else {
1971                PermissionResp::Allow
1972            })
1973        }
1974    }
1975
1976    #[derive(Debug, PartialEq, Eq)]
1977    struct CheckedAction {
1978        action: PermissionAction,
1979        targets: Option<PermissionTableTargets>,
1980    }
1981
1982    #[derive(Default)]
1983    struct RejectEndpointPermissionChecker {
1984        checks: std::sync::Mutex<Vec<CheckedAction>>,
1985    }
1986
1987    impl RejectEndpointPermissionChecker {
1988        fn reject(
1989            &self,
1990            action: PermissionAction,
1991            targets: Option<PermissionTableTargets>,
1992        ) -> PermissionResp {
1993            self.checks
1994                .lock()
1995                .unwrap()
1996                .push(CheckedAction { action, targets });
1997            PermissionResp::Reject
1998        }
1999
2000        fn take_check(&self) -> CheckedAction {
2001            let mut checks = self.checks.lock().unwrap();
2002            assert_eq!(1, checks.len());
2003            checks.pop().unwrap()
2004        }
2005    }
2006
2007    impl PermissionChecker for RejectEndpointPermissionChecker {
2008        fn check_permission(
2009            &self,
2010            _user_info: UserInfoRef,
2011            req: PermissionReq,
2012        ) -> auth::error::Result<PermissionResp> {
2013            Ok(match req {
2014                PermissionReq::Action(action) => self.reject(action, None),
2015                _ => PermissionResp::Allow,
2016            })
2017        }
2018
2019        fn check_permission_with_table_targets(
2020            &self,
2021            _user_info: UserInfoRef,
2022            req: PermissionReq,
2023            targets: PermissionTableTargets,
2024        ) -> auth::error::Result<PermissionResp> {
2025            Ok(match req {
2026                PermissionReq::Action(action) => self.reject(action, Some(targets)),
2027                _ => PermissionResp::Allow,
2028            })
2029        }
2030    }
2031
2032    struct WriteOnlyPermissionChecker;
2033
2034    impl PermissionChecker for WriteOnlyPermissionChecker {
2035        fn check_permission(
2036            &self,
2037            _user_info: UserInfoRef,
2038            req: PermissionReq,
2039        ) -> auth::error::Result<PermissionResp> {
2040            Ok(if req.is_readonly() {
2041                PermissionResp::Reject
2042            } else {
2043                PermissionResp::Allow
2044            })
2045        }
2046
2047        fn check_permission_with_table_targets(
2048            &self,
2049            user_info: UserInfoRef,
2050            req: PermissionReq,
2051            _targets: PermissionTableTargets,
2052        ) -> auth::error::Result<PermissionResp> {
2053            self.check_permission(user_info, req)
2054        }
2055    }
2056
2057    #[derive(Default)]
2058    struct TargetIndependentPermissionChecker {
2059        checks: atomic::AtomicUsize,
2060    }
2061
2062    impl PermissionChecker for TargetIndependentPermissionChecker {
2063        fn check_permission(
2064            &self,
2065            _user_info: UserInfoRef,
2066            _req: PermissionReq,
2067        ) -> auth::error::Result<PermissionResp> {
2068            self.checks.fetch_add(1, atomic::Ordering::Relaxed);
2069            Ok(PermissionResp::Allow)
2070        }
2071
2072        fn uses_table_targets(&self) -> bool {
2073            false
2074        }
2075
2076        fn check_permission_with_table_targets(
2077            &self,
2078            user_info: UserInfoRef,
2079            req: PermissionReq,
2080            _targets: PermissionTableTargets,
2081        ) -> auth::error::Result<PermissionResp> {
2082            self.check_permission(user_info, req)
2083        }
2084    }
2085
2086    struct BlockingInsertSelectInterceptor {
2087        started_tx: mpsc::UnboundedSender<()>,
2088        finish_rx: std::sync::Mutex<Option<oneshot::Receiver<()>>>,
2089    }
2090
2091    impl BlockingInsertSelectInterceptor {
2092        fn new(started_tx: mpsc::UnboundedSender<()>, finish_rx: oneshot::Receiver<()>) -> Self {
2093            Self {
2094                started_tx,
2095                finish_rx: std::sync::Mutex::new(Some(finish_rx)),
2096            }
2097        }
2098    }
2099
2100    impl SqlQueryInterceptor for BlockingInsertSelectInterceptor {
2101        type Error = Error;
2102
2103        fn pre_execute(
2104            &self,
2105            statement: Option<&Statement>,
2106            _plan: Option<&LogicalPlan>,
2107            _query_ctx: QueryContextRef,
2108        ) -> Result<()> {
2109            let Some(Statement::Insert(insert)) = statement else {
2110                return Ok(());
2111            };
2112            if !insert.has_non_values_query_source() {
2113                return Ok(());
2114            }
2115
2116            let finish_rx = self.finish_rx.lock().unwrap().take().unwrap();
2117            let _ = self.started_tx.send(());
2118            tokio::task::block_in_place(|| {
2119                tokio::runtime::Handle::current()
2120                    .block_on(finish_rx)
2121                    .unwrap();
2122            });
2123            Ok(())
2124        }
2125    }
2126
2127    struct PendingRecordBatchStream {
2128        schema: GtSchemaRef,
2129        polled_tx: Option<oneshot::Sender<()>>,
2130        _finish_tx: oneshot::Sender<()>,
2131        finish_rx: Pin<Box<oneshot::Receiver<()>>>,
2132    }
2133
2134    impl RecordBatchStream for PendingRecordBatchStream {
2135        fn schema(&self) -> GtSchemaRef {
2136            self.schema.clone()
2137        }
2138
2139        fn output_ordering(&self) -> Option<&[OrderOption]> {
2140            None
2141        }
2142
2143        fn metrics(&self) -> Option<common_recordbatch::adapter::RecordBatchMetrics> {
2144            None
2145        }
2146    }
2147
2148    impl Stream for PendingRecordBatchStream {
2149        type Item = common_recordbatch::error::Result<RecordBatch>;
2150
2151        fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2152            if let Some(polled_tx) = self.polled_tx.take() {
2153                let _ = polled_tx.send(());
2154            }
2155
2156            match self.finish_rx.as_mut().poll(cx) {
2157                Poll::Ready(_) => Poll::Ready(None),
2158                Poll::Pending => Poll::Pending,
2159            }
2160        }
2161    }
2162
2163    impl Unpin for PendingRecordBatchStream {}
2164
2165    #[test]
2166    fn test_record_explain_analyze_timeout_uses_empty_metrics_without_plan() {
2167        let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
2168        let timer = SlowQueryTimer::new(
2169            QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2170            "public".to_string(),
2171            Duration::from_secs(3600),
2172            0.0,
2173            SlowQueriesRecordType::SystemTable,
2174            event_recorder.clone(),
2175        );
2176        let timeout_recorder = timer.recorder();
2177
2178        record_explain_analyze_timeout(Some(&timeout_recorder), None);
2179        drop(timer);
2180
2181        let payloads = event_recorder.payloads.lock().unwrap();
2182        assert_eq!(payloads.len(), 1);
2183        assert_eq!(payloads[0]["timed_out"], true);
2184        assert_eq!(payloads[0]["metrics"], serde_json::json!([]));
2185    }
2186
2187    #[tokio::test]
2188    async fn test_attach_timeout_records_explain_analyze_metrics() {
2189        let event_recorder = Arc::new(RecordingSlowQueryEventRecorder::default());
2190        let timer = SlowQueryTimer::new(
2191            QueryStatement::Plan("EXPLAIN ANALYZE VERBOSE SELECT 1".to_string()),
2192            "public".to_string(),
2193            Duration::from_secs(3600),
2194            0.0,
2195            SlowQueriesRecordType::SystemTable,
2196            event_recorder.clone(),
2197        );
2198        let timeout_recorder = timer.recorder();
2199        let plan: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(Arc::new(Schema::empty())));
2200        let (finish_tx, finish_rx) = oneshot::channel();
2201        let stream = PendingRecordBatchStream {
2202            schema: Arc::new(GtSchema::new(vec![])),
2203            polled_tx: None,
2204            _finish_tx: finish_tx,
2205            finish_rx: Box::pin(finish_rx),
2206        };
2207        let output = Output::new(
2208            OutputData::Stream(Box::pin(stream)),
2209            OutputMeta::new_with_plan(plan),
2210        );
2211        let output =
2212            attach_timeout(output, Duration::from_millis(10), Some(timeout_recorder)).unwrap();
2213        let OutputData::Stream(mut stream) = output.data else {
2214            unreachable!();
2215        };
2216
2217        let err = stream.next().await.unwrap().unwrap_err();
2218        assert_eq!(err.to_string(), "Stream timeout");
2219        drop(stream);
2220        drop(timer);
2221
2222        let payloads = event_recorder.payloads.lock().unwrap();
2223        assert_eq!(payloads.len(), 1);
2224        assert_eq!(payloads[0]["timed_out"], true);
2225        assert!(
2226            payloads[0]["metrics"]
2227                .as_array()
2228                .is_some_and(|metrics| !metrics.is_empty())
2229        );
2230    }
2231
2232    struct PendingDataSource {
2233        schema: GtSchemaRef,
2234        polled_tx: std::sync::Mutex<Option<oneshot::Sender<()>>>,
2235    }
2236
2237    impl DataSource for PendingDataSource {
2238        fn get_stream(
2239            &self,
2240            _request: ScanRequest,
2241        ) -> std::result::Result<SendableRecordBatchStream, BoxedError> {
2242            let (finish_tx, finish_rx) = oneshot::channel();
2243            let mut polled_tx = self.polled_tx.lock().map_err(|_| {
2244                BoxedError::new(PlainError::new(
2245                    "pending data source lock poisoned".to_string(),
2246                    StatusCode::Unexpected,
2247                ))
2248            })?;
2249            Ok(Box::pin(PendingRecordBatchStream {
2250                schema: self.schema.clone(),
2251                polled_tx: polled_tx.take(),
2252                _finish_tx: finish_tx,
2253                finish_rx: Box::pin(finish_rx),
2254            }))
2255        }
2256    }
2257
2258    struct NoopProcedureExecutor;
2259
2260    #[async_trait::async_trait]
2261    impl ProcedureExecutor for NoopProcedureExecutor {
2262        async fn submit_ddl_task(
2263            &self,
2264            _ctx: &ExecutorContext,
2265            _request: SubmitDdlTaskRequest,
2266        ) -> common_meta::error::Result<SubmitDdlTaskResponse> {
2267            common_meta::error::UnsupportedSnafu {
2268                operation: "submit_ddl_task",
2269            }
2270            .fail()
2271        }
2272
2273        async fn migrate_region(
2274            &self,
2275            _ctx: &ExecutorContext,
2276            _request: MigrateRegionRequest,
2277        ) -> common_meta::error::Result<MigrateRegionResponse> {
2278            common_meta::error::UnsupportedSnafu {
2279                operation: "migrate_region",
2280            }
2281            .fail()
2282        }
2283
2284        async fn reconcile(
2285            &self,
2286            _ctx: &ExecutorContext,
2287            _request: ReconcileRequest,
2288        ) -> common_meta::error::Result<ReconcileResponse> {
2289            common_meta::error::UnsupportedSnafu {
2290                operation: "reconcile",
2291            }
2292            .fail()
2293        }
2294
2295        async fn query_procedure_state(
2296            &self,
2297            _ctx: &ExecutorContext,
2298            _pid: &str,
2299        ) -> common_meta::error::Result<ProcedureStateResponse> {
2300            common_meta::error::UnsupportedSnafu {
2301                operation: "query_procedure_state",
2302            }
2303            .fail()
2304        }
2305
2306        async fn list_procedures(
2307            &self,
2308            _ctx: &ExecutorContext,
2309        ) -> common_meta::error::Result<ProcedureDetailResponse> {
2310            common_meta::error::UnsupportedSnafu {
2311                operation: "list_procedures",
2312            }
2313            .fail()
2314        }
2315    }
2316
2317    /// A test [`ProcedureExecutor`] that completes create/drop DDL tasks against the
2318    /// in-memory catalog, mimicking what the meta DDL procedures do in production.
2319    /// This allows happy-path DDL requests (create/drop table/view) to be exercised
2320    /// end to end through the gRPC ingress.
2321    struct MockProcedureExecutor {
2322        catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
2323        next_table_id: std::sync::atomic::AtomicU32,
2324        submitted: std::sync::Mutex<Vec<DdlTask>>,
2325    }
2326
2327    impl MockProcedureExecutor {
2328        fn new(catalog_manager: Arc<catalog::memory::MemoryCatalogManager>) -> Self {
2329            Self {
2330                catalog_manager,
2331                next_table_id: std::sync::atomic::AtomicU32::new(1026),
2332                submitted: std::sync::Mutex::new(Vec::new()),
2333            }
2334        }
2335    }
2336
2337    #[async_trait::async_trait]
2338    impl ProcedureExecutor for MockProcedureExecutor {
2339        async fn submit_ddl_task(
2340            &self,
2341            _ctx: &ExecutorContext,
2342            request: SubmitDdlTaskRequest,
2343        ) -> common_meta::error::Result<SubmitDdlTaskResponse> {
2344            self.submitted.lock().unwrap().push(request.task.clone());
2345            match request.task {
2346                DdlTask::CreateTable(task) => {
2347                    let table_id = self
2348                        .next_table_id
2349                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2350                    let mut table_info = task.table_info;
2351                    table_info.ident.table_id = table_id;
2352                    self.catalog_manager
2353                        .register_table_sync(catalog::RegisterTableRequest {
2354                            catalog: table_info.catalog_name.clone(),
2355                            schema: table_info.schema_name.clone(),
2356                            table_name: table_info.name.clone(),
2357                            table_id,
2358                            table: table::dist_table::DistTable::table(Arc::new(table_info)),
2359                        })
2360                        .map_err(BoxedError::new)
2361                        .context(common_meta::error::ExternalSnafu)?;
2362                    Ok(SubmitDdlTaskResponse {
2363                        key: Vec::new(),
2364                        table_ids: vec![table_id],
2365                    })
2366                }
2367                DdlTask::CreateView(task) => {
2368                    let view_id = self
2369                        .next_table_id
2370                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2371                    let mut view_info = task.view_info;
2372                    view_info.ident.table_id = view_id;
2373                    self.catalog_manager
2374                        .register_table_sync(catalog::RegisterTableRequest {
2375                            catalog: task.create_view.catalog_name.clone(),
2376                            schema: task.create_view.schema_name.clone(),
2377                            table_name: task.create_view.view_name.clone(),
2378                            table_id: view_id,
2379                            table: table::dist_table::DistTable::table(Arc::new(view_info)),
2380                        })
2381                        .map_err(BoxedError::new)
2382                        .context(common_meta::error::ExternalSnafu)?;
2383                    Ok(SubmitDdlTaskResponse {
2384                        key: Vec::new(),
2385                        table_ids: vec![view_id],
2386                    })
2387                }
2388                DdlTask::DropView(task) => {
2389                    self.catalog_manager
2390                        .deregister_table_sync(catalog::DeregisterTableRequest {
2391                            catalog: task.catalog.clone(),
2392                            schema: task.schema.clone(),
2393                            table_name: task.view.clone(),
2394                        })
2395                        .map_err(BoxedError::new)
2396                        .context(common_meta::error::ExternalSnafu)?;
2397                    Ok(SubmitDdlTaskResponse::default())
2398                }
2399                other => common_meta::error::UnsupportedSnafu {
2400                    operation: format!("mock submit_ddl_task: {other:?}"),
2401                }
2402                .fail(),
2403            }
2404        }
2405
2406        async fn migrate_region(
2407            &self,
2408            _ctx: &ExecutorContext,
2409            _request: MigrateRegionRequest,
2410        ) -> common_meta::error::Result<MigrateRegionResponse> {
2411            common_meta::error::UnsupportedSnafu {
2412                operation: "migrate_region",
2413            }
2414            .fail()
2415        }
2416
2417        async fn reconcile(
2418            &self,
2419            _ctx: &ExecutorContext,
2420            _request: ReconcileRequest,
2421        ) -> common_meta::error::Result<ReconcileResponse> {
2422            common_meta::error::UnsupportedSnafu {
2423                operation: "reconcile",
2424            }
2425            .fail()
2426        }
2427
2428        async fn query_procedure_state(
2429            &self,
2430            _ctx: &ExecutorContext,
2431            _pid: &str,
2432        ) -> common_meta::error::Result<ProcedureStateResponse> {
2433            common_meta::error::UnsupportedSnafu {
2434                operation: "query_procedure_state",
2435            }
2436            .fail()
2437        }
2438
2439        async fn list_procedures(
2440            &self,
2441            _ctx: &ExecutorContext,
2442        ) -> common_meta::error::Result<ProcedureDetailResponse> {
2443            common_meta::error::UnsupportedSnafu {
2444                operation: "list_procedures",
2445            }
2446            .fail()
2447        }
2448    }
2449
2450    fn test_cache_registry(
2451        kv_backend: common_meta::kv_backend::KvBackendRef,
2452    ) -> TestResult<common_meta::cache::LayeredCacheRegistryRef> {
2453        Ok(Arc::new(
2454            cache::with_default_composite_cache_registry(
2455                LayeredCacheRegistryBuilder::default()
2456                    .add_cache_registry(cache::build_fundamental_cache_registry(kv_backend)),
2457            )
2458            .context(BuildCacheRegistrySnafu)?
2459            .build(),
2460        ))
2461    }
2462
2463    fn test_table_info(table_id: u32, table_name: &str) -> TestResult<TableInfo> {
2464        let schema = Arc::new(GtSchema::new(vec![
2465            ColumnSchema::new("id", ConcreteDataType::int32_datatype(), false),
2466            ColumnSchema::new(
2467                "ts",
2468                ConcreteDataType::timestamp_millisecond_datatype(),
2469                false,
2470            )
2471            .with_time_index(true),
2472        ]));
2473        let table_meta = TableMetaBuilder::empty()
2474            .schema(schema)
2475            .primary_key_indices(vec![0])
2476            .value_indices(vec![1])
2477            .next_column_id(1024)
2478            .build()
2479            .with_context(|_| BuildTableMetaSnafu {
2480                table_name: table_name.to_string(),
2481            })?;
2482
2483        TableInfoBuilder::new(table_name, table_meta)
2484            .table_id(table_id)
2485            .build()
2486            .with_context(|_| BuildTableInfoSnafu {
2487                table_name: table_name.to_string(),
2488            })
2489    }
2490
2491    fn test_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
2492        let table_info = test_table_info(table_id, table_name)?;
2493        Ok(EmptyTable::from_table_info(&table_info))
2494    }
2495
2496    fn test_physical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
2497        let mut table_info = test_table_info(table_id, table_name)?;
2498        table_info
2499            .meta
2500            .options
2501            .extra_options
2502            .insert(PHYSICAL_TABLE_METADATA_KEY.to_string(), String::new());
2503        Ok(EmptyTable::from_table_info(&table_info))
2504    }
2505
2506    fn test_logical_table(table_id: u32, table_name: &str) -> TestResult<table::TableRef> {
2507        let mut table_info = test_table_info(table_id, table_name)?;
2508        table_info.meta.engine = METRIC_ENGINE_NAME.to_string();
2509        table_info.meta.options.extra_options.insert(
2510            LOGICAL_TABLE_METADATA_KEY.to_string(),
2511            "physical_metric".to_string(),
2512        );
2513        Ok(EmptyTable::from_table_info(&table_info))
2514    }
2515
2516    fn test_metric_names_table() -> TableRef {
2517        let schema = Arc::new(GtSchema::new(vec![
2518            ColumnSchema::new("table_catalog", ConcreteDataType::string_datatype(), false),
2519            ColumnSchema::new("table_schema", ConcreteDataType::string_datatype(), false),
2520            ColumnSchema::new("table_name", ConcreteDataType::string_datatype(), false),
2521            ColumnSchema::new("engine", ConcreteDataType::string_datatype(), false),
2522            ColumnSchema::new("create_options", ConcreteDataType::string_datatype(), false),
2523        ]));
2524        let columns: Vec<VectorRef> = vec![
2525            Arc::new(StringVector::from(vec!["greptime", "greptime"])),
2526            Arc::new(StringVector::from(vec!["public", "public"])),
2527            Arc::new(StringVector::from(vec!["denied", "target"])),
2528            Arc::new(StringVector::from(vec!["metric", "metric"])),
2529            Arc::new(StringVector::from(vec![
2530                "on_physical_table=physical_metric",
2531                "on_physical_table=physical_metric",
2532            ])),
2533        ];
2534        let record_batch = RecordBatch::new(schema, columns).unwrap();
2535        MemTable::new_with_catalog(
2536            "tables",
2537            record_batch,
2538            2048,
2539            "greptime".to_string(),
2540            "information_schema".to_string(),
2541        )
2542    }
2543
2544    fn test_pipeline_table() -> TableRef {
2545        let schema = Arc::new(GtSchema::new(vec![
2546            ColumnSchema::new("name", ConcreteDataType::string_datatype(), false),
2547            ColumnSchema::new("schema", ConcreteDataType::string_datatype(), false),
2548            ColumnSchema::new("content_type", ConcreteDataType::string_datatype(), false),
2549            ColumnSchema::new("pipeline", ConcreteDataType::string_datatype(), false),
2550            ColumnSchema::new(
2551                "created_at",
2552                ConcreteDataType::timestamp_nanosecond_datatype(),
2553                false,
2554            )
2555            .with_time_index(true),
2556        ]));
2557        let columns: Vec<VectorRef> = vec![
2558            Arc::new(StringVector::from(vec!["pipeline"])),
2559            Arc::new(StringVector::from(vec!["public"])),
2560            Arc::new(StringVector::from(vec!["application/yaml"])),
2561            Arc::new(StringVector::from(vec![
2562                "transform:\n- field: ts\n  type: timestamp, ns\n  index: time\n",
2563            ])),
2564            Arc::new(TimestampNanosecondVector::from_values([1])),
2565        ];
2566        let record_batch = RecordBatch::new(schema, columns).unwrap();
2567        MemTable::new_with_catalog(
2568            "pipelines",
2569            record_batch,
2570            2049,
2571            "greptime".to_string(),
2572            DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
2573        )
2574    }
2575
2576    fn pending_table(
2577        table_id: u32,
2578        table_name: &str,
2579        polled_tx: oneshot::Sender<()>,
2580    ) -> TestResult<table::TableRef> {
2581        let table_info = test_table_info(table_id, table_name)?;
2582        let data_source = Arc::new(PendingDataSource {
2583            schema: table_info.meta.schema.clone(),
2584            polled_tx: std::sync::Mutex::new(Some(polled_tx)),
2585        });
2586
2587        Ok(Arc::new(Table::new(
2588            Arc::new(table_info),
2589            FilterPushDownType::Unsupported,
2590            data_source,
2591        )))
2592    }
2593
2594    async fn test_instance_with_tables(
2595        source_table: TableRef,
2596        target_table: TableRef,
2597    ) -> TestResult<Instance> {
2598        test_instance_with_plugins(source_table, target_table, Plugins::new()).await
2599    }
2600
2601    async fn test_instance_with_insert_select_interceptor(
2602        interceptor: SqlQueryInterceptorRef<Error>,
2603    ) -> TestResult<Instance> {
2604        let plugins = Plugins::new();
2605        plugins.insert::<SqlQueryInterceptorRef<Error>>(interceptor);
2606
2607        test_instance_with_plugins(
2608            test_table(1024, "source")?,
2609            test_table(1025, "target")?,
2610            plugins,
2611        )
2612        .await
2613    }
2614
2615    async fn test_instance_with_plugins(
2616        source_table: TableRef,
2617        target_table: TableRef,
2618        plugins: Plugins,
2619    ) -> TestResult<Instance> {
2620        test_instance_with_plugins_and_metric_names(source_table, target_table, plugins, None).await
2621    }
2622
2623    async fn test_instance_with_plugins_and_metric_names(
2624        source_table: TableRef,
2625        target_table: TableRef,
2626        plugins: Plugins,
2627        metric_names_table: Option<TableRef>,
2628    ) -> TestResult<Instance> {
2629        let catalog_manager = catalog::memory::MemoryCatalogManager::new_with_table(source_table);
2630        test_instance_with_catalog_manager(
2631            catalog_manager,
2632            target_table,
2633            plugins,
2634            metric_names_table,
2635            Arc::new(NoopProcedureExecutor),
2636        )
2637        .await
2638    }
2639
2640    /// Builds a test frontend `Instance` over the given (already source-registered)
2641    /// catalog manager, completing DDL tasks through `procedure_executor`.
2642    async fn test_instance_with_catalog_manager(
2643        catalog_manager: Arc<catalog::memory::MemoryCatalogManager>,
2644        target_table: TableRef,
2645        plugins: Plugins,
2646        metric_names_table: Option<TableRef>,
2647        procedure_executor: ProcedureExecutorRef,
2648    ) -> TestResult<Instance> {
2649        let kv_backend = Arc::new(MemoryKvBackend::new());
2650        let process_manager = Arc::new(ProcessManager::new("test-frontend".to_string(), None));
2651        let target_table_name = "target";
2652        catalog_manager
2653            .register_table_sync(catalog::RegisterTableRequest {
2654                catalog: "greptime".to_string(),
2655                schema: "public".to_string(),
2656                table_name: target_table_name.to_string(),
2657                table_id: 1025,
2658                table: target_table,
2659            })
2660            .with_context(|_| RegisterTableSnafu {
2661                table_name: target_table_name.to_string(),
2662            })?;
2663        if let Some(table) = metric_names_table {
2664            catalog_manager
2665                .deregister_table_sync(catalog::DeregisterTableRequest {
2666                    catalog: "greptime".to_string(),
2667                    schema: "information_schema".to_string(),
2668                    table_name: "tables".to_string(),
2669                })
2670                .unwrap();
2671            catalog_manager
2672                .register_table_sync(catalog::RegisterTableRequest {
2673                    catalog: "greptime".to_string(),
2674                    schema: "information_schema".to_string(),
2675                    table_name: "tables".to_string(),
2676                    table_id: 2048,
2677                    table,
2678                })
2679                .unwrap();
2680        }
2681        catalog_manager.register_process_list_table(process_manager.clone());
2682
2683        let cache_registry = test_cache_registry(kv_backend.clone())?;
2684
2685        FrontendBuilder::new(
2686            FrontendOptions::default(),
2687            kv_backend,
2688            cache_registry,
2689            catalog_manager,
2690            Arc::new(client::client_manager::NodeClients::default()),
2691            procedure_executor,
2692            process_manager,
2693        )
2694        .with_plugin(plugins)
2695        .try_build()
2696        .await
2697        .context(BuildFrontendSnafu)
2698    }
2699
2700    async fn execute_one_sql(
2701        instance: &Instance,
2702        sql: &str,
2703        query_ctx: QueryContextRef,
2704    ) -> TestResult<Output> {
2705        let mut results = instance.do_query_inner(sql, query_ctx).await;
2706        ensure!(
2707            results.len() == 1,
2708            UnexpectedOutputCountSnafu {
2709                sql: sql.to_string(),
2710                actual: results.len(),
2711            }
2712        );
2713        results.remove(0).with_context(|_| ExecuteSqlSnafu {
2714            sql: sql.to_string(),
2715        })
2716    }
2717
2718    fn assert_permission_denied<T>(result: servers::error::Result<T>) {
2719        let err = match result {
2720            Ok(_) => panic!("request should be rejected"),
2721            Err(err) => err,
2722        };
2723        assert_eq!(StatusCode::PermissionDenied, err.status_code());
2724    }
2725
2726    fn assert_action_checked(
2727        checker: &RejectEndpointPermissionChecker,
2728        action: PermissionAction,
2729        targets: Option<PermissionTableTargets>,
2730    ) {
2731        assert_eq!(CheckedAction { action, targets }, checker.take_check());
2732    }
2733
2734    #[tokio::test]
2735    async fn test_prom_remote_read_with_custom_timestamp_and_value_columns() -> TestResult<()> {
2736        let schema = Arc::new(GtSchema::new(vec![
2737            ColumnSchema::new(
2738                "custom_ts",
2739                ConcreteDataType::timestamp_millisecond_datatype(),
2740                false,
2741            )
2742            .with_time_index(true),
2743            ColumnSchema::new("custom_value", ConcreteDataType::float64_datatype(), false),
2744        ]));
2745        let recordbatch = RecordBatch::new(
2746            schema,
2747            vec![
2748                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
2749                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
2750            ],
2751        )
2752        .unwrap();
2753        let instance = test_instance_with_tables(
2754            MemTable::table("custom_metric", recordbatch),
2755            test_table(1025, "target")?,
2756        )
2757        .await?;
2758
2759        let response = PromStoreProtocolHandler::read(
2760            &instance,
2761            ReadRequest {
2762                queries: vec![RemoteQuery {
2763                    start_timestamp_ms: 1500,
2764                    end_timestamp_ms: 2500,
2765                    matchers: vec![LabelMatcher {
2766                        r#type: PromMatcherType::Eq as i32,
2767                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
2768                        value: "custom_metric".to_string(),
2769                    }],
2770                    ..Default::default()
2771                }],
2772                ..Default::default()
2773            },
2774            test_query_ctx(1),
2775        )
2776        .await
2777        .unwrap();
2778        let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
2779        let response = ReadResponse::decode(body.as_slice()).unwrap();
2780
2781        assert_eq!(1, response.results.len());
2782        assert_eq!(1, response.results[0].timeseries.len());
2783        let timeseries = &response.results[0].timeseries[0];
2784        assert_eq!(
2785            vec![Label {
2786                name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
2787                value: "custom_metric".to_string(),
2788            }],
2789            timeseries.labels
2790        );
2791        assert_eq!(
2792            vec![Sample {
2793                value: 2.0,
2794                timestamp: 2000,
2795            }],
2796            timeseries.samples
2797        );
2798
2799        Ok(())
2800    }
2801
2802    #[tokio::test]
2803    async fn test_prom_remote_read_prefers_default_value_column() -> TestResult<()> {
2804        let schema = Arc::new(GtSchema::new(vec![
2805            ColumnSchema::new(
2806                "custom_ts",
2807                ConcreteDataType::timestamp_millisecond_datatype(),
2808                false,
2809            )
2810            .with_time_index(true),
2811            ColumnSchema::new("extra_field", ConcreteDataType::float64_datatype(), false),
2812            ColumnSchema::new(
2813                greptime_value(),
2814                ConcreteDataType::float64_datatype(),
2815                false,
2816            ),
2817        ]));
2818        let recordbatch = RecordBatch::new(
2819            schema,
2820            vec![
2821                Arc::new(TimestampMillisecondVector::from_vec(vec![1000, 2000, 3000])) as VectorRef,
2822                Arc::new(Float64Vector::from_vec(vec![99.0, 99.0, 99.0])) as VectorRef,
2823                Arc::new(Float64Vector::from_vec(vec![1.0, 2.0, 3.0])) as VectorRef,
2824            ],
2825        )
2826        .unwrap();
2827        let instance = test_instance_with_tables(
2828            MemTable::table("multi_field_metric", recordbatch),
2829            test_table(1025, "target")?,
2830        )
2831        .await?;
2832
2833        let response = PromStoreProtocolHandler::read(
2834            &instance,
2835            ReadRequest {
2836                queries: vec![RemoteQuery {
2837                    start_timestamp_ms: 1500,
2838                    end_timestamp_ms: 2500,
2839                    matchers: vec![LabelMatcher {
2840                        r#type: PromMatcherType::Eq as i32,
2841                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
2842                        value: "multi_field_metric".to_string(),
2843                    }],
2844                    ..Default::default()
2845                }],
2846                ..Default::default()
2847            },
2848            test_query_ctx(1),
2849        )
2850        .await
2851        .unwrap();
2852        let body = servers::prom_store::snappy_decompress(&response.body).unwrap();
2853        let response = ReadResponse::decode(body.as_slice()).unwrap();
2854
2855        assert_eq!(1, response.results.len());
2856        assert_eq!(1, response.results[0].timeseries.len());
2857        let timeseries = &response.results[0].timeseries[0];
2858        assert_eq!(
2859            vec![
2860                Label {
2861                    name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
2862                    value: "multi_field_metric".to_string(),
2863                },
2864                Label {
2865                    name: "extra_field".to_string(),
2866                    value: "99".to_string(),
2867                },
2868            ],
2869            timeseries.labels
2870        );
2871        assert_eq!(
2872            vec![Sample {
2873                value: 2.0,
2874                timestamp: 2000,
2875            }],
2876            timeseries.samples
2877        );
2878
2879        Ok(())
2880    }
2881
2882    #[tokio::test]
2883    async fn test_prom_remote_read_rejects_ambiguous_value_columns() -> TestResult<()> {
2884        let schema = Arc::new(GtSchema::new(vec![
2885            ColumnSchema::new(
2886                "custom_ts",
2887                ConcreteDataType::timestamp_millisecond_datatype(),
2888                false,
2889            )
2890            .with_time_index(true),
2891            ColumnSchema::new("field_a", ConcreteDataType::float64_datatype(), false),
2892            ColumnSchema::new("field_b", ConcreteDataType::float64_datatype(), false),
2893        ]));
2894        let recordbatch = RecordBatch::new(
2895            schema,
2896            vec![
2897                Arc::new(TimestampMillisecondVector::from_vec(vec![1000])) as VectorRef,
2898                Arc::new(Float64Vector::from_vec(vec![1.0])) as VectorRef,
2899                Arc::new(Float64Vector::from_vec(vec![2.0])) as VectorRef,
2900            ],
2901        )
2902        .unwrap();
2903        let instance = test_instance_with_tables(
2904            MemTable::table("ambiguous_metric", recordbatch),
2905            test_table(1025, "target")?,
2906        )
2907        .await?;
2908
2909        let err = PromStoreProtocolHandler::read(
2910            &instance,
2911            ReadRequest {
2912                queries: vec![RemoteQuery {
2913                    matchers: vec![LabelMatcher {
2914                        r#type: PromMatcherType::Eq as i32,
2915                        name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
2916                        value: "ambiguous_metric".to_string(),
2917                    }],
2918                    ..Default::default()
2919                }],
2920                ..Default::default()
2921            },
2922            test_query_ctx(1),
2923        )
2924        .await
2925        .err()
2926        .expect("ambiguous value columns should fail remote read");
2927
2928        assert_eq!(StatusCode::InvalidArguments, err.status_code());
2929        assert!(format!("{err:?}").contains("Ambiguous value column"));
2930
2931        Ok(())
2932    }
2933
2934    #[tokio::test]
2935    async fn test_event_recorder_is_exposed() -> TestResult<()> {
2936        let instance =
2937            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
2938                .await?;
2939
2940        let _event_recorder = instance.event_recorder();
2941
2942        Ok(())
2943    }
2944
2945    #[tokio::test]
2946    async fn test_restricted_endpoint_handlers_check_permissions() -> TestResult<()> {
2947        let checker = Arc::new(RejectEndpointPermissionChecker::default());
2948        let plugins = Plugins::new();
2949        plugins.insert::<PermissionCheckerRef>(checker.clone());
2950        let instance = test_instance_with_plugins(
2951            test_table(1024, "denied")?,
2952            test_table(1025, "target")?,
2953            plugins,
2954        )
2955        .await?;
2956        let mut ctx = test_query_ctx(1);
2957        Arc::get_mut(&mut ctx).unwrap().set_extension(
2958            servers::http::jaeger::JAEGER_QUERY_TABLE_NAME_KEY,
2959            "denied".to_string(),
2960        );
2961        let jaeger_targets = Some(PermissionTableTargets::resolved(vec![
2962            PermissionTableTarget::new("greptime", "public", "denied"),
2963        ]));
2964
2965        assert_permission_denied(JaegerQueryHandler::get_services(&instance, ctx.clone()).await);
2966        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
2967        assert_permission_denied(
2968            JaegerQueryHandler::get_operations(&instance, ctx.clone(), "service", None).await,
2969        );
2970        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
2971        assert_permission_denied(
2972            JaegerQueryHandler::get_trace(&instance, ctx.clone(), "trace", None, None, None).await,
2973        );
2974        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets.clone());
2975        assert_permission_denied(
2976            JaegerQueryHandler::find_traces(
2977                &instance,
2978                ctx.clone(),
2979                servers::http::jaeger::QueryTraceParams {
2980                    service_name: "service".to_string(),
2981                    ..Default::default()
2982                },
2983            )
2984            .await,
2985        );
2986        assert_action_checked(&checker, JAEGER_QUERY, jaeger_targets);
2987
2988        assert_permission_denied(
2989            PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
2990        );
2991        assert_action_checked(&checker, PIPELINE_QUERY, None);
2992        assert_permission_denied(
2993            PipelineHandler::insert_pipeline(
2994                &instance,
2995                "pipeline",
2996                "application/yaml",
2997                "",
2998                ctx.clone(),
2999            )
3000            .await,
3001        );
3002        assert_action_checked(&checker, PIPELINE_INSERT, None);
3003        assert_permission_denied(
3004            PipelineHandler::delete_pipeline(&instance, "pipeline", None, ctx.clone()).await,
3005        );
3006        assert_action_checked(&checker, PIPELINE_DELETE, None);
3007        let app = axum::Router::new()
3008            .route(
3009                "/pipelines/_dryrun",
3010                axum::routing::post(servers::http::event::pipeline_dryrun),
3011            )
3012            .with_state(servers::http::event::LogState {
3013                log_handler: Arc::new(instance.clone()),
3014                log_validator: None,
3015                ingest_interceptor: None,
3016            })
3017            .layer(axum::Extension((*ctx).clone()));
3018        let response = app
3019            .oneshot(
3020                axum::http::Request::post("/pipelines/_dryrun")
3021                    .header("content-type", "application/json")
3022                    .body(axum::body::Body::from("{}"))
3023                    .unwrap(),
3024            )
3025            .await
3026            .unwrap();
3027        assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
3028        assert_action_checked(&checker, PIPELINE_QUERY, None);
3029
3030        assert_permission_denied(
3031            DashboardHandler::save(&instance, "dashboard", "{}", ctx.clone()).await,
3032        );
3033        assert_action_checked(&checker, DASHBOARD_SAVE, None);
3034        assert_permission_denied(DashboardHandler::list(&instance, ctx.clone()).await);
3035        assert_action_checked(&checker, DASHBOARD_QUERY, None);
3036        assert_permission_denied(
3037            DashboardHandler::delete(&instance, "dashboard", ctx.clone()).await,
3038        );
3039        assert_action_checked(&checker, DASHBOARD_DELETE, None);
3040
3041        Ok(())
3042    }
3043
3044    #[tokio::test]
3045    async fn test_write_only_ingestion_loads_named_pipeline() -> TestResult<()> {
3046        let plugins = Plugins::new();
3047        plugins.insert::<PermissionCheckerRef>(Arc::new(WriteOnlyPermissionChecker));
3048        let instance = test_instance_with_plugins(
3049            test_table(1024, "source")?,
3050            test_table(1025, "target")?,
3051            plugins,
3052        )
3053        .await?;
3054        instance
3055            .catalog_manager()
3056            .as_any()
3057            .downcast_ref::<catalog::memory::MemoryCatalogManager>()
3058            .unwrap()
3059            .register_table_sync(catalog::RegisterTableRequest {
3060                catalog: "greptime".to_string(),
3061                schema: DEFAULT_PRIVATE_SCHEMA_NAME.to_string(),
3062                table_name: "pipelines".to_string(),
3063                table_id: 2049,
3064                table: test_pipeline_table(),
3065            })
3066            .with_context(|_| RegisterTableSnafu {
3067                table_name: "pipelines".to_string(),
3068            })?;
3069        let ctx = test_query_ctx(1);
3070        let handler: PipelineHandlerRef = Arc::new(instance.clone());
3071
3072        handler
3073            .get_pipeline("pipeline", None, ctx.clone())
3074            .await
3075            .unwrap();
3076        assert_permission_denied(
3077            PipelineHandler::get_pipeline_str(&instance, "pipeline", None, ctx.clone()).await,
3078        );
3079
3080        let app = axum::Router::new()
3081            .route(
3082                "/pipelines/_dryrun",
3083                axum::routing::post(servers::http::event::pipeline_dryrun),
3084            )
3085            .with_state(servers::http::event::LogState {
3086                log_handler: handler,
3087                log_validator: None,
3088                ingest_interceptor: None,
3089            })
3090            .layer(axum::Extension((*ctx).clone()));
3091        let response = app
3092            .oneshot(
3093                axum::http::Request::post("/pipelines/_dryrun")
3094                    .header("content-type", "application/json")
3095                    .body(axum::body::Body::from("{}"))
3096                    .unwrap(),
3097            )
3098            .await
3099            .unwrap();
3100        assert_eq!(axum::http::StatusCode::FORBIDDEN, response.status());
3101
3102        Ok(())
3103    }
3104
3105    #[tokio::test]
3106    async fn test_target_independent_checker_skips_target_resolution() -> TestResult<()> {
3107        let physical_table = "physical_metric";
3108        let checker = Arc::new(TargetIndependentPermissionChecker::default());
3109        let plugins = Plugins::new();
3110        plugins.insert::<PermissionCheckerRef>(checker.clone());
3111        let instance = test_instance_with_plugins(
3112            test_physical_table(1024, physical_table)?,
3113            test_table(1025, "target")?,
3114            plugins,
3115        )
3116        .await?;
3117
3118        let ctx = test_query_ctx(1);
3119        let physical_target = PermissionTableTarget::new("greptime", "public", physical_table);
3120        assert_eq!(
3121            PermissionTableTargets::Resolved(vec![physical_target.clone()]),
3122            instance
3123                .resolve_query_permission_targets(
3124                    PermissionTableTargets::resolved(vec![physical_target]),
3125                    &ctx,
3126                )
3127                .await
3128                .unwrap()
3129        );
3130        assert_eq!(
3131            vec![physical_table.to_string(), "target".to_string()],
3132            PrometheusHandler::filter_metadata_metric_names(
3133                &instance,
3134                vec![physical_table.to_string(), "target".to_string()],
3135                "public",
3136                &ctx,
3137            )
3138            .await
3139            .unwrap()
3140        );
3141        assert_eq!(1, checker.checks.load(atomic::Ordering::Relaxed));
3142
3143        Ok(())
3144    }
3145
3146    #[tokio::test]
3147    async fn test_query_permission_targets_are_deduplicated() -> TestResult<()> {
3148        let plugins = Plugins::new();
3149        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
3150        let instance = test_instance_with_plugins(
3151            test_table(1024, "source")?,
3152            test_table(1025, "target")?,
3153            plugins,
3154        )
3155        .await?;
3156        let ctx = test_query_ctx(1);
3157        let target = PermissionTableTarget::new("greptime", "public", "target");
3158
3159        assert_eq!(
3160            PermissionTableTargets::Resolved(vec![target.clone()]),
3161            instance
3162                .resolve_query_permission_targets(
3163                    PermissionTableTargets::resolved(vec![target.clone(), target]),
3164                    &ctx,
3165                )
3166                .await
3167                .unwrap()
3168        );
3169
3170        Ok(())
3171    }
3172
3173    #[tokio::test]
3174    async fn test_physical_query_targets_fail_closed() -> TestResult<()> {
3175        let physical_table = "physical_metric";
3176        let plugins = Plugins::new();
3177        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
3178        let instance = test_instance_with_plugins(
3179            test_physical_table(1024, physical_table)?,
3180            test_table(1025, "target")?,
3181            plugins,
3182        )
3183        .await?;
3184
3185        let ctx = test_query_ctx(1);
3186        let logical_target = PermissionTableTarget::new("greptime", "public", "target");
3187        assert_eq!(
3188            PermissionTableTargets::Resolved(vec![logical_target.clone()]),
3189            instance
3190                .resolve_query_permission_targets(
3191                    PermissionTableTargets::resolved(vec![logical_target.clone()]),
3192                    &ctx,
3193                )
3194                .await
3195                .unwrap()
3196        );
3197        let physical_target = PermissionTableTarget::new("greptime", "public", physical_table);
3198        assert_eq!(
3199            PermissionTableTargets::Unresolved,
3200            instance
3201                .resolve_query_permission_targets(
3202                    PermissionTableTargets::resolved(
3203                        vec![logical_target, physical_target.clone(),]
3204                    ),
3205                    &ctx,
3206                )
3207                .await
3208                .unwrap()
3209        );
3210        assert_eq!(
3211            vec!["target".to_string()],
3212            PrometheusHandler::filter_metadata_metric_names(
3213                &instance,
3214                vec!["target".to_string(), "denied".to_string()],
3215                "public",
3216                &ctx,
3217            )
3218            .await
3219            .unwrap()
3220        );
3221
3222        let query = PromQuery {
3223            query: physical_table.to_string(),
3224            ..Default::default()
3225        };
3226        let err = PrometheusHandler::check_query_target_permission(
3227            &instance,
3228            PermissionTableTargets::resolved(vec![physical_target]),
3229            &ctx,
3230        )
3231        .await
3232        .unwrap_err();
3233        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3234        let err = PrometheusHandler::check_query_permission(
3235            &instance,
3236            std::slice::from_ref(&query),
3237            &ctx,
3238        )
3239        .await
3240        .unwrap_err();
3241        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3242        let err = PrometheusHandler::do_query(&instance, &query, ctx.clone())
3243            .await
3244            .unwrap_err();
3245        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3246
3247        for sql in [
3248            "SELECT * FROM physical_metric",
3249            "TQL EVAL (0, 10, '5s') physical_metric",
3250            "INSERT INTO target SELECT * FROM physical_metric",
3251        ] {
3252            let mut results = instance.do_query_inner(sql, ctx.clone()).await;
3253            assert_eq!(1, results.len(), "{sql}");
3254            let err = results.remove(0).unwrap_err();
3255            assert_eq!(StatusCode::PermissionDenied, err.status_code(), "{sql}");
3256        }
3257        let err = LogQueryHandler::query(
3258            &instance,
3259            LogQuery {
3260                table: TableName::new("greptime", "public", physical_table),
3261                ..Default::default()
3262            },
3263            ctx.clone(),
3264        )
3265        .await
3266        .unwrap_err();
3267        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3268        let err = instance
3269            .do_describe_inner(parse_one_sql("SELECT * FROM physical_metric"), ctx.clone())
3270            .await
3271            .unwrap_err();
3272        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3273
3274        let request = ReadRequest {
3275            queries: vec![RemoteQuery {
3276                matchers: vec![LabelMatcher {
3277                    r#type: PromMatcherType::Eq as i32,
3278                    name: servers::prom_store::METRIC_NAME_LABEL.to_string(),
3279                    value: physical_table.to_string(),
3280                }],
3281                ..Default::default()
3282            }],
3283            ..Default::default()
3284        };
3285        let Err(err) = PromStoreProtocolHandler::read(&instance, request, ctx.clone()).await else {
3286            panic!("physical remote-read target must be rejected");
3287        };
3288        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3289
3290        let err = PrometheusHandler::query_label_values(
3291            &instance,
3292            physical_table.to_string(),
3293            "host".to_string(),
3294            vec![],
3295            SystemTime::UNIX_EPOCH,
3296            SystemTime::UNIX_EPOCH,
3297            &ctx,
3298        )
3299        .await
3300        .unwrap_err();
3301        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3302
3303        Ok(())
3304    }
3305
3306    #[tokio::test]
3307    async fn test_non_exact_query_discovery_keeps_denied_targets_for_batch_check() -> TestResult<()>
3308    {
3309        let plugins = Plugins::new();
3310        plugins.insert::<PermissionCheckerRef>(Arc::new(RejectUnresolvedPermissionChecker));
3311        let instance = test_instance_with_plugins_and_metric_names(
3312            test_logical_table(1024, "denied")?,
3313            test_logical_table(1025, "target")?,
3314            plugins,
3315            Some(test_metric_names_table()),
3316        )
3317        .await?;
3318        let ctx = test_query_ctx(1);
3319
3320        let mut metric_names = PrometheusHandler::query_metric_names(
3321            &instance,
3322            vec![Matcher::new(
3323                promql_parser::label::MatchOp::NotEqual,
3324                "__name__",
3325                "",
3326            )],
3327            "public",
3328            &ctx,
3329        )
3330        .await
3331        .unwrap();
3332        metric_names.sort_unstable();
3333        assert_eq!(
3334            vec!["denied".to_string(), "target".to_string()],
3335            metric_names
3336        );
3337
3338        let queries = metric_names
3339            .into_iter()
3340            .map(|query| PromQuery {
3341                query,
3342                ..Default::default()
3343            })
3344            .collect::<Vec<_>>();
3345        let err = PrometheusHandler::check_query_permission(&instance, &queries, &ctx)
3346            .await
3347            .unwrap_err();
3348        assert_eq!(StatusCode::PermissionDenied, err.status_code());
3349
3350        Ok(())
3351    }
3352
3353    #[test]
3354    fn test_fast_legacy_check_is_read_only() {
3355        let cache = DashMap::new();
3356        cache.insert("metric1".to_string(), true);
3357
3358        let names = vec!["metric1".to_string(), "metric2".to_string()];
3359        assert_eq!(Some(true), fast_legacy_check(&cache, &names).unwrap());
3360        assert!(!cache.contains_key("metric2"));
3361
3362        cache_legacy_mode(&cache, &names, true).unwrap();
3363        assert!(*cache.get("metric2").unwrap().value());
3364        assert!(cache_legacy_mode(&cache, &names, false).is_err());
3365        assert!(*cache.get("metric2").unwrap().value());
3366
3367        let cache_incompatible = DashMap::new();
3368        cache_incompatible.insert("metric1".to_string(), true);
3369        cache_incompatible.insert("metric2".to_string(), false);
3370        assert!(fast_legacy_check(&cache_incompatible, &names).is_err());
3371    }
3372
3373    #[test]
3374    fn test_should_track_statement_process() {
3375        assert!(should_track_statement_process(&parse_one_sql(
3376            "SELECT * FROM demo"
3377        )));
3378        assert!(should_track_statement_process(&parse_one_sql(
3379            "INSERT INTO demo SELECT * FROM source"
3380        )));
3381        assert!(!should_track_statement_process(&parse_one_sql(
3382            "INSERT INTO demo VALUES (1)"
3383        )));
3384        assert!(!should_track_statement_process(&parse_one_sql(
3385            "INSERT INTO demo VALUES (now())"
3386        )));
3387    }
3388
3389    #[test]
3390    fn test_should_track_plan_process() {
3391        let select_stmt = parse_one_sql("SELECT * FROM demo");
3392        let insert_select_stmt = parse_one_sql("INSERT INTO demo SELECT * FROM source");
3393        let insert_values_stmt = parse_one_sql("INSERT INTO demo VALUES (now())");
3394
3395        let empty_plan = LogicalPlanBuilder::empty(false).build().unwrap();
3396        assert!(should_track_plan_process(Some(&select_stmt), &empty_plan));
3397        assert!(should_track_plan_process(
3398            Some(&insert_select_stmt),
3399            &insert_dml_plan()
3400        ));
3401        assert!(!should_track_plan_process(
3402            Some(&insert_values_stmt),
3403            &insert_dml_plan()
3404        ));
3405        assert!(!should_track_plan_process(None, &insert_dml_plan()));
3406    }
3407
3408    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3409    async fn test_insert_select_is_visible_in_show_processlist() -> TestResult<()> {
3410        let insert_sql = "INSERT INTO target SELECT * FROM source";
3411        let (started_tx, mut started_rx) = mpsc::unbounded_channel();
3412        let (finish_tx, finish_rx) = oneshot::channel();
3413        let interceptor = Arc::new(BlockingInsertSelectInterceptor::new(started_tx, finish_rx));
3414        let instance = Arc::new(test_instance_with_insert_select_interceptor(interceptor).await?);
3415
3416        let insert_task = tokio::spawn({
3417            let instance = instance.clone();
3418            async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
3419        });
3420
3421        tokio::time::timeout(Duration::from_secs(5), started_rx.recv())
3422            .await
3423            .context(InsertStartTimeoutSnafu)?
3424            .context(InsertStartChannelClosedSnafu)?;
3425
3426        let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
3427        let process_list = output.data.pretty_print().await;
3428        assert!(
3429            process_list.contains(insert_sql),
3430            "process list did not contain running insert:\n{process_list}"
3431        );
3432
3433        finish_tx
3434            .send(())
3435            .map_err(|_| ReleaseBlockedInsertSnafu.build())?;
3436        insert_task.await.context(InsertTaskPanicSnafu)??;
3437
3438        Ok(())
3439    }
3440
3441    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3442    async fn test_kill_query_cancels_insert_select() -> TestResult<()> {
3443        assert_kill_cancels_insert_select("KILL QUERY 4242").await
3444    }
3445
3446    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3447    async fn test_kill_process_id_cancels_insert_select() -> TestResult<()> {
3448        assert_kill_cancels_insert_select("KILL 'test-frontend/4242'").await
3449    }
3450
3451    async fn assert_kill_cancels_insert_select(kill_sql: &str) -> TestResult<()> {
3452        let insert_sql = "INSERT INTO target SELECT * FROM source";
3453        let (source_polled_tx, source_polled_rx) = oneshot::channel();
3454        let instance = Arc::new(
3455            test_instance_with_tables(
3456                pending_table(1024, "source", source_polled_tx)?,
3457                test_table(1025, "target")?,
3458            )
3459            .await?,
3460        );
3461
3462        let insert_task = tokio::spawn({
3463            let instance = instance.clone();
3464            async move { execute_one_sql(&instance, insert_sql, test_query_ctx(4242)).await }
3465        });
3466
3467        tokio::time::timeout(Duration::from_secs(5), source_polled_rx)
3468            .await
3469            .context(SourcePollTimeoutSnafu)?
3470            .context(SourcePollChannelClosedSnafu)?;
3471
3472        let output = execute_one_sql(&instance, kill_sql, test_query_ctx(43)).await?;
3473        assert!(matches!(output.data, OutputData::AffectedRows(1)));
3474
3475        let insert_result = tokio::time::timeout(Duration::from_secs(5), insert_task)
3476            .await
3477            .context(InsertTaskTimeoutSnafu)?
3478            .context(InsertTaskPanicSnafu)?;
3479        let err = match insert_result {
3480            Ok(_) => return InsertSelectNotCancelledSnafu.fail(),
3481            Err(TestError::ExecuteSql { source, .. }) => source,
3482            Err(err) => return Err(err),
3483        };
3484        assert_eq!(StatusCode::Cancelled, err.status_code());
3485
3486        let output = execute_one_sql(&instance, "SHOW PROCESSLIST", test_query_ctx(43)).await?;
3487        let process_list = output.data.pretty_print().await;
3488        assert!(
3489            !process_list.contains(insert_sql),
3490            "process list still contains killed insert:\n{process_list}"
3491        );
3492
3493        Ok(())
3494    }
3495
3496    fn insert_dml_plan() -> LogicalPlan {
3497        let schema = SchemaRef::new(Schema::new(vec![Field::new(
3498            "value",
3499            DataType::Int64,
3500            true,
3501        )]));
3502        let target = Arc::new(LogicalTableSource::new(schema));
3503        let input = LogicalPlanBuilder::empty(false).build().unwrap();
3504
3505        LogicalPlanBuilder::insert_into(input, "demo", target, InsertOp::Append)
3506            .unwrap()
3507            .build()
3508            .unwrap()
3509    }
3510
3511    #[test]
3512    fn test_exec_validation() {
3513        let query_ctx = QueryContext::arc();
3514        let plugins: Plugins = Plugins::new();
3515        plugins.insert(QueryOptions {
3516            disallow_cross_catalog_query: true,
3517        });
3518
3519        let sql = r#"
3520        SELECT * FROM demo;
3521        EXPLAIN SELECT * FROM demo;
3522        CREATE DATABASE test_database;
3523        SHOW DATABASES;
3524        "#;
3525        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
3526        assert_eq!(stmts.len(), 4);
3527        for stmt in stmts {
3528            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
3529            re.unwrap();
3530        }
3531
3532        let sql = r#"
3533        SHOW CREATE TABLE demo;
3534        ALTER TABLE demo ADD COLUMN new_col INT;
3535        "#;
3536        let stmts = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
3537        assert_eq!(stmts.len(), 2);
3538        for stmt in stmts {
3539            let re = check_permission(plugins.clone(), &stmt, &query_ctx);
3540            re.unwrap();
3541        }
3542
3543        fn replace_test(template_sql: &str, plugins: Plugins, query_ctx: &QueryContextRef) {
3544            // test right
3545            let right = vec![("", ""), ("", "public."), ("greptime.", "public.")];
3546            for (catalog, schema) in right {
3547                let sql = do_fmt(template_sql, catalog, schema);
3548                do_test(&sql, plugins.clone(), query_ctx, true);
3549            }
3550
3551            let wrong = vec![
3552                ("wrongcatalog.", "public."),
3553                ("wrongcatalog.", "wrongschema."),
3554            ];
3555            for (catalog, schema) in wrong {
3556                let sql = do_fmt(template_sql, catalog, schema);
3557                do_test(&sql, plugins.clone(), query_ctx, false);
3558            }
3559        }
3560
3561        fn do_fmt(template: &str, catalog: &str, schema: &str) -> String {
3562            let vars = HashMap::from([
3563                ("catalog".to_string(), catalog),
3564                ("schema".to_string(), schema),
3565            ]);
3566            template.format(&vars).unwrap()
3567        }
3568
3569        fn do_test(sql: &str, plugins: Plugins, query_ctx: &QueryContextRef, is_ok: bool) {
3570            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
3571            let re = check_permission(plugins, stmt, query_ctx);
3572            if is_ok {
3573                re.unwrap();
3574            } else {
3575                assert!(re.is_err());
3576            }
3577        }
3578
3579        // test insert
3580        let sql = "INSERT INTO {catalog}{schema}monitor(host) VALUES ('host1');";
3581        replace_test(sql, plugins.clone(), &query_ctx);
3582
3583        // test create table
3584        let sql = r#"CREATE TABLE {catalog}{schema}demo(
3585                            host STRING,
3586                            ts TIMESTAMP,
3587                            TIME INDEX (ts),
3588                            PRIMARY KEY(host)
3589                        ) engine=mito;"#;
3590        replace_test(sql, plugins.clone(), &query_ctx);
3591
3592        // test drop table
3593        let sql = "DROP TABLE {catalog}{schema}demo;";
3594        replace_test(sql, plugins.clone(), &query_ctx);
3595
3596        // test undrop table
3597        #[cfg(feature = "enterprise")]
3598        {
3599            let sql = "UNDROP TABLE {catalog}{schema}demo;";
3600            replace_test(sql, plugins.clone(), &query_ctx);
3601        }
3602
3603        // test show tables
3604        let sql = "SHOW TABLES FROM public";
3605        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
3606        check_permission(plugins.clone(), &stmt[0], &query_ctx).unwrap();
3607
3608        let sql = "SHOW TABLES FROM private";
3609        let stmt = parse_stmt(sql, &GreptimeDbDialect {}).unwrap();
3610        let re = check_permission(plugins.clone(), &stmt[0], &query_ctx);
3611        assert!(re.is_ok());
3612
3613        // test describe table
3614        let sql = "DESC TABLE {catalog}{schema}demo;";
3615        replace_test(sql, plugins.clone(), &query_ctx);
3616
3617        let comment_flow_cases = [
3618            ("COMMENT ON FLOW my_flow IS 'comment';", true),
3619            ("COMMENT ON FLOW greptime.my_flow IS 'comment';", true),
3620            ("COMMENT ON FLOW wrongcatalog.my_flow IS 'comment';", false),
3621        ];
3622        for (sql, is_ok) in comment_flow_cases {
3623            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
3624            let result = check_permission(plugins.clone(), stmt, &query_ctx);
3625            assert_eq!(result.is_ok(), is_ok);
3626        }
3627
3628        let show_flow_cases = [
3629            ("SHOW CREATE FLOW my_flow;", true),
3630            ("SHOW CREATE FLOW greptime.my_flow;", true),
3631            ("SHOW CREATE FLOW wrongcatalog.my_flow;", false),
3632        ];
3633        for (sql, is_ok) in show_flow_cases {
3634            let stmt = &parse_stmt(sql, &GreptimeDbDialect {}).unwrap()[0];
3635            let result = check_permission(plugins.clone(), stmt, &query_ctx);
3636            assert_eq!(result.is_ok(), is_ok);
3637        }
3638    }
3639
3640    /// A `DropView` DDL sent through the direct gRPC ingress must return an error
3641    /// (e.g. table not found) instead of panicking on `todo!()`.
3642    #[tokio::test]
3643    async fn qx_152_drop_view_via_grpc_ddl_returns_error_not_panic() -> TestResult<()> {
3644        let instance =
3645            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
3646                .await?;
3647
3648        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3649            expr: Some(api::v1::ddl_request::Expr::DropView(
3650                api::v1::DropViewExpr {
3651                    catalog_name: String::new(),
3652                    schema_name: String::new(),
3653                    view_name: "non_existent_view".to_string(),
3654                    view_id: None,
3655                    drop_if_exists: false,
3656                },
3657            )),
3658        });
3659
3660        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
3661            &instance,
3662            request,
3663            QueryContext::arc(),
3664        )
3665        .await;
3666
3667        let err = match result {
3668            Ok(_) => panic!("DropView DDL request must return an error instead of panicking"),
3669            Err(err) => err,
3670        };
3671        assert_eq!(
3672            err.status_code(),
3673            StatusCode::TableNotFound,
3674            "dropping a non-existent view without IF EXISTS must report TableNotFound, got {err}"
3675        );
3676        Ok(())
3677    }
3678
3679    /// `DROP VIEW IF EXISTS` on a missing view through the direct gRPC ingress must
3680    /// succeed with 0 affected rows (no error, no DDL task submitted), instead of
3681    /// returning `TableNotFound`.
3682    #[tokio::test]
3683    async fn qx_152_drop_view_if_exists_missing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
3684        let catalog_manager =
3685            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
3686        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
3687        let instance = test_instance_with_catalog_manager(
3688            catalog_manager,
3689            test_table(1025, "target")?,
3690            Plugins::new(),
3691            None,
3692            procedure_executor.clone() as ProcedureExecutorRef,
3693        )
3694        .await?;
3695
3696        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3697            expr: Some(api::v1::ddl_request::Expr::DropView(
3698                api::v1::DropViewExpr {
3699                    catalog_name: String::new(),
3700                    schema_name: String::new(),
3701                    view_name: "non_existent_view".to_string(),
3702                    view_id: None,
3703                    drop_if_exists: true,
3704                },
3705            )),
3706        });
3707
3708        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
3709            &instance,
3710            request,
3711            QueryContext::arc(),
3712        )
3713        .await;
3714
3715        let output = match result {
3716            Ok(output) => output,
3717            Err(err) => {
3718                panic!("DROP VIEW IF EXISTS on a missing view must succeed, got error: {err}")
3719            }
3720        };
3721        assert!(
3722            matches!(output.data, OutputData::AffectedRows(0)),
3723            "DROP VIEW IF EXISTS on a missing view must report 0 affected rows"
3724        );
3725        assert!(
3726            procedure_executor.submitted.lock().unwrap().is_empty(),
3727            "DROP VIEW IF EXISTS on a missing view must not submit a DDL task"
3728        );
3729        Ok(())
3730    }
3731
3732    /// A `CREATE VIEW` followed by `DROP VIEW` through the direct gRPC ingress must
3733    /// succeed end to end: the view is registered in the catalog and then removed.
3734    #[tokio::test]
3735    async fn qx_152_drop_existing_view_via_grpc_ddl_succeeds() -> TestResult<()> {
3736        let catalog_manager =
3737            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
3738        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
3739        let instance = test_instance_with_catalog_manager(
3740            catalog_manager,
3741            test_table(1025, "target")?,
3742            Plugins::new(),
3743            None,
3744            procedure_executor.clone() as ProcedureExecutorRef,
3745        )
3746        .await?;
3747
3748        // The default "greptime.public" schema must be visible to the kv-backed table
3749        // metadata manager for `CREATE VIEW`/`CREATE TABLE` to pass validation.
3750        instance
3751            .table_metadata_manager()
3752            .schema_manager()
3753            .create(
3754                common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
3755                None,
3756                true,
3757            )
3758            .await
3759            .unwrap();
3760
3761        let create_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3762            expr: Some(api::v1::ddl_request::Expr::CreateView(
3763                api::v1::CreateViewExpr {
3764                    catalog_name: String::new(),
3765                    schema_name: String::new(),
3766                    view_name: "my_view".to_string(),
3767                    logical_plan: vec![1, 2, 3],
3768                    create_if_not_exists: false,
3769                    or_replace: false,
3770                    table_names: vec![],
3771                    columns: vec![],
3772                    plan_columns: vec![],
3773                    definition: "CREATE VIEW my_view AS SELECT * FROM source".to_string(),
3774                },
3775            )),
3776        });
3777
3778        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
3779            &instance,
3780            create_view_request,
3781            QueryContext::arc(),
3782        )
3783        .await
3784        {
3785            Ok(output) => output,
3786            Err(err) => panic!("CREATE VIEW via gRPC DDL must succeed, got error: {err}"),
3787        };
3788        assert!(
3789            matches!(output.data, OutputData::AffectedRows(0)),
3790            "CREATE VIEW via gRPC DDL must report 0 affected rows"
3791        );
3792
3793        // The view is registered in the catalog as a view.
3794        let view = instance
3795            .catalog_manager()
3796            .table("greptime", "public", "my_view", None)
3797            .await
3798            .unwrap()
3799            .expect("view should exist after CREATE VIEW");
3800        assert_eq!(view.table_info().table_type, TableType::View);
3801
3802        let drop_view_request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3803            expr: Some(api::v1::ddl_request::Expr::DropView(
3804                api::v1::DropViewExpr {
3805                    catalog_name: String::new(),
3806                    schema_name: String::new(),
3807                    view_name: "my_view".to_string(),
3808                    view_id: None,
3809                    drop_if_exists: false,
3810                },
3811            )),
3812        });
3813
3814        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
3815            &instance,
3816            drop_view_request,
3817            QueryContext::arc(),
3818        )
3819        .await
3820        {
3821            Ok(output) => output,
3822            Err(err) => panic!("DROP VIEW via gRPC DDL must succeed, got error: {err}"),
3823        };
3824        assert!(
3825            matches!(output.data, OutputData::AffectedRows(0)),
3826            "DROP VIEW via gRPC DDL must report 0 affected rows"
3827        );
3828
3829        // The view is gone after the drop.
3830        assert!(
3831            instance
3832                .catalog_manager()
3833                .table("greptime", "public", "my_view", None)
3834                .await
3835                .unwrap()
3836                .is_none(),
3837            "view should be removed after DROP VIEW"
3838        );
3839
3840        let submitted = procedure_executor.submitted.lock().unwrap();
3841        assert_eq!(
3842            submitted.len(),
3843            2,
3844            "expected create and drop view tasks, got {submitted:?}"
3845        );
3846        assert!(matches!(&submitted[0], DdlTask::CreateView(_)));
3847        assert!(matches!(&submitted[1], DdlTask::DropView(_)));
3848        Ok(())
3849    }
3850
3851    /// A direct gRPC `CreateTable` whose time index column is not a timestamp must
3852    /// be rejected with `InvalidArguments` instead of panicking while building the schema.
3853    #[tokio::test]
3854    async fn qx_153_create_table_with_non_timestamp_time_index_via_grpc_returns_error()
3855    -> TestResult<()> {
3856        let instance =
3857            test_instance_with_tables(test_table(1024, "source")?, test_table(1025, "target")?)
3858                .await?;
3859
3860        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3861            expr: Some(api::v1::ddl_request::Expr::CreateTable(
3862                api::v1::CreateTableExpr {
3863                    catalog_name: String::new(),
3864                    schema_name: String::new(),
3865                    table_name: "demo".to_string(),
3866                    desc: String::new(),
3867                    column_defs: vec![api::v1::ColumnDef {
3868                        name: "host".to_string(),
3869                        data_type: api::v1::ColumnDataType::String as i32,
3870                        is_nullable: true,
3871                        default_constraint: vec![],
3872                        semantic_type: 0,
3873                        comment: String::new(),
3874                        datatype_extension: None,
3875                        options: None,
3876                    }],
3877                    time_index: "host".to_string(),
3878                    primary_keys: vec![],
3879                    create_if_not_exists: false,
3880                    table_options: HashMap::new(),
3881                    table_id: None,
3882                    engine: "mito".to_string(),
3883                },
3884            )),
3885        });
3886
3887        let result = servers::query_handler::grpc::GrpcQueryHandler::do_query(
3888            &instance,
3889            request,
3890            QueryContext::arc(),
3891        )
3892        .await;
3893
3894        let err = match result {
3895            Ok(_) => panic!("CreateTable with a non-timestamp time index must be rejected"),
3896            Err(err) => err,
3897        };
3898        assert_eq!(err.status_code(), StatusCode::InvalidArguments, "{err}");
3899        Ok(())
3900    }
3901
3902    /// A valid `CREATE TABLE` (timestamp time index) through the direct gRPC ingress
3903    /// must succeed, guarding that the `validate_create_expr` ingress check doesn't
3904    /// accidentally reject good requests.
3905    #[tokio::test]
3906    async fn qx_153_create_table_with_timestamp_time_index_via_grpc_succeeds() -> TestResult<()> {
3907        let catalog_manager =
3908            catalog::memory::MemoryCatalogManager::new_with_table(test_table(1024, "source")?);
3909        let procedure_executor = Arc::new(MockProcedureExecutor::new(catalog_manager.clone()));
3910        let instance = test_instance_with_catalog_manager(
3911            catalog_manager,
3912            test_table(1025, "target")?,
3913            Plugins::new(),
3914            None,
3915            procedure_executor.clone() as ProcedureExecutorRef,
3916        )
3917        .await?;
3918
3919        // The default "greptime.public" schema must be visible to the kv-backed table
3920        // metadata manager for `CREATE TABLE` to pass validation.
3921        instance
3922            .table_metadata_manager()
3923            .schema_manager()
3924            .create(
3925                common_meta::key::schema_name::SchemaNameKey::new("greptime", "public"),
3926                None,
3927                true,
3928            )
3929            .await
3930            .unwrap();
3931
3932        let request = api::v1::greptime_request::Request::Ddl(api::v1::DdlRequest {
3933            expr: Some(api::v1::ddl_request::Expr::CreateTable(
3934                api::v1::CreateTableExpr {
3935                    catalog_name: String::new(),
3936                    schema_name: String::new(),
3937                    table_name: "demo".to_string(),
3938                    desc: String::new(),
3939                    column_defs: vec![
3940                        api::v1::ColumnDef {
3941                            name: "host".to_string(),
3942                            data_type: api::v1::ColumnDataType::String as i32,
3943                            is_nullable: true,
3944                            default_constraint: vec![],
3945                            semantic_type: 0,
3946                            comment: String::new(),
3947                            datatype_extension: None,
3948                            options: None,
3949                        },
3950                        api::v1::ColumnDef {
3951                            name: "ts".to_string(),
3952                            data_type: api::v1::ColumnDataType::TimestampMillisecond as i32,
3953                            is_nullable: true,
3954                            default_constraint: vec![],
3955                            semantic_type: 0,
3956                            comment: String::new(),
3957                            datatype_extension: None,
3958                            options: None,
3959                        },
3960                    ],
3961                    time_index: "ts".to_string(),
3962                    primary_keys: vec![],
3963                    create_if_not_exists: false,
3964                    table_options: HashMap::new(),
3965                    table_id: None,
3966                    engine: "mito".to_string(),
3967                },
3968            )),
3969        });
3970
3971        let output = match servers::query_handler::grpc::GrpcQueryHandler::do_query(
3972            &instance,
3973            request,
3974            QueryContext::arc(),
3975        )
3976        .await
3977        {
3978            Ok(output) => output,
3979            Err(err) => panic!("CREATE TABLE via gRPC DDL must succeed, got error: {err}"),
3980        };
3981        assert!(
3982            matches!(output.data, OutputData::AffectedRows(0)),
3983            "CREATE TABLE via gRPC DDL must report 0 affected rows"
3984        );
3985
3986        // The table is registered in the catalog.
3987        let table = instance
3988            .catalog_manager()
3989            .table("greptime", "public", "demo", None)
3990            .await
3991            .unwrap()
3992            .expect("table should exist after CREATE TABLE");
3993        assert_eq!(table.table_info().table_type, TableType::Base);
3994
3995        let submitted = procedure_executor.submitted.lock().unwrap();
3996        assert_eq!(
3997            submitted.len(),
3998            1,
3999            "expected one create table task, got {submitted:?}"
4000        );
4001        assert!(matches!(&submitted[0], DdlTask::CreateTable(_)));
4002        Ok(())
4003    }
4004}