Skip to main content

servers/mysql/
handler.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
15use std::collections::HashMap;
16use std::net::SocketAddr;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU32, Ordering};
19use std::time::Duration;
20
21use ::auth::{BEARER_TOKEN_USER, Identity, MysqlAuthMethod, Password, UserProviderRef};
22use async_trait::async_trait;
23use chrono::{NaiveDate, NaiveDateTime};
24use common_catalog::parse_optional_catalog_and_schema_from_db_string;
25use common_error::ext::ErrorExt;
26use common_frontend::metrics;
27use common_query::Output;
28use common_telemetry::{debug, error, tracing, warn};
29use common_time::Timezone;
30use datafusion_common::{ParamValues, ScalarValue};
31use datafusion_expr::LogicalPlan;
32use datatypes::prelude::ConcreteDataType;
33use datatypes::schema::Schema;
34use itertools::Itertools;
35use mysql_common::Value as MysqlValue;
36use opensrv_mysql::{
37    AsyncMysqlShim, Column, ErrorKind, InitWriter, ParamParser, ParamValue, QueryResultWriter,
38    StatementMetaWriter, ValueInner,
39};
40use parking_lot::RwLock;
41use query::planner::DfLogicalPlanner;
42use query::query_engine::DescribeResult;
43use rand::RngCore;
44use session::context::{Channel, QueryContextRef};
45use session::{Session, SessionRef};
46use snafu::{ResultExt, ensure};
47use sql::dialect::MySqlDialect;
48use sql::parser::{ParseOptions, ParserContext};
49use sql::statements::statement::Statement;
50use tokio::io::AsyncWrite;
51
52use crate::SqlPlan;
53use crate::error::{
54    self, DataFrameSnafu, InferParameterTypesSnafu, InvalidPrepareStatementSnafu, Result,
55};
56use crate::metrics::METRIC_AUTH_FAILURE;
57use crate::mysql::helper::{self, format_placeholder, transform_placeholders_with_count};
58use crate::mysql::writer;
59use crate::mysql::writer::{create_mysql_column, handle_err};
60use crate::query_handler::sql::ServerSqlQueryHandlerRef;
61
62/// Parameters for the prepared statement
63enum Params<'a> {
64    /// Parameters passed through protocol
65    ProtocolParams(Vec<ParamValue<'a>>),
66    /// Parameters passed through cli
67    CliParams(Vec<sql::ast::Expr>),
68}
69
70impl Params<'_> {
71    fn len(&self) -> usize {
72        match self {
73            Params::ProtocolParams(params) => params.len(),
74            Params::CliParams(params) => params.len(),
75        }
76    }
77}
78
79// An intermediate shim for executing MySQL queries.
80pub struct MysqlInstanceShim {
81    query_handler: ServerSqlQueryHandlerRef,
82    salt: [u8; 20],
83    session: SessionRef,
84    user_provider: Option<UserProviderRef>,
85    prepared_stmts: Arc<RwLock<HashMap<String, SqlPlan>>>,
86    prepared_stmts_counter: AtomicU32,
87    process_id: u32,
88    prepared_stmt_cache_size: usize,
89    batching_enabled: bool,
90}
91
92impl MysqlInstanceShim {
93    pub fn create(
94        query_handler: ServerSqlQueryHandlerRef,
95        user_provider: Option<UserProviderRef>,
96        client_addr: SocketAddr,
97        process_id: u32,
98        prepared_stmt_cache_size: usize,
99    ) -> MysqlInstanceShim {
100        // init a random salt
101        let mut bs = vec![0u8; 20];
102        let mut rng = rand::rng();
103        rng.fill_bytes(bs.as_mut());
104
105        let mut scramble: [u8; 20] = [0; 20];
106        for i in 0..20 {
107            scramble[i] = bs[i] & 0x7fu8;
108            if scramble[i] == b'\0' || scramble[i] == b'$' {
109                scramble[i] += 1;
110            }
111        }
112
113        MysqlInstanceShim {
114            query_handler,
115            salt: scramble,
116            session: Arc::new(Session::new(
117                Some(client_addr),
118                Channel::Mysql,
119                Default::default(),
120                process_id,
121            )),
122            user_provider,
123            prepared_stmts: Default::default(),
124            prepared_stmts_counter: AtomicU32::new(1),
125            process_id,
126            prepared_stmt_cache_size,
127            batching_enabled: false,
128        }
129    }
130
131    /// Enables ordinary-table batching for this connection.
132    pub fn with_batching_enabled(mut self, enabled: bool) -> Self {
133        self.batching_enabled = enabled;
134        self
135    }
136
137    fn new_query_context(&self) -> QueryContextRef {
138        let mut ctx = self.session.new_query_context();
139        Arc::make_mut(&mut ctx).set_batching_enabled(self.batching_enabled);
140        ctx
141    }
142
143    #[tracing::instrument(skip_all, name = "mysql::do_query")]
144    async fn do_query(&self, query: &str, query_ctx: QueryContextRef) -> Vec<Result<Output>> {
145        if let Some(output) =
146            crate::mysql::federated::check(query, query_ctx.clone(), self.session.clone())
147        {
148            vec![Ok(output)]
149        } else {
150            self.query_handler.do_query(query, query_ctx.clone()).await
151        }
152    }
153
154    async fn authenticate_handshake_user(
155        &self,
156        auth_plugin: &str,
157        username: &str,
158        salt: &[u8],
159        auth_data: &[u8],
160        catalog: &str,
161    ) -> Option<auth::UserInfoRef> {
162        let Some(user_provider) = &self.user_provider else {
163            return Some(auth::userinfo_by_name(Some(username.to_string())));
164        };
165        let addr = self
166            .session
167            .conn_info()
168            .client_addr
169            .map(|addr| addr.to_string());
170        let result = if username == BEARER_TOKEN_USER {
171            if auth_plugin != MysqlAuthMethod::CLEAR_PASSWORD_PLUGIN {
172                warn!("Bearer-token MySQL authentication requires mysql_clear_password");
173                return None;
174            }
175            let token = auth_data.strip_suffix(&[0]).unwrap_or(auth_data);
176            let Ok(token) = std::str::from_utf8(token) else {
177                warn!("Bearer token is not valid UTF-8");
178                return None;
179            };
180            user_provider
181                .authenticate_bearer_token(token, catalog)
182                .await
183        } else {
184            let user_id = Identity::UserId(username, addr.as_deref());
185            let password = match auth_plugin {
186                MysqlAuthMethod::NATIVE_PASSWORD_PLUGIN => {
187                    Password::MysqlNativePassword(auth_data, salt)
188                }
189                MysqlAuthMethod::CLEAR_PASSWORD_PLUGIN => {
190                    // The raw bytes received could be represented in C-like string, ended in '\0'.
191                    // We must "trim" it to get the real password string.
192                    let password = auth_data.strip_suffix(&[0]).unwrap_or(auth_data);
193                    Password::PlainText(String::from_utf8_lossy(password).to_string().into())
194                }
195                other => {
196                    error!("Unsupported mysql auth plugin: {}", other);
197                    return None;
198                }
199            };
200            user_provider.authenticate(user_id, password).await
201        };
202        match result {
203            Ok(user_info) => Some(user_info),
204            Err(error) => {
205                METRIC_AUTH_FAILURE
206                    .with_label_values(&[error.status_code().as_ref()])
207                    .inc();
208                warn!(error; "Failed to auth");
209                None
210            }
211        }
212    }
213
214    // on_init can write an ERR without ending the handshake. Validate here before
215    // publishing the authenticated session or entering opensrv's command loop.
216    async fn select_handshake_database(
217        &self,
218        catalog: &str,
219        schema: String,
220        user_info: &auth::UserInfoRef,
221        explicit_database: bool,
222    ) -> Option<String> {
223        if let Some(provider) = &self.user_provider
224            && let Err(error) = provider.authorize(catalog, &schema, user_info).await
225        {
226            let denied = matches!(
227                error.status_code(),
228                common_error::status_code::StatusCode::AccessDenied
229                    | common_error::status_code::StatusCode::PermissionDenied
230            );
231            if !explicit_database && denied {
232                debug!(user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
233                    reason = %error.status_code(),
234                    "Default database not authorized; starting without a selected database");
235                return Some(String::new());
236            }
237            METRIC_AUTH_FAILURE
238                .with_label_values(&[error.status_code().as_ref()])
239                .inc();
240            if denied {
241                warn!(user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
242                    reason = %error.status_code(), "Handshake database authorization denied");
243            } else {
244                error!(error; user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
245                    "Handshake database authorization failed");
246            }
247            return None;
248        }
249        if !explicit_database && schema.is_empty() {
250            return Some(schema);
251        }
252        match self.query_handler.is_valid_schema(catalog, &schema).await {
253            Ok(true) => Some(schema),
254            Ok(false) if !explicit_database => {
255                debug!(user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
256                    "Default database does not exist; starting without a selected database");
257                Some(String::new())
258            }
259            Ok(false) => {
260                warn!(user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
261                    "Unknown MySQL handshake database");
262                None
263            }
264            Err(error) => {
265                error!(error; user = user_info.username(), protocol = "mysql", catalog, schema = %schema,
266                    "Failed to validate MySQL handshake database");
267                None
268            }
269        }
270    }
271
272    /// Describe the statement
273    async fn do_describe(
274        &self,
275        statement: Statement,
276        query_ctx: QueryContextRef,
277    ) -> Result<Option<DescribeResult>> {
278        self.query_handler.do_describe(statement, query_ctx).await
279    }
280
281    /// Save query and logical plan with a given statement key
282    fn save_plan(&self, plan: SqlPlan, stmt_key: String) -> Result<()> {
283        let mut prepared_stmts = self.prepared_stmts.write();
284        let max_capacity = self.prepared_stmt_cache_size;
285
286        let is_update = prepared_stmts.contains_key(&stmt_key);
287
288        if !is_update && prepared_stmts.len() >= max_capacity {
289            return error::InternalSnafu {
290                err_msg: format!(
291                    "Prepared statement cache is full, max capacity: {}",
292                    max_capacity
293                ),
294            }
295            .fail();
296        }
297
298        let _ = prepared_stmts.insert(stmt_key, plan);
299        Ok(())
300    }
301
302    /// Retrieve the query and logical plan by a given statement key
303    fn plan(&self, stmt_key: &str) -> Option<SqlPlan> {
304        let plan = self.prepared_stmts.read().get(stmt_key).cloned();
305        metrics::record_cache_lookup("mysql_prepared_stmt", plan.is_some());
306        plan
307    }
308
309    /// Save the prepared statement and return the parameters and result columns
310    async fn do_prepare(
311        &mut self,
312        raw_query: &str,
313        query_ctx: QueryContextRef,
314        stmt_key: String,
315    ) -> Result<(Vec<Column>, Vec<Column>)> {
316        if crate::mysql::federated::check(raw_query, query_ctx.clone(), self.session.clone())
317            .is_some()
318        {
319            self.save_plan(SqlPlan::Shortcut(raw_query.to_string()), stmt_key)
320                .inspect_err(|e| {
321                    error!(e; "Failed to save prepared statement");
322                })?;
323            return Ok((vec![], vec![]));
324        }
325
326        let statement = validate_query(raw_query).await?;
327
328        // We have to transform the placeholder, because DataFusion only parses placeholders
329        // in the form of "$i", it can't process "?" right now.
330        let (statement, placeholder_count) = transform_placeholders_with_count(statement);
331        let param_num = placeholder_count + 1;
332
333        let describe_result = self
334            .do_describe(statement.clone(), query_ctx.clone())
335            .await?;
336        let plan = describe_result.map(|DescribeResult { logical_plan }| logical_plan);
337
338        let (params, can_cache_as_plan) = if let Some(plan) = &plan {
339            let param_types = DfLogicalPlanner::get_inferred_parameter_types(plan)
340                .context(InferParameterTypesSnafu)?
341                .into_iter()
342                .map(|(k, v)| (k, v.map(|v| ConcreteDataType::from_arrow_type(&v))))
343                .collect();
344
345            (
346                prepared_params(&param_types, param_num)?,
347                all_params_have_types(&param_types, param_num),
348            )
349        } else {
350            (dummy_params(param_num)?, false)
351        };
352
353        let columns =
354            plan.as_ref()
355                .map(|plan| {
356                    let schema: Schema = plan.schema().clone().try_into().map_err(
357                        |e: datatypes::error::Error| {
358                            error::InternalSnafu {
359                                err_msg: e.to_string(),
360                            }
361                            .build()
362                        },
363                    )?;
364                    schema
365                        .column_schemas()
366                        .iter()
367                        .map(|column_schema| {
368                            create_mysql_column(&column_schema.data_type, &column_schema.name)
369                        })
370                        .collect::<Result<Vec<_>>>()
371                })
372                .transpose()?
373                .unwrap_or_default();
374
375        match plan {
376            Some(plan) if can_cache_as_plan => {
377                self.save_plan(SqlPlan::Plan(plan, statement), stmt_key)
378                    .inspect_err(|e| {
379                        error!(e; "Failed to save prepared statement");
380                    })?;
381            }
382            _ => {
383                self.save_plan(
384                    SqlPlan::Statement(statement, raw_query.to_string()),
385                    stmt_key,
386                )
387                .inspect_err(|e| {
388                    error!(e; "Failed to save prepared statement");
389                })?;
390            }
391        }
392
393        Ok((params, columns))
394    }
395
396    async fn do_execute(
397        &mut self,
398        query_ctx: QueryContextRef,
399        stmt_key: String,
400        params: Params<'_>,
401    ) -> Result<Vec<std::result::Result<Output, error::Error>>> {
402        let sql_plan = match self.plan(&stmt_key) {
403            None => {
404                return error::PrepareStatementNotFoundSnafu { name: stmt_key }.fail();
405            }
406            Some(sql_plan) => sql_plan,
407        };
408
409        let outputs = match sql_plan {
410            SqlPlan::Plan(plan, stmt) => {
411                let param_types = DfLogicalPlanner::get_inferred_parameter_types(&plan)
412                    .context(InferParameterTypesSnafu)?
413                    .into_iter()
414                    .map(|(k, v)| (k, v.map(|v| ConcreteDataType::from_arrow_type(&v))))
415                    .collect::<HashMap<_, _>>();
416
417                if params.len() != param_types.len() {
418                    return error::InternalSnafu {
419                        err_msg: "Prepare statement params number mismatch".to_string(),
420                    }
421                    .fail();
422                }
423
424                let timezone = query_ctx.timezone();
425                let replaced_plan = match params {
426                    Params::ProtocolParams(params) => {
427                        replace_params_with_values(&plan, param_types, &params, &timezone)
428                    }
429                    Params::CliParams(params) => {
430                        replace_params_with_exprs(&plan, param_types, &params, &timezone)
431                    }
432                }?;
433
434                debug!(
435                    "Mysql execute prepared plan: {}",
436                    replaced_plan.display_indent()
437                );
438                vec![
439                    self.query_handler
440                        .do_exec_plan(replaced_plan, Some(stmt), query_ctx.clone())
441                        .await,
442                ]
443            }
444            SqlPlan::Shortcut(query) => self.do_query(&query, query_ctx.clone()).await,
445            SqlPlan::Statement(stmt, query) => {
446                let param_strs = match params {
447                    Params::ProtocolParams(params) => {
448                        params.iter().map(convert_param_value_to_string).collect()
449                    }
450                    Params::CliParams(params) => params.iter().map(|x| x.to_string()).collect(),
451                };
452                debug!(
453                    "do_execute Replacing with Params: {:?}, Original Query: {}",
454                    param_strs, query
455                );
456                let query = replace_params(param_strs, stmt, query)?;
457                debug!("Mysql execute replaced query: {}", query);
458                self.do_query(&query, query_ctx.clone()).await
459            }
460            _ => {
461                return error::PrepareStatementNotFoundSnafu { name: stmt_key }.fail();
462            }
463        };
464
465        Ok(outputs)
466    }
467
468    /// Remove the prepared statement by a given statement key
469    fn do_close(&mut self, stmt_key: String) {
470        let mut guard = self.prepared_stmts.write();
471        let _ = guard.remove(&stmt_key);
472    }
473
474    fn auth_plugin(&self) -> &'static str {
475        self.user_provider
476            .as_ref()
477            .map(|provider| provider.mysql_auth_method())
478            .unwrap_or(MysqlAuthMethod::NativePassword)
479            .plugin_name()
480    }
481}
482
483#[async_trait]
484impl<W: AsyncWrite + Send + Sync + Unpin> AsyncMysqlShim<W> for MysqlInstanceShim {
485    type Error = error::Error;
486
487    fn version(&self) -> String {
488        std::env::var("GREPTIMEDB_MYSQL_SERVER_VERSION").unwrap_or_else(|_| "8.4.2".to_string())
489    }
490
491    fn connect_id(&self) -> u32 {
492        self.process_id
493    }
494
495    fn default_auth_plugin(&self) -> &str {
496        self.auth_plugin()
497    }
498
499    async fn auth_plugin_for_username(&self, user: &[u8]) -> &'static str {
500        if user == BEARER_TOKEN_USER.as_bytes() {
501            return MysqlAuthMethod::ClearPassword.plugin_name();
502        }
503        if let Some(provider) = &self.user_provider {
504            let username = String::from_utf8_lossy(user);
505            match provider.mysql_auth_method_for_user(&username).await {
506                Ok(method) => return method.plugin_name(),
507                // This hook cannot return an error. Keep the default challenge;
508                // authentication still validates the credentials separately.
509                Err(e) => warn!(e; "Failed to select MySQL authentication method"),
510            }
511        }
512        self.auth_plugin()
513    }
514
515    fn salt(&self) -> [u8; 20] {
516        self.salt
517    }
518
519    async fn authenticate(
520        &self,
521        auth_plugin: &str,
522        username: &[u8],
523        salt: &[u8],
524        auth_data: &[u8],
525    ) -> bool {
526        <Self as AsyncMysqlShim<W>>::authenticate_with_database(
527            self,
528            auth_plugin,
529            username,
530            salt,
531            auth_data,
532            None,
533        )
534        .await
535    }
536
537    async fn authenticate_with_database(
538        &self,
539        auth_plugin: &str,
540        username: &[u8],
541        salt: &[u8],
542        auth_data: &[u8],
543        database: Option<&[u8]>,
544    ) -> bool {
545        let database = match database.map(std::str::from_utf8).transpose() {
546            Ok(database) => database,
547            Err(_) => {
548                warn!("MySQL database is not valid UTF-8");
549                return false;
550            }
551        };
552        let (catalog, schema) = if let Some(database) = database {
553            let (catalog, schema) = parse_optional_catalog_and_schema_from_db_string(database);
554            (catalog.unwrap_or_else(|| self.session.catalog()), schema)
555        } else {
556            (self.session.catalog(), self.session.schema())
557        };
558        // if not specified then **greptime** will be used
559        let username = String::from_utf8_lossy(username);
560
561        let Some(user_info) = self
562            .authenticate_handshake_user(auth_plugin, &username, salt, auth_data, &catalog)
563            .await
564        else {
565            return false;
566        };
567        let Some(schema) = self
568            .select_handshake_database(&catalog, schema, &user_info, database.is_some())
569            .await
570        else {
571            return false;
572        };
573        self.session.set_catalog(catalog);
574        self.session.set_schema(schema);
575        self.session.set_user_info(user_info);
576        debug!(user = self.session.user_info().username(), protocol = "mysql",
577            catalog = %self.session.catalog(), schema = %self.session.schema(),
578            client_addr = ?self.session.conn_info().client_addr, "Handshake database selected");
579
580        true
581    }
582
583    async fn on_prepare<'a>(
584        &'a mut self,
585        raw_query: &'a str,
586        w: StatementMetaWriter<'a, W>,
587    ) -> Result<()> {
588        let query_ctx = self.new_query_context();
589        let stmt_id = self.prepared_stmts_counter.fetch_add(1, Ordering::Relaxed);
590        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
591        let (params, columns) = match self
592            .do_prepare(raw_query, query_ctx.clone(), stmt_key)
593            .await
594        {
595            Ok(x) => x,
596            Err(e) => {
597                let (kind, msg) = handle_err(e, query_ctx.clone());
598                w.error(kind, msg.as_bytes()).await?;
599                return Ok(());
600            }
601        };
602        debug!("on_prepare: Params: {:?}, Columns: {:?}", params, columns);
603        w.reply(stmt_id, &params, &columns).await?;
604        crate::metrics::METRIC_MYSQL_PREPARED_COUNT
605            .with_label_values(&[query_ctx.get_db_string().as_str()])
606            .inc();
607        return Ok(());
608    }
609
610    async fn on_execute<'a>(
611        &'a mut self,
612        stmt_id: u32,
613        p: ParamParser<'a>,
614        w: QueryResultWriter<'a, W>,
615    ) -> Result<()> {
616        self.session.clear_warnings();
617
618        let query_ctx = self.new_query_context();
619        let db = query_ctx.get_db_string();
620        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
621            .with_label_values(&[crate::metrics::METRIC_MYSQL_BINQUERY, db.as_str()])
622            .start_timer();
623
624        let params: Vec<ParamValue> = p.into_iter().collect();
625        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
626
627        let outputs = match self
628            .do_execute(query_ctx.clone(), stmt_key, Params::ProtocolParams(params))
629            .await
630        {
631            Ok(outputs) => outputs,
632            Err(e) => {
633                let (kind, err) = handle_err(e, query_ctx);
634                debug!(
635                    "Failed to execute prepared statement, kind: {:?}, err: {}",
636                    kind, err
637                );
638                w.error(kind, err.as_bytes()).await?;
639                return Ok(());
640            }
641        };
642
643        writer::write_output(w, query_ctx, self.session.clone(), outputs).await?;
644
645        Ok(())
646    }
647
648    async fn on_close<'a>(&'a mut self, stmt_id: u32)
649    where
650        W: 'async_trait,
651    {
652        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
653        self.do_close(stmt_key);
654    }
655
656    #[tracing::instrument(skip_all, fields(protocol = "mysql"))]
657    async fn on_query<'a>(
658        &'a mut self,
659        query: &'a str,
660        writer: QueryResultWriter<'a, W>,
661    ) -> Result<()> {
662        let query_ctx = self.new_query_context();
663        let db = query_ctx.get_db_string();
664        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
665            .with_label_values(&[crate::metrics::METRIC_MYSQL_TEXTQUERY, db.as_str()])
666            .start_timer();
667
668        // Clear warnings for non SHOW WARNINGS queries
669        let query_upcase = query.to_uppercase();
670        if !query_upcase.starts_with("SHOW WARNINGS") {
671            self.session.clear_warnings();
672        }
673
674        if query_upcase.starts_with("PREPARE ") {
675            match ParserContext::parse_mysql_prepare_stmt(query, query_ctx.sql_dialect()) {
676                Ok((stmt_name, stmt)) => {
677                    let prepare_results =
678                        self.do_prepare(&stmt, query_ctx.clone(), stmt_name).await;
679                    match prepare_results {
680                        Ok(_) => {
681                            let outputs = vec![Ok(Output::new_with_affected_rows(0))];
682                            writer::write_output(writer, query_ctx, self.session.clone(), outputs)
683                                .await?;
684                            return Ok(());
685                        }
686                        Err(e) => {
687                            let kind = if writer::is_no_database_selected(&e) {
688                                ErrorKind::ER_NO_DB_ERROR
689                            } else {
690                                ErrorKind::ER_SP_BADSTATEMENT
691                            };
692                            writer.error(kind, e.output_msg().as_bytes()).await?;
693                            return Ok(());
694                        }
695                    }
696                }
697                Err(e) => {
698                    writer
699                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
700                        .await?;
701                    return Ok(());
702                }
703            }
704        } else if query_upcase.starts_with("EXECUTE ") {
705            match ParserContext::parse_mysql_execute_stmt(query, query_ctx.sql_dialect()) {
706                Ok((stmt_name, params)) => {
707                    let outputs = match self
708                        .do_execute(query_ctx.clone(), stmt_name, Params::CliParams(params))
709                        .await
710                    {
711                        Ok(outputs) => outputs,
712                        Err(e) => {
713                            let (kind, err) = handle_err(e, query_ctx);
714                            debug!(
715                                "Failed to execute prepared statement, kind: {:?}, err: {}",
716                                kind, err
717                            );
718                            writer.error(kind, err.as_bytes()).await?;
719                            return Ok(());
720                        }
721                    };
722                    writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
723
724                    return Ok(());
725                }
726                Err(e) => {
727                    writer
728                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
729                        .await?;
730                    return Ok(());
731                }
732            }
733        } else if query_upcase.starts_with("DEALLOCATE ") {
734            match ParserContext::parse_mysql_deallocate_stmt(query, query_ctx.sql_dialect()) {
735                Ok(stmt_name) => {
736                    self.do_close(stmt_name);
737                    let outputs = vec![Ok(Output::new_with_affected_rows(0))];
738                    writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
739                    return Ok(());
740                }
741                Err(e) => {
742                    writer
743                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
744                        .await?;
745                    return Ok(());
746                }
747            }
748        }
749
750        let outputs = self.do_query(query, query_ctx.clone()).await;
751        writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
752
753        Ok(())
754    }
755
756    async fn on_init<'a>(&'a mut self, database: &'a str, w: InitWriter<'a, W>) -> Result<()> {
757        let (catalog_from_db, schema) = parse_optional_catalog_and_schema_from_db_string(database);
758        let catalog = if let Some(catalog) = &catalog_from_db {
759            catalog.clone()
760        } else {
761            self.session.catalog()
762        };
763
764        let user_info = &self.session.user_info();
765
766        if let Some(schema_validator) = &self.user_provider
767            && let Err(e) = schema_validator
768                .authorize(&catalog, &schema, user_info)
769                .await
770        {
771            METRIC_AUTH_FAILURE
772                .with_label_values(&[e.status_code().as_ref()])
773                .inc();
774            if e.status_code().should_log_error() {
775                error!(e; user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
776                    client_addr = ?self.session.conn_info().client_addr, reason = %e.status_code(),
777                    "Database selection authorization failed");
778            } else {
779                warn!(user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
780                    previous_schema = %self.session.schema(), client_addr = ?self.session.conn_info().client_addr,
781                    reason = %e.status_code(), "Database selection denied");
782            }
783            return w
784                .error(
785                    ErrorKind::ER_DBACCESS_DENIED_ERROR,
786                    e.output_msg().as_bytes(),
787                )
788                .await
789                .map_err(|e| e.into());
790        }
791
792        if !self
793            .query_handler
794            .is_valid_schema(&catalog, &schema)
795            .await?
796        {
797            debug!(user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
798                client_addr = ?self.session.conn_info().client_addr, reason = "schema_not_found",
799                "Database selection failed");
800            return w
801                .error(
802                    ErrorKind::ER_WRONG_DB_NAME,
803                    format!("Unknown database '{}'", database).as_bytes(),
804                )
805                .await
806                .map_err(|e| e.into());
807        }
808
809        let previous_catalog = self.session.catalog();
810        let previous_schema = self.session.schema();
811        if catalog_from_db.is_some() {
812            self.session.set_catalog(catalog)
813        }
814        self.session.set_schema(schema);
815        debug!(user = user_info.username(), protocol = "mysql", catalog = %self.session.catalog(),
816            schema = %self.session.schema(), previous_catalog, previous_schema,
817            client_addr = ?self.session.conn_info().client_addr, "Database selected");
818
819        w.ok().await.map_err(|e| e.into())
820    }
821}
822
823fn convert_param_value_to_string(param: &ParamValue) -> String {
824    match param.value.into_inner() {
825        ValueInner::Int(u) => u.to_string(),
826        ValueInner::UInt(u) => u.to_string(),
827        ValueInner::Double(u) => u.to_string(),
828        ValueInner::NULL => "NULL".to_string(),
829        // MySQL prepared fallback emits SQL text. Delegate bytes/string literal
830        // escaping to mysql_common. `false` means normal MySQL backslash escapes;
831        // if NO_BACKSLASH_ESCAPES is supported in this path later, wire the
832        // session SQL mode here.
833        ValueInner::Bytes(b) => MysqlValue::Bytes(b.to_vec()).as_sql(false),
834        ValueInner::Date(_) => format!("'{}'", NaiveDate::from(param.value)),
835        ValueInner::Datetime(_) => format!("'{}'", NaiveDateTime::from(param.value)),
836        ValueInner::Time(_) => format_duration(Duration::from(param.value)),
837    }
838}
839
840fn replace_params(params: Vec<String>, stmt: Statement, mut query: String) -> Result<String> {
841    let spans = helper::placeholder_spans(stmt);
842    ensure!(
843        spans.len() == params.len(),
844        error::InternalSnafu {
845            err_msg: format!(
846                "Prepared statement expected {} parameters but got {}",
847                spans.len(),
848                params.len()
849            )
850        }
851    );
852
853    let mut replacements = Vec::with_capacity(spans.len());
854    for span in spans {
855        let start = location_to_byte_offset(&query, span.start_line, span.start_column)
856            .ok_or_else(|| {
857                error::InternalSnafu {
858                    err_msg: format!(
859                        "Invalid placeholder start span: line {}, column {}",
860                        span.start_line, span.start_column
861                    ),
862                }
863                .build()
864            })?;
865        let end =
866            location_to_byte_offset(&query, span.end_line, span.end_column).ok_or_else(|| {
867                error::InternalSnafu {
868                    err_msg: format!(
869                        "Invalid placeholder end span: line {}, column {}",
870                        span.end_line, span.end_column
871                    ),
872                }
873                .build()
874            })?;
875        let param = span
876            .index
877            .checked_sub(1)
878            .and_then(|idx| params.get(idx))
879            .ok_or_else(|| {
880                error::InternalSnafu {
881                    err_msg: format!("Missing prepared statement parameter {}", span.index),
882                }
883                .build()
884            })?;
885
886        ensure!(
887            start < end && end <= query.len(),
888            error::InternalSnafu {
889                err_msg: format!(
890                    "Invalid placeholder byte span: {}..{} for query length {}",
891                    start,
892                    end,
893                    query.len()
894                )
895            }
896        );
897        ensure!(
898            query.get(start..end) == Some("?"),
899            error::InternalSnafu {
900                err_msg: format!(
901                    "Prepared statement placeholder span maps to {:?} instead of '?'",
902                    query.get(start..end)
903                )
904            }
905        );
906
907        replacements.push((start, end, param.clone()));
908    }
909
910    replacements.sort_unstable_by_key(|(start, _, _)| *start);
911    for windows in replacements.windows(2) {
912        ensure!(
913            windows[0].1 <= windows[1].0,
914            error::InternalSnafu {
915                err_msg: "Overlapping placeholder spans in prepared statement".to_string()
916            }
917        );
918    }
919
920    // All spans are computed against the original query. Apply replacements
921    // from right to left so changing one parameter's string length never shifts
922    // the byte offsets of placeholders that have not been replaced yet.
923    for (start, end, param) in replacements.into_iter().rev() {
924        query.replace_range(start..end, &param);
925    }
926
927    Ok(query)
928}
929
930fn location_to_byte_offset(query: &str, line: u64, column: u64) -> Option<usize> {
931    // sqlparser spans are 1-based line/column locations, and columns advance by
932    // Rust `char`s rather than bytes. Convert them to byte offsets before using
933    // `String::replace_range` on the original SQL text.
934    if line == 0 || column == 0 {
935        return None;
936    }
937
938    let mut current_line = 1;
939    let mut current_column = 1;
940    for (index, ch) in query.char_indices() {
941        if current_line == line && current_column == column {
942            return Some(index);
943        }
944
945        if ch == '\n' {
946            current_line += 1;
947            current_column = 1;
948        } else {
949            current_column += 1;
950        }
951    }
952
953    // The exclusive end location of a trailing placeholder points just past
954    // the last character, for example the end span of `SELECT ?`.
955    (current_line == line && current_column == column).then_some(query.len())
956}
957
958fn format_duration(duration: Duration) -> String {
959    let seconds = duration.as_secs() % 60;
960    let minutes = (duration.as_secs() / 60) % 60;
961    let hours = (duration.as_secs() / 60) / 60;
962    format!("'{}:{}:{}'", hours, minutes, seconds)
963}
964
965fn replace_params_with_values(
966    plan: &LogicalPlan,
967    param_types: HashMap<String, Option<ConcreteDataType>>,
968    params: &[ParamValue],
969    timezone: &Timezone,
970) -> Result<LogicalPlan> {
971    debug!(
972        "replace_params_with_values(param_types: {:#?}, params: {:#?}, plan: {:#?})",
973        param_types,
974        params
975            .iter()
976            .map(|x| format!("({:?}, {:?})", x.value, x.coltype))
977            .join(", "),
978        plan
979    );
980    replace_plan_params(plan, &param_types, params, |param, t| {
981        helper::convert_value(param, t, timezone)
982    })
983}
984
985fn replace_params_with_exprs(
986    plan: &LogicalPlan,
987    param_types: HashMap<String, Option<ConcreteDataType>>,
988    params: &[sql::ast::Expr],
989    timezone: &Timezone,
990) -> Result<LogicalPlan> {
991    debug!(
992        "replace_params_with_exprs(param_types: {:#?}, params: {:#?}, plan: {:#?})",
993        param_types,
994        params.iter().map(|x| format!("({:?})", x)).join(", "),
995        plan
996    );
997    replace_plan_params(plan, &param_types, params, |param, t| {
998        helper::convert_expr_to_scalar_value(param, t, timezone)
999    })
1000}
1001
1002fn replace_plan_params<P>(
1003    plan: &LogicalPlan,
1004    param_types: &HashMap<String, Option<ConcreteDataType>>,
1005    params: &[P],
1006    convert: impl Fn(&P, &ConcreteDataType) -> Result<ScalarValue>,
1007) -> Result<LogicalPlan> {
1008    debug_assert_eq!(param_types.len(), params.len());
1009
1010    let mut values = Vec::with_capacity(params.len());
1011    for (i, param) in params.iter().enumerate() {
1012        if let Some(Some(t)) = param_types.get(&format_placeholder(i + 1)) {
1013            values.push(convert(param, t)?.into());
1014        }
1015    }
1016
1017    plan.clone()
1018        .replace_params_with_values(&ParamValues::List(values))
1019        .context(DataFrameSnafu)
1020}
1021
1022async fn validate_query(query: &str) -> Result<Statement> {
1023    let statement =
1024        ParserContext::create_with_dialect(query, &MySqlDialect {}, ParseOptions::default());
1025    let mut statement = statement.map_err(|e| {
1026        InvalidPrepareStatementSnafu {
1027            err_msg: e.output_msg(),
1028        }
1029        .build()
1030    })?;
1031
1032    ensure!(
1033        statement.len() == 1,
1034        InvalidPrepareStatementSnafu {
1035            err_msg: "prepare statement only support single statement".to_string(),
1036        }
1037    );
1038
1039    let statement = statement.remove(0);
1040
1041    Ok(statement)
1042}
1043
1044fn dummy_params(index: usize) -> Result<Vec<Column>> {
1045    let mut params = Vec::with_capacity(index - 1);
1046
1047    for _ in 1..index {
1048        params.push(create_mysql_column(&ConcreteDataType::null_datatype(), "")?);
1049    }
1050
1051    Ok(params)
1052}
1053
1054/// Parameters that the client must provide when executing the prepared statement.
1055fn prepared_params(
1056    param_types: &HashMap<String, Option<ConcreteDataType>>,
1057    param_num: usize,
1058) -> Result<Vec<Column>> {
1059    let mut params = Vec::with_capacity(param_num - 1);
1060
1061    // Placeholder index starts from 1
1062    for i in 1..param_num {
1063        let column = if let Some(Some(t)) = param_types.get(&format_placeholder(i)) {
1064            create_mysql_column(t, "")?
1065        } else {
1066            create_mysql_column(&ConcreteDataType::null_datatype(), "")?
1067        };
1068        params.push(column);
1069    }
1070
1071    Ok(params)
1072}
1073
1074fn all_params_have_types(
1075    param_types: &HashMap<String, Option<ConcreteDataType>>,
1076    param_num: usize,
1077) -> bool {
1078    param_types.len() == param_num - 1
1079        && (1..param_num).all(|i| matches!(param_types.get(&format_placeholder(i)), Some(Some(_))))
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use std::sync::Arc;
1085
1086    use async_trait::async_trait;
1087    use auth::UserProvider;
1088    use common_query::Output;
1089    use datafusion_expr::LogicalPlan;
1090    use query::parser::PromQuery;
1091    use query::query_engine::DescribeResult;
1092    use session::context::QueryContext;
1093    use sql::statements::statement::Statement;
1094
1095    use super::*;
1096    use crate::error::Result;
1097    use crate::query_handler::sql::SqlQueryHandler;
1098
1099    struct DummyQueryHandler;
1100
1101    #[async_trait]
1102    impl SqlQueryHandler for DummyQueryHandler {
1103        async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1104            unimplemented!()
1105        }
1106
1107        async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1108            unimplemented!()
1109        }
1110
1111        async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1112            unimplemented!()
1113        }
1114
1115        async fn do_exec_plan(
1116            &self,
1117            _: LogicalPlan,
1118            _: Option<Statement>,
1119            _: QueryContextRef,
1120        ) -> Result<Output> {
1121            unimplemented!()
1122        }
1123
1124        async fn do_describe(
1125            &self,
1126            _: Statement,
1127            _: QueryContextRef,
1128        ) -> Result<Option<DescribeResult>> {
1129            unimplemented!()
1130        }
1131
1132        async fn is_valid_schema(&self, _: &str, schema: &str) -> Result<bool> {
1133            if schema == "backend_error" {
1134                return crate::error::InternalSnafu {
1135                    err_msg: "Schema backend unavailable",
1136                }
1137                .fail();
1138            }
1139            Ok(schema != "missing")
1140        }
1141    }
1142
1143    fn create_shim() -> MysqlInstanceShim {
1144        MysqlInstanceShim::create(
1145            Arc::new(DummyQueryHandler),
1146            None,
1147            "127.0.0.1:3306".parse().unwrap(),
1148            1,
1149            1024,
1150        )
1151    }
1152
1153    struct HandshakeUserProvider {
1154        inner: auth::tests::MockUserProvider,
1155        fail_authorization: bool,
1156    }
1157
1158    #[async_trait]
1159    impl UserProvider for HandshakeUserProvider {
1160        fn name(&self) -> &str {
1161            "handshake_test"
1162        }
1163
1164        async fn authenticate(
1165            &self,
1166            identity: Identity<'_>,
1167            password: Password<'_>,
1168        ) -> auth::error::Result<auth::UserInfoRef> {
1169            self.inner.authenticate(identity, password).await
1170        }
1171
1172        async fn authorize(
1173            &self,
1174            catalog: &str,
1175            schema: &str,
1176            user_info: &auth::UserInfoRef,
1177        ) -> auth::error::Result<()> {
1178            if self.fail_authorization {
1179                auth::error::InternalStateSnafu {
1180                    msg: "Authorization backend unavailable",
1181                }
1182                .fail()
1183            } else {
1184                self.inner.authorize(catalog, schema, user_info).await
1185            }
1186        }
1187    }
1188
1189    #[tokio::test]
1190    async fn test_handshake_database_selection() {
1191        for (allowed, default_schema, database, fail_authorization, expected_schema) in [
1192            ("allowed", "public", None, false, Some("")),
1193            ("allowed", "public", Some("denied"), false, None),
1194            ("allowed", "public", Some("allowed"), false, Some("allowed")),
1195            ("missing", "public", Some("missing"), false, None),
1196            ("public", "public", None, false, Some("public")),
1197            ("missing", "missing", None, false, Some("")),
1198            ("backend_error", "backend_error", None, false, None),
1199            ("public", "public", None, true, None),
1200        ] {
1201            let mut shim = create_shim();
1202            shim.session.set_schema(default_schema.to_string());
1203            shim.user_provider = Some(Arc::new(HandshakeUserProvider {
1204                inner: auth::tests::MockUserProvider {
1205                    schema: allowed.to_string(),
1206                    ..Default::default()
1207                },
1208                fail_authorization,
1209            }));
1210            let result =
1211                <MysqlInstanceShim as AsyncMysqlShim<tokio::io::Sink>>::authenticate_with_database(
1212                    &shim,
1213                    MysqlAuthMethod::CLEAR_PASSWORD_PLUGIN,
1214                    b"greptime",
1215                    &[],
1216                    b"greptime\0",
1217                    database.map(str::as_bytes),
1218                )
1219                .await;
1220            assert_eq!(expected_schema.is_some(), result, "{allowed}: {database:?}");
1221            assert_eq!(
1222                expected_schema.unwrap_or(default_schema),
1223                shim.session.schema()
1224            );
1225        }
1226    }
1227
1228    #[tokio::test]
1229    async fn test_reject_invalid_handshake_database() {
1230        let shim = create_shim();
1231        assert!(
1232            !<MysqlInstanceShim as AsyncMysqlShim<tokio::io::Sink>>::authenticate_with_database(
1233                &shim,
1234                MysqlAuthMethod::NATIVE_PASSWORD_PLUGIN,
1235                b"greptime",
1236                &[],
1237                &[],
1238                Some(&[0xff]),
1239            )
1240            .await
1241        );
1242    }
1243
1244    #[test]
1245    fn test_prepared_statement_cache_metrics() {
1246        use common_frontend::metrics::{CACHE_HIT, CACHE_MISS};
1247
1248        let hits = CACHE_HIT.with_label_values(&["mysql_prepared_stmt"]);
1249        let misses = CACHE_MISS.with_label_values(&["mysql_prepared_stmt"]);
1250        let before = (hits.get(), misses.get());
1251        let mut shim = create_shim();
1252        assert!(shim.plan("stmt").is_none());
1253        shim.save_plan(SqlPlan::Shortcut("SELECT 1".into()), "stmt".into())
1254            .unwrap();
1255        assert!(shim.plan("stmt").is_some());
1256        shim.do_close("stmt".into());
1257        assert!(shim.plan("stmt").is_none());
1258        assert_eq!((hits.get(), misses.get()), (before.0 + 1, before.1 + 2));
1259    }
1260
1261    #[test]
1262    fn test_batching_context() {
1263        for enabled in [false, true] {
1264            let shim = create_shim().with_batching_enabled(enabled);
1265            let ctx = shim.new_query_context();
1266            assert_eq!(ctx.batching_enabled(), enabled);
1267            assert!(!ctx.logical_batching_enabled());
1268            assert_eq!(ctx.channel(), Channel::Mysql);
1269        }
1270    }
1271
1272    fn statement_with_transformed_placeholders(query: &str) -> Statement {
1273        let mut statements =
1274            ParserContext::create_with_dialect(query, &MySqlDialect {}, ParseOptions::default())
1275                .unwrap();
1276        assert_eq!(statements.len(), 1);
1277        transform_placeholders_with_count(statements.remove(0)).0
1278    }
1279
1280    #[test]
1281    fn test_prepared_params_keep_unknown_type_placeholders() {
1282        let mut param_types = HashMap::new();
1283        param_types.insert(format_placeholder(1), None);
1284        param_types.insert(
1285            format_placeholder(2),
1286            Some(ConcreteDataType::int32_datatype()),
1287        );
1288
1289        let params = prepared_params(&param_types, 3).unwrap();
1290        assert_eq!(params.len(), 2);
1291        assert!(!all_params_have_types(&param_types, 3));
1292    }
1293
1294    #[test]
1295    fn test_replace_params_by_placeholder_span() {
1296        let query = "SELECT ?, ?".to_string();
1297        let stmt = statement_with_transformed_placeholders(&query);
1298        let params = vec!["'$2 should stay'".to_string(), "'value'".to_string()];
1299
1300        assert_eq!(
1301            "SELECT '$2 should stay', 'value'",
1302            replace_params(params, stmt, query).unwrap()
1303        );
1304
1305        let query = "SELECT ?, ?, ?".to_string();
1306        let stmt = statement_with_transformed_placeholders(&query);
1307        let params = vec![
1308            "'much longer than a placeholder'".to_string(),
1309            "0".to_string(),
1310            "'also much longer than a placeholder'".to_string(),
1311        ];
1312
1313        assert_eq!(
1314            "SELECT 'much longer than a placeholder', 0, 'also much longer than a placeholder'",
1315            replace_params(params, stmt, query).unwrap()
1316        );
1317
1318        let query = "SELECT '$1', \"$2\", `$3`, ?, ?".to_string();
1319        let stmt = statement_with_transformed_placeholders(&query);
1320        let params = vec!["'1'".to_string(), "'2'".to_string()];
1321
1322        assert_eq!(
1323            "SELECT '$1', \"$2\", `$3`, '1', '2'",
1324            replace_params(params, stmt, query).unwrap()
1325        );
1326
1327        let query = "SELECT /* ? */ ? -- ?\n, ?".to_string();
1328        let stmt = statement_with_transformed_placeholders(&query);
1329        let params = vec!["'first'".to_string(), "'second'".to_string()];
1330
1331        assert_eq!(
1332            "SELECT /* ? */ 'first' -- ?\n, 'second'",
1333            replace_params(params, stmt, query).unwrap()
1334        );
1335
1336        let query = "SELECT '中文', ?".to_string();
1337        let stmt = statement_with_transformed_placeholders(&query);
1338        let params = vec!["'value'".to_string()];
1339
1340        assert_eq!(
1341            "SELECT '中文', 'value'",
1342            replace_params(params, stmt, query).unwrap()
1343        );
1344
1345        let query = "SELECT '中文',\n  ?".to_string();
1346        let stmt = statement_with_transformed_placeholders(&query);
1347        let params = vec!["'value'".to_string()];
1348
1349        assert_eq!(
1350            "SELECT '中文',\n  'value'",
1351            replace_params(params, stmt, query).unwrap()
1352        );
1353
1354        let query = "SELECT 'x'\r\n, ?".to_string();
1355        let stmt = statement_with_transformed_placeholders(&query);
1356        let params = vec!["'crlf'".to_string()];
1357
1358        assert_eq!(
1359            "SELECT 'x'\r\n, 'crlf'",
1360            replace_params(params, stmt, query).unwrap()
1361        );
1362
1363        let query = "SELECT\t?".to_string();
1364        let stmt = statement_with_transformed_placeholders(&query);
1365        let params = vec!["NULL".to_string()];
1366
1367        assert_eq!("SELECT\tNULL", replace_params(params, stmt, query).unwrap());
1368
1369        let query = "SELECT CAST(? AS INT64), ? + (SELECT ?)".to_string();
1370        let stmt = statement_with_transformed_placeholders(&query);
1371        let params = vec!["1".to_string(), "2".to_string(), "3".to_string()];
1372
1373        assert_eq!(
1374            "SELECT CAST(1 AS INT64), 2 + (SELECT 3)",
1375            replace_params(params, stmt, query).unwrap()
1376        );
1377
1378        let query = "SET time_zone = ?".to_string();
1379        let stmt = statement_with_transformed_placeholders(&query);
1380        let params = vec!["'UTC'".to_string()];
1381
1382        assert_eq!(
1383            "SET time_zone = 'UTC'",
1384            replace_params(params, stmt, query).unwrap()
1385        );
1386    }
1387
1388    #[tokio::test]
1389    async fn test_prepare_federated_query() {
1390        let mut shim = create_shim();
1391        let query_ctx = QueryContext::arc();
1392        let stmt_key = "test_federated".to_string();
1393
1394        let (params, columns) = shim
1395            .do_prepare(
1396                "SELECT @@version_comment",
1397                query_ctx.clone(),
1398                stmt_key.clone(),
1399            )
1400            .await
1401            .unwrap();
1402
1403        assert!(params.is_empty());
1404        assert!(columns.is_empty());
1405
1406        let plan = shim.plan(&stmt_key).unwrap();
1407        assert!(matches!(plan, SqlPlan::Shortcut(q) if q == "SELECT @@version_comment"));
1408    }
1409
1410    #[tokio::test]
1411    async fn test_execute_federated_shortcut() {
1412        let mut shim = create_shim();
1413        let query_ctx = QueryContext::arc();
1414        let stmt_key = "test_federated_exec".to_string();
1415
1416        shim.do_prepare(
1417            "SELECT @@version_comment",
1418            query_ctx.clone(),
1419            stmt_key.clone(),
1420        )
1421        .await
1422        .unwrap();
1423
1424        let outputs = shim
1425            .do_execute(query_ctx.clone(), stmt_key, Params::CliParams(vec![]))
1426            .await
1427            .unwrap();
1428
1429        assert_eq!(outputs.len(), 1);
1430        let output = outputs.into_iter().next().unwrap().unwrap();
1431        let pretty = output.data.pretty_print().await;
1432        assert!(pretty.contains("GreptimeDB"));
1433    }
1434
1435    #[tokio::test]
1436    async fn test_prepare_non_federated_query_not_shortcut() {
1437        let mut shim = create_shim();
1438        let query_ctx = QueryContext::arc();
1439        let stmt_key = "test_non_federated".to_string();
1440
1441        let result = shim
1442            .do_prepare("SET NAMES utf8", query_ctx.clone(), stmt_key.clone())
1443            .await;
1444
1445        assert!(result.is_ok());
1446        let plan = shim.plan(&stmt_key).unwrap();
1447        assert!(matches!(plan, SqlPlan::Shortcut(_)));
1448    }
1449
1450    #[tokio::test]
1451    async fn test_execute_set_shortcut() {
1452        let mut shim = create_shim();
1453        let query_ctx = QueryContext::arc();
1454        let stmt_key = "test_set_shortcut".to_string();
1455
1456        shim.do_prepare("SET NAMES utf8", query_ctx.clone(), stmt_key.clone())
1457            .await
1458            .unwrap();
1459
1460        let outputs = shim
1461            .do_execute(query_ctx.clone(), stmt_key, Params::CliParams(vec![]))
1462            .await
1463            .unwrap();
1464
1465        assert_eq!(outputs.len(), 1);
1466        let output = outputs.into_iter().next().unwrap().unwrap();
1467        match output.data {
1468            common_query::OutputData::RecordBatches(batches) => {
1469                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
1470                assert_eq!(total_rows, 0);
1471            }
1472            other => panic!("Expected RecordBatches, got {:?}", other),
1473        }
1474    }
1475}