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;
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) => {
445                if let Some(output) =
446                    crate::mysql::federated::check(&query, query_ctx.clone(), self.session.clone())
447                {
448                    vec![Ok(output)]
449                } else {
450                    self.do_query(&query, query_ctx.clone()).await
451                }
452            }
453            SqlPlan::Statement(stmt, query) => {
454                let param_strs = match params {
455                    Params::ProtocolParams(params) => {
456                        params.iter().map(convert_param_value_to_string).collect()
457                    }
458                    Params::CliParams(params) => params.iter().map(|x| x.to_string()).collect(),
459                };
460                debug!(
461                    "do_execute Replacing with Params: {:?}, Original Query: {}",
462                    param_strs, query
463                );
464                let query = replace_params(param_strs, stmt, query)?;
465                debug!("Mysql execute replaced query: {}", query);
466                self.do_query(&query, query_ctx.clone()).await
467            }
468            _ => {
469                return error::PrepareStatementNotFoundSnafu { name: stmt_key }.fail();
470            }
471        };
472
473        Ok(outputs)
474    }
475
476    /// Remove the prepared statement by a given statement key
477    fn do_close(&mut self, stmt_key: String) {
478        let mut guard = self.prepared_stmts.write();
479        let _ = guard.remove(&stmt_key);
480    }
481
482    fn auth_plugin(&self) -> &'static str {
483        self.user_provider
484            .as_ref()
485            .map(|provider| provider.mysql_auth_method())
486            .unwrap_or(MysqlAuthMethod::NativePassword)
487            .plugin_name()
488    }
489}
490
491#[async_trait]
492impl<W: AsyncWrite + Send + Sync + Unpin> AsyncMysqlShim<W> for MysqlInstanceShim {
493    type Error = error::Error;
494
495    fn version(&self) -> String {
496        std::env::var("GREPTIMEDB_MYSQL_SERVER_VERSION").unwrap_or_else(|_| "8.4.2".to_string())
497    }
498
499    fn connect_id(&self) -> u32 {
500        self.process_id
501    }
502
503    fn default_auth_plugin(&self) -> &str {
504        self.auth_plugin()
505    }
506
507    async fn auth_plugin_for_username(&self, user: &[u8]) -> &'static str {
508        if user == BEARER_TOKEN_USER.as_bytes() {
509            return MysqlAuthMethod::ClearPassword.plugin_name();
510        }
511        if let Some(provider) = &self.user_provider {
512            let username = String::from_utf8_lossy(user);
513            match provider.mysql_auth_method_for_user(&username).await {
514                Ok(method) => return method.plugin_name(),
515                // This hook cannot return an error. Keep the default challenge;
516                // authentication still validates the credentials separately.
517                Err(e) => warn!(e; "Failed to select MySQL authentication method"),
518            }
519        }
520        self.auth_plugin()
521    }
522
523    fn salt(&self) -> [u8; 20] {
524        self.salt
525    }
526
527    async fn authenticate(
528        &self,
529        auth_plugin: &str,
530        username: &[u8],
531        salt: &[u8],
532        auth_data: &[u8],
533    ) -> bool {
534        <Self as AsyncMysqlShim<W>>::authenticate_with_database(
535            self,
536            auth_plugin,
537            username,
538            salt,
539            auth_data,
540            None,
541        )
542        .await
543    }
544
545    async fn authenticate_with_database(
546        &self,
547        auth_plugin: &str,
548        username: &[u8],
549        salt: &[u8],
550        auth_data: &[u8],
551        database: Option<&[u8]>,
552    ) -> bool {
553        let database = match database.map(std::str::from_utf8).transpose() {
554            Ok(database) => database,
555            Err(_) => {
556                warn!("MySQL database is not valid UTF-8");
557                return false;
558            }
559        };
560        let (catalog, schema) = if let Some(database) = database {
561            let (catalog, schema) = parse_optional_catalog_and_schema_from_db_string(database);
562            (catalog.unwrap_or_else(|| self.session.catalog()), schema)
563        } else {
564            (self.session.catalog(), self.session.schema())
565        };
566        // if not specified then **greptime** will be used
567        let username = String::from_utf8_lossy(username);
568
569        let Some(user_info) = self
570            .authenticate_handshake_user(auth_plugin, &username, salt, auth_data, &catalog)
571            .await
572        else {
573            return false;
574        };
575        let Some(schema) = self
576            .select_handshake_database(&catalog, schema, &user_info, database.is_some())
577            .await
578        else {
579            return false;
580        };
581        self.session.set_catalog(catalog);
582        self.session.set_schema(schema);
583        self.session.set_user_info(user_info);
584        debug!(user = self.session.user_info().username(), protocol = "mysql",
585            catalog = %self.session.catalog(), schema = %self.session.schema(),
586            client_addr = ?self.session.conn_info().client_addr, "Handshake database selected");
587
588        true
589    }
590
591    async fn on_prepare<'a>(
592        &'a mut self,
593        raw_query: &'a str,
594        w: StatementMetaWriter<'a, W>,
595    ) -> Result<()> {
596        let query_ctx = self.new_query_context();
597        let stmt_id = self.prepared_stmts_counter.fetch_add(1, Ordering::Relaxed);
598        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
599        let (params, columns) = match self
600            .do_prepare(raw_query, query_ctx.clone(), stmt_key)
601            .await
602        {
603            Ok(x) => x,
604            Err(e) => {
605                let (kind, msg) = handle_err(e, query_ctx.clone());
606                w.error(kind, msg.as_bytes()).await?;
607                return Ok(());
608            }
609        };
610        debug!("on_prepare: Params: {:?}, Columns: {:?}", params, columns);
611        w.reply(stmt_id, &params, &columns).await?;
612        crate::metrics::METRIC_MYSQL_PREPARED_COUNT
613            .with_label_values(&[query_ctx.get_db_string().as_str()])
614            .inc();
615        return Ok(());
616    }
617
618    async fn on_execute<'a>(
619        &'a mut self,
620        stmt_id: u32,
621        p: ParamParser<'a>,
622        w: QueryResultWriter<'a, W>,
623    ) -> Result<()> {
624        self.session.clear_warnings();
625
626        let query_ctx = self.new_query_context();
627        let db = query_ctx.get_db_string();
628        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
629            .with_label_values(&[crate::metrics::METRIC_MYSQL_BINQUERY, db.as_str()])
630            .start_timer();
631
632        let params: Vec<ParamValue> = p.into_iter().collect();
633        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
634
635        let outputs = match self
636            .do_execute(query_ctx.clone(), stmt_key, Params::ProtocolParams(params))
637            .await
638        {
639            Ok(outputs) => outputs,
640            Err(e) => {
641                let (kind, err) = handle_err(e, query_ctx);
642                debug!(
643                    "Failed to execute prepared statement, kind: {:?}, err: {}",
644                    kind, err
645                );
646                w.error(kind, err.as_bytes()).await?;
647                return Ok(());
648            }
649        };
650
651        writer::write_output(w, query_ctx, self.session.clone(), outputs).await?;
652
653        Ok(())
654    }
655
656    async fn on_close<'a>(&'a mut self, stmt_id: u32)
657    where
658        W: 'async_trait,
659    {
660        let stmt_key = uuid::Uuid::from_u128(stmt_id as u128).to_string();
661        self.do_close(stmt_key);
662    }
663
664    #[tracing::instrument(skip_all, fields(protocol = "mysql"))]
665    async fn on_query<'a>(
666        &'a mut self,
667        query: &'a str,
668        writer: QueryResultWriter<'a, W>,
669    ) -> Result<()> {
670        let query_ctx = self.new_query_context();
671        let db = query_ctx.get_db_string();
672        let _timer = crate::metrics::METRIC_MYSQL_QUERY_TIMER
673            .with_label_values(&[crate::metrics::METRIC_MYSQL_TEXTQUERY, db.as_str()])
674            .start_timer();
675
676        // Clear warnings for non SHOW WARNINGS queries
677        let query_upcase = query.to_uppercase();
678        if !query_upcase.starts_with("SHOW WARNINGS") {
679            self.session.clear_warnings();
680        }
681
682        if query_upcase.starts_with("PREPARE ") {
683            match ParserContext::parse_mysql_prepare_stmt(query, query_ctx.sql_dialect()) {
684                Ok((stmt_name, stmt)) => {
685                    let prepare_results =
686                        self.do_prepare(&stmt, query_ctx.clone(), stmt_name).await;
687                    match prepare_results {
688                        Ok(_) => {
689                            let outputs = vec![Ok(Output::new_with_affected_rows(0))];
690                            writer::write_output(writer, query_ctx, self.session.clone(), outputs)
691                                .await?;
692                            return Ok(());
693                        }
694                        Err(e) => {
695                            let kind = if writer::is_no_database_selected(&e) {
696                                ErrorKind::ER_NO_DB_ERROR
697                            } else {
698                                ErrorKind::ER_SP_BADSTATEMENT
699                            };
700                            writer.error(kind, e.output_msg().as_bytes()).await?;
701                            return Ok(());
702                        }
703                    }
704                }
705                Err(e) => {
706                    writer
707                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
708                        .await?;
709                    return Ok(());
710                }
711            }
712        } else if query_upcase.starts_with("EXECUTE ") {
713            match ParserContext::parse_mysql_execute_stmt(query, query_ctx.sql_dialect()) {
714                Ok((stmt_name, params)) => {
715                    let outputs = match self
716                        .do_execute(query_ctx.clone(), stmt_name, Params::CliParams(params))
717                        .await
718                    {
719                        Ok(outputs) => outputs,
720                        Err(e) => {
721                            let (kind, err) = handle_err(e, query_ctx);
722                            debug!(
723                                "Failed to execute prepared statement, kind: {:?}, err: {}",
724                                kind, err
725                            );
726                            writer.error(kind, err.as_bytes()).await?;
727                            return Ok(());
728                        }
729                    };
730                    writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
731
732                    return Ok(());
733                }
734                Err(e) => {
735                    writer
736                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
737                        .await?;
738                    return Ok(());
739                }
740            }
741        } else if query_upcase.starts_with("DEALLOCATE ") {
742            match ParserContext::parse_mysql_deallocate_stmt(query, query_ctx.sql_dialect()) {
743                Ok(stmt_name) => {
744                    self.do_close(stmt_name);
745                    let outputs = vec![Ok(Output::new_with_affected_rows(0))];
746                    writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
747                    return Ok(());
748                }
749                Err(e) => {
750                    writer
751                        .error(ErrorKind::ER_PARSE_ERROR, e.output_msg().as_bytes())
752                        .await?;
753                    return Ok(());
754                }
755            }
756        }
757
758        let outputs = self.do_query(query, query_ctx.clone()).await;
759        writer::write_output(writer, query_ctx, self.session.clone(), outputs).await?;
760
761        Ok(())
762    }
763
764    async fn on_init<'a>(&'a mut self, database: &'a str, w: InitWriter<'a, W>) -> Result<()> {
765        let (catalog_from_db, schema) = parse_optional_catalog_and_schema_from_db_string(database);
766        let catalog = if let Some(catalog) = &catalog_from_db {
767            catalog.clone()
768        } else {
769            self.session.catalog()
770        };
771
772        let user_info = &self.session.user_info();
773
774        if let Some(schema_validator) = &self.user_provider
775            && let Err(e) = schema_validator
776                .authorize(&catalog, &schema, user_info)
777                .await
778        {
779            METRIC_AUTH_FAILURE
780                .with_label_values(&[e.status_code().as_ref()])
781                .inc();
782            if e.status_code().should_log_error() {
783                error!(e; user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
784                    client_addr = ?self.session.conn_info().client_addr, reason = %e.status_code(),
785                    "Database selection authorization failed");
786            } else {
787                warn!(user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
788                    previous_schema = %self.session.schema(), client_addr = ?self.session.conn_info().client_addr,
789                    reason = %e.status_code(), "Database selection denied");
790            }
791            return w
792                .error(
793                    ErrorKind::ER_DBACCESS_DENIED_ERROR,
794                    e.output_msg().as_bytes(),
795                )
796                .await
797                .map_err(|e| e.into());
798        }
799
800        if !self
801            .query_handler
802            .is_valid_schema(&catalog, &schema)
803            .await?
804        {
805            debug!(user = user_info.username(), protocol = "mysql", catalog = %catalog, schema = %schema,
806                client_addr = ?self.session.conn_info().client_addr, reason = "schema_not_found",
807                "Database selection failed");
808            return w
809                .error(
810                    ErrorKind::ER_WRONG_DB_NAME,
811                    format!("Unknown database '{}'", database).as_bytes(),
812                )
813                .await
814                .map_err(|e| e.into());
815        }
816
817        let previous_catalog = self.session.catalog();
818        let previous_schema = self.session.schema();
819        if catalog_from_db.is_some() {
820            self.session.set_catalog(catalog)
821        }
822        self.session.set_schema(schema);
823        debug!(user = user_info.username(), protocol = "mysql", catalog = %self.session.catalog(),
824            schema = %self.session.schema(), previous_catalog, previous_schema,
825            client_addr = ?self.session.conn_info().client_addr, "Database selected");
826
827        w.ok().await.map_err(|e| e.into())
828    }
829}
830
831fn convert_param_value_to_string(param: &ParamValue) -> String {
832    match param.value.into_inner() {
833        ValueInner::Int(u) => u.to_string(),
834        ValueInner::UInt(u) => u.to_string(),
835        ValueInner::Double(u) => u.to_string(),
836        ValueInner::NULL => "NULL".to_string(),
837        // MySQL prepared fallback emits SQL text. Delegate bytes/string literal
838        // escaping to mysql_common. `false` means normal MySQL backslash escapes;
839        // if NO_BACKSLASH_ESCAPES is supported in this path later, wire the
840        // session SQL mode here.
841        ValueInner::Bytes(b) => MysqlValue::Bytes(b.to_vec()).as_sql(false),
842        ValueInner::Date(_) => format!("'{}'", NaiveDate::from(param.value)),
843        ValueInner::Datetime(_) => format!("'{}'", NaiveDateTime::from(param.value)),
844        ValueInner::Time(_) => format_duration(Duration::from(param.value)),
845    }
846}
847
848fn replace_params(params: Vec<String>, stmt: Statement, mut query: String) -> Result<String> {
849    let spans = helper::placeholder_spans(stmt);
850    ensure!(
851        spans.len() == params.len(),
852        error::InternalSnafu {
853            err_msg: format!(
854                "Prepared statement expected {} parameters but got {}",
855                spans.len(),
856                params.len()
857            )
858        }
859    );
860
861    let mut replacements = Vec::with_capacity(spans.len());
862    for span in spans {
863        let start = location_to_byte_offset(&query, span.start_line, span.start_column)
864            .ok_or_else(|| {
865                error::InternalSnafu {
866                    err_msg: format!(
867                        "Invalid placeholder start span: line {}, column {}",
868                        span.start_line, span.start_column
869                    ),
870                }
871                .build()
872            })?;
873        let end =
874            location_to_byte_offset(&query, span.end_line, span.end_column).ok_or_else(|| {
875                error::InternalSnafu {
876                    err_msg: format!(
877                        "Invalid placeholder end span: line {}, column {}",
878                        span.end_line, span.end_column
879                    ),
880                }
881                .build()
882            })?;
883        let param = span
884            .index
885            .checked_sub(1)
886            .and_then(|idx| params.get(idx))
887            .ok_or_else(|| {
888                error::InternalSnafu {
889                    err_msg: format!("Missing prepared statement parameter {}", span.index),
890                }
891                .build()
892            })?;
893
894        ensure!(
895            start < end && end <= query.len(),
896            error::InternalSnafu {
897                err_msg: format!(
898                    "Invalid placeholder byte span: {}..{} for query length {}",
899                    start,
900                    end,
901                    query.len()
902                )
903            }
904        );
905        ensure!(
906            query.get(start..end) == Some("?"),
907            error::InternalSnafu {
908                err_msg: format!(
909                    "Prepared statement placeholder span maps to {:?} instead of '?'",
910                    query.get(start..end)
911                )
912            }
913        );
914
915        replacements.push((start, end, param.clone()));
916    }
917
918    replacements.sort_unstable_by_key(|(start, _, _)| *start);
919    for windows in replacements.windows(2) {
920        ensure!(
921            windows[0].1 <= windows[1].0,
922            error::InternalSnafu {
923                err_msg: "Overlapping placeholder spans in prepared statement".to_string()
924            }
925        );
926    }
927
928    // All spans are computed against the original query. Apply replacements
929    // from right to left so changing one parameter's string length never shifts
930    // the byte offsets of placeholders that have not been replaced yet.
931    for (start, end, param) in replacements.into_iter().rev() {
932        query.replace_range(start..end, &param);
933    }
934
935    Ok(query)
936}
937
938fn location_to_byte_offset(query: &str, line: u64, column: u64) -> Option<usize> {
939    // sqlparser spans are 1-based line/column locations, and columns advance by
940    // Rust `char`s rather than bytes. Convert them to byte offsets before using
941    // `String::replace_range` on the original SQL text.
942    if line == 0 || column == 0 {
943        return None;
944    }
945
946    let mut current_line = 1;
947    let mut current_column = 1;
948    for (index, ch) in query.char_indices() {
949        if current_line == line && current_column == column {
950            return Some(index);
951        }
952
953        if ch == '\n' {
954            current_line += 1;
955            current_column = 1;
956        } else {
957            current_column += 1;
958        }
959    }
960
961    // The exclusive end location of a trailing placeholder points just past
962    // the last character, for example the end span of `SELECT ?`.
963    (current_line == line && current_column == column).then_some(query.len())
964}
965
966fn format_duration(duration: Duration) -> String {
967    let seconds = duration.as_secs() % 60;
968    let minutes = (duration.as_secs() / 60) % 60;
969    let hours = (duration.as_secs() / 60) / 60;
970    format!("'{}:{}:{}'", hours, minutes, seconds)
971}
972
973fn replace_params_with_values(
974    plan: &LogicalPlan,
975    param_types: HashMap<String, Option<ConcreteDataType>>,
976    params: &[ParamValue],
977    timezone: &Timezone,
978) -> Result<LogicalPlan> {
979    debug_assert_eq!(param_types.len(), params.len());
980
981    debug!(
982        "replace_params_with_values(param_types: {:#?}, params: {:#?}, plan: {:#?})",
983        param_types,
984        params
985            .iter()
986            .map(|x| format!("({:?}, {:?})", x.value, x.coltype))
987            .join(", "),
988        plan
989    );
990
991    let mut values = Vec::with_capacity(params.len());
992
993    for (i, param) in params.iter().enumerate() {
994        if let Some(Some(t)) = param_types.get(&format_placeholder(i + 1)) {
995            let value = helper::convert_value(param, t, timezone)?;
996
997            values.push(value.into());
998        }
999    }
1000
1001    plan.clone()
1002        .replace_params_with_values(&ParamValues::List(values.clone()))
1003        .context(DataFrameSnafu)
1004}
1005
1006fn replace_params_with_exprs(
1007    plan: &LogicalPlan,
1008    param_types: HashMap<String, Option<ConcreteDataType>>,
1009    params: &[sql::ast::Expr],
1010    timezone: &Timezone,
1011) -> Result<LogicalPlan> {
1012    debug_assert_eq!(param_types.len(), params.len());
1013
1014    debug!(
1015        "replace_params_with_exprs(param_types: {:#?}, params: {:#?}, plan: {:#?})",
1016        param_types,
1017        params.iter().map(|x| format!("({:?})", x)).join(", "),
1018        plan
1019    );
1020
1021    let mut values = Vec::with_capacity(params.len());
1022
1023    for (i, param) in params.iter().enumerate() {
1024        if let Some(Some(t)) = param_types.get(&format_placeholder(i + 1)) {
1025            let value = helper::convert_expr_to_scalar_value(param, t, timezone)?;
1026
1027            values.push(value.into());
1028        }
1029    }
1030
1031    plan.clone()
1032        .replace_params_with_values(&ParamValues::List(values.clone()))
1033        .context(DataFrameSnafu)
1034}
1035
1036async fn validate_query(query: &str) -> Result<Statement> {
1037    let statement =
1038        ParserContext::create_with_dialect(query, &MySqlDialect {}, ParseOptions::default());
1039    let mut statement = statement.map_err(|e| {
1040        InvalidPrepareStatementSnafu {
1041            err_msg: e.output_msg(),
1042        }
1043        .build()
1044    })?;
1045
1046    ensure!(
1047        statement.len() == 1,
1048        InvalidPrepareStatementSnafu {
1049            err_msg: "prepare statement only support single statement".to_string(),
1050        }
1051    );
1052
1053    let statement = statement.remove(0);
1054
1055    Ok(statement)
1056}
1057
1058fn dummy_params(index: usize) -> Result<Vec<Column>> {
1059    let mut params = Vec::with_capacity(index - 1);
1060
1061    for _ in 1..index {
1062        params.push(create_mysql_column(&ConcreteDataType::null_datatype(), "")?);
1063    }
1064
1065    Ok(params)
1066}
1067
1068/// Parameters that the client must provide when executing the prepared statement.
1069fn prepared_params(
1070    param_types: &HashMap<String, Option<ConcreteDataType>>,
1071    param_num: usize,
1072) -> Result<Vec<Column>> {
1073    let mut params = Vec::with_capacity(param_num - 1);
1074
1075    // Placeholder index starts from 1
1076    for i in 1..param_num {
1077        let column = if let Some(Some(t)) = param_types.get(&format_placeholder(i)) {
1078            create_mysql_column(t, "")?
1079        } else {
1080            create_mysql_column(&ConcreteDataType::null_datatype(), "")?
1081        };
1082        params.push(column);
1083    }
1084
1085    Ok(params)
1086}
1087
1088fn all_params_have_types(
1089    param_types: &HashMap<String, Option<ConcreteDataType>>,
1090    param_num: usize,
1091) -> bool {
1092    param_types.len() == param_num - 1
1093        && (1..param_num).all(|i| matches!(param_types.get(&format_placeholder(i)), Some(Some(_))))
1094}
1095
1096#[cfg(test)]
1097mod tests {
1098    use std::sync::Arc;
1099
1100    use async_trait::async_trait;
1101    use auth::UserProvider;
1102    use common_query::Output;
1103    use datafusion_expr::LogicalPlan;
1104    use query::parser::PromQuery;
1105    use query::query_engine::DescribeResult;
1106    use session::context::QueryContext;
1107    use sql::statements::statement::Statement;
1108
1109    use super::*;
1110    use crate::error::Result;
1111    use crate::query_handler::sql::SqlQueryHandler;
1112
1113    struct DummyQueryHandler;
1114
1115    #[async_trait]
1116    impl SqlQueryHandler for DummyQueryHandler {
1117        async fn do_query(&self, _: &str, _: QueryContextRef) -> Vec<Result<Output>> {
1118            unimplemented!()
1119        }
1120
1121        async fn do_analyze_stream_query(&self, _: &str, _: QueryContextRef) -> Result<Output> {
1122            unimplemented!()
1123        }
1124
1125        async fn do_promql_query(&self, _: &PromQuery, _: QueryContextRef) -> Vec<Result<Output>> {
1126            unimplemented!()
1127        }
1128
1129        async fn do_exec_plan(
1130            &self,
1131            _: LogicalPlan,
1132            _: Option<Statement>,
1133            _: QueryContextRef,
1134        ) -> Result<Output> {
1135            unimplemented!()
1136        }
1137
1138        async fn do_describe(
1139            &self,
1140            _: Statement,
1141            _: QueryContextRef,
1142        ) -> Result<Option<DescribeResult>> {
1143            unimplemented!()
1144        }
1145
1146        async fn is_valid_schema(&self, _: &str, schema: &str) -> Result<bool> {
1147            if schema == "backend_error" {
1148                return crate::error::InternalSnafu {
1149                    err_msg: "Schema backend unavailable",
1150                }
1151                .fail();
1152            }
1153            Ok(schema != "missing")
1154        }
1155    }
1156
1157    fn create_shim() -> MysqlInstanceShim {
1158        MysqlInstanceShim::create(
1159            Arc::new(DummyQueryHandler),
1160            None,
1161            "127.0.0.1:3306".parse().unwrap(),
1162            1,
1163            1024,
1164        )
1165    }
1166
1167    struct HandshakeUserProvider {
1168        inner: auth::tests::MockUserProvider,
1169        fail_authorization: bool,
1170    }
1171
1172    #[async_trait]
1173    impl UserProvider for HandshakeUserProvider {
1174        fn name(&self) -> &str {
1175            "handshake_test"
1176        }
1177
1178        async fn authenticate(
1179            &self,
1180            identity: Identity<'_>,
1181            password: Password<'_>,
1182        ) -> auth::error::Result<auth::UserInfoRef> {
1183            self.inner.authenticate(identity, password).await
1184        }
1185
1186        async fn authorize(
1187            &self,
1188            catalog: &str,
1189            schema: &str,
1190            user_info: &auth::UserInfoRef,
1191        ) -> auth::error::Result<()> {
1192            if self.fail_authorization {
1193                auth::error::InternalStateSnafu {
1194                    msg: "Authorization backend unavailable",
1195                }
1196                .fail()
1197            } else {
1198                self.inner.authorize(catalog, schema, user_info).await
1199            }
1200        }
1201    }
1202
1203    #[tokio::test]
1204    async fn test_handshake_database_selection() {
1205        for (allowed, default_schema, database, fail_authorization, expected_schema) in [
1206            ("allowed", "public", None, false, Some("")),
1207            ("allowed", "public", Some("denied"), false, None),
1208            ("allowed", "public", Some("allowed"), false, Some("allowed")),
1209            ("missing", "public", Some("missing"), false, None),
1210            ("public", "public", None, false, Some("public")),
1211            ("missing", "missing", None, false, Some("")),
1212            ("backend_error", "backend_error", None, false, None),
1213            ("public", "public", None, true, None),
1214        ] {
1215            let mut shim = create_shim();
1216            shim.session.set_schema(default_schema.to_string());
1217            shim.user_provider = Some(Arc::new(HandshakeUserProvider {
1218                inner: auth::tests::MockUserProvider {
1219                    schema: allowed.to_string(),
1220                    ..Default::default()
1221                },
1222                fail_authorization,
1223            }));
1224            let result =
1225                <MysqlInstanceShim as AsyncMysqlShim<tokio::io::Sink>>::authenticate_with_database(
1226                    &shim,
1227                    MysqlAuthMethod::CLEAR_PASSWORD_PLUGIN,
1228                    b"greptime",
1229                    &[],
1230                    b"greptime\0",
1231                    database.map(str::as_bytes),
1232                )
1233                .await;
1234            assert_eq!(expected_schema.is_some(), result, "{allowed}: {database:?}");
1235            assert_eq!(
1236                expected_schema.unwrap_or(default_schema),
1237                shim.session.schema()
1238            );
1239        }
1240    }
1241
1242    #[tokio::test]
1243    async fn test_reject_invalid_handshake_database() {
1244        let shim = create_shim();
1245        assert!(
1246            !<MysqlInstanceShim as AsyncMysqlShim<tokio::io::Sink>>::authenticate_with_database(
1247                &shim,
1248                MysqlAuthMethod::NATIVE_PASSWORD_PLUGIN,
1249                b"greptime",
1250                &[],
1251                &[],
1252                Some(&[0xff]),
1253            )
1254            .await
1255        );
1256    }
1257
1258    #[test]
1259    fn test_prepared_statement_cache_metrics() {
1260        use common_frontend::metrics::{CACHE_HIT, CACHE_MISS};
1261
1262        let hits = CACHE_HIT.with_label_values(&["mysql_prepared_stmt"]);
1263        let misses = CACHE_MISS.with_label_values(&["mysql_prepared_stmt"]);
1264        let before = (hits.get(), misses.get());
1265        let mut shim = create_shim();
1266        assert!(shim.plan("stmt").is_none());
1267        shim.save_plan(SqlPlan::Shortcut("SELECT 1".into()), "stmt".into())
1268            .unwrap();
1269        assert!(shim.plan("stmt").is_some());
1270        shim.do_close("stmt".into());
1271        assert!(shim.plan("stmt").is_none());
1272        assert_eq!((hits.get(), misses.get()), (before.0 + 1, before.1 + 2));
1273    }
1274
1275    #[test]
1276    fn test_batching_context() {
1277        for enabled in [false, true] {
1278            let shim = create_shim().with_batching_enabled(enabled);
1279            let ctx = shim.new_query_context();
1280            assert_eq!(ctx.batching_enabled(), enabled);
1281            assert!(!ctx.logical_batching_enabled());
1282            assert_eq!(ctx.channel(), Channel::Mysql);
1283        }
1284    }
1285
1286    fn statement_with_transformed_placeholders(query: &str) -> Statement {
1287        let mut statements =
1288            ParserContext::create_with_dialect(query, &MySqlDialect {}, ParseOptions::default())
1289                .unwrap();
1290        assert_eq!(statements.len(), 1);
1291        transform_placeholders_with_count(statements.remove(0)).0
1292    }
1293
1294    #[test]
1295    fn test_prepared_params_keep_unknown_type_placeholders() {
1296        let mut param_types = HashMap::new();
1297        param_types.insert(format_placeholder(1), None);
1298        param_types.insert(
1299            format_placeholder(2),
1300            Some(ConcreteDataType::int32_datatype()),
1301        );
1302
1303        let params = prepared_params(&param_types, 3).unwrap();
1304        assert_eq!(params.len(), 2);
1305        assert!(!all_params_have_types(&param_types, 3));
1306    }
1307
1308    #[test]
1309    fn test_replace_params_by_placeholder_span() {
1310        let query = "SELECT ?, ?".to_string();
1311        let stmt = statement_with_transformed_placeholders(&query);
1312        let params = vec!["'$2 should stay'".to_string(), "'value'".to_string()];
1313
1314        assert_eq!(
1315            "SELECT '$2 should stay', 'value'",
1316            replace_params(params, stmt, query).unwrap()
1317        );
1318
1319        let query = "SELECT ?, ?, ?".to_string();
1320        let stmt = statement_with_transformed_placeholders(&query);
1321        let params = vec![
1322            "'much longer than a placeholder'".to_string(),
1323            "0".to_string(),
1324            "'also much longer than a placeholder'".to_string(),
1325        ];
1326
1327        assert_eq!(
1328            "SELECT 'much longer than a placeholder', 0, 'also much longer than a placeholder'",
1329            replace_params(params, stmt, query).unwrap()
1330        );
1331
1332        let query = "SELECT '$1', \"$2\", `$3`, ?, ?".to_string();
1333        let stmt = statement_with_transformed_placeholders(&query);
1334        let params = vec!["'1'".to_string(), "'2'".to_string()];
1335
1336        assert_eq!(
1337            "SELECT '$1', \"$2\", `$3`, '1', '2'",
1338            replace_params(params, stmt, query).unwrap()
1339        );
1340
1341        let query = "SELECT /* ? */ ? -- ?\n, ?".to_string();
1342        let stmt = statement_with_transformed_placeholders(&query);
1343        let params = vec!["'first'".to_string(), "'second'".to_string()];
1344
1345        assert_eq!(
1346            "SELECT /* ? */ 'first' -- ?\n, 'second'",
1347            replace_params(params, stmt, query).unwrap()
1348        );
1349
1350        let query = "SELECT '中文', ?".to_string();
1351        let stmt = statement_with_transformed_placeholders(&query);
1352        let params = vec!["'value'".to_string()];
1353
1354        assert_eq!(
1355            "SELECT '中文', 'value'",
1356            replace_params(params, stmt, query).unwrap()
1357        );
1358
1359        let query = "SELECT '中文',\n  ?".to_string();
1360        let stmt = statement_with_transformed_placeholders(&query);
1361        let params = vec!["'value'".to_string()];
1362
1363        assert_eq!(
1364            "SELECT '中文',\n  'value'",
1365            replace_params(params, stmt, query).unwrap()
1366        );
1367
1368        let query = "SELECT 'x'\r\n, ?".to_string();
1369        let stmt = statement_with_transformed_placeholders(&query);
1370        let params = vec!["'crlf'".to_string()];
1371
1372        assert_eq!(
1373            "SELECT 'x'\r\n, 'crlf'",
1374            replace_params(params, stmt, query).unwrap()
1375        );
1376
1377        let query = "SELECT\t?".to_string();
1378        let stmt = statement_with_transformed_placeholders(&query);
1379        let params = vec!["NULL".to_string()];
1380
1381        assert_eq!("SELECT\tNULL", replace_params(params, stmt, query).unwrap());
1382
1383        let query = "SELECT CAST(? AS INT64), ? + (SELECT ?)".to_string();
1384        let stmt = statement_with_transformed_placeholders(&query);
1385        let params = vec!["1".to_string(), "2".to_string(), "3".to_string()];
1386
1387        assert_eq!(
1388            "SELECT CAST(1 AS INT64), 2 + (SELECT 3)",
1389            replace_params(params, stmt, query).unwrap()
1390        );
1391
1392        let query = "SET time_zone = ?".to_string();
1393        let stmt = statement_with_transformed_placeholders(&query);
1394        let params = vec!["'UTC'".to_string()];
1395
1396        assert_eq!(
1397            "SET time_zone = 'UTC'",
1398            replace_params(params, stmt, query).unwrap()
1399        );
1400    }
1401
1402    #[tokio::test]
1403    async fn test_prepare_federated_query() {
1404        let mut shim = create_shim();
1405        let query_ctx = QueryContext::arc();
1406        let stmt_key = "test_federated".to_string();
1407
1408        let (params, columns) = shim
1409            .do_prepare(
1410                "SELECT @@version_comment",
1411                query_ctx.clone(),
1412                stmt_key.clone(),
1413            )
1414            .await
1415            .unwrap();
1416
1417        assert!(params.is_empty());
1418        assert!(columns.is_empty());
1419
1420        let plan = shim.plan(&stmt_key).unwrap();
1421        assert!(matches!(plan, SqlPlan::Shortcut(q) if q == "SELECT @@version_comment"));
1422    }
1423
1424    #[tokio::test]
1425    async fn test_execute_federated_shortcut() {
1426        let mut shim = create_shim();
1427        let query_ctx = QueryContext::arc();
1428        let stmt_key = "test_federated_exec".to_string();
1429
1430        shim.do_prepare(
1431            "SELECT @@version_comment",
1432            query_ctx.clone(),
1433            stmt_key.clone(),
1434        )
1435        .await
1436        .unwrap();
1437
1438        let outputs = shim
1439            .do_execute(query_ctx.clone(), stmt_key, Params::CliParams(vec![]))
1440            .await
1441            .unwrap();
1442
1443        assert_eq!(outputs.len(), 1);
1444        let output = outputs.into_iter().next().unwrap().unwrap();
1445        let pretty = output.data.pretty_print().await;
1446        assert!(pretty.contains("GreptimeDB"));
1447    }
1448
1449    #[tokio::test]
1450    async fn test_prepare_non_federated_query_not_shortcut() {
1451        let mut shim = create_shim();
1452        let query_ctx = QueryContext::arc();
1453        let stmt_key = "test_non_federated".to_string();
1454
1455        let result = shim
1456            .do_prepare("SET NAMES utf8", query_ctx.clone(), stmt_key.clone())
1457            .await;
1458
1459        assert!(result.is_ok());
1460        let plan = shim.plan(&stmt_key).unwrap();
1461        assert!(matches!(plan, SqlPlan::Shortcut(_)));
1462    }
1463
1464    #[tokio::test]
1465    async fn test_execute_set_shortcut() {
1466        let mut shim = create_shim();
1467        let query_ctx = QueryContext::arc();
1468        let stmt_key = "test_set_shortcut".to_string();
1469
1470        shim.do_prepare("SET NAMES utf8", query_ctx.clone(), stmt_key.clone())
1471            .await
1472            .unwrap();
1473
1474        let outputs = shim
1475            .do_execute(query_ctx.clone(), stmt_key, Params::CliParams(vec![]))
1476            .await
1477            .unwrap();
1478
1479        assert_eq!(outputs.len(), 1);
1480        let output = outputs.into_iter().next().unwrap().unwrap();
1481        match output.data {
1482            common_query::OutputData::RecordBatches(batches) => {
1483                let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
1484                assert_eq!(total_rows, 0);
1485            }
1486            other => panic!("Expected RecordBatches, got {:?}", other),
1487        }
1488    }
1489}